packages feed

nova-nix 0.10.0.0 → 0.11.0.0

raw patch · API changes only · 222 files changed · show whitespace changes · browse nova-nix-0.11.0.0

+128724/−38137 lines, 222 filesdep +binarydep +direct-sqlitedep +primitivedep ~Win32dep ~containersdep ~directorynew-component:exe:nova-nix-sandboxnew-c-sourcesnew-system-library:advapi32new-system-library:authznew-system-library:bcryptnew-system-library:netapi32new-system-library:user32PVP ok

Dependencies added: binary, direct-sqlite, primitive

Dependency ranges changed: Win32, containers, directory, nova-cache, process, sqlite-simple

API changes (from Hackage documentation)

155 removed, 3325 added, 226 changed

version bump matches the API change (PVP)

- Nix.Builder: [bcBuildLog] :: BuildConfig -> Handle
- Nix.Builder: [bcTmpDir] :: BuildConfig -> FilePath
- Nix.Builder.Log: DropEscapes :: EscapeFilter
- Nix.Builder.Log: KeepColour :: EscapeFilter
- Nix.Builder.Log: data EscapeFilter
- Nix.Builder.Log: filterLogLine :: EscapeFilter -> ByteString -> ByteString
- Nix.Builder.Log: instance GHC.Internal.Classes.Eq Nix.Builder.Log.EscapeFilter
- Nix.Builder.Log: instance GHC.Internal.Classes.Eq Nix.Builder.Log.EscapeKind
- Nix.Builder.Log: instance GHC.Internal.Show.Show Nix.Builder.Log.EscapeFilter
- Nix.Eval: BuiltinDef :: NonEmpty ArgMode -> ([BuiltinArg] -> m NixValue) -> BuiltinDef (m :: Type -> Type)
- Nix.Eval: CompiledRegex :: ByteString -> Regex -> CompiledRegex
- Nix.Eval: ForceOnApply :: ArgMode
- Nix.Eval: ForceOnUse :: ArgMode
- Nix.Eval: VCompiledRegex :: CompiledRegex -> NixValue
- Nix.Eval: VPath :: Text -> NixValue
- Nix.Eval: VStr :: ByteString -> StringContext -> NixValue
- Nix.Eval: [bdApply] :: BuiltinDef (m :: Type -> Type) -> [BuiltinArg] -> m NixValue
- Nix.Eval: [bdArgs] :: BuiltinDef (m :: Type -> Type) -> NonEmpty ArgMode
- Nix.Eval: addErrorTrace :: MonadEval m => Text -> m a -> m a
- Nix.Eval: builtinNames :: [Text]
- Nix.Eval: builtinRegistry :: forall (m :: Type -> Type). MonadEval m => Map Text (BuiltinDef m)
- Nix.Eval: data ArgMode
- Nix.Eval: data BuiltinDef (m :: Type -> Type)
- Nix.Eval: data CompiledRegex
- Nix.Eval.Arena: ArenaNotInitialized :: String -> CStatusError
- Nix.Eval.Arena: CAllocationFailed :: String -> String -> CStatusError
- Nix.Eval.Arena: CInvariantViolated :: String -> String -> CStatusError
- Nix.Eval.Arena: arenaDestroy :: IO ()
- Nix.Eval.Arena: arenaInit :: IO ()
- Nix.Eval.Arena: arenaLive :: IO Bool
- Nix.Eval.Arena: data CStatusError
- Nix.Eval.CAttrSet: cattrsetGetKey :: CAttrSet -> Word32 -> IO Symbol
- Nix.Eval.CAttrSet: cattrsetGetPos :: CAttrSet -> Word32 -> IO PosIdx
- Nix.Eval.CAttrSet: cattrsetGetValue :: CAttrSet -> Word32 -> IO CThunkPtr
- Nix.Eval.CAttrSet: cattrsetKeys :: CAttrSet -> IO [Symbol]
- Nix.Eval.CBytecode: appDeferred :: Word8
- Nix.Eval.CBytecode: appDirect :: Word8
- Nix.Eval.CBytecode: cbcDestroy :: IO ()
- Nix.Eval.CBytecode: cbcInit :: Word32 -> Word32 -> IO ()
- Nix.Eval.CBytecode: pattern OpSearchPath :: Word8
- Nix.Eval.CBytecode: reservedApply1 :: Word32
- Nix.Eval.CBytecode: reservedApply2 :: Word32
- Nix.Eval.CCtxStr: cctxstrFreeAll :: IO ()
- Nix.Eval.CEnv: cenvAllocSlots :: Word32 -> IO (Ptr CThunkPtr)
- Nix.Eval.CEnv: cenvAllocWithScopes :: Word32 -> IO (Ptr (Ptr ()))
- Nix.Eval.CEnv: cenvDestroy :: IO ()
- Nix.Eval.CEnv: cenvFromSlots :: Ptr CThunkPtr -> Word32 -> Ptr NnEnv -> IO (Ptr NnEnv)
- Nix.Eval.CEnv: cenvInit :: IO ()
- Nix.Eval.CEnv: cenvLazyScope :: Ptr NnEnv -> IO (Ptr ())
- Nix.Eval.CEnv: cenvNewMinimal :: Ptr CThunkPtr -> Word32 -> IO (Ptr NnEnv)
- Nix.Eval.CEnv: cenvRootScope :: Ptr NnEnv -> IO (Ptr ())
- Nix.Eval.CLambda: clambdaFreeAll :: IO ()
- Nix.Eval.CList: clistCount :: CListPtr -> IO Word32
- Nix.Eval.CList: clistFreeAll :: IO ()
- Nix.Eval.CList: clistGet :: CListPtr -> Word32 -> IO CThunkPtr
- Nix.Eval.CList: clistNew :: Word32 -> IO CListPtr
- Nix.Eval.CList: clistSet :: CListPtr -> Word32 -> CThunkPtr -> IO ()
- Nix.Eval.CList: clistToThunkList :: CListPtr -> IO [CThunkPtr]
- Nix.Eval.CThunk: cthunkCount :: IO Word32
- Nix.Eval.CThunk: cthunkDestroy :: IO ()
- Nix.Eval.CThunk: cthunkGet :: Word32 -> IO CThunkPtr
- Nix.Eval.CThunk: cthunkGetAttrs :: CThunkPtr -> IO (Ptr ())
- Nix.Eval.CThunk: cthunkGetCtxStr :: CThunkPtr -> IO (Ptr ())
- Nix.Eval.CThunk: cthunkGetLambda :: CThunkPtr -> IO (Ptr ())
- Nix.Eval.CThunk: cthunkGetList :: CThunkPtr -> IO (Ptr ())
- Nix.Eval.CThunk: cthunkGetPath :: CThunkPtr -> IO Word32
- Nix.Eval.CThunk: cthunkGetStr :: CThunkPtr -> IO Word32
- Nix.Eval.CThunk: cthunkInit :: Word32 -> IO ()
- Nix.Eval.CThunk: cthunkNewComputed :: Ptr () -> IO CThunkPtr
- Nix.Eval.CThunk: cthunkSetComputed :: CThunkPtr -> Ptr () -> IO Bool
- Nix.Eval.CThunk: cthunkSetPayload :: CThunkPtr -> Ptr () -> IO Bool
- Nix.Eval.CallDepth: maxCallDepthExceeded :: Text
- Nix.Eval.Compile: BcDynamicKey :: Word32 -> BcAttrKey
- Nix.Eval.Compile: BcStaticKey :: Word32 -> BcAttrKey
- Nix.Eval.Compile: data BcAttrKey
- Nix.Eval.Context: firstContextEncoded :: StringContext -> Maybe Text
- Nix.Eval.IO: ErrorThrown :: EvalErrorKind
- Nix.Eval.IO: ErrorUncatchable :: EvalErrorKind
- Nix.Eval.IO: EvalState :: IORef (Map FilePath NixValue) -> IORef (Map Text Text) -> IORef (Map Text ByteString) -> IORef (Map Text Text) -> IORef (Map Text ([StorePath], StoreWriteMode)) -> FilePath -> StoreDir -> Int64 -> [Thunk] -> CallDepth -> EvalPolicy -> IORef AllowedPaths -> EvalState
- Nix.Eval.IO: NixAbortError :: EvalFailure -> NixAbortError
- Nix.Eval.IO: NixEvalError :: EvalErrorKind -> EvalFailure -> NixEvalError
- Nix.Eval.IO: [esAllowedPaths] :: EvalState -> IORef AllowedPaths
- Nix.Eval.IO: [esBaseDir] :: EvalState -> FilePath
- Nix.Eval.IO: [esCallDepth] :: EvalState -> CallDepth
- Nix.Eval.IO: [esDrvClosure] :: EvalState -> IORef (Map Text ByteString)
- Nix.Eval.IO: [esDrvModuloCache] :: EvalState -> IORef (Map Text Text)
- Nix.Eval.IO: [esImportCache] :: EvalState -> IORef (Map FilePath NixValue)
- Nix.Eval.IO: [esPolicy] :: EvalState -> EvalPolicy
- Nix.Eval.IO: [esSearchPaths] :: EvalState -> [Thunk]
- Nix.Eval.IO: [esSourcePathCache] :: EvalState -> IORef (Map Text Text)
- Nix.Eval.IO: [esStoreDir] :: EvalState -> StoreDir
- Nix.Eval.IO: [esStoreWriteCache] :: EvalState -> IORef (Map Text ([StorePath], StoreWriteMode))
- Nix.Eval.IO: [esTimestamp] :: EvalState -> Int64
- Nix.Eval.IO: data EvalErrorKind
- Nix.Eval.IO: data NixEvalError
- Nix.Eval.IO: instance GHC.Internal.Classes.Eq Nix.Eval.IO.SymlinkResolution
- Nix.Eval.IO: instance GHC.Internal.Show.Show Nix.Eval.IO.SymlinkResolution
- Nix.Eval.IO: newEvalState :: StoreDir -> FilePath -> IO EvalState
- Nix.Eval.IO: newtype NixAbortError
- Nix.Eval.Policy: forbiddenUriMessage :: Text -> Text
- Nix.Eval.Policy: modeInformation :: EvalPolicy -> Text
- Nix.Eval.Symbol: symbolBytes :: Symbol -> ByteString
- Nix.Eval.Symbol: symbolDestroy :: IO ()
- Nix.Eval.Symbol: symbolInit :: Word32 -> IO ()
- Nix.Eval.Symbol: symbolInternBytes :: ByteString -> IO Symbol
- Nix.Eval.Types: CompiledRegex :: ByteString -> Regex -> CompiledRegex
- Nix.Eval.Types: VCompiledRegex :: CompiledRegex -> NixValue
- Nix.Eval.Types: VPath :: Text -> NixValue
- Nix.Eval.Types: VStr :: ByteString -> StringContext -> NixValue
- Nix.Eval.Types: allocCSlots :: Int -> Ptr CThunkPtr
- Nix.Eval.Types: attrSetUnionWith :: (Thunk -> Thunk -> Thunk) -> AttrSet -> AttrSet -> AttrSet
- Nix.Eval.Types: buildCSlots :: [Thunk] -> (Ptr CThunkPtr, Int)
- Nix.Eval.Types: checkedCPtr :: String -> Ptr a -> IO (Ptr a)
- Nix.Eval.Types: data CompiledRegex
- Nix.Eval.Types: envFromSlots :: Ptr CThunkPtr -> Int -> Env -> Env
- Nix.Eval.Types: fillCSlots :: Ptr CThunkPtr -> [Thunk] -> ()
- Nix.Eval.Types: instance GHC.Internal.Classes.Eq Nix.Eval.Types.CompiledRegex
- Nix.Eval.Types: instance GHC.Internal.Show.Show Nix.Eval.Types.CompiledRegex
- Nix.Eval.Types: lookupWithScopes :: Text -> [AttrSet] -> Maybe Thunk
- Nix.Eval.Types: marshalStringContext :: ByteString -> StringContext -> IO CCtxStrPtr
- Nix.Eval.Types: mkSyntheticThunk :: Env -> Word32 -> Thunk
- Nix.Eval.Types: mkThunk :: Env -> Expr -> Thunk
- Nix.Eval.Types: newCEnv :: Ptr CThunkPtr -> Int -> Maybe AttrSet -> Maybe Env -> Ptr (Ptr ()) -> Word32 -> Env
- Nix.Eval.Types: newMinimalEnv :: Ptr CThunkPtr -> Int -> Env
- Nix.Eval.Types: pushWithScope :: AttrSet -> Env -> Env
- Nix.Eval.Types: thunkSameRef :: Thunk -> Thunk -> Bool
- Nix.Eval.Types: thunkToCPtr :: Thunk -> CThunkPtr
- Nix.Eval.Types: unmarshalLambdaValue :: Ptr () -> IO NixValue
- Nix.Eval.Types: unmarshalStringContext :: CCtxStrPtr -> IO (ByteString, StringContext)
- Nix.Eval.Types: withScopesForCapture :: Env -> (Ptr (Ptr ()), Word32)
- Nix.Expr.Types: ESearchPath :: Text -> Expr
- Nix.Parser: parseNixFile :: FilePath -> IO (Either SourceError Expr)
- Nix.Push: loadApiKeyFile :: FilePath -> IO (Either Text Text)
- Nix.Realise: FetchFailed :: FetchOutcome
- Nix.Realise: FetchMissed :: FetchOutcome
- Nix.Realise: [reAllValid] :: RealiseEffects (m :: Type -> Type) -> Derivation -> m Bool
- Nix.Realise: instance GHC.Internal.Classes.Eq Nix.Realise.Offer
- Nix.Realise: instance GHC.Internal.Show.Show Nix.Realise.Offer
- Nix.Store: DeleteOutcome :: Bool -> Bool -> DeleteOutcome
- Nix.Store: [doRowRemoved] :: DeleteOutcome -> Bool
- Nix.Store: [doTreeRemoved] :: DeleteOutcome -> Bool
- Nix.Store: data DeleteOutcome
- Nix.Store: deleteStorePathChecked :: Store -> LiveSet -> Text -> IO (Either Text DeleteOutcome)
- Nix.Store: deleteStorePathRaw :: Store -> Text -> IO (Either Text DeleteOutcome)
- Nix.Store: instance GHC.Internal.Classes.Eq Nix.Store.DeleteOutcome
- Nix.Store: instance GHC.Internal.Show.Show Nix.Store.DeleteOutcome
- Nix.Store: processCaseHack :: CaseHack
- Nix.Store: setReadOnly :: FilePath -> IO ()
- Nix.Store.GC: data LiveSet
- Nix.Store.GC: isLive :: LiveSet -> Text -> Bool
- Nix.Store.GC: withLiveSet :: Store -> (LiveSet -> IO a) -> IO (Either Text a)
- Nix.Substituter: sortCaches :: [CacheConfig] -> [CacheConfig]
- Nix.Substituter: tryCachesWith :: Monad m => (CacheConfig -> m SubstResult) -> [CacheConfig] -> m SubstResult
- Nix.Substituter: trySubstitute :: Store -> [CacheConfig] -> StorePath -> IO SubstResult
- Nix.Substituter: trySubstituteWith :: FetchRetryPolicy -> RetryEffects IO -> Store -> [CacheConfig] -> StorePath -> IO SubstResult
+ Nix.Builder: BuildLayout :: BuildPlace -> [(Text, BuildPlace)] -> FilePath -> BuildLayout
+ Nix.Builder: BuildPlace :: FilePath -> FilePath -> BuildPlace
+ Nix.Builder: BuildStop :: Text -> Int -> BuildStop
+ Nix.Builder: BuilderInvocation :: FilePath -> [String] -> Map Text Text -> [Text] -> [(FilePath, ByteString)] -> FilePath -> BuilderInvocation
+ Nix.Builder: FixedOutputRefused :: Text -> BuildStop
+ Nix.Builder: RefuseSubstitution :: SubstitutionAccess
+ Nix.Builder: SubstituteFromCaches :: SubstitutionAccess
+ Nix.Builder: [bcBuildUsers] :: BuildConfig -> BuildUsers
+ Nix.Builder: [bcCores] :: BuildConfig -> Word32
+ Nix.Builder: [bcFailedBuilds] :: BuildConfig -> FailedBuilds
+ Nix.Builder: [bcMode] :: BuildConfig -> BuildMode
+ Nix.Builder: [bcSandbox] :: BuildConfig -> SandboxConfig
+ Nix.Builder: [bcSubstitutes] :: BuildConfig -> SubstitutesSetting
+ Nix.Builder: [bcSubstitution] :: BuildConfig -> SubstitutionAccess
+ Nix.Builder: [invArgs] :: BuilderInvocation -> [String]
+ Nix.Builder: [invEnv] :: BuilderInvocation -> Map Text Text
+ Nix.Builder: [invFiles] :: BuilderInvocation -> [(FilePath, ByteString)]
+ Nix.Builder: [invImpureVars] :: BuilderInvocation -> [Text]
+ Nix.Builder: [invProgram] :: BuilderInvocation -> FilePath
+ Nix.Builder: [invWorkDir] :: BuilderInvocation -> FilePath
+ Nix.Builder: [layoutBuildDir] :: BuildLayout -> BuildPlace
+ Nix.Builder: [layoutHome] :: BuildLayout -> FilePath
+ Nix.Builder: [layoutOutputs] :: BuildLayout -> [(Text, BuildPlace)]
+ Nix.Builder: [placeOnDisk] :: BuildPlace -> FilePath
+ Nix.Builder: [placeSeen] :: BuildPlace -> FilePath
+ Nix.Builder: buildRequests :: BuildConfig -> Store -> [(StorePath, Set Text)] -> IO (Either BuildStop ())
+ Nix.Builder: buildRequestsEach :: BuildConfig -> BuildMode -> Store -> [(StorePath, Set Text)] -> IO (Either BuildStop (Map StorePath RequestOutcome))
+ Nix.Builder: builderInvocation :: BuildConfig -> Derivation -> BuildLayout -> Either Text BuilderInvocation
+ Nix.Builder: checkDerivation :: BuildConfig -> Store -> Derivation -> StorePath -> IO (Either Text CheckVerdict)
+ Nix.Builder: checkStored :: BuildConfig -> Store -> StorePath -> IO (Either BuildStop ())
+ Nix.Builder: data BuildLayout
+ Nix.Builder: data BuildPlace
+ Nix.Builder: data BuildStop
+ Nix.Builder: data BuilderInvocation
+ Nix.Builder: data SubstitutionAccess
+ Nix.Builder: instance GHC.Internal.Classes.Eq Nix.Builder.BuildLayout
+ Nix.Builder: instance GHC.Internal.Classes.Eq Nix.Builder.BuildPlace
+ Nix.Builder: instance GHC.Internal.Classes.Eq Nix.Builder.BuildStop
+ Nix.Builder: instance GHC.Internal.Classes.Eq Nix.Builder.BuilderInvocation
+ Nix.Builder: instance GHC.Internal.Classes.Eq Nix.Builder.SubstitutionAccess
+ Nix.Builder: instance GHC.Internal.Show.Show Nix.Builder.BuildLayout
+ Nix.Builder: instance GHC.Internal.Show.Show Nix.Builder.BuildPlace
+ Nix.Builder: instance GHC.Internal.Show.Show Nix.Builder.BuildStop
+ Nix.Builder: instance GHC.Internal.Show.Show Nix.Builder.BuilderInvocation
+ Nix.Builder: instance GHC.Internal.Show.Show Nix.Builder.SubstitutionAccess
+ Nix.Builder: planMissingPaths :: BuildConfig -> Store -> [Wanted] -> IO (Either Text MissingPaths)
+ Nix.Builder: readDrvFromStore :: BuildConfig -> StorePath -> IO (Either Text Derivation)
+ Nix.Builder: realiseWithoutWriting :: Logger -> BuildConfig -> (StorePath -> IO Bool) -> Text -> [(StorePath, Set Text)] -> IO (Either BuildStop ())
+ Nix.Builder: stopReported :: BuildStop -> (Text, Int)
+ Nix.Builder: substitutablePaths :: BuildConfig -> Store -> [StorePath] -> IO (Either Text (Set StorePath))
+ Nix.Builder: substituteFromCaches :: BuildConfig -> Store -> [StorePath] -> IO ClosureOutcome
+ Nix.Builder.BuildDir: BuildFailed :: BuildEnding
+ Nix.Builder.BuildDir: BuildSucceeded :: BuildEnding
+ Nix.Builder.BuildDir: KeepFailed :: FailedBuilds
+ Nix.Builder.BuildDir: RemoveFailed :: FailedBuilds
+ Nix.Builder.BuildDir: WorksInBuildDir :: WorkDir
+ Nix.Builder.BuildDir: WorksInSandboxedBuildDir :: WorkDir
+ Nix.Builder.BuildDir: buildDirFor :: StoreDir -> StorePath -> FilePath
+ Nix.Builder.BuildDir: clearLeftover :: Logger -> FilePath -> IO ()
+ Nix.Builder.BuildDir: createBuildDir :: FilePath -> IO ()
+ Nix.Builder.BuildDir: data BuildEnding
+ Nix.Builder.BuildDir: data FailedBuilds
+ Nix.Builder.BuildDir: data WorkDir
+ Nix.Builder.BuildDir: instance GHC.Internal.Classes.Eq Nix.Builder.BuildDir.BuildEnding
+ Nix.Builder.BuildDir: instance GHC.Internal.Classes.Eq Nix.Builder.BuildDir.FailedBuilds
+ Nix.Builder.BuildDir: instance GHC.Internal.Classes.Eq Nix.Builder.BuildDir.WorkDir
+ Nix.Builder.BuildDir: instance GHC.Internal.Show.Show Nix.Builder.BuildDir.BuildEnding
+ Nix.Builder.BuildDir: instance GHC.Internal.Show.Show Nix.Builder.BuildDir.FailedBuilds
+ Nix.Builder.BuildDir: instance GHC.Internal.Show.Show Nix.Builder.BuildDir.WorkDir
+ Nix.Builder.BuildDir: sandboxedBuildDir :: FilePath -> FilePath
+ Nix.Builder.BuildDir: withBuildDir :: Logger -> StoreDir -> StorePath -> WorkDir -> FailedBuilds -> (a -> BuildEnding) -> (FilePath -> IO a) -> IO a
+ Nix.Builder.BuildDir: workDirIn :: WorkDir -> FilePath -> FilePath
+ Nix.Builder.BuildUser: Member :: Word32 -> Word32 -> [Word32] -> Member
+ Nix.Builder.BuildUser: NoBuildUsers :: BuildUsers
+ Nix.Builder.BuildUser: RunsAsRoot :: ProcessPrivilege
+ Nix.Builder.BuildUser: RunsUnprivileged :: ProcessPrivilege
+ Nix.Builder.BuildUser: UserDatabase :: (ByteString -> m (Maybe (Word32, [ByteString]))) -> (ByteString -> m (Maybe (Word32, Word32))) -> (ByteString -> Word32 -> m [Word32]) -> (Word32 -> m (Either Text (Maybe lock))) -> (lock -> m ()) -> UserDatabase (m :: Type -> Type) lock
+ Nix.Builder.BuildUser: [memberGid] :: Member -> Word32
+ Nix.Builder.BuildUser: [memberGroups] :: Member -> [Word32]
+ Nix.Builder.BuildUser: [memberUid] :: Member -> Word32
+ Nix.Builder.BuildUser: [udGroup] :: UserDatabase (m :: Type -> Type) lock -> ByteString -> m (Maybe (Word32, [ByteString]))
+ Nix.Builder.BuildUser: [udGroups] :: UserDatabase (m :: Type -> Type) lock -> ByteString -> Word32 -> m [Word32]
+ Nix.Builder.BuildUser: [udRelease] :: UserDatabase (m :: Type -> Type) lock -> lock -> m ()
+ Nix.Builder.BuildUser: [udTryLock] :: UserDatabase (m :: Type -> Type) lock -> Word32 -> m (Either Text (Maybe lock))
+ Nix.Builder.BuildUser: [udUser] :: UserDatabase (m :: Type -> Type) lock -> ByteString -> m (Maybe (Word32, Word32))
+ Nix.Builder.BuildUser: acquireBuildUser :: Monad m => UserDatabase m lock -> [Word32] -> ByteString -> m (Either Text (Maybe (Member, lock)))
+ Nix.Builder.BuildUser: buGid :: BuildUser -> Word32
+ Nix.Builder.BuildUser: buSupplementaryGids :: BuildUser -> [Word32]
+ Nix.Builder.BuildUser: buUid :: BuildUser -> Word32
+ Nix.Builder.BuildUser: buildUsersFor :: ProcessPrivilege -> FilePath -> ByteString -> BuildUsers
+ Nix.Builder.BuildUser: data BuildUser
+ Nix.Builder.BuildUser: data BuildUsers
+ Nix.Builder.BuildUser: data Member
+ Nix.Builder.BuildUser: data ProcessPrivilege
+ Nix.Builder.BuildUser: data UserDatabase (m :: Type -> Type) lock
+ Nix.Builder.BuildUser: defaultBuildUsersGroup :: ProcessPrivilege -> ByteString
+ Nix.Builder.BuildUser: giveToBuildUser :: BuildUser -> FilePath -> IO ()
+ Nix.Builder.BuildUser: instance GHC.Internal.Classes.Eq Nix.Builder.BuildUser.BuildUser
+ Nix.Builder.BuildUser: instance GHC.Internal.Classes.Eq Nix.Builder.BuildUser.BuildUsers
+ Nix.Builder.BuildUser: instance GHC.Internal.Classes.Eq Nix.Builder.BuildUser.Member
+ Nix.Builder.BuildUser: instance GHC.Internal.Classes.Eq Nix.Builder.BuildUser.ProcessPrivilege
+ Nix.Builder.BuildUser: instance GHC.Internal.Show.Show Nix.Builder.BuildUser.BuildUser
+ Nix.Builder.BuildUser: instance GHC.Internal.Show.Show Nix.Builder.BuildUser.BuildUsers
+ Nix.Builder.BuildUser: instance GHC.Internal.Show.Show Nix.Builder.BuildUser.Member
+ Nix.Builder.BuildUser: instance GHC.Internal.Show.Show Nix.Builder.BuildUser.ProcessPrivilege
+ Nix.Builder.BuildUser: invokingUserIds :: IO (Word32, Word32)
+ Nix.Builder.BuildUser: killBuildUser :: BuildUser -> IO (Either Text ())
+ Nix.Builder.BuildUser: openStoreToBuildUsers :: FilePath -> BuildUser -> IO ()
+ Nix.Builder.BuildUser: peerInBuildUsersGroup :: ByteString -> Maybe ByteString -> Bool
+ Nix.Builder.BuildUser: processPrivilege :: IO ProcessPrivilege
+ Nix.Builder.BuildUser: runAsBuildUser :: Logger -> BuildUser -> FilePath -> [String] -> [ByteString] -> FilePath -> IO (Either Text ExitCode)
+ Nix.Builder.BuildUser: runAsInvoker :: Logger -> FilePath -> [String] -> [ByteString] -> FilePath -> IO (Either Text ExitCode)
+ Nix.Builder.BuildUser: userPoolDir :: Maybe FilePath -> FilePath
+ Nix.Builder.BuildUser: waitingForBuildUserMessage :: Text -> Text
+ Nix.Builder.BuildUser: withBuildUser :: Logger -> BuildUsers -> Text -> (Maybe BuildUser -> IO a) -> IO (Either Text a)
+ Nix.Builder.BuildUser: worldWritableAncestor :: FilePath -> IO (Maybe FilePath)
+ Nix.Builder.BuildUser: worldWritableMessage :: FilePath -> Text
+ Nix.Builder.Buildenv: Active :: Activity
+ Nix.Builder.Buildenv: BadOutputCount :: ByteString -> DerivationsError
+ Nix.Builder.Buildenv: BadPriority :: ByteString -> DerivationsError
+ Nix.Builder.Buildenv: Element :: Activity -> Int -> [ByteString] -> Element
+ Nix.Builder.Buildenv: EndsInsideElement :: DerivationsError
+ Nix.Builder.Buildenv: Inactive :: Activity
+ Nix.Builder.Buildenv: [elementActivity] :: Element -> Activity
+ Nix.Builder.Buildenv: [elementPaths] :: Element -> [ByteString]
+ Nix.Builder.Buildenv: [elementPriority] :: Element -> Int
+ Nix.Builder.Buildenv: builtinBuildenvBuilder :: ByteString
+ Nix.Builder.Buildenv: data Activity
+ Nix.Builder.Buildenv: data DerivationsError
+ Nix.Builder.Buildenv: data Element
+ Nix.Builder.Buildenv: derivationsErrorText :: DerivationsError -> Text
+ Nix.Builder.Buildenv: elementPackages :: [Element] -> [(ByteString, Int)]
+ Nix.Builder.Buildenv: instance GHC.Internal.Classes.Eq Nix.Builder.Buildenv.Activity
+ Nix.Builder.Buildenv: instance GHC.Internal.Classes.Eq Nix.Builder.Buildenv.DerivationsError
+ Nix.Builder.Buildenv: instance GHC.Internal.Classes.Eq Nix.Builder.Buildenv.Element
+ Nix.Builder.Buildenv: instance GHC.Internal.Show.Show Nix.Builder.Buildenv.Activity
+ Nix.Builder.Buildenv: instance GHC.Internal.Show.Show Nix.Builder.Buildenv.DerivationsError
+ Nix.Builder.Buildenv: instance GHC.Internal.Show.Show Nix.Builder.Buildenv.Element
+ Nix.Builder.Buildenv: parseDerivations :: ByteString -> Either DerivationsError [Element]
+ Nix.Builder.Buildenv: runBuiltinBuildenv :: Logger -> StoreDir -> Derivation -> [(Text, FilePath)] -> IO (Either (Int, Text) ())
+ Nix.Builder.Cores: cgroup2MountPoint :: ByteString -> Maybe ByteString
+ Nix.Builder.Cores: cgroupCoreLimit :: Monad m => ReadKernelFile m -> m (Maybe Word32)
+ Nix.Builder.Cores: cpuMaxCores :: ByteString -> Maybe Word32
+ Nix.Builder.Cores: defaultCores :: Maybe Word32 -> Word32 -> Word32
+ Nix.Builder.Cores: hardwareConcurrency :: IO Word32
+ Nix.Builder.Cores: parseCgroups :: ByteString -> Maybe (Map ByteString ByteString)
+ Nix.Builder.Cores: type ReadKernelFile (m :: Type -> Type) = OsPath -> m Maybe ByteString
+ Nix.Builder.Sandbox: Bind :: ByteString -> ByteString -> BindAccess -> PathPresence -> SourceResolution -> Bind
+ Nix.Builder.Sandbox: BuilderIds :: Word32 -> Word32 -> BuilderIds
+ Nix.Builder.Sandbox: BuilderRan :: ExitCode -> HelperOutcome
+ Nix.Builder.Sandbox: DarwinBackend :: SandboxBackend
+ Nix.Builder.Sandbox: DarwinOptions :: ByteString -> Set ByteString -> LocalNetworking -> DarwinOptions
+ Nix.Builder.Sandbox: DarwinPath :: ByteString -> ByteString -> PathPresence -> DarwinPath
+ Nix.Builder.Sandbox: DarwinPathInputs :: StorePath -> ByteString -> ByteString -> ByteString -> ByteString -> [SandboxPath] -> [ByteString] -> Set ByteString -> Set ByteString -> [ByteString] -> DarwinPathInputs
+ Nix.Builder.Sandbox: DarwinPaths :: [DarwinPath] -> [ByteString] -> DarwinPaths
+ Nix.Builder.Sandbox: DarwinPlan :: ByteString -> ByteString -> Maybe BuilderIds -> [(ByteString, ByteString)] -> [ByteString] -> DarwinPlan
+ Nix.Builder.Sandbox: DarwinProfile :: ViolationLog -> Network -> ByteString -> [ByteString] -> [ProfileFilter] -> [ByteString] -> ByteString -> DarwinProfile
+ Nix.Builder.Sandbox: DarwinStageChdir :: DarwinStage
+ Nix.Builder.Sandbox: DarwinStageExec :: DarwinStage
+ Nix.Builder.Sandbox: DarwinStageFork :: DarwinStage
+ Nix.Builder.Sandbox: DarwinStageLog :: DarwinStage
+ Nix.Builder.Sandbox: DarwinStageLogMode :: DarwinStage
+ Nix.Builder.Sandbox: DarwinStageLogWatch :: DarwinStage
+ Nix.Builder.Sandbox: DarwinStageOutput :: DarwinStage
+ Nix.Builder.Sandbox: DarwinStagePlan :: DarwinStage
+ Nix.Builder.Sandbox: DarwinStageRelay :: DarwinStage
+ Nix.Builder.Sandbox: DarwinStageReport :: DarwinStage
+ Nix.Builder.Sandbox: DarwinStageSandbox :: DarwinStage
+ Nix.Builder.Sandbox: DarwinStageSetgid :: DarwinStage
+ Nix.Builder.Sandbox: DarwinStageSetgroups :: DarwinStage
+ Nix.Builder.Sandbox: DarwinStageSetsid :: DarwinStage
+ Nix.Builder.Sandbox: DarwinStageSetuid :: DarwinStage
+ Nix.Builder.Sandbox: DarwinStageSigchld :: DarwinStage
+ Nix.Builder.Sandbox: DarwinStageSignals :: DarwinStage
+ Nix.Builder.Sandbox: DarwinStageStdin :: DarwinStage
+ Nix.Builder.Sandbox: DarwinStageStdout :: DarwinStage
+ Nix.Builder.Sandbox: DarwinStageSweep :: DarwinStage
+ Nix.Builder.Sandbox: FallBackUnsandboxed :: SandboxFallback
+ Nix.Builder.Sandbox: FoundDirectory :: PathFound
+ Nix.Builder.Sandbox: FoundOther :: PathFound
+ Nix.Builder.Sandbox: HelperNotFound :: Unavailability
+ Nix.Builder.Sandbox: HelperUnrunnable :: Text -> Unavailability
+ Nix.Builder.Sandbox: HostNetwork :: Network
+ Nix.Builder.Sandbox: LinuxBackend :: SandboxBackend
+ Nix.Builder.Sandbox: Literal :: ByteString -> ProfileFilter
+ Nix.Builder.Sandbox: LocalNetworkingAllowed :: LocalNetworking
+ Nix.Builder.Sandbox: LocalNetworkingDenied :: LocalNetworking
+ Nix.Builder.Sandbox: LstatFailed :: Int -> PathFound
+ Nix.Builder.Sandbox: OptionalPath :: PathPresence
+ Nix.Builder.Sandbox: PlanInputs :: ByteString -> ByteString -> ByteString -> ByteString -> [ByteString] -> [SandboxPath] -> [ByteString] -> [ByteString] -> [ByteString] -> Network -> Maybe ByteString -> ByteString -> DropGroups -> BuilderIds -> PlanInputs
+ Nix.Builder.Sandbox: PlatformUnsupported :: Unavailability
+ Nix.Builder.Sandbox: PrivateNetwork :: Network
+ Nix.Builder.Sandbox: ProbeAppArmor :: ProbeStage
+ Nix.Builder.Sandbox: ProbeFailed :: StatusRecord ProbeStage -> Unavailability
+ Nix.Builder.Sandbox: ProbeMountns :: ProbeStage
+ Nix.Builder.Sandbox: ProbePrivileges :: ProbeStage
+ Nix.Builder.Sandbox: ProbeProcRemount :: ProbeStage
+ Nix.Builder.Sandbox: ProbeSandbox :: ProbeStage
+ Nix.Builder.Sandbox: ProbeSigchld :: ProbeStage
+ Nix.Builder.Sandbox: ProbeUnreadable :: Text -> Unavailability
+ Nix.Builder.Sandbox: ProbeUserns :: ProbeStage
+ Nix.Builder.Sandbox: ProbeUsernsClone :: ProbeStage
+ Nix.Builder.Sandbox: ProbeUsernsMax :: ProbeStage
+ Nix.Builder.Sandbox: ProbeUsernsMissing :: ProbeStage
+ Nix.Builder.Sandbox: ReadOnlyBind :: BindAccess
+ Nix.Builder.Sandbox: ReadWriteBind :: BindAccess
+ Nix.Builder.Sandbox: RefuseUnsandboxed :: SandboxFallback
+ Nix.Builder.Sandbox: RequireDropGroups :: DropGroups
+ Nix.Builder.Sandbox: RequiredPath :: PathPresence
+ Nix.Builder.Sandbox: SandboxConfig :: SandboxMode -> SandboxFallback -> [SandboxPath] -> ByteString -> ByteString -> DropGroups -> Set ByteString -> ViolationLog -> Maybe ByteString -> Maybe FilePath -> SandboxConfig
+ Nix.Builder.Sandbox: SandboxDisabled :: SandboxMode
+ Nix.Builder.Sandbox: SandboxEnabled :: SandboxMode
+ Nix.Builder.Sandbox: SandboxPath :: ByteString -> ByteString -> PathPresence -> SandboxPath
+ Nix.Builder.Sandbox: SandboxPlan :: ByteString -> ByteString -> ByteString -> Network -> DropGroups -> BuilderIds -> [Bind] -> [ByteString] -> SandboxPlan
+ Nix.Builder.Sandbox: SandboxRelaxed :: SandboxMode
+ Nix.Builder.Sandbox: Sandboxed :: Network -> SandboxUse
+ Nix.Builder.Sandbox: SetupIncomplete :: Text -> HelperOutcome
+ Nix.Builder.Sandbox: SkeletonDir :: ByteString -> Word32 -> SkeletonEntry
+ Nix.Builder.Sandbox: SkeletonFile :: ByteString -> ByteString -> SkeletonEntry
+ Nix.Builder.Sandbox: SkeletonLink :: ByteString -> ByteString -> SkeletonEntry
+ Nix.Builder.Sandbox: SkeletonStoreDir :: ByteString -> SkeletonEntry
+ Nix.Builder.Sandbox: SourceAsGiven :: SourceResolution
+ Nix.Builder.Sandbox: SourceResolved :: SourceResolution
+ Nix.Builder.Sandbox: StageBind :: SetupStage
+ Nix.Builder.Sandbox: StageBindRoot :: SetupStage
+ Nix.Builder.Sandbox: StageBindSource :: SetupStage
+ Nix.Builder.Sandbox: StageBindTarget :: SetupStage
+ Nix.Builder.Sandbox: StageChdir :: SetupStage
+ Nix.Builder.Sandbox: StageChdirRoot :: SetupStage
+ Nix.Builder.Sandbox: StageChroot :: SetupStage
+ Nix.Builder.Sandbox: StageClone :: SetupStage
+ Nix.Builder.Sandbox: StageDevShm :: SetupStage
+ Nix.Builder.Sandbox: StageDevpts :: SetupStage
+ Nix.Builder.Sandbox: StageDomainname :: SetupStage
+ Nix.Builder.Sandbox: StageEtc :: SetupStage
+ Nix.Builder.Sandbox: StageExec :: SetupStage
+ Nix.Builder.Sandbox: StageGidMap :: SetupStage
+ Nix.Builder.Sandbox: StageHostname :: SetupStage
+ Nix.Builder.Sandbox: StageKeyring :: SetupStage
+ Nix.Builder.Sandbox: StageLoopback :: SetupStage
+ Nix.Builder.Sandbox: StageLoopbackSocket :: SetupStage
+ Nix.Builder.Sandbox: StageNoNewPrivs :: SetupStage
+ Nix.Builder.Sandbox: StagePdeathsig :: SetupStage
+ Nix.Builder.Sandbox: StagePivot :: SetupStage
+ Nix.Builder.Sandbox: StagePlan :: SetupStage
+ Nix.Builder.Sandbox: StagePrivate :: SetupStage
+ Nix.Builder.Sandbox: StageProc :: SetupStage
+ Nix.Builder.Sandbox: StageRealRoot :: SetupStage
+ Nix.Builder.Sandbox: StageRelease :: SetupStage
+ Nix.Builder.Sandbox: StageRemount :: SetupStage
+ Nix.Builder.Sandbox: StageRmdir :: SetupStage
+ Nix.Builder.Sandbox: StageSetgid :: SetupStage
+ Nix.Builder.Sandbox: StageSetgroups :: SetupStage
+ Nix.Builder.Sandbox: StageSetgroupsDeny :: SetupStage
+ Nix.Builder.Sandbox: StageSetsid :: SetupStage
+ Nix.Builder.Sandbox: StageSetuid :: SetupStage
+ Nix.Builder.Sandbox: StageSigchld :: SetupStage
+ Nix.Builder.Sandbox: StageSignals :: SetupStage
+ Nix.Builder.Sandbox: StageStdin :: SetupStage
+ Nix.Builder.Sandbox: StageStdout :: SetupStage
+ Nix.Builder.Sandbox: StageSync :: SetupStage
+ Nix.Builder.Sandbox: StageUidMap :: SetupStage
+ Nix.Builder.Sandbox: StageUmount :: SetupStage
+ Nix.Builder.Sandbox: StatusRecord :: stage -> Int -> Maybe Int -> StatusRecord stage
+ Nix.Builder.Sandbox: Subpath :: ByteString -> ProfileFilter
+ Nix.Builder.Sandbox: TolerateKeptGroups :: DropGroups
+ Nix.Builder.Sandbox: Unsandboxed :: SandboxUse
+ Nix.Builder.Sandbox: ViolationsLogged :: ViolationLog
+ Nix.Builder.Sandbox: ViolationsUnlogged :: ViolationLog
+ Nix.Builder.Sandbox: WindowsPlan :: ByteString -> Word32 -> Sid -> Word64 -> [ByteString] -> WindowsPlan
+ Nix.Builder.Sandbox: WindowsStageAssign :: WindowsStage
+ Nix.Builder.Sandbox: WindowsStageAttributes :: WindowsStage
+ Nix.Builder.Sandbox: WindowsStageBuildDir :: WindowsStage
+ Nix.Builder.Sandbox: WindowsStageCommandLine :: WindowsStage
+ Nix.Builder.Sandbox: WindowsStageConsole :: WindowsStage
+ Nix.Builder.Sandbox: WindowsStageEnvironment :: WindowsStage
+ Nix.Builder.Sandbox: WindowsStageExec :: WindowsStage
+ Nix.Builder.Sandbox: WindowsStageImpersonate :: WindowsStage
+ Nix.Builder.Sandbox: WindowsStageJob :: WindowsStage
+ Nix.Builder.Sandbox: WindowsStageLifeline :: WindowsStage
+ Nix.Builder.Sandbox: WindowsStageLog :: WindowsStage
+ Nix.Builder.Sandbox: WindowsStagePlan :: WindowsStage
+ Nix.Builder.Sandbox: WindowsStagePrivileges :: WindowsStage
+ Nix.Builder.Sandbox: WindowsStageResume :: WindowsStage
+ Nix.Builder.Sandbox: WindowsStageRevert :: WindowsStage
+ Nix.Builder.Sandbox: WindowsStageSlotSid :: WindowsStage
+ Nix.Builder.Sandbox: WindowsStageStdin :: WindowsStage
+ Nix.Builder.Sandbox: WindowsStageSweep :: WindowsStage
+ Nix.Builder.Sandbox: WindowsStageToken :: WindowsStage
+ Nix.Builder.Sandbox: WindowsStageTokenUser :: WindowsStage
+ Nix.Builder.Sandbox: [bindAccess] :: Bind -> BindAccess
+ Nix.Builder.Sandbox: [bindPresence] :: Bind -> PathPresence
+ Nix.Builder.Sandbox: [bindResolution] :: Bind -> SourceResolution
+ Nix.Builder.Sandbox: [bindSource] :: Bind -> ByteString
+ Nix.Builder.Sandbox: [bindTarget] :: Bind -> ByteString
+ Nix.Builder.Sandbox: [builderGid] :: BuilderIds -> Word32
+ Nix.Builder.Sandbox: [builderUid] :: BuilderIds -> Word32
+ Nix.Builder.Sandbox: [darwinPlanBuildDir] :: DarwinPlan -> ByteString
+ Nix.Builder.Sandbox: [darwinPlanBuildUser] :: DarwinPlan -> Maybe BuilderIds
+ Nix.Builder.Sandbox: [darwinPlanEnvironment] :: DarwinPlan -> [ByteString]
+ Nix.Builder.Sandbox: [darwinPlanParameters] :: DarwinPlan -> [(ByteString, ByteString)]
+ Nix.Builder.Sandbox: [darwinPlanProfile] :: DarwinPlan -> ByteString
+ Nix.Builder.Sandbox: [darwinPresence] :: DarwinPath -> PathPresence
+ Nix.Builder.Sandbox: [darwinSource] :: DarwinPath -> ByteString
+ Nix.Builder.Sandbox: [darwinTarget] :: DarwinPath -> ByteString
+ Nix.Builder.Sandbox: [doExtraProfile] :: DarwinOptions -> ByteString
+ Nix.Builder.Sandbox: [doImpureHostDeps] :: DarwinOptions -> Set ByteString
+ Nix.Builder.Sandbox: [doLocalNetworking] :: DarwinOptions -> LocalNetworking
+ Nix.Builder.Sandbox: [dpAncestry] :: DarwinPaths -> [ByteString]
+ Nix.Builder.Sandbox: [dpPaths] :: DarwinPaths -> [DarwinPath]
+ Nix.Builder.Sandbox: [dpiAllowedImpureHostDeps] :: DarwinPathInputs -> Set ByteString
+ Nix.Builder.Sandbox: [dpiBuildDir] :: DarwinPathInputs -> ByteString
+ Nix.Builder.Sandbox: [dpiDrvPath] :: DarwinPathInputs -> StorePath
+ Nix.Builder.Sandbox: [dpiImpureHostDeps] :: DarwinPathInputs -> Set ByteString
+ Nix.Builder.Sandbox: [dpiInputs] :: DarwinPathInputs -> [ByteString]
+ Nix.Builder.Sandbox: [dpiRealBuildDir] :: DarwinPathInputs -> ByteString
+ Nix.Builder.Sandbox: [dpiRealStoreDir] :: DarwinPathInputs -> ByteString
+ Nix.Builder.Sandbox: [dpiSandboxClosure] :: DarwinPathInputs -> [ByteString]
+ Nix.Builder.Sandbox: [dpiSandboxPaths] :: DarwinPathInputs -> [SandboxPath]
+ Nix.Builder.Sandbox: [dpiStoreDir] :: DarwinPathInputs -> ByteString
+ Nix.Builder.Sandbox: [dprAncestry] :: DarwinProfile -> [ByteString]
+ Nix.Builder.Sandbox: [dprExtra] :: DarwinProfile -> ByteString
+ Nix.Builder.Sandbox: [dprNetwork] :: DarwinProfile -> Network
+ Nix.Builder.Sandbox: [dprOutputs] :: DarwinProfile -> [ByteString]
+ Nix.Builder.Sandbox: [dprPaths] :: DarwinProfile -> [ProfileFilter]
+ Nix.Builder.Sandbox: [dprStoreDir] :: DarwinProfile -> ByteString
+ Nix.Builder.Sandbox: [dprViolationLog] :: DarwinProfile -> ViolationLog
+ Nix.Builder.Sandbox: [piBuildDirOnDisk] :: PlanInputs -> ByteString
+ Nix.Builder.Sandbox: [piBuildDirSeen] :: PlanInputs -> ByteString
+ Nix.Builder.Sandbox: [piBuilderIds] :: PlanInputs -> BuilderIds
+ Nix.Builder.Sandbox: [piCaFile] :: PlanInputs -> Maybe ByteString
+ Nix.Builder.Sandbox: [piDevShmSize] :: PlanInputs -> ByteString
+ Nix.Builder.Sandbox: [piDropGroups] :: PlanInputs -> DropGroups
+ Nix.Builder.Sandbox: [piEnvironment] :: PlanInputs -> [ByteString]
+ Nix.Builder.Sandbox: [piInputs] :: PlanInputs -> [ByteString]
+ Nix.Builder.Sandbox: [piNetwork] :: PlanInputs -> Network
+ Nix.Builder.Sandbox: [piOutputs] :: PlanInputs -> [ByteString]
+ Nix.Builder.Sandbox: [piRoot] :: PlanInputs -> ByteString
+ Nix.Builder.Sandbox: [piSandboxClosure] :: PlanInputs -> [ByteString]
+ Nix.Builder.Sandbox: [piSandboxPaths] :: PlanInputs -> [SandboxPath]
+ Nix.Builder.Sandbox: [piStoreDir] :: PlanInputs -> ByteString
+ Nix.Builder.Sandbox: [planBinds] :: SandboxPlan -> [Bind]
+ Nix.Builder.Sandbox: [planBuildDir] :: SandboxPlan -> ByteString
+ Nix.Builder.Sandbox: [planBuilderIds] :: SandboxPlan -> BuilderIds
+ Nix.Builder.Sandbox: [planDevShmSize] :: SandboxPlan -> ByteString
+ Nix.Builder.Sandbox: [planDropGroups] :: SandboxPlan -> DropGroups
+ Nix.Builder.Sandbox: [planEnvironment] :: SandboxPlan -> [ByteString]
+ Nix.Builder.Sandbox: [planNetwork] :: SandboxPlan -> Network
+ Nix.Builder.Sandbox: [planRoot] :: SandboxPlan -> ByteString
+ Nix.Builder.Sandbox: [recordErrno] :: StatusRecord stage -> Int
+ Nix.Builder.Sandbox: [recordIndex] :: StatusRecord stage -> Maybe Int
+ Nix.Builder.Sandbox: [recordStage] :: StatusRecord stage -> stage
+ Nix.Builder.Sandbox: [scAllowedImpureHostDeps] :: SandboxConfig -> Set ByteString
+ Nix.Builder.Sandbox: [scBuildDir] :: SandboxConfig -> ByteString
+ Nix.Builder.Sandbox: [scCaFile] :: SandboxConfig -> Maybe ByteString
+ Nix.Builder.Sandbox: [scDevShmSize] :: SandboxConfig -> ByteString
+ Nix.Builder.Sandbox: [scDropGroups] :: SandboxConfig -> DropGroups
+ Nix.Builder.Sandbox: [scFallback] :: SandboxConfig -> SandboxFallback
+ Nix.Builder.Sandbox: [scHelper] :: SandboxConfig -> Maybe FilePath
+ Nix.Builder.Sandbox: [scMode] :: SandboxConfig -> SandboxMode
+ Nix.Builder.Sandbox: [scPaths] :: SandboxConfig -> [SandboxPath]
+ Nix.Builder.Sandbox: [scViolationLog] :: SandboxConfig -> ViolationLog
+ Nix.Builder.Sandbox: [spPresence] :: SandboxPath -> PathPresence
+ Nix.Builder.Sandbox: [spSource] :: SandboxPath -> ByteString
+ Nix.Builder.Sandbox: [spTarget] :: SandboxPath -> ByteString
+ Nix.Builder.Sandbox: [windowsPlanBuildDir] :: WindowsPlan -> ByteString
+ Nix.Builder.Sandbox: [windowsPlanEnvironment] :: WindowsPlan -> [ByteString]
+ Nix.Builder.Sandbox: [windowsPlanMemoryCap] :: WindowsPlan -> Word64
+ Nix.Builder.Sandbox: [windowsPlanSlot] :: WindowsPlan -> Sid
+ Nix.Builder.Sandbox: [windowsPlanToken] :: WindowsPlan -> Word32
+ Nix.Builder.Sandbox: backendFallback :: Maybe SandboxBackend -> SandboxFallback -> SandboxFallback
+ Nix.Builder.Sandbox: buildNetwork :: Derivation -> Network
+ Nix.Builder.Sandbox: chrootSkeleton :: ByteString -> ByteString -> Network -> [SandboxPath] -> [SkeletonEntry]
+ Nix.Builder.Sandbox: darwinImpureHostPrefixes :: Set ByteString
+ Nix.Builder.Sandbox: darwinOptions :: StorePath -> Derivation -> Either Text DarwinOptions
+ Nix.Builder.Sandbox: darwinParameters :: ByteString -> ByteString -> LocalNetworking -> [(ByteString, ByteString)]
+ Nix.Builder.Sandbox: darwinPathTarget :: DarwinPath -> Either Text ByteString
+ Nix.Builder.Sandbox: darwinPathsInSandbox :: DarwinPathInputs -> Either Text DarwinPaths
+ Nix.Builder.Sandbox: darwinProfile :: DarwinProfile -> ByteString
+ Nix.Builder.Sandbox: darwinSandboxPaths :: Set ByteString
+ Nix.Builder.Sandbox: darwinSetupFailureMessage :: DarwinPlan -> ByteString -> StatusRecord DarwinStage -> Text
+ Nix.Builder.Sandbox: darwinStageName :: DarwinStage -> ByteString
+ Nix.Builder.Sandbox: data Bind
+ Nix.Builder.Sandbox: data BindAccess
+ Nix.Builder.Sandbox: data BuilderIds
+ Nix.Builder.Sandbox: data DarwinOptions
+ Nix.Builder.Sandbox: data DarwinPath
+ Nix.Builder.Sandbox: data DarwinPathInputs
+ Nix.Builder.Sandbox: data DarwinPaths
+ Nix.Builder.Sandbox: data DarwinPlan
+ Nix.Builder.Sandbox: data DarwinProfile
+ Nix.Builder.Sandbox: data DarwinStage
+ Nix.Builder.Sandbox: data DropGroups
+ Nix.Builder.Sandbox: data HelperOutcome
+ Nix.Builder.Sandbox: data LocalNetworking
+ Nix.Builder.Sandbox: data Network
+ Nix.Builder.Sandbox: data PathFound
+ Nix.Builder.Sandbox: data PathPresence
+ Nix.Builder.Sandbox: data PlanInputs
+ Nix.Builder.Sandbox: data ProbeStage
+ Nix.Builder.Sandbox: data ProfileFilter
+ Nix.Builder.Sandbox: data SandboxBackend
+ Nix.Builder.Sandbox: data SandboxConfig
+ Nix.Builder.Sandbox: data SandboxFallback
+ Nix.Builder.Sandbox: data SandboxMode
+ Nix.Builder.Sandbox: data SandboxPath
+ Nix.Builder.Sandbox: data SandboxPlan
+ Nix.Builder.Sandbox: data SandboxUse
+ Nix.Builder.Sandbox: data SetupStage
+ Nix.Builder.Sandbox: data SkeletonEntry
+ Nix.Builder.Sandbox: data SourceResolution
+ Nix.Builder.Sandbox: data StatusRecord stage
+ Nix.Builder.Sandbox: data Unavailability
+ Nix.Builder.Sandbox: data ViolationLog
+ Nix.Builder.Sandbox: data WindowsPlan
+ Nix.Builder.Sandbox: data WindowsStage
+ Nix.Builder.Sandbox: defaultSandboxConfig :: SandboxConfig
+ Nix.Builder.Sandbox: errnoSuffix :: Int -> Text
+ Nix.Builder.Sandbox: fallbackWarning :: Unavailability -> Text
+ Nix.Builder.Sandbox: groupFile :: ByteString
+ Nix.Builder.Sandbox: helperOutcome :: (Enum stage, Bounded stage) => (stage -> ByteString) -> (StatusRecord stage -> Text) -> Either Text () -> ExitCode -> ByteString -> HelperOutcome
+ Nix.Builder.Sandbox: hostSandboxBackend :: Maybe SandboxBackend
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.Bind
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.BindAccess
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.BuilderIds
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.DarwinOptions
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.DarwinPath
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.DarwinPathInputs
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.DarwinPaths
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.DarwinPlan
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.DarwinProfile
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.DarwinStage
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.DropGroups
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.HelperOutcome
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.LocalNetworking
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.Network
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.PathFound
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.PathPresence
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.PlanInputs
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.ProbeStage
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.ProfileFilter
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.SandboxBackend
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.SandboxConfig
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.SandboxFallback
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.SandboxMode
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.SandboxPath
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.SandboxPlan
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.SandboxUse
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.SetupStage
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.SkeletonEntry
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.SourceResolution
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.Unavailability
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.ViolationLog
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.WindowsPlan
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.WindowsStage
+ Nix.Builder.Sandbox: instance GHC.Internal.Classes.Eq stage => GHC.Internal.Classes.Eq (Nix.Builder.Sandbox.StatusRecord stage)
+ Nix.Builder.Sandbox: instance GHC.Internal.Enum.Bounded Nix.Builder.Sandbox.DarwinStage
+ Nix.Builder.Sandbox: instance GHC.Internal.Enum.Bounded Nix.Builder.Sandbox.ProbeStage
+ Nix.Builder.Sandbox: instance GHC.Internal.Enum.Bounded Nix.Builder.Sandbox.SetupStage
+ Nix.Builder.Sandbox: instance GHC.Internal.Enum.Bounded Nix.Builder.Sandbox.WindowsStage
+ Nix.Builder.Sandbox: instance GHC.Internal.Enum.Enum Nix.Builder.Sandbox.DarwinStage
+ Nix.Builder.Sandbox: instance GHC.Internal.Enum.Enum Nix.Builder.Sandbox.ProbeStage
+ Nix.Builder.Sandbox: instance GHC.Internal.Enum.Enum Nix.Builder.Sandbox.SetupStage
+ Nix.Builder.Sandbox: instance GHC.Internal.Enum.Enum Nix.Builder.Sandbox.WindowsStage
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.Bind
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.BindAccess
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.BuilderIds
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.DarwinOptions
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.DarwinPath
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.DarwinPathInputs
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.DarwinPaths
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.DarwinPlan
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.DarwinProfile
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.DarwinStage
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.DropGroups
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.HelperOutcome
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.LocalNetworking
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.Network
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.PathFound
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.PathPresence
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.PlanInputs
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.ProbeStage
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.ProfileFilter
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.SandboxBackend
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.SandboxConfig
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.SandboxFallback
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.SandboxMode
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.SandboxPath
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.SandboxPlan
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.SandboxUse
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.SetupStage
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.SkeletonEntry
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.SourceResolution
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.Unavailability
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.ViolationLog
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.WindowsPlan
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.WindowsStage
+ Nix.Builder.Sandbox: instance GHC.Internal.Show.Show stage => GHC.Internal.Show.Show (Nix.Builder.Sandbox.StatusRecord stage)
+ Nix.Builder.Sandbox: parseSandboxMode :: ByteString -> Either Text SandboxMode
+ Nix.Builder.Sandbox: parseSandboxPaths :: Set ByteString -> [SandboxPath]
+ Nix.Builder.Sandbox: parseStatus :: (Enum stage, Bounded stage) => (stage -> ByteString) -> ByteString -> Either Text (Maybe (StatusRecord stage))
+ Nix.Builder.Sandbox: passwdFile :: ByteString -> ByteString
+ Nix.Builder.Sandbox: planVersionLine :: ByteString
+ Nix.Builder.Sandbox: probeStageName :: ProbeStage -> ByteString
+ Nix.Builder.Sandbox: profileFilter :: DarwinPath -> PathFound -> Either Text (Maybe ProfileFilter)
+ Nix.Builder.Sandbox: renderDarwinPlan :: DarwinPlan -> ByteString
+ Nix.Builder.Sandbox: renderPlan :: SandboxPlan -> ByteString
+ Nix.Builder.Sandbox: renderSandboxMode :: SandboxMode -> ByteString
+ Nix.Builder.Sandbox: renderWindowsPlan :: WindowsPlan -> ByteString
+ Nix.Builder.Sandbox: rootRefusal :: Text
+ Nix.Builder.Sandbox: sandboxGid :: Word32
+ Nix.Builder.Sandbox: sandboxHome :: FilePath
+ Nix.Builder.Sandbox: sandboxPlan :: PlanInputs -> Either Text SandboxPlan
+ Nix.Builder.Sandbox: sandboxSettingName :: ByteString
+ Nix.Builder.Sandbox: sandboxUid :: Word32
+ Nix.Builder.Sandbox: sandboxUse :: Maybe SandboxBackend -> SandboxMode -> StorePath -> Derivation -> Either Text SandboxUse
+ Nix.Builder.Sandbox: setupContext :: Text
+ Nix.Builder.Sandbox: setupFailureMessage :: SandboxPlan -> ByteString -> StatusRecord SetupStage -> Text
+ Nix.Builder.Sandbox: setupStageName :: SetupStage -> ByteString
+ Nix.Builder.Sandbox: unavailabilityCause :: Unavailability -> Text
+ Nix.Builder.Sandbox: unavailableMessage :: Maybe SandboxBackend -> Unavailability -> Text
+ Nix.Builder.Sandbox: windowsStageName :: WindowsStage -> ByteString
+ Nix.Builder.Sandbox.Spawn: HelperRun :: Either Text () -> ExitCode -> ByteString -> HelperRun
+ Nix.Builder.Sandbox.Spawn: [hrDelivered] :: HelperRun -> Either Text ()
+ Nix.Builder.Sandbox.Spawn: [hrExit] :: HelperRun -> ExitCode
+ Nix.Builder.Sandbox.Spawn: [hrStatus] :: HelperRun -> ByteString
+ Nix.Builder.Sandbox.Spawn: bytesFilePath :: ByteString -> IO FilePath
+ Nix.Builder.Sandbox.Spawn: chrootDirFor :: FilePath -> FilePath
+ Nix.Builder.Sandbox.Spawn: data HelperRun
+ Nix.Builder.Sandbox.Spawn: filePathBytes :: FilePath -> IO ByteString
+ Nix.Builder.Sandbox.Spawn: instance GHC.Internal.Classes.Eq Nix.Builder.Sandbox.Spawn.HelperRun
+ Nix.Builder.Sandbox.Spawn: instance GHC.Internal.Show.Show Nix.Builder.Sandbox.Spawn.HelperRun
+ Nix.Builder.Sandbox.Spawn: mountPointsWithin :: ByteString -> ByteString -> [ByteString]
+ Nix.Builder.Sandbox.Spawn: processIsRoot :: IO Bool
+ Nix.Builder.Sandbox.Spawn: profileFilters :: [DarwinPath] -> IO (Either Text [ProfileFilter])
+ Nix.Builder.Sandbox.Spawn: resolvedPath :: ByteString -> IO ByteString
+ Nix.Builder.Sandbox.Spawn: runHelper :: Logger -> FilePath -> ByteString -> FilePath -> [String] -> IO HelperRun
+ Nix.Builder.Sandbox.Spawn: sandboxAvailability :: Maybe FilePath -> IO (Either Unavailability (SandboxBackend, FilePath))
+ Nix.Builder.Sandbox.Spawn: sealChroot :: FilePath -> FilePath -> IO (Either Text (Set FilePath))
+ Nix.Builder.Sandbox.Spawn: warnFallback :: Logger -> Unavailability -> IO ()
+ Nix.Builder.Sandbox.Spawn: withChroot :: Logger -> FilePath -> Maybe Word32 -> [SkeletonEntry] -> (FilePath -> IO a) -> IO (Either Text a)
+ Nix.Builder.Settings: MachineDefaults :: Word32 -> Maybe FilePath -> Set ByteString -> ProcessPrivilege -> FilePath -> Maybe ByteString -> MachineDefaults
+ Nix.Builder.Settings: [mdCaFile] :: MachineDefaults -> Maybe ByteString
+ Nix.Builder.Settings: [mdCores] :: MachineDefaults -> Word32
+ Nix.Builder.Settings: [mdPrivilege] :: MachineDefaults -> ProcessPrivilege
+ Nix.Builder.Settings: [mdSandboxHelper] :: MachineDefaults -> Maybe FilePath
+ Nix.Builder.Settings: [mdSandboxShell] :: MachineDefaults -> Set ByteString
+ Nix.Builder.Settings: [mdUserPool] :: MachineDefaults -> FilePath
+ Nix.Builder.Settings: configToCaches :: NixConfig -> [CacheConfig]
+ Nix.Builder.Settings: data MachineDefaults
+ Nix.Builder.Settings: instance GHC.Internal.Classes.Eq Nix.Builder.Settings.MachineDefaults
+ Nix.Builder.Settings: instance GHC.Internal.Show.Show Nix.Builder.Settings.MachineDefaults
+ Nix.Builder.Settings: machineDefaults :: ReadKernelFile IO -> IO MachineDefaults
+ Nix.Builder.Settings: settingsBuildConfig :: MachineDefaults -> NixConfig -> StoreDir -> BuildConfig
+ Nix.Builder.Settings: settingsFallback :: NixConfig -> Fallback
+ Nix.Builder.Settings: settingsFetchRetry :: NixConfig -> FetchRetryPolicy
+ Nix.Builder.Settings: settingsSubstitutes :: NixConfig -> SubstitutesSetting
+ Nix.Builder.Unpack: envOmit :: Text
+ Nix.CacheDirectory: CacheInfo :: Maybe Int -> CacheInfo
+ Nix.CacheDirectory: CachePriorityInvalid :: Text -> CacheOpenFailure
+ Nix.CacheDirectory: CacheUnopenable :: Text -> CacheOpenFailure
+ Nix.CacheDirectory: [ciPriority] :: CacheInfo -> Maybe Int
+ Nix.CacheDirectory: cacheFilePath :: FilePath -> Text -> Either Text FilePath
+ Nix.CacheDirectory: cacheInfoFileName :: FilePath
+ Nix.CacheDirectory: cacheInfoText :: ByteString
+ Nix.CacheDirectory: cacheOpenFailureMessage :: CacheOpenFailure -> Text
+ Nix.CacheDirectory: data CacheOpenFailure
+ Nix.CacheDirectory: directoryUrl :: FilePath -> Text
+ Nix.CacheDirectory: fileUrlDirectory :: Text -> String -> Maybe (Either Text FilePath)
+ Nix.CacheDirectory: instance GHC.Internal.Classes.Eq Nix.CacheDirectory.CacheInfo
+ Nix.CacheDirectory: instance GHC.Internal.Classes.Eq Nix.CacheDirectory.CacheOpenFailure
+ Nix.CacheDirectory: instance GHC.Internal.Show.Show Nix.CacheDirectory.CacheInfo
+ Nix.CacheDirectory: instance GHC.Internal.Show.Show Nix.CacheDirectory.CacheOpenFailure
+ Nix.CacheDirectory: newtype CacheInfo
+ Nix.CacheDirectory: openCacheDirectory :: Text -> FilePath -> IO (Either CacheOpenFailure CacheInfo)
+ Nix.CacheDirectory: parsePriority :: ByteString -> Maybe Int
+ Nix.CacheDirectory: readCacheInfo :: Text -> ByteString -> Either CacheOpenFailure CacheInfo
+ Nix.CacheDirectory: realisationsDirName :: FilePath
+ Nix.CacheDirectory: writeCacheFile :: FilePath -> ByteString -> IO ()
+ Nix.Compression.Stream: Bzip2 :: Compression
+ Nix.Compression.Stream: Gzip :: Compression
+ Nix.Compression.Stream: Uncompressed :: Compression
+ Nix.Compression.Stream: Xz :: Compression
+ Nix.Compression.Stream: Zstd :: Compression
+ Nix.Compression.Stream: bzip2Reason :: Bzip2Error -> Text
+ Nix.Compression.Stream: compressionMagicBytes :: Int
+ Nix.Compression.Stream: compressionOf :: ByteString -> Compression
+ Nix.Compression.Stream: data Compression
+ Nix.Compression.Stream: decodingFailure :: IO a -> IO (Either Text a)
+ Nix.Compression.Stream: instance GHC.Internal.Classes.Eq Nix.Compression.Stream.Compression
+ Nix.Compression.Stream: instance GHC.Internal.Exception.Type.Exception Nix.Compression.Stream.GzipFailure
+ Nix.Compression.Stream: instance GHC.Internal.Show.Show Nix.Compression.Stream.Compression
+ Nix.Compression.Stream: instance GHC.Internal.Show.Show Nix.Compression.Stream.GzipFailure
+ Nix.Compression.Stream: withDecompressed :: Compression -> IO ByteString -> (IO ByteString -> IO a) -> IO a
+ Nix.Compression.Stream: xzReason :: XzError -> Text
+ Nix.Config: AssignedSettings :: Map ByteString HowAssigned -> AssignedSettings
+ Nix.Config: ExtendedOnly :: HowAssigned
+ Nix.Config: KeepsDefault :: DefaultUse
+ Nix.Config: PathSetValue :: DefaultUse -> Set ByteString -> PathSetValue
+ Nix.Config: Replaced :: HowAssigned
+ Nix.Config: ReplacesDefault :: DefaultUse
+ Nix.Config: [clNixConfigHome] :: ConfigLocations -> Maybe ByteString
+ Nix.Config: [ncAllowImportFromDerivation] :: NixConfig -> Bool
+ Nix.Config: [ncAllowedImpureHostDeps] :: NixConfig -> PathSetValue
+ Nix.Config: [ncAllowedUsers] :: NixConfig -> [ByteString]
+ Nix.Config: [ncAlwaysAllowSubstitutes] :: NixConfig -> Bool
+ Nix.Config: [ncBashPromptPrefix] :: NixConfig -> ByteString
+ Nix.Config: [ncBashPromptSuffix] :: NixConfig -> ByteString
+ Nix.Config: [ncBashPrompt] :: NixConfig -> ByteString
+ Nix.Config: [ncBuildUsersGroup] :: NixConfig -> Maybe ByteString
+ Nix.Config: [ncCores] :: NixConfig -> Maybe Word32
+ Nix.Config: [ncDarwinLogSandboxViolations] :: NixConfig -> Bool
+ Nix.Config: [ncDownloadAttempts] :: NixConfig -> Word32
+ Nix.Config: [ncExperimentalFeatures] :: NixConfig -> FeatureSet
+ Nix.Config: [ncKeepFailed] :: NixConfig -> Bool
+ Nix.Config: [ncRequireDropSupplementaryGroups] :: NixConfig -> Maybe Bool
+ Nix.Config: [ncRequireSigs] :: NixConfig -> Bool
+ Nix.Config: [ncSandboxBuildDir] :: NixConfig -> ByteString
+ Nix.Config: [ncSandboxDevShmSize] :: NixConfig -> ByteString
+ Nix.Config: [ncSandboxFallback] :: NixConfig -> Bool
+ Nix.Config: [ncSandboxPaths] :: NixConfig -> PathSetValue
+ Nix.Config: [ncSandbox] :: NixConfig -> Maybe SandboxMode
+ Nix.Config: [ncSecretKeyFiles] :: NixConfig -> [ByteString]
+ Nix.Config: [ncSslCertFile] :: NixConfig -> Maybe ByteString
+ Nix.Config: [ncStore] :: NixConfig -> Maybe ByteString
+ Nix.Config: [ncTraceImportFromDerivation] :: NixConfig -> Bool
+ Nix.Config: [ncTrustedSubstituters] :: NixConfig -> [Text]
+ Nix.Config: [ncTrustedUsers] :: NixConfig -> [ByteString]
+ Nix.Config: [ncUseXdgBaseDirectories] :: NixConfig -> Bool
+ Nix.Config: [psvDefault] :: PathSetValue -> DefaultUse
+ Nix.Config: [psvPaths] :: PathSetValue -> Set ByteString
+ Nix.Config: assignedSettings :: [ConfigAssignment] -> AssignedSettings
+ Nix.Config: data DefaultUse
+ Nix.Config: data HowAssigned
+ Nix.Config: data PathSetValue
+ Nix.Config: instance GHC.Internal.Base.Semigroup Nix.Config.AssignedSettings
+ Nix.Config: instance GHC.Internal.Base.Semigroup Nix.Config.HowAssigned
+ Nix.Config: instance GHC.Internal.Classes.Eq Nix.Config.AssignedSettings
+ Nix.Config: instance GHC.Internal.Classes.Eq Nix.Config.BytesField
+ Nix.Config: instance GHC.Internal.Classes.Eq Nix.Config.DefaultUse
+ Nix.Config: instance GHC.Internal.Classes.Eq Nix.Config.HowAssigned
+ Nix.Config: instance GHC.Internal.Classes.Eq Nix.Config.PathSetField
+ Nix.Config: instance GHC.Internal.Classes.Eq Nix.Config.PathSetValue
+ Nix.Config: instance GHC.Internal.Classes.Eq Nix.Config.WordsField
+ Nix.Config: instance GHC.Internal.Show.Show Nix.Config.AssignedSettings
+ Nix.Config: instance GHC.Internal.Show.Show Nix.Config.BytesField
+ Nix.Config: instance GHC.Internal.Show.Show Nix.Config.DefaultUse
+ Nix.Config: instance GHC.Internal.Show.Show Nix.Config.HowAssigned
+ Nix.Config: instance GHC.Internal.Show.Show Nix.Config.PathSetField
+ Nix.Config: instance GHC.Internal.Show.Show Nix.Config.PathSetValue
+ Nix.Config: instance GHC.Internal.Show.Show Nix.Config.WordsField
+ Nix.Config: loadConfigAssigned :: Monad m => ReadConfigFile m -> [OsPath] -> Maybe ByteString -> m (Either Text (NixConfig, AssignedSettings))
+ Nix.Config: newtype AssignedSettings
+ Nix.Config: storeSettingOverrides :: AssignedSettings -> NixConfig -> Map ByteString ByteString
+ Nix.Daemon.Auth: AccountDatabase :: (AccountKind -> ByteString -> m (Either Text (Maybe Sid))) -> (Sid -> m (Maybe ByteString)) -> (Sid -> m (Either Text [Sid])) -> AccountDatabase (m :: Type -> Type)
+ Nix.Daemon.Auth: AccountPeer :: Maybe Word32 -> Sid -> [Sid] -> AccountPeer
+ Nix.Daemon.Auth: Admitted :: Trust -> Maybe ByteString -> Admission
+ Nix.Daemon.Auth: AuthSettings :: [ByteString] -> [ByteString] -> ByteString -> AuthSettings
+ Nix.Daemon.Auth: GroupAccount :: AccountKind
+ Nix.Daemon.Auth: GroupEntry :: Word32 -> [ByteString] -> GroupEntry
+ Nix.Daemon.Auth: Peer :: Maybe Word32 -> Maybe Word32 -> Maybe Word32 -> Peer
+ Nix.Daemon.Auth: Refused :: Text -> Admission
+ Nix.Daemon.Auth: UserAccount :: AccountKind
+ Nix.Daemon.Auth: UserDatabase :: (Word32 -> m (Maybe ByteString)) -> (Word32 -> m (Maybe ByteString)) -> (ByteString -> m (Maybe GroupEntry)) -> (Word32 -> Word32 -> m (Maybe Bool)) -> UserDatabase (m :: Type -> Type)
+ Nix.Daemon.Auth: [accountGroups] :: AccountPeer -> [Sid]
+ Nix.Daemon.Auth: [accountProcess] :: AccountPeer -> Maybe Word32
+ Nix.Daemon.Auth: [accountUser] :: AccountPeer -> Sid
+ Nix.Daemon.Auth: [adAccountGroups] :: AccountDatabase (m :: Type -> Type) -> Sid -> m (Either Text [Sid])
+ Nix.Daemon.Auth: [adAccountName] :: AccountDatabase (m :: Type -> Type) -> Sid -> m (Maybe ByteString)
+ Nix.Daemon.Auth: [adAccountSid] :: AccountDatabase (m :: Type -> Type) -> AccountKind -> ByteString -> m (Either Text (Maybe Sid))
+ Nix.Daemon.Auth: [asAllowedUsers] :: AuthSettings -> [ByteString]
+ Nix.Daemon.Auth: [asBuildUsersGroup] :: AuthSettings -> ByteString
+ Nix.Daemon.Auth: [asTrustedUsers] :: AuthSettings -> [ByteString]
+ Nix.Daemon.Auth: [groupEntryId] :: GroupEntry -> Word32
+ Nix.Daemon.Auth: [groupEntryMembers] :: GroupEntry -> [ByteString]
+ Nix.Daemon.Auth: [peerGroup] :: Peer -> Maybe Word32
+ Nix.Daemon.Auth: [peerProcess] :: Peer -> Maybe Word32
+ Nix.Daemon.Auth: [peerUser] :: Peer -> Maybe Word32
+ Nix.Daemon.Auth: [udGroupName] :: UserDatabase (m :: Type -> Type) -> Word32 -> m (Maybe ByteString)
+ Nix.Daemon.Auth: [udGroup] :: UserDatabase (m :: Type -> Type) -> ByteString -> m (Maybe GroupEntry)
+ Nix.Daemon.Auth: [udMembership] :: UserDatabase (m :: Type -> Type) -> Word32 -> Word32 -> m (Maybe Bool)
+ Nix.Daemon.Auth: [udUserName] :: UserDatabase (m :: Type -> Type) -> Word32 -> m (Maybe ByteString)
+ Nix.Daemon.Auth: acceptedMessage :: Maybe Word32 -> Admission -> Text
+ Nix.Daemon.Auth: admitAccount :: Monad m => AccountDatabase m -> AuthSettings -> AccountPeer -> m Admission
+ Nix.Daemon.Auth: admitPeer :: Monad m => UserDatabase m -> AuthSettings -> Peer -> m Admission
+ Nix.Daemon.Auth: data AccountDatabase (m :: Type -> Type)
+ Nix.Daemon.Auth: data AccountKind
+ Nix.Daemon.Auth: data AccountPeer
+ Nix.Daemon.Auth: data Admission
+ Nix.Daemon.Auth: data AuthSettings
+ Nix.Daemon.Auth: data GroupEntry
+ Nix.Daemon.Auth: data Peer
+ Nix.Daemon.Auth: data UserDatabase (m :: Type -> Type)
+ Nix.Daemon.Auth: instance GHC.Internal.Classes.Eq Nix.Daemon.Auth.AccountKind
+ Nix.Daemon.Auth: instance GHC.Internal.Classes.Eq Nix.Daemon.Auth.AccountPeer
+ Nix.Daemon.Auth: instance GHC.Internal.Classes.Eq Nix.Daemon.Auth.Admission
+ Nix.Daemon.Auth: instance GHC.Internal.Classes.Eq Nix.Daemon.Auth.AuthSettings
+ Nix.Daemon.Auth: instance GHC.Internal.Classes.Eq Nix.Daemon.Auth.GroupEntry
+ Nix.Daemon.Auth: instance GHC.Internal.Classes.Eq Nix.Daemon.Auth.Peer
+ Nix.Daemon.Auth: instance GHC.Internal.Show.Show Nix.Daemon.Auth.AccountKind
+ Nix.Daemon.Auth: instance GHC.Internal.Show.Show Nix.Daemon.Auth.AccountPeer
+ Nix.Daemon.Auth: instance GHC.Internal.Show.Show Nix.Daemon.Auth.Admission
+ Nix.Daemon.Auth: instance GHC.Internal.Show.Show Nix.Daemon.Auth.AuthSettings
+ Nix.Daemon.Auth: instance GHC.Internal.Show.Show Nix.Daemon.Auth.GroupEntry
+ Nix.Daemon.Auth: instance GHC.Internal.Show.Show Nix.Daemon.Auth.Peer
+ Nix.Daemon.Auth: trustsPipeOwner :: Sid -> Sid -> Bool
+ Nix.Daemon.Auth: unknownPeer :: Peer
+ Nix.Daemon.Client: ConnectionLost :: Text -> ClientFailure
+ Nix.Daemon.Client: DaemonFailed :: DaemonError -> ClientFailure
+ Nix.Daemon.Client: NotSent :: Text -> ClientFailure
+ Nix.Daemon.Client: RelayedHookLine :: ByteString -> Relayed
+ Nix.Daemon.Client: RelayedLine :: Word64 -> ByteString -> Relayed
+ Nix.Daemon.Client: RelayedMessage :: Text -> Relayed
+ Nix.Daemon.Client: RelayedNothing :: Relayed
+ Nix.Daemon.Client: RelayedStart :: Word64 -> ActivityStart -> Relayed
+ Nix.Daemon.Client: RelayedStop :: Word64 -> Relayed
+ Nix.Daemon.Client: addIndirectRoot :: forall (m :: Type -> Type). Monad m => ByteString -> ClientT m ()
+ Nix.Daemon.Client: addTempRoot :: forall (m :: Type -> Type). Monad m => StorePath -> ClientT m ()
+ Nix.Daemon.Client: addToStore :: AddToStoreRequest -> IO ByteString -> ClientT IO ValidPathInfo
+ Nix.Daemon.Client: addToStoreNar :: ValidPathInfo -> Repair -> CheckSigs -> IO ByteString -> ClientT IO ()
+ Nix.Daemon.Client: agreedVersion :: forall (m :: Type -> Type). Monad m => ClientT m Version
+ Nix.Daemon.Client: attempt :: forall (m :: Type -> Type) a. Monad m => ClientT m a -> ClientT m (Either ClientFailure a)
+ Nix.Daemon.Client: buildPaths :: forall (m :: Type -> Type). Monad m => [DerivedPath] -> BuildMode -> ClientT m ()
+ Nix.Daemon.Client: buildPathsWithResults :: forall (m :: Type -> Type). Monad m => [DerivedPath] -> BuildMode -> ClientT m [KeyedBuildResult]
+ Nix.Daemon.Client: continueSession :: StoreDir -> Transport m -> (StderrMessage -> m ()) -> ClientSession -> ClientT m a -> m (Either ClientFailure a, ClientSession)
+ Nix.Daemon.Client: daemonInfo :: forall (m :: Type -> Type). Monad m => ClientT m (Maybe HandshakeInfo)
+ Nix.Daemon.Client: data ClientFailure
+ Nix.Daemon.Client: data ClientSession
+ Nix.Daemon.Client: data ClientT (m :: Type -> Type) a
+ Nix.Daemon.Client: data Relay
+ Nix.Daemon.Client: data Relayed
+ Nix.Daemon.Client: disconnectedMessage :: Text
+ Nix.Daemon.Client: ensurePath :: forall (m :: Type -> Type). Monad m => StorePath -> ClientT m ()
+ Nix.Daemon.Client: instance GHC.Internal.Base.Functor m => GHC.Internal.Base.Functor (Nix.Daemon.Client.ClientT m)
+ Nix.Daemon.Client: instance GHC.Internal.Base.Monad m => Control.Monad.Error.Class.MonadError Nix.Daemon.Client.ClientFailure (Nix.Daemon.Client.ClientT m)
+ Nix.Daemon.Client: instance GHC.Internal.Base.Monad m => Control.Monad.Reader.Class.MonadReader (Nix.Daemon.Client.ClientEnv m) (Nix.Daemon.Client.ClientT m)
+ Nix.Daemon.Client: instance GHC.Internal.Base.Monad m => Control.Monad.State.Class.MonadState Nix.Daemon.Client.ClientSession (Nix.Daemon.Client.ClientT m)
+ Nix.Daemon.Client: instance GHC.Internal.Base.Monad m => GHC.Internal.Base.Applicative (Nix.Daemon.Client.ClientT m)
+ Nix.Daemon.Client: instance GHC.Internal.Base.Monad m => GHC.Internal.Base.Monad (Nix.Daemon.Client.ClientT m)
+ Nix.Daemon.Client: instance GHC.Internal.Classes.Eq Nix.Daemon.Client.ClientFailure
+ Nix.Daemon.Client: instance GHC.Internal.Classes.Eq Nix.Daemon.Client.Relayed
+ Nix.Daemon.Client: instance GHC.Internal.Show.Show Nix.Daemon.Client.ClientFailure
+ Nix.Daemon.Client: instance GHC.Internal.Show.Show Nix.Daemon.Client.Relayed
+ Nix.Daemon.Client: isValidPath :: forall (m :: Type -> Type). Monad m => StorePath -> ClientT m Bool
+ Nix.Daemon.Client: newRelay :: StoreDir -> Logger -> IO Relay
+ Nix.Daemon.Client: offeredVersion :: Version
+ Nix.Daemon.Client: openSession :: Monad m => StoreDir -> Version -> Transport m -> (StderrMessage -> m ()) -> m (Either ClientFailure ClientSession)
+ Nix.Daemon.Client: queryAllValidPaths :: forall (m :: Type -> Type). Monad m => ClientT m (Set StorePath)
+ Nix.Daemon.Client: queryDerivationOutputMap :: forall (m :: Type -> Type). Monad m => StorePath -> ClientT m (Map OutputName (Maybe StorePath))
+ Nix.Daemon.Client: queryMissing :: forall (m :: Type -> Type). Monad m => [DerivedPath] -> ClientT m Missing
+ Nix.Daemon.Client: queryPathInfo :: forall (m :: Type -> Type). Monad m => StorePath -> ClientT m (Maybe UnkeyedValidPathInfo)
+ Nix.Daemon.Client: queryReferrers :: forall (m :: Type -> Type). Monad m => StorePath -> ClientT m (Set StorePath)
+ Nix.Daemon.Client: querySubstitutablePaths :: forall (m :: Type -> Type). Monad m => Set StorePath -> ClientT m (Set StorePath)
+ Nix.Daemon.Client: queryValidDerivers :: forall (m :: Type -> Type). Monad m => StorePath -> ClientT m (Set StorePath)
+ Nix.Daemon.Client: queryValidPaths :: forall (m :: Type -> Type). Monad m => Set StorePath -> Substitute -> ClientT m (Set StorePath)
+ Nix.Daemon.Client: relayMessage :: Relay -> StderrMessage -> IO ()
+ Nix.Daemon.Client: relayed :: StoreDir -> StderrMessage -> Relayed
+ Nix.Daemon.Client: runClient :: Monad m => StoreDir -> Version -> Transport m -> (StderrMessage -> m ()) -> ClientT m a -> m (Either ClientFailure a)
+ Nix.Daemon.Client: setOptions :: forall (m :: Type -> Type). Monad m => ClientSettings -> ClientT m ()
+ Nix.Daemon.Client: stopOpenActivities :: Relay -> IO ()
+ Nix.Daemon.ClientStore: DaemonRefused :: DaemonError -> DaemonOpFailure
+ Nix.Daemon.ClientStore: DaemonStoreConfig :: DaemonAddress -> StoreDir -> ClientSettings -> Logger -> DaemonStoreConfig
+ Nix.Daemon.ClientStore: DefaultSocket :: ByteString -> DaemonAddress
+ Nix.Daemon.ClientStore: LinkFailed :: Text -> DaemonOpFailure
+ Nix.Daemon.ClientStore: NamedSocket :: ByteString -> DaemonAddress
+ Nix.Daemon.ClientStore: [dscAddress] :: DaemonStoreConfig -> DaemonAddress
+ Nix.Daemon.ClientStore: [dscFileDir] :: DaemonStoreConfig -> StoreDir
+ Nix.Daemon.ClientStore: [dscLogger] :: DaemonStoreConfig -> Logger
+ Nix.Daemon.ClientStore: [dscSettings] :: DaemonStoreConfig -> ClientSettings
+ Nix.Daemon.ClientStore: clientSettings :: AssignedSettings -> NixConfig -> ClientSettings
+ Nix.Daemon.ClientStore: connectFailureText :: DaemonAddress -> Text -> Text
+ Nix.Daemon.ClientStore: daemonAddressPath :: DaemonAddress -> ByteString
+ Nix.Daemon.ClientStore: daemonOperation :: DaemonSession -> IO () -> ClientT IO a -> IO (Either DaemonOpFailure a)
+ Nix.Daemon.ClientStore: daemonStoreName :: DaemonAddress -> Text
+ Nix.Daemon.ClientStore: data DaemonAddress
+ Nix.Daemon.ClientStore: data DaemonOpFailure
+ Nix.Daemon.ClientStore: data DaemonSession
+ Nix.Daemon.ClientStore: data DaemonStoreConfig
+ Nix.Daemon.ClientStore: derivationAddOrder :: Map Text ByteString -> Either Text [(StorePath, Derivation, ByteString)]
+ Nix.Daemon.ClientStore: dialDaemon :: DaemonAddress -> Connector
+ Nix.Daemon.ClientStore: evalWriteRequest :: EvalWrite -> AddToStoreRequest
+ Nix.Daemon.ClientStore: flatMethod :: ByteString
+ Nix.Daemon.ClientStore: instance GHC.Internal.Classes.Eq Nix.Daemon.ClientStore.DaemonAddress
+ Nix.Daemon.ClientStore: instance GHC.Internal.Classes.Eq Nix.Daemon.ClientStore.DaemonOpFailure
+ Nix.Daemon.ClientStore: instance GHC.Internal.Show.Show Nix.Daemon.ClientStore.DaemonAddress
+ Nix.Daemon.ClientStore: instance GHC.Internal.Show.Show Nix.Daemon.ClientStore.DaemonOpFailure
+ Nix.Daemon.ClientStore: narMethod :: ByteString
+ Nix.Daemon.ClientStore: opFailureText :: DaemonOpFailure -> Text
+ Nix.Daemon.ClientStore: openFailureText :: DaemonAddress -> ClientFailure -> Text
+ Nix.Daemon.ClientStore: previouslyFailedText :: DaemonAddress -> Text
+ Nix.Daemon.ClientStore: textMethod :: ByteString
+ Nix.Daemon.ClientStore: type Connector = IO Either Text (Transport IO, IO ())
+ Nix.Daemon.ClientStore: withDaemonFixedOutputs :: DaemonStoreConfig -> Connector -> (StorePath -> Either Text ByteString) -> (FixedOutputStore IO -> IO a) -> IO a
+ Nix.Daemon.ClientStore: withDaemonPushSource :: DaemonStoreConfig -> Connector -> (PushSource -> IO a) -> IO a
+ Nix.Daemon.ClientStore: withDaemonSession :: Connector -> DaemonAddress -> ClientSettings -> (StderrMessage -> IO ()) -> (DaemonSession -> IO a) -> IO a
+ Nix.Daemon.ClientStore: withDaemonStore :: DaemonStoreConfig -> Connector -> (StoreOps IO -> IO a) -> IO a
+ Nix.Daemon.Connection: ClientClosed :: ConnectionEnd
+ Nix.Daemon.Connection: ClosedOnError :: DaemonError -> ConnectionEnd
+ Nix.Daemon.Connection: HandshakeFailed :: Text -> ConnectionEnd
+ Nix.Daemon.Connection: ServerConfig :: StoreDir -> Version -> ByteString -> Verbosity -> NixConfig -> ServerConfig
+ Nix.Daemon.Connection: Transport :: m (Maybe ByteString) -> (Builder -> m ()) -> Transport (m :: Type -> Type)
+ Nix.Daemon.Connection: [scConfig] :: ServerConfig -> NixConfig
+ Nix.Daemon.Connection: [scNixVersion] :: ServerConfig -> ByteString
+ Nix.Daemon.Connection: [scStoreDir] :: ServerConfig -> StoreDir
+ Nix.Daemon.Connection: [scVerbosity] :: ServerConfig -> Verbosity
+ Nix.Daemon.Connection: [scVersion] :: ServerConfig -> Version
+ Nix.Daemon.Connection: [transportReceive] :: Transport (m :: Type -> Type) -> m (Maybe ByteString)
+ Nix.Daemon.Connection: [transportSend] :: Transport (m :: Type -> Type) -> Builder -> m ()
+ Nix.Daemon.Connection: data ConnectionEnd
+ Nix.Daemon.Connection: data ServerConfig
+ Nix.Daemon.Connection: data Transport (m :: Type -> Type)
+ Nix.Daemon.Connection: instance GHC.Internal.Classes.Eq Nix.Daemon.Connection.ConnectionEnd
+ Nix.Daemon.Connection: instance GHC.Internal.Show.Show Nix.Daemon.Connection.ConnectionEnd
+ Nix.Daemon.Connection: serveConnection :: Monad m => ServerConfig -> Trust -> DaemonStore m -> Transport m -> m ConnectionEnd
+ Nix.Daemon.Dial: AddressAbsent :: AddressPresence
+ Nix.Daemon.Dial: AddressPresent :: AddressPresence
+ Nix.Daemon.Dial: addressPresence :: ByteString -> IO AddressPresence
+ Nix.Daemon.Dial: closeDaemonConnection :: DaemonConnection -> IO ()
+ Nix.Daemon.Dial: connectDaemon :: ByteString -> IO (Either Text DaemonConnection)
+ Nix.Daemon.Dial: connectFailureText :: Text -> Text -> Text
+ Nix.Daemon.Dial: connectionTransport :: DaemonConnection -> Transport IO
+ Nix.Daemon.Dial: data AddressPresence
+ Nix.Daemon.Dial: data DaemonConnection
+ Nix.Daemon.Dial: instance GHC.Internal.Classes.Eq Nix.Daemon.Dial.AddressPresence
+ Nix.Daemon.Dial: instance GHC.Internal.Show.Show Nix.Daemon.Dial.AddressPresence
+ Nix.Daemon.Dial: sunPathSize :: Int
+ Nix.Daemon.Listen: DaemonOptions :: TrustOverride -> AuthSettings -> (Trust -> Transport IO -> IO ConnectionEnd) -> DaemonOptions
+ Nix.Daemon.Listen: DefaultTrust :: TrustOverride
+ Nix.Daemon.Listen: ForceTrusted :: TrustOverride
+ Nix.Daemon.Listen: ForceUntrusted :: TrustOverride
+ Nix.Daemon.Listen: [doAuth] :: DaemonOptions -> AuthSettings
+ Nix.Daemon.Listen: [doServe] :: DaemonOptions -> Trust -> Transport IO -> IO ConnectionEnd
+ Nix.Daemon.Listen: [doTrust] :: DaemonOptions -> TrustOverride
+ Nix.Daemon.Listen: authSettingsFor :: NixConfig -> IO AuthSettings
+ Nix.Daemon.Listen: closeListener :: Listener -> IO ()
+ Nix.Daemon.Listen: daemonSocketPath :: IO ByteString
+ Nix.Daemon.Listen: data DaemonOptions
+ Nix.Daemon.Listen: data Listener
+ Nix.Daemon.Listen: data TrustOverride
+ Nix.Daemon.Listen: instance GHC.Internal.Classes.Eq Nix.Daemon.Listen.TrustOverride
+ Nix.Daemon.Listen: instance GHC.Internal.Exception.Type.Exception Nix.Daemon.Listen.ClientHungUp
+ Nix.Daemon.Listen: instance GHC.Internal.Show.Show Nix.Daemon.Listen.ClientHungUp
+ Nix.Daemon.Listen: instance GHC.Internal.Show.Show Nix.Daemon.Listen.TrustOverride
+ Nix.Daemon.Listen: openListener :: ByteString -> IO (Either Text Listener)
+ Nix.Daemon.Listen: serveListener :: Logger -> DaemonOptions -> Listener -> IO a
+ Nix.Daemon.LocalStore: data ServedStore
+ Nix.Daemon.LocalStore: newServedStore :: MachineDefaults -> Store -> IO ServedStore
+ Nix.Daemon.LocalStore: serveLocal :: ServedStore -> ServerConfig -> Trust -> Transport IO -> IO ConnectionEnd
+ Nix.Daemon.Ops: ActivityResult :: ActivityId -> ResultType -> [Field] -> LogEvent
+ Nix.Daemon.Ops: ActivityStarted :: Activity -> LogEvent
+ Nix.Daemon.Ops: ActivityStopped :: ActivityId -> LogEvent
+ Nix.Daemon.Ops: AddIndirectRoot :: ByteString -> Request
+ Nix.Daemon.Ops: AddMultipleToStore :: Repair -> CheckSigs -> Request
+ Nix.Daemon.Ops: AddSignatures :: StorePath -> Set Signature -> Request
+ Nix.Daemon.Ops: AddTempRoot :: StorePath -> Request
+ Nix.Daemon.Ops: AddToStore :: AddToStoreRequest -> Request
+ Nix.Daemon.Ops: AddToStoreNar :: ValidPathInfo -> Repair -> CheckSigs -> Request
+ Nix.Daemon.Ops: AddToStoreRequest :: ByteString -> ByteString -> Set StorePath -> Repair -> AddToStoreRequest
+ Nix.Daemon.Ops: BoundaryAhead :: (ByteString -> NarBoundary) -> NarBoundary
+ Nix.Daemon.Ops: BoundaryReached :: ByteString -> NarBoundary
+ Nix.Daemon.Ops: BuildPaths :: [DerivedPath] -> BuildMode -> Request
+ Nix.Daemon.Ops: BuildPathsWithResults :: [DerivedPath] -> BuildMode -> Request
+ Nix.Daemon.Ops: CensorRoots :: RootCensoring
+ Nix.Daemon.Ops: CheckContents :: CheckContents
+ Nix.Daemon.Ops: CheckSigs :: CheckSigs
+ Nix.Daemon.Ops: ClientSettings :: Bool -> Bool -> Bool -> Verbosity -> Word32 -> Word32 -> Bool -> Word32 -> Bool -> Map ByteString ByteString -> ClientSettings
+ Nix.Daemon.Ops: CollectGarbage :: GCRequest -> Liveness -> Request
+ Nix.Daemon.Ops: ConnectionSettings :: Verbosity -> NixConfig -> Maybe ClientSettings -> ConnectionSettings
+ Nix.Daemon.Ops: DaemonStore :: (Work m -> StorePath -> m (Either DaemonError Bool)) -> (Work m -> Substitute -> Set StorePath -> m (Either DaemonError (Set StorePath))) -> (Work m -> Set StorePath -> m (Either DaemonError (Set StorePath))) -> (Work m -> StorePath -> m (Either DaemonError (Set StorePath))) -> (Work m -> StorePath -> m (Either DaemonError (Set StorePath))) -> (Work m -> StorePath -> m (Either DaemonError (Map OutputName (Maybe StorePath)))) -> (Work m -> m (Either DaemonError (Set StorePath))) -> (Work m -> StorePath -> m (Either DaemonError (Maybe UnkeyedValidPathInfo))) -> (Work m -> [DerivedPath] -> m (Either DaemonError Missing)) -> (Work m -> DumpUpload -> m (Intake m ValidPathInfo)) -> (Work m -> ValidPathInfo -> Repair -> CheckSigs -> m (Intake m ())) -> (Work m -> [DerivedPath] -> BuildMode -> m (Either DaemonError ())) -> (Work m -> [DerivedPath] -> BuildMode -> m (Either DaemonError [KeyedBuildResult])) -> (Work m -> StorePath -> m (Either DaemonError ())) -> (Work m -> StorePath -> m (Either DaemonError ())) -> (Work m -> ByteString -> m (Either DaemonError ())) -> (Work m -> RootCensoring -> m (Either DaemonError (Map StorePath (Set ByteString)))) -> (Work m -> GCRequest -> m (Either DaemonError GCResult)) -> (Work m -> m (Either DaemonError ())) -> (Work m -> CheckContents -> Repair -> m (Either DaemonError Bool)) -> (Work m -> StorePath -> Set Signature -> m (Either DaemonError ())) -> (StorePath -> (ByteString -> m ()) -> m (Either DaemonError ())) -> DaemonStore (m :: Type -> Type)
+ Nix.Daemon.Ops: DumpUpload :: ByteString -> ContentAddressMethod -> Text -> Set StorePath -> Repair -> DumpUpload
+ Nix.Daemon.Ops: EnsurePath :: StorePath -> Request
+ Nix.Daemon.Ops: FindRoots :: Request
+ Nix.Daemon.Ops: GCRequest :: GCAction -> GCPaths -> Word64 -> GCRequest
+ Nix.Daemon.Ops: IgnoreLiveness :: Liveness
+ Nix.Daemon.Ops: IsValidPath :: StorePath -> Request
+ Nix.Daemon.Ops: KeepLiveness :: Liveness
+ Nix.Daemon.Ops: LogLine :: Verbosity -> ByteString -> LogEvent
+ Nix.Daemon.Ops: NarFromPath :: StorePath -> Request
+ Nix.Daemon.Ops: NoCheckSigs :: CheckSigs
+ Nix.Daemon.Ops: NoRepair :: Repair
+ Nix.Daemon.Ops: NoSubstitute :: Substitute
+ Nix.Daemon.Ops: OptimiseStore :: Request
+ Nix.Daemon.Ops: Permitted :: Request -> Authorization
+ Nix.Daemon.Ops: QueryAllValidPaths :: Request
+ Nix.Daemon.Ops: QueryDerivationOutputMap :: StorePath -> Request
+ Nix.Daemon.Ops: QueryMissing :: [DerivedPath] -> Request
+ Nix.Daemon.Ops: QueryPathInfo :: StorePath -> Request
+ Nix.Daemon.Ops: QueryReferrers :: StorePath -> Request
+ Nix.Daemon.Ops: QuerySubstitutablePaths :: Set StorePath -> Request
+ Nix.Daemon.Ops: QueryValidDerivers :: StorePath -> Request
+ Nix.Daemon.Ops: QueryValidPaths :: Set StorePath -> Substitute -> Request
+ Nix.Daemon.Ops: RefusedBeforeWork :: Text -> Authorization
+ Nix.Daemon.Ops: RefusedInWork :: Text -> Authorization
+ Nix.Daemon.Ops: Repair :: Repair
+ Nix.Daemon.Ops: SetOptions :: ClientSettings -> Request
+ Nix.Daemon.Ops: ShowRoots :: RootCensoring
+ Nix.Daemon.Ops: SkipContents :: CheckContents
+ Nix.Daemon.Ops: Substitute :: Substitute
+ Nix.Daemon.Ops: Taken :: Either DaemonError a -> Intake (m :: Type -> Type) a
+ Nix.Daemon.Ops: Taking :: (ByteString -> m (Intake m a)) -> m (Either DaemonError a) -> m () -> Intake (m :: Type -> Type) a
+ Nix.Daemon.Ops: VerifyStore :: CheckContents -> Repair -> Request
+ Nix.Daemon.Ops: Work :: (LogEvent -> m ()) -> ConnectionSettings -> Work (m :: Type -> Type)
+ Nix.Daemon.Ops: [atsMethod] :: AddToStoreRequest -> ByteString
+ Nix.Daemon.Ops: [atsName] :: AddToStoreRequest -> ByteString
+ Nix.Daemon.Ops: [atsReferences] :: AddToStoreRequest -> Set StorePath
+ Nix.Daemon.Ops: [atsRepair] :: AddToStoreRequest -> Repair
+ Nix.Daemon.Ops: [connClient] :: ConnectionSettings -> Maybe ClientSettings
+ Nix.Daemon.Ops: [connConfig] :: ConnectionSettings -> NixConfig
+ Nix.Daemon.Ops: [connVerbosity] :: ConnectionSettings -> Verbosity
+ Nix.Daemon.Ops: [csBuildCores] :: ClientSettings -> Word32
+ Nix.Daemon.Ops: [csKeepFailed] :: ClientSettings -> Bool
+ Nix.Daemon.Ops: [csKeepGoing] :: ClientSettings -> Bool
+ Nix.Daemon.Ops: [csMaxBuildJobs] :: ClientSettings -> Word32
+ Nix.Daemon.Ops: [csMaxSilentTime] :: ClientSettings -> Word32
+ Nix.Daemon.Ops: [csOverrides] :: ClientSettings -> Map ByteString ByteString
+ Nix.Daemon.Ops: [csTryFallback] :: ClientSettings -> Bool
+ Nix.Daemon.Ops: [csUseSubstitutes] :: ClientSettings -> Bool
+ Nix.Daemon.Ops: [csVerboseBuild] :: ClientSettings -> Bool
+ Nix.Daemon.Ops: [csVerbosity] :: ClientSettings -> Verbosity
+ Nix.Daemon.Ops: [dsAddIndirectRoot] :: DaemonStore (m :: Type -> Type) -> Work m -> ByteString -> m (Either DaemonError ())
+ Nix.Daemon.Ops: [dsAddSignatures] :: DaemonStore (m :: Type -> Type) -> Work m -> StorePath -> Set Signature -> m (Either DaemonError ())
+ Nix.Daemon.Ops: [dsAddTempRoot] :: DaemonStore (m :: Type -> Type) -> Work m -> StorePath -> m (Either DaemonError ())
+ Nix.Daemon.Ops: [dsAddToStoreNar] :: DaemonStore (m :: Type -> Type) -> Work m -> ValidPathInfo -> Repair -> CheckSigs -> m (Intake m ())
+ Nix.Daemon.Ops: [dsAddToStore] :: DaemonStore (m :: Type -> Type) -> Work m -> DumpUpload -> m (Intake m ValidPathInfo)
+ Nix.Daemon.Ops: [dsBuildPathsWithResults] :: DaemonStore (m :: Type -> Type) -> Work m -> [DerivedPath] -> BuildMode -> m (Either DaemonError [KeyedBuildResult])
+ Nix.Daemon.Ops: [dsBuildPaths] :: DaemonStore (m :: Type -> Type) -> Work m -> [DerivedPath] -> BuildMode -> m (Either DaemonError ())
+ Nix.Daemon.Ops: [dsCollectGarbage] :: DaemonStore (m :: Type -> Type) -> Work m -> GCRequest -> m (Either DaemonError GCResult)
+ Nix.Daemon.Ops: [dsEnsurePath] :: DaemonStore (m :: Type -> Type) -> Work m -> StorePath -> m (Either DaemonError ())
+ Nix.Daemon.Ops: [dsFindRoots] :: DaemonStore (m :: Type -> Type) -> Work m -> RootCensoring -> m (Either DaemonError (Map StorePath (Set ByteString)))
+ Nix.Daemon.Ops: [dsIsValidPath] :: DaemonStore (m :: Type -> Type) -> Work m -> StorePath -> m (Either DaemonError Bool)
+ Nix.Daemon.Ops: [dsNarFromPath] :: DaemonStore (m :: Type -> Type) -> StorePath -> (ByteString -> m ()) -> m (Either DaemonError ())
+ Nix.Daemon.Ops: [dsOptimiseStore] :: DaemonStore (m :: Type -> Type) -> Work m -> m (Either DaemonError ())
+ Nix.Daemon.Ops: [dsQueryAllValidPaths] :: DaemonStore (m :: Type -> Type) -> Work m -> m (Either DaemonError (Set StorePath))
+ Nix.Daemon.Ops: [dsQueryDerivationOutputMap] :: DaemonStore (m :: Type -> Type) -> Work m -> StorePath -> m (Either DaemonError (Map OutputName (Maybe StorePath)))
+ Nix.Daemon.Ops: [dsQueryMissing] :: DaemonStore (m :: Type -> Type) -> Work m -> [DerivedPath] -> m (Either DaemonError Missing)
+ Nix.Daemon.Ops: [dsQueryPathInfo] :: DaemonStore (m :: Type -> Type) -> Work m -> StorePath -> m (Either DaemonError (Maybe UnkeyedValidPathInfo))
+ Nix.Daemon.Ops: [dsQueryReferrers] :: DaemonStore (m :: Type -> Type) -> Work m -> StorePath -> m (Either DaemonError (Set StorePath))
+ Nix.Daemon.Ops: [dsQuerySubstitutablePaths] :: DaemonStore (m :: Type -> Type) -> Work m -> Set StorePath -> m (Either DaemonError (Set StorePath))
+ Nix.Daemon.Ops: [dsQueryValidDerivers] :: DaemonStore (m :: Type -> Type) -> Work m -> StorePath -> m (Either DaemonError (Set StorePath))
+ Nix.Daemon.Ops: [dsQueryValidPaths] :: DaemonStore (m :: Type -> Type) -> Work m -> Substitute -> Set StorePath -> m (Either DaemonError (Set StorePath))
+ Nix.Daemon.Ops: [dsVerifyStore] :: DaemonStore (m :: Type -> Type) -> Work m -> CheckContents -> Repair -> m (Either DaemonError Bool)
+ Nix.Daemon.Ops: [duAlgo] :: DumpUpload -> Text
+ Nix.Daemon.Ops: [duMethod] :: DumpUpload -> ContentAddressMethod
+ Nix.Daemon.Ops: [duName] :: DumpUpload -> ByteString
+ Nix.Daemon.Ops: [duReferences] :: DumpUpload -> Set StorePath
+ Nix.Daemon.Ops: [duRepair] :: DumpUpload -> Repair
+ Nix.Daemon.Ops: [gcAction] :: GCRequest -> GCAction
+ Nix.Daemon.Ops: [gcMaxFreed] :: GCRequest -> Word64
+ Nix.Daemon.Ops: [gcPaths] :: GCRequest -> GCPaths
+ Nix.Daemon.Ops: [workReport] :: Work (m :: Type -> Type) -> LogEvent -> m ()
+ Nix.Daemon.Ops: [workSettings] :: Work (m :: Type -> Type) -> ConnectionSettings
+ Nix.Daemon.Ops: activityStart :: StoreDir -> Activity -> Maybe ActivityStart
+ Nix.Daemon.Ops: applyClientSettings :: Trust -> ClientSettings -> ConnectionSettings -> (ConnectionSettings, [ByteString])
+ Nix.Daemon.Ops: authorize :: Trust -> Request -> Authorization
+ Nix.Daemon.Ops: buildResultsSince :: VersionNumber
+ Nix.Daemon.Ops: daemonError :: Text -> DaemonError
+ Nix.Daemon.Ops: data AddToStoreRequest
+ Nix.Daemon.Ops: data Authorization
+ Nix.Daemon.Ops: data CheckContents
+ Nix.Daemon.Ops: data CheckSigs
+ Nix.Daemon.Ops: data ClientSettings
+ Nix.Daemon.Ops: data ConnectionSettings
+ Nix.Daemon.Ops: data DaemonStore (m :: Type -> Type)
+ Nix.Daemon.Ops: data DumpUpload
+ Nix.Daemon.Ops: data GCRequest
+ Nix.Daemon.Ops: data Intake (m :: Type -> Type) a
+ Nix.Daemon.Ops: data Liveness
+ Nix.Daemon.Ops: data LogEvent
+ Nix.Daemon.Ops: data NarBoundary
+ Nix.Daemon.Ops: data Repair
+ Nix.Daemon.Ops: data Request
+ Nix.Daemon.Ops: data RootCensoring
+ Nix.Daemon.Ops: data Substitute
+ Nix.Daemon.Ops: data Work (m :: Type -> Type)
+ Nix.Daemon.Ops: framedAddToStoreNarSince :: VersionNumber
+ Nix.Daemon.Ops: framedAddToStoreSince :: VersionNumber
+ Nix.Daemon.Ops: getClientSettings :: Decoder ClientSettings
+ Nix.Daemon.Ops: getRequest :: StoreDir -> Version -> Word32 -> Maybe (Decoder Request)
+ Nix.Daemon.Ops: getUploadPathInfo :: StoreDir -> Decoder ValidPathInfo
+ Nix.Daemon.Ops: instance GHC.Internal.Classes.Eq Nix.Daemon.Ops.AddToStoreRequest
+ Nix.Daemon.Ops: instance GHC.Internal.Classes.Eq Nix.Daemon.Ops.Authorization
+ Nix.Daemon.Ops: instance GHC.Internal.Classes.Eq Nix.Daemon.Ops.CheckContents
+ Nix.Daemon.Ops: instance GHC.Internal.Classes.Eq Nix.Daemon.Ops.CheckSigs
+ Nix.Daemon.Ops: instance GHC.Internal.Classes.Eq Nix.Daemon.Ops.ClientSettings
+ Nix.Daemon.Ops: instance GHC.Internal.Classes.Eq Nix.Daemon.Ops.ConnectionSettings
+ Nix.Daemon.Ops: instance GHC.Internal.Classes.Eq Nix.Daemon.Ops.DumpUpload
+ Nix.Daemon.Ops: instance GHC.Internal.Classes.Eq Nix.Daemon.Ops.GCRequest
+ Nix.Daemon.Ops: instance GHC.Internal.Classes.Eq Nix.Daemon.Ops.Liveness
+ Nix.Daemon.Ops: instance GHC.Internal.Classes.Eq Nix.Daemon.Ops.LogEvent
+ Nix.Daemon.Ops: instance GHC.Internal.Classes.Eq Nix.Daemon.Ops.Op
+ Nix.Daemon.Ops: instance GHC.Internal.Classes.Eq Nix.Daemon.Ops.Repair
+ Nix.Daemon.Ops: instance GHC.Internal.Classes.Eq Nix.Daemon.Ops.Request
+ Nix.Daemon.Ops: instance GHC.Internal.Classes.Eq Nix.Daemon.Ops.RootCensoring
+ Nix.Daemon.Ops: instance GHC.Internal.Classes.Eq Nix.Daemon.Ops.Substitute
+ Nix.Daemon.Ops: instance GHC.Internal.Enum.Bounded Nix.Daemon.Ops.Op
+ Nix.Daemon.Ops: instance GHC.Internal.Enum.Enum Nix.Daemon.Ops.Op
+ Nix.Daemon.Ops: instance GHC.Internal.Show.Show Nix.Daemon.Ops.AddToStoreRequest
+ Nix.Daemon.Ops: instance GHC.Internal.Show.Show Nix.Daemon.Ops.Authorization
+ Nix.Daemon.Ops: instance GHC.Internal.Show.Show Nix.Daemon.Ops.CheckContents
+ Nix.Daemon.Ops: instance GHC.Internal.Show.Show Nix.Daemon.Ops.CheckSigs
+ Nix.Daemon.Ops: instance GHC.Internal.Show.Show Nix.Daemon.Ops.ClientSettings
+ Nix.Daemon.Ops: instance GHC.Internal.Show.Show Nix.Daemon.Ops.ConnectionSettings
+ Nix.Daemon.Ops: instance GHC.Internal.Show.Show Nix.Daemon.Ops.DumpUpload
+ Nix.Daemon.Ops: instance GHC.Internal.Show.Show Nix.Daemon.Ops.GCRequest
+ Nix.Daemon.Ops: instance GHC.Internal.Show.Show Nix.Daemon.Ops.Liveness
+ Nix.Daemon.Ops: instance GHC.Internal.Show.Show Nix.Daemon.Ops.LogEvent
+ Nix.Daemon.Ops: instance GHC.Internal.Show.Show Nix.Daemon.Ops.Op
+ Nix.Daemon.Ops: instance GHC.Internal.Show.Show Nix.Daemon.Ops.Repair
+ Nix.Daemon.Ops: instance GHC.Internal.Show.Show Nix.Daemon.Ops.Request
+ Nix.Daemon.Ops: instance GHC.Internal.Show.Show Nix.Daemon.Ops.RootCensoring
+ Nix.Daemon.Ops: instance GHC.Internal.Show.Show Nix.Daemon.Ops.Substitute
+ Nix.Daemon.Ops: logVerbosity :: Level -> Verbosity
+ Nix.Daemon.Ops: narSizeBoundary :: Word64 -> NarBoundary
+ Nix.Daemon.Ops: outputMapSince :: VersionNumber
+ Nix.Daemon.Ops: putClientSettings :: ClientSettings -> Builder
+ Nix.Daemon.Ops: putRequest :: StoreDir -> Version -> Request -> Either Text Builder
+ Nix.Daemon.Ops: putUploadPathInfo :: StoreDir -> ValidPathInfo -> Builder
+ Nix.Daemon.Ops: queryMissingSince :: VersionNumber
+ Nix.Daemon.Ops: rootCensoring :: Trust -> RootCensoring
+ Nix.Daemon.Ops: storeActivity :: StoreDir -> ActivityId -> ActivityStart -> Activity
+ Nix.Daemon.Ops: substituteFlagSince :: VersionNumber
+ Nix.Daemon.Ops: unsetCores :: Word32
+ Nix.Daemon.Protocol: Activity :: ActivityId -> Verbosity -> ActivityType -> ByteString -> [Field] -> ActivityId -> Activity
+ Nix.Daemon.Protocol: ActivityId :: Word64 -> ActivityId
+ Nix.Daemon.Protocol: ActivityType :: Word32 -> ActivityType
+ Nix.Daemon.Protocol: AllOutputs :: OutputsSpec
+ Nix.Daemon.Protocol: AlreadyValid :: SuccessStatus
+ Nix.Daemon.Protocol: BuildCheck :: BuildMode
+ Nix.Daemon.Protocol: BuildNormal :: BuildMode
+ Nix.Daemon.Protocol: BuildRepair :: BuildMode
+ Nix.Daemon.Protocol: BuildResult :: BuildOutcome -> Word32 -> Int64 -> Int64 -> Maybe Int64 -> Maybe Int64 -> BuildResult
+ Nix.Daemon.Protocol: Built :: SuccessStatus
+ Nix.Daemon.Protocol: CachedFailure :: FailureStatus
+ Nix.Daemon.Protocol: DaemonError :: Verbosity -> ByteString -> [ByteString] -> Word32 -> DaemonError
+ Nix.Daemon.Protocol: DeleteDead :: GCAction
+ Nix.Daemon.Protocol: DeleteSpecific :: GCAction
+ Nix.Daemon.Protocol: DependencyFailed :: FailureStatus
+ Nix.Daemon.Protocol: DerivedBuilt :: StorePath -> OutputsSpec -> DerivedPath
+ Nix.Daemon.Protocol: DerivedOpaque :: StorePath -> DerivedPath
+ Nix.Daemon.Protocol: DrvOutput :: StorePath -> OutputName -> DrvOutput
+ Nix.Daemon.Protocol: Failed :: Failure -> BuildOutcome
+ Nix.Daemon.Protocol: Failure :: FailureStatus -> ByteString -> Bool -> Failure
+ Nix.Daemon.Protocol: Feature :: ByteString -> Feature
+ Nix.Daemon.Protocol: FieldInt :: Word64 -> Field
+ Nix.Daemon.Protocol: FieldString :: ByteString -> Field
+ Nix.Daemon.Protocol: FixedMethod :: FileIngestionMethod -> ContentAddressMethod
+ Nix.Daemon.Protocol: GCResult :: Set ByteString -> Word64 -> GCResult
+ Nix.Daemon.Protocol: HandshakeInfo :: Maybe ByteString -> Maybe Trust -> HandshakeInfo
+ Nix.Daemon.Protocol: InputRejected :: FailureStatus
+ Nix.Daemon.Protocol: KeyedBuildResult :: DerivedPath -> BuildResult -> KeyedBuildResult
+ Nix.Daemon.Protocol: LogLimitExceeded :: FailureStatus
+ Nix.Daemon.Protocol: MiscFailure :: FailureStatus
+ Nix.Daemon.Protocol: Missing :: Set StorePath -> Set StorePath -> Set StorePath -> Word64 -> Word64 -> Missing
+ Nix.Daemon.Protocol: NoSubstituters :: FailureStatus
+ Nix.Daemon.Protocol: NotDeterministic :: FailureStatus
+ Nix.Daemon.Protocol: NotTrusted :: Trust
+ Nix.Daemon.Protocol: OutputName :: Text -> OutputName
+ Nix.Daemon.Protocol: OutputRejected :: FailureStatus
+ Nix.Daemon.Protocol: PermanentFailure :: FailureStatus
+ Nix.Daemon.Protocol: Realisation :: DrvOutput -> UnkeyedRealisation -> Realisation
+ Nix.Daemon.Protocol: ResolvesToAlreadyValid :: SuccessStatus
+ Nix.Daemon.Protocol: ResultType :: Word32 -> ResultType
+ Nix.Daemon.Protocol: ReturnDead :: GCAction
+ Nix.Daemon.Protocol: ReturnLive :: GCAction
+ Nix.Daemon.Protocol: SpecificPaths :: Set StorePath -> Bool -> GCPaths
+ Nix.Daemon.Protocol: StderrError :: DaemonError -> StderrMessage
+ Nix.Daemon.Protocol: StderrLast :: StderrMessage
+ Nix.Daemon.Protocol: StderrNext :: ByteString -> StderrMessage
+ Nix.Daemon.Protocol: StderrRead :: Word64 -> StderrMessage
+ Nix.Daemon.Protocol: StderrResult :: ActivityId -> ResultType -> [Field] -> StderrMessage
+ Nix.Daemon.Protocol: StderrStartActivity :: Activity -> StderrMessage
+ Nix.Daemon.Protocol: StderrStopActivity :: ActivityId -> StderrMessage
+ Nix.Daemon.Protocol: StderrWrite :: ByteString -> StderrMessage
+ Nix.Daemon.Protocol: Substituted :: SuccessStatus
+ Nix.Daemon.Protocol: Succeeded :: Success -> BuildOutcome
+ Nix.Daemon.Protocol: Success :: SuccessStatus -> Map OutputName UnkeyedRealisation -> Success
+ Nix.Daemon.Protocol: TextMethod :: ContentAddressMethod
+ Nix.Daemon.Protocol: TimedOut :: FailureStatus
+ Nix.Daemon.Protocol: TransientFailure :: FailureStatus
+ Nix.Daemon.Protocol: Trusted :: Trust
+ Nix.Daemon.Protocol: UnkeyedRealisation :: StorePath -> Set Signature -> UnkeyedRealisation
+ Nix.Daemon.Protocol: UnkeyedValidPathInfo :: Maybe StorePath -> NarHash -> Set StorePath -> Int64 -> Word64 -> Bool -> Set Signature -> Maybe ContentAddress -> UnkeyedValidPathInfo
+ Nix.Daemon.Protocol: ValidPathInfo :: StorePath -> UnkeyedValidPathInfo -> ValidPathInfo
+ Nix.Daemon.Protocol: Verbosity :: Word32 -> Verbosity
+ Nix.Daemon.Protocol: Version :: VersionNumber -> Set Feature -> Version
+ Nix.Daemon.Protocol: VersionNumber :: Word8 -> Word8 -> VersionNumber
+ Nix.Daemon.Protocol: WholeStore :: GCPaths
+ Nix.Daemon.Protocol: [actFields] :: Activity -> [Field]
+ Nix.Daemon.Protocol: [actId] :: Activity -> ActivityId
+ Nix.Daemon.Protocol: [actLevel] :: Activity -> Verbosity
+ Nix.Daemon.Protocol: [actParent] :: Activity -> ActivityId
+ Nix.Daemon.Protocol: [actText] :: Activity -> ByteString
+ Nix.Daemon.Protocol: [actType] :: Activity -> ActivityType
+ Nix.Daemon.Protocol: [brCpuSystem] :: BuildResult -> Maybe Int64
+ Nix.Daemon.Protocol: [brCpuUser] :: BuildResult -> Maybe Int64
+ Nix.Daemon.Protocol: [brOutcome] :: BuildResult -> BuildOutcome
+ Nix.Daemon.Protocol: [brStartTime] :: BuildResult -> Int64
+ Nix.Daemon.Protocol: [brStopTime] :: BuildResult -> Int64
+ Nix.Daemon.Protocol: [brTimesBuilt] :: BuildResult -> Word32
+ Nix.Daemon.Protocol: [doDrvPath] :: DrvOutput -> StorePath
+ Nix.Daemon.Protocol: [doOutputName] :: DrvOutput -> OutputName
+ Nix.Daemon.Protocol: [errExitStatus] :: DaemonError -> Word32
+ Nix.Daemon.Protocol: [errLevel] :: DaemonError -> Verbosity
+ Nix.Daemon.Protocol: [errMessage] :: DaemonError -> ByteString
+ Nix.Daemon.Protocol: [errTraces] :: DaemonError -> [ByteString]
+ Nix.Daemon.Protocol: [failureMessage] :: Failure -> ByteString
+ Nix.Daemon.Protocol: [failureNonDeterministic] :: Failure -> Bool
+ Nix.Daemon.Protocol: [failureStatus] :: Failure -> FailureStatus
+ Nix.Daemon.Protocol: [gcResultBytesFreed] :: GCResult -> Word64
+ Nix.Daemon.Protocol: [gcResultPaths] :: GCResult -> Set ByteString
+ Nix.Daemon.Protocol: [hiDaemonVersion] :: HandshakeInfo -> Maybe ByteString
+ Nix.Daemon.Protocol: [hiTrust] :: HandshakeInfo -> Maybe Trust
+ Nix.Daemon.Protocol: [kbrPath] :: KeyedBuildResult -> DerivedPath
+ Nix.Daemon.Protocol: [kbrResult] :: KeyedBuildResult -> BuildResult
+ Nix.Daemon.Protocol: [missingDownloadSize] :: Missing -> Word64
+ Nix.Daemon.Protocol: [missingNarSize] :: Missing -> Word64
+ Nix.Daemon.Protocol: [missingUnknown] :: Missing -> Set StorePath
+ Nix.Daemon.Protocol: [missingWillBuild] :: Missing -> Set StorePath
+ Nix.Daemon.Protocol: [missingWillSubstitute] :: Missing -> Set StorePath
+ Nix.Daemon.Protocol: [rId] :: Realisation -> DrvOutput
+ Nix.Daemon.Protocol: [rRealisation] :: Realisation -> UnkeyedRealisation
+ Nix.Daemon.Protocol: [successOutputs] :: Success -> Map OutputName UnkeyedRealisation
+ Nix.Daemon.Protocol: [successStatus] :: Success -> SuccessStatus
+ Nix.Daemon.Protocol: [upiContentAddress] :: UnkeyedValidPathInfo -> Maybe ContentAddress
+ Nix.Daemon.Protocol: [upiDeriver] :: UnkeyedValidPathInfo -> Maybe StorePath
+ Nix.Daemon.Protocol: [upiNarHash] :: UnkeyedValidPathInfo -> NarHash
+ Nix.Daemon.Protocol: [upiNarSize] :: UnkeyedValidPathInfo -> Word64
+ Nix.Daemon.Protocol: [upiReferences] :: UnkeyedValidPathInfo -> Set StorePath
+ Nix.Daemon.Protocol: [upiRegistrationTime] :: UnkeyedValidPathInfo -> Int64
+ Nix.Daemon.Protocol: [upiSignatures] :: UnkeyedValidPathInfo -> Set Signature
+ Nix.Daemon.Protocol: [upiUltimate] :: UnkeyedValidPathInfo -> Bool
+ Nix.Daemon.Protocol: [urOutPath] :: UnkeyedRealisation -> StorePath
+ Nix.Daemon.Protocol: [urSignatures] :: UnkeyedRealisation -> Set Signature
+ Nix.Daemon.Protocol: [versionFeatures] :: Version -> Set Feature
+ Nix.Daemon.Protocol: [versionNumber] :: Version -> VersionNumber
+ Nix.Daemon.Protocol: [vnMajor] :: VersionNumber -> Word8
+ Nix.Daemon.Protocol: [vnMinor] :: VersionNumber -> Word8
+ Nix.Daemon.Protocol: [vpiInfo] :: ValidPathInfo -> UnkeyedValidPathInfo
+ Nix.Daemon.Protocol: [vpiPath] :: ValidPathInfo -> StorePath
+ Nix.Daemon.Protocol: actBuild :: ActivityType
+ Nix.Daemon.Protocol: actSubstitute :: ActivityType
+ Nix.Daemon.Protocol: caAlgo :: ContentAddress -> Text
+ Nix.Daemon.Protocol: caDigest :: ContentAddress -> ByteString
+ Nix.Daemon.Protocol: caMethod :: ContentAddress -> ContentAddressMethod
+ Nix.Daemon.Protocol: contentAddressFromParts :: ContentAddressMethod -> Text -> ByteString -> Maybe ContentAddress
+ Nix.Daemon.Protocol: data Activity
+ Nix.Daemon.Protocol: data BuildMode
+ Nix.Daemon.Protocol: data BuildOutcome
+ Nix.Daemon.Protocol: data BuildResult
+ Nix.Daemon.Protocol: data ContentAddress
+ Nix.Daemon.Protocol: data ContentAddressMethod
+ Nix.Daemon.Protocol: data DaemonError
+ Nix.Daemon.Protocol: data DerivedPath
+ Nix.Daemon.Protocol: data DrvOutput
+ Nix.Daemon.Protocol: data Failure
+ Nix.Daemon.Protocol: data FailureStatus
+ Nix.Daemon.Protocol: data Field
+ Nix.Daemon.Protocol: data GCAction
+ Nix.Daemon.Protocol: data GCPaths
+ Nix.Daemon.Protocol: data GCResult
+ Nix.Daemon.Protocol: data HandshakeInfo
+ Nix.Daemon.Protocol: data KeyedBuildResult
+ Nix.Daemon.Protocol: data Missing
+ Nix.Daemon.Protocol: data NarHash
+ Nix.Daemon.Protocol: data OutputsSpec
+ Nix.Daemon.Protocol: data Realisation
+ Nix.Daemon.Protocol: data Signature
+ Nix.Daemon.Protocol: data StderrMessage
+ Nix.Daemon.Protocol: data Success
+ Nix.Daemon.Protocol: data SuccessStatus
+ Nix.Daemon.Protocol: data Trust
+ Nix.Daemon.Protocol: data UnkeyedRealisation
+ Nix.Daemon.Protocol: data UnkeyedValidPathInfo
+ Nix.Daemon.Protocol: data ValidPathInfo
+ Nix.Daemon.Protocol: data Version
+ Nix.Daemon.Protocol: data VersionNumber
+ Nix.Daemon.Protocol: defaultExitStatus :: Word32
+ Nix.Daemon.Protocol: errorVerbosity :: Verbosity
+ Nix.Daemon.Protocol: featureDeleteDeadSpecificReferrers :: Feature
+ Nix.Daemon.Protocol: featureDisableSetOptions :: Feature
+ Nix.Daemon.Protocol: featureRealisationWithPath :: Feature
+ Nix.Daemon.Protocol: getBuildMode :: Decoder BuildMode
+ Nix.Daemon.Protocol: getBuildResult :: StoreDir -> Version -> Decoder BuildResult
+ Nix.Daemon.Protocol: getClientMagic :: Decoder ()
+ Nix.Daemon.Protocol: getClientObsoleteFields :: Version -> Decoder ()
+ Nix.Daemon.Protocol: getContentAddress :: Decoder ContentAddress
+ Nix.Daemon.Protocol: getDerivedPath :: StoreDir -> Version -> Decoder DerivedPath
+ Nix.Daemon.Protocol: getDrvOutput :: StoreDir -> Version -> Decoder DrvOutput
+ Nix.Daemon.Protocol: getFeatures :: Decoder (Set Feature)
+ Nix.Daemon.Protocol: getGCAction :: Decoder GCAction
+ Nix.Daemon.Protocol: getGCPaths :: StoreDir -> Decoder GCPaths
+ Nix.Daemon.Protocol: getGCResult :: Decoder GCResult
+ Nix.Daemon.Protocol: getHandshakeInfo :: Version -> Decoder HandshakeInfo
+ Nix.Daemon.Protocol: getKeyedBuildResult :: StoreDir -> Version -> Decoder KeyedBuildResult
+ Nix.Daemon.Protocol: getKeyedBuildResults :: StoreDir -> Version -> Decoder [KeyedBuildResult]
+ Nix.Daemon.Protocol: getMissing :: StoreDir -> Decoder Missing
+ Nix.Daemon.Protocol: getNarHash :: Decoder NarHash
+ Nix.Daemon.Protocol: getOptionalContentAddress :: Decoder (Maybe ContentAddress)
+ Nix.Daemon.Protocol: getOptionalStorePath :: StoreDir -> Decoder (Maybe StorePath)
+ Nix.Daemon.Protocol: getOptionalUnkeyedRealisation :: StoreDir -> Version -> Decoder (Maybe UnkeyedRealisation)
+ Nix.Daemon.Protocol: getOutputMap :: StoreDir -> Decoder (Map OutputName (Maybe StorePath))
+ Nix.Daemon.Protocol: getOutputName :: Decoder OutputName
+ Nix.Daemon.Protocol: getRealisation :: StoreDir -> Version -> Decoder Realisation
+ Nix.Daemon.Protocol: getRoots :: StoreDir -> Decoder (Map StorePath (Set ByteString))
+ Nix.Daemon.Protocol: getServerMagic :: Decoder ()
+ Nix.Daemon.Protocol: getSignatureSet :: Decoder (Set Signature)
+ Nix.Daemon.Protocol: getStderrMessage :: Version -> Decoder StderrMessage
+ Nix.Daemon.Protocol: getStorePath :: StoreDir -> Decoder StorePath
+ Nix.Daemon.Protocol: getStorePathSet :: StoreDir -> Decoder (Set StorePath)
+ Nix.Daemon.Protocol: getTrust :: Decoder (Maybe Trust)
+ Nix.Daemon.Protocol: getUnkeyedRealisation :: StoreDir -> Version -> Decoder UnkeyedRealisation
+ Nix.Daemon.Protocol: getUnkeyedValidPathInfo :: StoreDir -> Version -> Decoder UnkeyedValidPathInfo
+ Nix.Daemon.Protocol: getValidPathInfo :: StoreDir -> Version -> Decoder ValidPathInfo
+ Nix.Daemon.Protocol: getVersionNumber :: Decoder VersionNumber
+ Nix.Daemon.Protocol: grammarText :: ByteString -> Text
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.Activity
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.ActivityId
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.ActivityType
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.BuildMode
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.BuildOutcome
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.BuildResult
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.ContentAddress
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.ContentAddressMethod
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.DaemonError
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.DerivedPath
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.DrvOutput
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.Failure
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.FailureStatus
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.Feature
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.Field
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.GCAction
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.GCPaths
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.GCResult
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.HandshakeInfo
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.KeyedBuildResult
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.Missing
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.NarHash
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.OutputName
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.OutputsSpec
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.Realisation
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.ResultType
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.Signature
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.StderrMessage
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.Success
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.SuccessStatus
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.Trust
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.UnkeyedRealisation
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.UnkeyedValidPathInfo
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.ValidPathInfo
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.Verbosity
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.Version
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Eq Nix.Daemon.Protocol.VersionNumber
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Ord Nix.Daemon.Protocol.Feature
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Ord Nix.Daemon.Protocol.OutputName
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Ord Nix.Daemon.Protocol.Signature
+ Nix.Daemon.Protocol: instance GHC.Internal.Classes.Ord Nix.Daemon.Protocol.VersionNumber
+ Nix.Daemon.Protocol: instance GHC.Internal.Enum.Bounded Nix.Daemon.Protocol.FailureStatus
+ Nix.Daemon.Protocol: instance GHC.Internal.Enum.Bounded Nix.Daemon.Protocol.SuccessStatus
+ Nix.Daemon.Protocol: instance GHC.Internal.Enum.Enum Nix.Daemon.Protocol.FailureStatus
+ Nix.Daemon.Protocol: instance GHC.Internal.Enum.Enum Nix.Daemon.Protocol.SuccessStatus
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.Activity
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.ActivityId
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.ActivityType
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.BuildMode
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.BuildOutcome
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.BuildResult
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.ContentAddress
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.ContentAddressMethod
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.DaemonError
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.DerivedPath
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.DrvOutput
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.Failure
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.FailureStatus
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.Feature
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.Field
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.GCAction
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.GCPaths
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.GCResult
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.HandshakeInfo
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.KeyedBuildResult
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.Missing
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.NarHash
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.OutputName
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.OutputsSpec
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.Realisation
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.ResultType
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.Signature
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.StderrMessage
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.Success
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.SuccessStatus
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.Trust
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.UnkeyedRealisation
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.UnkeyedValidPathInfo
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.ValidPathInfo
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.Verbosity
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.Version
+ Nix.Daemon.Protocol: instance GHC.Internal.Show.Show Nix.Daemon.Protocol.VersionNumber
+ Nix.Daemon.Protocol: latestVersionNumber :: VersionNumber
+ Nix.Daemon.Protocol: minimumVersionNumber :: VersionNumber
+ Nix.Daemon.Protocol: namedOutputs :: Set OutputName -> Maybe OutputsSpec
+ Nix.Daemon.Protocol: narHashDigest :: NarHash -> ByteString
+ Nix.Daemon.Protocol: narHashFromDigest :: ByteString -> Maybe NarHash
+ Nix.Daemon.Protocol: newtype ActivityId
+ Nix.Daemon.Protocol: newtype ActivityType
+ Nix.Daemon.Protocol: newtype Feature
+ Nix.Daemon.Protocol: newtype OutputName
+ Nix.Daemon.Protocol: newtype ResultType
+ Nix.Daemon.Protocol: newtype Verbosity
+ Nix.Daemon.Protocol: outputsSpecNames :: OutputsSpec -> Maybe (Set OutputName)
+ Nix.Daemon.Protocol: parseContentAddress :: Text -> Either Text ContentAddress
+ Nix.Daemon.Protocol: parseContentAddressMethod :: ByteString -> Either Text (ContentAddressMethod, Text)
+ Nix.Daemon.Protocol: parseSignature :: ByteString -> Either Text Signature
+ Nix.Daemon.Protocol: putBuildMode :: BuildMode -> Builder
+ Nix.Daemon.Protocol: putBuildResult :: StoreDir -> Version -> BuildResult -> Builder
+ Nix.Daemon.Protocol: putClientMagic :: Builder
+ Nix.Daemon.Protocol: putClientObsoleteFields :: Version -> Builder
+ Nix.Daemon.Protocol: putContentAddress :: ContentAddress -> Builder
+ Nix.Daemon.Protocol: putDerivedPath :: StoreDir -> Version -> DerivedPath -> Either Text Builder
+ Nix.Daemon.Protocol: putDrvOutput :: StoreDir -> Version -> DrvOutput -> Either Text Builder
+ Nix.Daemon.Protocol: putFeatures :: Set Feature -> Builder
+ Nix.Daemon.Protocol: putGCAction :: GCAction -> Builder
+ Nix.Daemon.Protocol: putGCPaths :: StoreDir -> GCPaths -> Builder
+ Nix.Daemon.Protocol: putGCResult :: GCResult -> Builder
+ Nix.Daemon.Protocol: putHandshakeInfo :: Version -> ByteString -> Maybe Trust -> Builder
+ Nix.Daemon.Protocol: putKeyedBuildResult :: StoreDir -> Version -> KeyedBuildResult -> Either Text Builder
+ Nix.Daemon.Protocol: putKeyedBuildResults :: StoreDir -> Version -> [KeyedBuildResult] -> (Builder, Maybe Text)
+ Nix.Daemon.Protocol: putMissing :: StoreDir -> Missing -> Builder
+ Nix.Daemon.Protocol: putNarHash :: NarHash -> Builder
+ Nix.Daemon.Protocol: putOptionalContentAddress :: Maybe ContentAddress -> Builder
+ Nix.Daemon.Protocol: putOptionalStorePath :: StoreDir -> Maybe StorePath -> Builder
+ Nix.Daemon.Protocol: putOptionalUnkeyedRealisation :: StoreDir -> Version -> Maybe UnkeyedRealisation -> Either Text Builder
+ Nix.Daemon.Protocol: putOutputMap :: StoreDir -> Map OutputName (Maybe StorePath) -> Builder
+ Nix.Daemon.Protocol: putOutputName :: OutputName -> Builder
+ Nix.Daemon.Protocol: putRealisation :: StoreDir -> Version -> Realisation -> Either Text Builder
+ Nix.Daemon.Protocol: putRoots :: StoreDir -> Map StorePath (Set ByteString) -> Builder
+ Nix.Daemon.Protocol: putServerMagic :: Builder
+ Nix.Daemon.Protocol: putSignatureSet :: Set Signature -> Builder
+ Nix.Daemon.Protocol: putStderrMessage :: Version -> StderrMessage -> Builder
+ Nix.Daemon.Protocol: putStorePath :: StoreDir -> StorePath -> Builder
+ Nix.Daemon.Protocol: putStorePathSet :: StoreDir -> Set StorePath -> Builder
+ Nix.Daemon.Protocol: putTrust :: Maybe Trust -> Builder
+ Nix.Daemon.Protocol: putUnkeyedRealisation :: StoreDir -> Version -> UnkeyedRealisation -> Either Text Builder
+ Nix.Daemon.Protocol: putUnkeyedValidPathInfo :: StoreDir -> Version -> UnkeyedValidPathInfo -> Builder
+ Nix.Daemon.Protocol: putValidPathInfo :: StoreDir -> Version -> ValidPathInfo -> Builder
+ Nix.Daemon.Protocol: putVersionNumber :: VersionNumber -> Builder
+ Nix.Daemon.Protocol: renderContentAddress :: ContentAddress -> Text
+ Nix.Daemon.Protocol: renderSignature :: Signature -> ByteString
+ Nix.Daemon.Protocol: resBuildLogLine :: ResultType
+ Nix.Daemon.Protocol: resPostBuildLogLine :: ResultType
+ Nix.Daemon.Protocol: sigBytes :: Signature -> ByteString
+ Nix.Daemon.Protocol: sigKeyName :: Signature -> ByteString
+ Nix.Daemon.Protocol: signatureFromParts :: ByteString -> ByteString -> Maybe Signature
+ Nix.Daemon.StoreChoice: AutoStore :: StoreTarget
+ Nix.Daemon.StoreChoice: DaemonSocket :: Maybe ByteString -> StoreTarget
+ Nix.Daemon.StoreChoice: DirectStore :: Maybe ByteString -> StoreChoice
+ Nix.Daemon.StoreChoice: LocalStore :: Maybe ByteString -> StoreTarget
+ Nix.Daemon.StoreChoice: SettingFlag :: StoreFlag
+ Nix.Daemon.StoreChoice: StoreProbe :: m StoreWriting -> (ByteString -> m AddressPresence) -> StoreProbe (m :: Type -> Type)
+ Nix.Daemon.StoreChoice: ThroughDaemon :: DaemonAddress -> StoreChoice
+ Nix.Daemon.StoreChoice: ValueFlag :: StoreFlag
+ Nix.Daemon.StoreChoice: [probePresence] :: StoreProbe (m :: Type -> Type) -> ByteString -> m AddressPresence
+ Nix.Daemon.StoreChoice: [probeWriting] :: StoreProbe (m :: Type -> Type) -> m StoreWriting
+ Nix.Daemon.StoreChoice: chooseStore :: Monad m => StoreProbe m -> ByteString -> StoreTarget -> m StoreChoice
+ Nix.Daemon.StoreChoice: data StoreChoice
+ Nix.Daemon.StoreChoice: data StoreFlag
+ Nix.Daemon.StoreChoice: data StoreProbe (m :: Type -> Type)
+ Nix.Daemon.StoreChoice: data StoreTarget
+ Nix.Daemon.StoreChoice: instance GHC.Internal.Classes.Eq Nix.Daemon.StoreChoice.StoreChoice
+ Nix.Daemon.StoreChoice: instance GHC.Internal.Classes.Eq Nix.Daemon.StoreChoice.StoreFlag
+ Nix.Daemon.StoreChoice: instance GHC.Internal.Classes.Eq Nix.Daemon.StoreChoice.StoreTarget
+ Nix.Daemon.StoreChoice: instance GHC.Internal.Show.Show Nix.Daemon.StoreChoice.StoreChoice
+ Nix.Daemon.StoreChoice: instance GHC.Internal.Show.Show Nix.Daemon.StoreChoice.StoreFlag
+ Nix.Daemon.StoreChoice: instance GHC.Internal.Show.Show Nix.Daemon.StoreChoice.StoreTarget
+ Nix.Daemon.StoreChoice: parseStoreTarget :: ByteString -> Either Text StoreTarget
+ Nix.Daemon.StoreChoice: parseStoreTargetOn :: PathRules -> ByteString -> Either Text StoreTarget
+ Nix.Daemon.StoreChoice: storeOverride :: PathRules -> StoreFlag -> Maybe ByteString -> Maybe ByteString -> Maybe ByteString -> Either Text (Map ByteString ByteString)
+ Nix.Daemon.StoreChoice: storeReference :: Maybe ByteString -> Maybe ByteString -> Maybe ByteString -> ByteString
+ Nix.Daemon.Wire: DecodeFailed :: DecodeError -> ByteString -> Decoding a
+ Nix.Daemon.Wire: Decoded :: a -> ByteString -> Decoding a
+ Nix.Daemon.Wire: InputEnded :: DecodeError
+ Nix.Daemon.Wire: Malformed :: Text -> DecodeError
+ Nix.Daemon.Wire: NeedInput :: (Maybe ByteString -> Decoding a) -> Decoding a
+ Nix.Daemon.Wire: data DecodeError
+ Nix.Daemon.Wire: data Decoder a
+ Nix.Daemon.Wire: data Decoding a
+ Nix.Daemon.Wire: feedInput :: Maybe ByteString -> Decoding a -> Decoding a
+ Nix.Daemon.Wire: getBool :: Decoder Bool
+ Nix.Daemon.Wire: getBytes :: Decoder ByteString
+ Nix.Daemon.Wire: getCount :: Decoder Int
+ Nix.Daemon.Wire: getFrame :: Decoder (Maybe ByteString)
+ Nix.Daemon.Wire: getInt64 :: Decoder Int64
+ Nix.Daemon.Wire: getList :: Decoder a -> Decoder [a]
+ Nix.Daemon.Wire: getWord32 :: Decoder Word32
+ Nix.Daemon.Wire: getWord64 :: Decoder Word64
+ Nix.Daemon.Wire: getWord8 :: Decoder Word8
+ Nix.Daemon.Wire: instance GHC.Internal.Base.Applicative Nix.Daemon.Wire.Decoder
+ Nix.Daemon.Wire: instance GHC.Internal.Base.Functor Nix.Daemon.Wire.Decoder
+ Nix.Daemon.Wire: instance GHC.Internal.Base.Monad Nix.Daemon.Wire.Decoder
+ Nix.Daemon.Wire: instance GHC.Internal.Classes.Eq Nix.Daemon.Wire.DecodeError
+ Nix.Daemon.Wire: instance GHC.Internal.Show.Show Nix.Daemon.Wire.DecodeError
+ Nix.Daemon.Wire: malformed :: Text -> Decoder a
+ Nix.Daemon.Wire: putBool :: Bool -> Builder
+ Nix.Daemon.Wire: putBytes :: ByteString -> Builder
+ Nix.Daemon.Wire: putFrame :: ByteString -> Builder
+ Nix.Daemon.Wire: putFrameEnd :: Builder
+ Nix.Daemon.Wire: putList :: (a -> Builder) -> [a] -> Builder
+ Nix.Daemon.Wire: putNum :: Integral a => a -> Builder
+ Nix.Daemon.Wire: runDecoder :: Decoder a -> ByteString -> Either DecodeError (a, ByteString)
+ Nix.Daemon.Wire: startDecoding :: Decoder a -> Decoding a
+ Nix.DependencyGraph: buildDepGraphFrom :: Monad m => (StorePath -> m (Either Text Derivation)) -> [StorePath] -> m (Either Text DepGraph)
+ Nix.Derivation: data DrvFile
+ Nix.Derivation: drvExtension :: Text
+ Nix.Derivation: drvFile :: Text -> Derivation -> Either BadStorePath DrvFile
+ Nix.Derivation: drvFileATerm :: DrvFile -> ByteString
+ Nix.Derivation: drvFileDerivation :: DrvFile -> Derivation
+ Nix.Derivation: drvFilePath :: DrvFile -> StorePath
+ Nix.Derivation: fixedOutput :: Derivation -> Maybe DerivationOutput
+ Nix.Derivation: fixedOutputModulo :: Derivation -> Maybe ByteString
+ Nix.Derivation: impureOutputHash :: Text
+ Nix.Derivation: inputAddressed :: Text -> [(Text, [Text])] -> Derivation -> Either BadStorePath DrvFile
+ Nix.Derivation: inputAddressedModulo :: [(Text, [Text])] -> Derivation -> ByteString
+ Nix.Derivation: instance GHC.Internal.Classes.Eq Nix.Derivation.DrvFile
+ Nix.Derivation: instance GHC.Internal.Show.Show Nix.Derivation.DrvFile
+ Nix.Develop.Capture: BadCaptureName :: BadStorePath -> CaptureFailure
+ Nix.Develop.Capture: NotBashBuilder :: CaptureFailure
+ Nix.Develop.Capture: NotRegularFile :: OutputObject
+ Nix.Develop.Capture: RegularFile :: Word64 -> OutputObject
+ Nix.Develop.Capture: UncapturableOutputs :: CaptureFailure
+ Nix.Develop.Capture: UnreadableStructuredAttrs :: Text -> CaptureFailure
+ Nix.Develop.Capture: captureDerivation :: StorePath -> Text -> [(Text, [Text])] -> Derivation -> Either CaptureFailure DrvFile
+ Nix.Develop.Capture: captureFailureMessage :: CaptureFailure -> Text
+ Nix.Develop.Capture: data CaptureFailure
+ Nix.Develop.Capture: data OutputObject
+ Nix.Develop.Capture: environmentOutput :: Map Text OutputObject -> Maybe Text
+ Nix.Develop.Capture: getEnvScriptContents :: ByteString -> ByteString
+ Nix.Develop.Capture: getEnvScriptName :: Text
+ Nix.Develop.Capture: getEnvScriptPath :: ByteString -> Either BadStorePath StorePath
+ Nix.Develop.Capture: instance GHC.Internal.Classes.Eq Nix.Develop.Capture.CaptureFailure
+ Nix.Develop.Capture: instance GHC.Internal.Classes.Eq Nix.Develop.Capture.OutputObject
+ Nix.Develop.Capture: instance GHC.Internal.Show.Show Nix.Develop.Capture.CaptureFailure
+ Nix.Develop.Capture: instance GHC.Internal.Show.Show Nix.Develop.Capture.OutputObject
+ Nix.Develop.Capture: noEnvironmentMessage :: Text
+ Nix.Develop.Environment: AssociativeArray :: Map Text Text -> Variable
+ Nix.Develop.Environment: AttrsFiles :: Text -> Text -> AttrsFiles
+ Nix.Develop.Environment: BuildEnvironment :: Map Text Variable -> Map Text Text -> Maybe AttrsFiles -> BuildEnvironment
+ Nix.Develop.Environment: EnvironmentScript :: ByteString -> [ScriptFile] -> EnvironmentScript
+ Nix.Develop.Environment: ExportedString :: Text -> Variable
+ Nix.Develop.Environment: IndexedArray :: [Text] -> Variable
+ Nix.Develop.Environment: Interactive :: Prompt -> ShellMode
+ Nix.Develop.Environment: Prompt :: ByteString -> ByteString -> ByteString -> Prompt
+ Nix.Develop.Environment: RunCommand :: NonEmpty ByteString -> ShellMode
+ Nix.Develop.Environment: RunPhase :: ByteString -> ShellMode
+ Nix.Develop.Environment: ScriptDirectories :: ByteString -> ByteString -> ScriptDirectories
+ Nix.Develop.Environment: ScriptFile :: ByteString -> ByteString -> ScriptFile
+ Nix.Develop.Environment: Shell :: ByteString -> ShellMode -> ByteString -> Shell
+ Nix.Develop.Environment: ShellString :: Text -> Variable
+ Nix.Develop.Environment: [attrsJson] :: AttrsFiles -> Text
+ Nix.Develop.Environment: [attrsSh] :: AttrsFiles -> Text
+ Nix.Develop.Environment: [bashPromptPrefix] :: Prompt -> ByteString
+ Nix.Develop.Environment: [bashPromptSuffix] :: Prompt -> ByteString
+ Nix.Develop.Environment: [bashPrompt] :: Prompt -> ByteString
+ Nix.Develop.Environment: [beAttrsFiles] :: BuildEnvironment -> Maybe AttrsFiles
+ Nix.Develop.Environment: [beFunctions] :: BuildEnvironment -> Map Text Text
+ Nix.Develop.Environment: [beVariables] :: BuildEnvironment -> Map Text Variable
+ Nix.Develop.Environment: [scriptFileContents] :: ScriptFile -> ByteString
+ Nix.Develop.Environment: [scriptFilePath] :: ScriptFile -> ByteString
+ Nix.Develop.Environment: [scriptFiles] :: EnvironmentScript -> [ScriptFile]
+ Nix.Develop.Environment: [scriptText] :: EnvironmentScript -> ByteString
+ Nix.Develop.Environment: [shellMode] :: Shell -> ShellMode
+ Nix.Develop.Environment: [shellProgram] :: Shell -> ByteString
+ Nix.Develop.Environment: [shellRcfile] :: Shell -> ByteString
+ Nix.Develop.Environment: [temporaryDirectory] :: ScriptDirectories -> ByteString
+ Nix.Develop.Environment: [workingDirectory] :: ScriptDirectories -> ByteString
+ Nix.Develop.Environment: appendPath :: ByteString -> ByteString -> ByteString
+ Nix.Develop.Environment: buildEnvironmentJson :: BuildEnvironment -> Json
+ Nix.Develop.Environment: data AttrsFiles
+ Nix.Develop.Environment: data BuildEnvironment
+ Nix.Develop.Environment: data EnvironmentScript
+ Nix.Develop.Environment: data Prompt
+ Nix.Develop.Environment: data ScriptDirectories
+ Nix.Develop.Environment: data ScriptFile
+ Nix.Develop.Environment: data Shell
+ Nix.Develop.Environment: data ShellMode
+ Nix.Develop.Environment: data Variable
+ Nix.Develop.Environment: environmentScript :: ScriptDirectories -> BuildEnvironment -> Either Text EnvironmentScript
+ Nix.Develop.Environment: escapeShellArgAlways :: ByteString -> ByteString
+ Nix.Develop.Environment: ignoreVars :: Set Text
+ Nix.Develop.Environment: instance GHC.Internal.Classes.Eq Nix.Develop.Environment.AttrsFiles
+ Nix.Develop.Environment: instance GHC.Internal.Classes.Eq Nix.Develop.Environment.BuildEnvironment
+ Nix.Develop.Environment: instance GHC.Internal.Classes.Eq Nix.Develop.Environment.EnvironmentScript
+ Nix.Develop.Environment: instance GHC.Internal.Classes.Eq Nix.Develop.Environment.Prompt
+ Nix.Develop.Environment: instance GHC.Internal.Classes.Eq Nix.Develop.Environment.ScriptDirectories
+ Nix.Develop.Environment: instance GHC.Internal.Classes.Eq Nix.Develop.Environment.ScriptFile
+ Nix.Develop.Environment: instance GHC.Internal.Classes.Eq Nix.Develop.Environment.Shell
+ Nix.Develop.Environment: instance GHC.Internal.Classes.Eq Nix.Develop.Environment.ShellMode
+ Nix.Develop.Environment: instance GHC.Internal.Classes.Eq Nix.Develop.Environment.Variable
+ Nix.Develop.Environment: instance GHC.Internal.Show.Show Nix.Develop.Environment.AttrsFiles
+ Nix.Develop.Environment: instance GHC.Internal.Show.Show Nix.Develop.Environment.BuildEnvironment
+ Nix.Develop.Environment: instance GHC.Internal.Show.Show Nix.Develop.Environment.EnvironmentScript
+ Nix.Develop.Environment: instance GHC.Internal.Show.Show Nix.Develop.Environment.Prompt
+ Nix.Develop.Environment: instance GHC.Internal.Show.Show Nix.Develop.Environment.ScriptDirectories
+ Nix.Develop.Environment: instance GHC.Internal.Show.Show Nix.Develop.Environment.ScriptFile
+ Nix.Develop.Environment: instance GHC.Internal.Show.Show Nix.Develop.Environment.Shell
+ Nix.Develop.Environment: instance GHC.Internal.Show.Show Nix.Develop.Environment.ShellMode
+ Nix.Develop.Environment: instance GHC.Internal.Show.Show Nix.Develop.Environment.Variable
+ Nix.Develop.Environment: parseBuildEnvironment :: ByteString -> Either Text BuildEnvironment
+ Nix.Develop.Environment: renderRcfile :: Shell -> EnvironmentScript -> ByteString
+ Nix.Develop.Shell: CallerEnvironment :: EnvironmentBase
+ Nix.Develop.Shell: DevelopHost :: (ByteString -> IO ByteString) -> ((ByteString -> ByteString) -> IO ByteString) -> IO (Map ByteString ByteString) -> ([ByteString] -> Map ByteString ByteString -> IO Void) -> DevelopHost
+ Nix.Develop.Shell: EmptyEnvironment :: EnvironmentBase
+ Nix.Develop.Shell: EnvironmentChanges :: EnvironmentBase -> Set ByteString -> Set ByteString -> Map ByteString ByteString -> EnvironmentChanges
+ Nix.Develop.Shell: [createRcfile] :: DevelopHost -> (ByteString -> ByteString) -> IO ByteString
+ Nix.Develop.Shell: [ecBase] :: EnvironmentChanges -> EnvironmentBase
+ Nix.Develop.Shell: [ecKeep] :: EnvironmentChanges -> Set ByteString
+ Nix.Develop.Shell: [ecSet] :: EnvironmentChanges -> Map ByteString ByteString
+ Nix.Develop.Shell: [ecUnset] :: EnvironmentChanges -> Set ByteString
+ Nix.Develop.Shell: [makeTemporaryDirectory] :: DevelopHost -> ByteString -> IO ByteString
+ Nix.Develop.Shell: [processEnvironment] :: DevelopHost -> IO (Map ByteString ByteString)
+ Nix.Develop.Shell: [replaceProcess] :: DevelopHost -> [ByteString] -> Map ByteString ByteString -> IO Void
+ Nix.Develop.Shell: bashProgram :: ByteString
+ Nix.Develop.Shell: data DevelopHost
+ Nix.Develop.Shell: data EnvironmentBase
+ Nix.Develop.Shell: data EnvironmentChanges
+ Nix.Develop.Shell: developHost :: Either Text DevelopHost
+ Nix.Develop.Shell: instance GHC.Internal.Classes.Eq Nix.Develop.Shell.EnvironmentBase
+ Nix.Develop.Shell: instance GHC.Internal.Classes.Eq Nix.Develop.Shell.EnvironmentChanges
+ Nix.Develop.Shell: instance GHC.Internal.Show.Show Nix.Develop.Shell.EnvironmentBase
+ Nix.Develop.Shell: instance GHC.Internal.Show.Show Nix.Develop.Shell.EnvironmentChanges
+ Nix.Develop.Shell: shellArguments :: ShellMode -> ByteString -> [ByteString]
+ Nix.Develop.Shell: shellEnvironment :: EnvironmentChanges -> ByteString -> Map ByteString ByteString -> Either Text (Map ByteString ByteString)
+ Nix.Develop.Shell: shellModeFor :: Maybe (NonEmpty ByteString) -> Maybe ByteString -> Prompt -> Either Text ShellMode
+ Nix.DrvName: drvNameDash :: (s -> Maybe (Char, s)) -> s -> Maybe Int
+ Nix.Environment: argumentBytes :: String -> IO (Maybe ByteString)
+ Nix.Eval: VPathHeld :: Text -> HeldBytes -> NixValue
+ Nix.Eval: VStrHeld :: ByteString -> StringContext -> HeldBytes -> NixValue
+ Nix.Eval: [epExperimentalFeatures] :: EvalPolicy -> FeatureSet
+ Nix.Eval: [epImportFromDerivation] :: EvalPolicy -> ImportFromDerivation
+ Nix.Eval: addEvaluatedTrace :: MonadEval m => (Text -> Text) -> m Text -> m a -> m a
+ Nix.Eval: compileSource :: MonadCData m => ParsedSource -> m Word32
+ Nix.Eval: deepForce :: MonadEval m => NixValue -> m ()
+ Nix.Eval: evalParsed :: MonadEval m => m Env -> ParsedSource -> m NixValue
+ Nix.Eval: fetchArchiveToStore :: MonadEval m => Text -> Text -> Maybe (ByteString, ByteString -> Text) -> m (Either FetchFailure Text)
+ Nix.Eval: fetchUrlBytes :: MonadEval m => Text -> m (Either Text ByteString)
+ Nix.Eval: findInSearchPath :: MonadEval m => [Thunk] -> ByteString -> m Text
+ Nix.Eval: inputModuloHashes :: MonadEval m => Map StorePath [Text] -> m [(Text, [Text])]
+ Nix.Eval: listedBuiltins :: [Builtin]
+ Nix.Eval: pattern VPath :: Text -> NixValue
+ Nix.Eval: pattern VStr :: ByteString -> StringContext -> NixValue
+ Nix.Eval: pinnedFetchHeld :: MonadEval m => StorePath -> m Bool
+ Nix.Eval: realiseContext :: MonadEval m => StringContext -> m (Either ContextRefusal ())
+ Nix.Eval.AllocSite: EnvCall :: EnvSite
+ Nix.Eval.AllocSite: EnvCallFormals :: EnvSite
+ Nix.Eval.AllocSite: EnvClosure :: EnvSite
+ Nix.Eval.AllocSite: EnvInheritFrom :: EnvSite
+ Nix.Eval.AllocSite: EnvLet :: EnvSite
+ Nix.Eval.AllocSite: EnvLetCapture :: EnvSite
+ Nix.Eval.AllocSite: EnvRec :: EnvSite
+ Nix.Eval.AllocSite: EnvRecCapture :: EnvSite
+ Nix.Eval.AllocSite: EnvRoot :: EnvSite
+ Nix.Eval.AllocSite: EnvWith :: EnvSite
+ Nix.Eval.AllocSite: SetDerivationStrict :: SetSite
+ Nix.Eval.AllocSite: SetFetchGit :: SetSite
+ Nix.Eval.AllocSite: SetFromJSON :: SetSite
+ Nix.Eval.AllocSite: SetFromTOML :: SetSite
+ Nix.Eval.AllocSite: SetFunctionArgs :: SetSite
+ Nix.Eval.AllocSite: SetGetContext :: SetSite
+ Nix.Eval.AllocSite: SetGroupBy :: SetSite
+ Nix.Eval.AllocSite: SetIntersectAttrs :: SetSite
+ Nix.Eval.AllocSite: SetListToAttrs :: SetSite
+ Nix.Eval.AllocSite: SetLiteral :: SetSite
+ Nix.Eval.AllocSite: SetMapAttrs :: SetSite
+ Nix.Eval.AllocSite: SetParseDrvName :: SetSite
+ Nix.Eval.AllocSite: SetParseFlakeRef :: SetSite
+ Nix.Eval.AllocSite: SetPartition :: SetSite
+ Nix.Eval.AllocSite: SetPosition :: SetSite
+ Nix.Eval.AllocSite: SetReadDir :: SetSite
+ Nix.Eval.AllocSite: SetRec :: SetSite
+ Nix.Eval.AllocSite: SetRemoveAttrs :: SetSite
+ Nix.Eval.AllocSite: SetRoot :: SetSite
+ Nix.Eval.AllocSite: SetScope :: SetSite
+ Nix.Eval.AllocSite: SetTryEval :: SetSite
+ Nix.Eval.AllocSite: SetUpdate :: SetSite
+ Nix.Eval.AllocSite: SetZipAttrsWith :: SetSite
+ Nix.Eval.AllocSite: data EnvSite
+ Nix.Eval.AllocSite: data SetSite
+ Nix.Eval.AllocSite: envSiteIndex :: EnvSite -> Word32
+ Nix.Eval.AllocSite: envSiteName :: EnvSite -> ByteString
+ Nix.Eval.AllocSite: instance GHC.Internal.Classes.Eq Nix.Eval.AllocSite.EnvSite
+ Nix.Eval.AllocSite: instance GHC.Internal.Classes.Eq Nix.Eval.AllocSite.SetSite
+ Nix.Eval.AllocSite: instance GHC.Internal.Classes.Ord Nix.Eval.AllocSite.EnvSite
+ Nix.Eval.AllocSite: instance GHC.Internal.Classes.Ord Nix.Eval.AllocSite.SetSite
+ Nix.Eval.AllocSite: instance GHC.Internal.Enum.Bounded Nix.Eval.AllocSite.EnvSite
+ Nix.Eval.AllocSite: instance GHC.Internal.Enum.Bounded Nix.Eval.AllocSite.SetSite
+ Nix.Eval.AllocSite: instance GHC.Internal.Enum.Enum Nix.Eval.AllocSite.EnvSite
+ Nix.Eval.AllocSite: instance GHC.Internal.Enum.Enum Nix.Eval.AllocSite.SetSite
+ Nix.Eval.AllocSite: instance GHC.Internal.Show.Show Nix.Eval.AllocSite.EnvSite
+ Nix.Eval.AllocSite: instance GHC.Internal.Show.Show Nix.Eval.AllocSite.SetSite
+ Nix.Eval.AllocSite: setSiteIndex :: SetSite -> Word32
+ Nix.Eval.AllocSite: setSiteName :: SetSite -> ByteString
+ Nix.Eval.AutoCall: autoCallFunction :: MonadEval m => AutoArgs -> NixValue -> m NixValue
+ Nix.Eval.AutoCall: type AutoArgs = Map Text Thunk
+ Nix.Eval.Builtin: Abort :: Builtin
+ Nix.Eval.Builtin: Add :: Builtin
+ Nix.Eval.Builtin: AddDrvOutputDependencies :: Builtin
+ Nix.Eval.Builtin: AddErrorContext :: Builtin
+ Nix.Eval.Builtin: All :: Builtin
+ Nix.Eval.Builtin: Any :: Builtin
+ Nix.Eval.Builtin: AppendContext :: Builtin
+ Nix.Eval.Builtin: AttrNames :: Builtin
+ Nix.Eval.Builtin: AttrValues :: Builtin
+ Nix.Eval.Builtin: BaseNameOf :: Builtin
+ Nix.Eval.Builtin: BitAnd :: Builtin
+ Nix.Eval.Builtin: BitOr :: Builtin
+ Nix.Eval.Builtin: BitXor :: Builtin
+ Nix.Eval.Builtin: Break :: Builtin
+ Nix.Eval.Builtin: CatAttrs :: Builtin
+ Nix.Eval.Builtin: Ceil :: Builtin
+ Nix.Eval.Builtin: CompareVersions :: Builtin
+ Nix.Eval.Builtin: ConcatLists :: Builtin
+ Nix.Eval.Builtin: ConcatMap :: Builtin
+ Nix.Eval.Builtin: ConcatStringsSep :: Builtin
+ Nix.Eval.Builtin: ConvertHash :: Builtin
+ Nix.Eval.Builtin: DeepSeq :: Builtin
+ Nix.Eval.Builtin: DerivationStrict :: Builtin
+ Nix.Eval.Builtin: DirOf :: Builtin
+ Nix.Eval.Builtin: Div :: Builtin
+ Nix.Eval.Builtin: Elem :: Builtin
+ Nix.Eval.Builtin: ElemAt :: Builtin
+ Nix.Eval.Builtin: FetchGit :: Builtin
+ Nix.Eval.Builtin: FetchMercurial :: Builtin
+ Nix.Eval.Builtin: FetchTarball :: Builtin
+ Nix.Eval.Builtin: Fetchurl :: Builtin
+ Nix.Eval.Builtin: Filter :: Builtin
+ Nix.Eval.Builtin: FilterSource :: Builtin
+ Nix.Eval.Builtin: FindFile :: Builtin
+ Nix.Eval.Builtin: FlakeRefToString :: Builtin
+ Nix.Eval.Builtin: Floor :: Builtin
+ Nix.Eval.Builtin: FoldlStrict :: Builtin
+ Nix.Eval.Builtin: FromJSON :: Builtin
+ Nix.Eval.Builtin: FromTOML :: Builtin
+ Nix.Eval.Builtin: FunctionArgs :: Builtin
+ Nix.Eval.Builtin: GenList :: Builtin
+ Nix.Eval.Builtin: GenericClosure :: Builtin
+ Nix.Eval.Builtin: GetAttr :: Builtin
+ Nix.Eval.Builtin: GetContext :: Builtin
+ Nix.Eval.Builtin: GetEnv :: Builtin
+ Nix.Eval.Builtin: GetFlake :: Builtin
+ Nix.Eval.Builtin: GroupBy :: Builtin
+ Nix.Eval.Builtin: HasAttr :: Builtin
+ Nix.Eval.Builtin: HasContext :: Builtin
+ Nix.Eval.Builtin: HashFile :: Builtin
+ Nix.Eval.Builtin: HashString :: Builtin
+ Nix.Eval.Builtin: Head :: Builtin
+ Nix.Eval.Builtin: Import :: Builtin
+ Nix.Eval.Builtin: IntersectAttrs :: Builtin
+ Nix.Eval.Builtin: IsAttrs :: Builtin
+ Nix.Eval.Builtin: IsBool :: Builtin
+ Nix.Eval.Builtin: IsFloat :: Builtin
+ Nix.Eval.Builtin: IsFunction :: Builtin
+ Nix.Eval.Builtin: IsInt :: Builtin
+ Nix.Eval.Builtin: IsList :: Builtin
+ Nix.Eval.Builtin: IsNull :: Builtin
+ Nix.Eval.Builtin: IsPath :: Builtin
+ Nix.Eval.Builtin: IsString :: Builtin
+ Nix.Eval.Builtin: Length :: Builtin
+ Nix.Eval.Builtin: LessThan :: Builtin
+ Nix.Eval.Builtin: ListToAttrs :: Builtin
+ Nix.Eval.Builtin: Map :: Builtin
+ Nix.Eval.Builtin: MapAttrs :: Builtin
+ Nix.Eval.Builtin: Match :: Builtin
+ Nix.Eval.Builtin: Mul :: Builtin
+ Nix.Eval.Builtin: ParseDrvName :: Builtin
+ Nix.Eval.Builtin: ParseFlakeRef :: Builtin
+ Nix.Eval.Builtin: Partition :: Builtin
+ Nix.Eval.Builtin: Path :: Builtin
+ Nix.Eval.Builtin: PathExists :: Builtin
+ Nix.Eval.Builtin: Placeholder :: Builtin
+ Nix.Eval.Builtin: ReadDir :: Builtin
+ Nix.Eval.Builtin: ReadFile :: Builtin
+ Nix.Eval.Builtin: ReadFileType :: Builtin
+ Nix.Eval.Builtin: RemoveAttrs :: Builtin
+ Nix.Eval.Builtin: ReplaceStrings :: Builtin
+ Nix.Eval.Builtin: ScopedImport :: Builtin
+ Nix.Eval.Builtin: Seq :: Builtin
+ Nix.Eval.Builtin: Sort :: Builtin
+ Nix.Eval.Builtin: Split :: Builtin
+ Nix.Eval.Builtin: SplitVersion :: Builtin
+ Nix.Eval.Builtin: StorePath :: Builtin
+ Nix.Eval.Builtin: StringLength :: Builtin
+ Nix.Eval.Builtin: Sub :: Builtin
+ Nix.Eval.Builtin: Substring :: Builtin
+ Nix.Eval.Builtin: Tail :: Builtin
+ Nix.Eval.Builtin: Throw :: Builtin
+ Nix.Eval.Builtin: ToFile :: Builtin
+ Nix.Eval.Builtin: ToJSON :: Builtin
+ Nix.Eval.Builtin: ToPath :: Builtin
+ Nix.Eval.Builtin: ToString :: Builtin
+ Nix.Eval.Builtin: ToXML :: Builtin
+ Nix.Eval.Builtin: Trace :: Builtin
+ Nix.Eval.Builtin: TraceVerbose :: Builtin
+ Nix.Eval.Builtin: TryEval :: Builtin
+ Nix.Eval.Builtin: TypeOf :: Builtin
+ Nix.Eval.Builtin: UnsafeDiscardOutputDependency :: Builtin
+ Nix.Eval.Builtin: UnsafeDiscardStringContext :: Builtin
+ Nix.Eval.Builtin: UnsafeGetAttrPos :: Builtin
+ Nix.Eval.Builtin: Warn :: Builtin
+ Nix.Eval.Builtin: ZipAttrsWith :: Builtin
+ Nix.Eval.Builtin: builtinAtIndex :: Word32 -> Maybe Builtin
+ Nix.Eval.Builtin: builtinIndex :: Builtin -> Word32
+ Nix.Eval.Builtin: builtinName :: Builtin -> Text
+ Nix.Eval.Builtin: builtinNamed :: Text -> Maybe Builtin
+ Nix.Eval.Builtin: data Builtin
+ Nix.Eval.Builtin: instance GHC.Internal.Classes.Eq Nix.Eval.Builtin.Builtin
+ Nix.Eval.Builtin: instance GHC.Internal.Classes.Ord Nix.Eval.Builtin.Builtin
+ Nix.Eval.Builtin: instance GHC.Internal.Enum.Bounded Nix.Eval.Builtin.Builtin
+ Nix.Eval.Builtin: instance GHC.Internal.Enum.Enum Nix.Eval.Builtin.Builtin
+ Nix.Eval.Builtin: instance GHC.Internal.Show.Show Nix.Eval.Builtin.Builtin
+ Nix.Eval.CAttrSet: CAttrSetDone :: CAttrSetStep
+ Nix.Eval.CAttrSet: CAttrSetEntry :: Symbol -> PosIdx -> CThunkPtr -> CAttrSetWalk -> CAttrSetStep
+ Nix.Eval.CAttrSet: cattrsetEmpty :: CAttrSet
+ Nix.Eval.CAttrSet: cattrsetFind :: MonadCData m => CAttrSet -> Symbol -> m (Maybe (PosIdx, CThunkPtr))
+ Nix.Eval.CAttrSet: cattrsetFromNames :: MonadCData m => SetSite -> [Symbol] -> m FlatCAttrSet
+ Nix.Eval.CAttrSet: cattrsetMember :: MonadCData m => CAttrSet -> Symbol -> m Bool
+ Nix.Eval.CAttrSet: cattrsetUpdate :: MonadCData m => SetSite -> CAttrSet -> CAttrSet -> m CAttrSet
+ Nix.Eval.CAttrSet: cattrsetWalk :: MonadCData m => CAttrSet -> m CAttrSetWalk
+ Nix.Eval.CAttrSet: cattrsetWalkNext :: MonadCData m => CAttrSetWalk -> m CAttrSetStep
+ Nix.Eval.CAttrSet: data CAttrSetStep
+ Nix.Eval.CAttrSet: data CAttrSetWalk
+ Nix.Eval.CAttrSet: data FlatCAttrSet
+ Nix.Eval.CAttrSet: flatCAttrSet :: FlatCAttrSet -> CAttrSet
+ Nix.Eval.CBytecode: attrsPlain :: Word8
+ Nix.Eval.CBytecode: attrsRec :: Word8
+ Nix.Eval.CBytecode: attrsRecOverrides :: Word8
+ Nix.Eval.CBytecode: cbcEmitString :: MonadCData m => ByteString -> m Word32
+ Nix.Eval.CBytecode: cbcEmitText :: MonadCData m => Text -> m Word32
+ Nix.Eval.CBytecode: cbcString :: MonadCData m => Word32 -> m CStrPtr
+ Nix.Eval.CBytecode: cbcStringBytes :: MonadCData m => Word32 -> m ByteString
+ Nix.Eval.CBytecode: cbcStringText :: MonadCData m => Word32 -> m Text
+ Nix.Eval.CBytecode: formalDefault :: Word32
+ Nix.Eval.CBytecode: formalNoDefault :: Word32
+ Nix.Eval.CBytecode: formalSharedDefault :: Word32
+ Nix.Eval.CBytecode: pattern OpPos :: Word8
+ Nix.Eval.CCtxStr: pattern SceAllOutputs :: Word8
+ Nix.Eval.CCtxStr: pattern SceDrvOutput :: Word8
+ Nix.Eval.CCtxStr: pattern ScePlain :: Word8
+ Nix.Eval.CData: cdataIO :: MonadCData m => IO a -> m a
+ Nix.Eval.CData: class Monad m => MonadCData (m :: Type -> Type)
+ Nix.Eval.CData: data CData a
+ Nix.Eval.CData: instance GHC.Internal.Base.Applicative Nix.Eval.CData.CData
+ Nix.Eval.CData: instance GHC.Internal.Base.Functor Nix.Eval.CData.CData
+ Nix.Eval.CData: instance GHC.Internal.Base.Monad Nix.Eval.CData.CData
+ Nix.Eval.CData: instance Nix.Eval.CData.MonadCData GHC.Internal.Types.IO
+ Nix.Eval.CData: instance Nix.Eval.CData.MonadCData Nix.Eval.CData.CData
+ Nix.Eval.CData: liftCData :: MonadCData m => CData a -> m a
+ Nix.Eval.CData: readImmutable :: CData a -> a
+ Nix.Eval.CData: runCData :: CData a -> IO a
+ Nix.Eval.CData: runCDataPure :: CData a -> a
+ Nix.Eval.CEnv: cenvNameTable :: MonadCData m => Ptr NnEnv -> m (Ptr ())
+ Nix.Eval.CEnv: cenvNewScoped :: MonadCData m => EnvSite -> Word32 -> Ptr NnEnv -> Ptr () -> Ptr (Ptr ()) -> Word32 -> m (Ptr NnEnv)
+ Nix.Eval.CEnv: cenvResolveWith :: MonadCData m => Ptr (Ptr ()) -> Word32 -> Ptr () -> m ()
+ Nix.Eval.CEnv: cenvWithOwner :: MonadCData m => Ptr NnEnv -> m (Ptr NnEnv)
+ Nix.Eval.CLambda: clambdaLambdaNameSym :: MonadCData m => CLambdaPtr -> m Word32
+ Nix.Eval.CLambda: clambdaShape :: Word8 -> Word8 -> Word32 -> Word32
+ Nix.Eval.CLambda: clambdaShapeAllowExtra :: Word32 -> Word8
+ Nix.Eval.CLambda: clambdaShapeFormalCount :: Word32 -> Word32
+ Nix.Eval.CLambda: clambdaShapeFormalsType :: Word32 -> Word8
+ Nix.Eval.CLambda: pattern FormalsName :: Word8
+ Nix.Eval.CLambda: pattern FormalsNamedSet :: Word8
+ Nix.Eval.CLambda: pattern FormalsSet :: Word8
+ Nix.Eval.CPrimop: cprimopAppArg :: MonadCData m => CPrimopAppPtr -> Word16 -> m CThunkPtr
+ Nix.Eval.CPrimop: cprimopAppForced :: MonadCData m => CPrimopAppPtr -> m Word16
+ Nix.Eval.CPrimop: cprimopAppNew :: MonadCData m => Word32 -> Word16 -> [CThunkPtr] -> m CPrimopAppPtr
+ Nix.Eval.CPrimop: cprimopAppPrimop :: MonadCData m => CPrimopAppPtr -> m Word32
+ Nix.Eval.CPrimop: cprimopAppTaken :: MonadCData m => CPrimopAppPtr -> m Word16
+ Nix.Eval.CPrimop: data NnPrimopApp
+ Nix.Eval.CPrimop: type CPrimopAppPtr = Ptr NnPrimopApp
+ Nix.Eval.CRegion: RegionFigures :: Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> [SizeClass] -> [Threshold] -> [Tenure] -> RegionFigures
+ Nix.Eval.CRegion: RegionsCensus :: Regions
+ Nix.Eval.CRegion: RegionsCollect :: Regions
+ Nix.Eval.CRegion: RegionsOff :: Regions
+ Nix.Eval.CRegion: SizeClass :: Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> SizeClass
+ Nix.Eval.CRegion: Tenure :: Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> [Word64] -> Tenure
+ Nix.Eval.CRegion: Threshold :: Word64 -> Word64 -> Word64 -> Word64 -> [Word64] -> Threshold
+ Nix.Eval.CRegion: [classAllocated] :: SizeClass -> Word64
+ Nix.Eval.CRegion: [classCloses] :: SizeClass -> Word64
+ Nix.Eval.CRegion: [classEntered] :: SizeClass -> Word64
+ Nix.Eval.CRegion: [classExamined] :: SizeClass -> Word64
+ Nix.Eval.CRegion: [classFloor] :: SizeClass -> Word64
+ Nix.Eval.CRegion: [classRecords] :: SizeClass -> Word64
+ Nix.Eval.CRegion: [classSurviving] :: SizeClass -> Word64
+ Nix.Eval.CRegion: [regionAllocated] :: RegionFigures -> Word64
+ Nix.Eval.CRegion: [regionClasses] :: RegionFigures -> [SizeClass]
+ Nix.Eval.CRegion: [regionCloses] :: RegionFigures -> Word64
+ Nix.Eval.CRegion: [regionDepth] :: RegionFigures -> Word64
+ Nix.Eval.CRegion: [regionOutside] :: RegionFigures -> Word64
+ Nix.Eval.CRegion: [regionRecords] :: RegionFigures -> Word64
+ Nix.Eval.CRegion: [regionResurrectedBytes] :: RegionFigures -> Word64
+ Nix.Eval.CRegion: [regionResurrected] :: RegionFigures -> Word64
+ Nix.Eval.CRegion: [regionTenures] :: RegionFigures -> [Tenure]
+ Nix.Eval.CRegion: [regionThresholds] :: RegionFigures -> [Threshold]
+ Nix.Eval.CRegion: [regionUnplaced] :: RegionFigures -> Word64
+ Nix.Eval.CRegion: [tenureBudget] :: Tenure -> Word64
+ Nix.Eval.CRegion: [tenureBytes] :: Tenure -> Word64
+ Nix.Eval.CRegion: [tenureCloses] :: Tenure -> Word64
+ Nix.Eval.CRegion: [tenureEntered] :: Tenure -> Word64
+ Nix.Eval.CRegion: [tenureExamined] :: Tenure -> Word64
+ Nix.Eval.CRegion: [tenureFullFreed] :: Tenure -> Word64
+ Nix.Eval.CRegion: [tenureFull] :: Tenure -> Word64
+ Nix.Eval.CRegion: [tenureHeld] :: Tenure -> Word64
+ Nix.Eval.CRegion: [tenurePeaks] :: Tenure -> [Word64]
+ Nix.Eval.CRegion: [tenureReached] :: Tenure -> Word64
+ Nix.Eval.CRegion: [tenureRecords] :: Tenure -> Word64
+ Nix.Eval.CRegion: [tenureRemembered] :: Tenure -> Word64
+ Nix.Eval.CRegion: [tenureResurrectedBytes] :: Tenure -> Word64
+ Nix.Eval.CRegion: [tenureResurrected] :: Tenure -> Word64
+ Nix.Eval.CRegion: [thresholdBytes] :: Threshold -> Word64
+ Nix.Eval.CRegion: [thresholdCloses] :: Threshold -> Word64
+ Nix.Eval.CRegion: [thresholdEntered] :: Threshold -> Word64
+ Nix.Eval.CRegion: [thresholdExamined] :: Threshold -> Word64
+ Nix.Eval.CRegion: [thresholdPeaks] :: Threshold -> [Word64]
+ Nix.Eval.CRegion: data RegionFigures
+ Nix.Eval.CRegion: data Regions
+ Nix.Eval.CRegion: data SizeClass
+ Nix.Eval.CRegion: data Tenure
+ Nix.Eval.CRegion: data Threshold
+ Nix.Eval.CRegion: inRegion :: Regions -> IO a -> IO a
+ Nix.Eval.CRegion: instance GHC.Internal.Classes.Eq Nix.Eval.CRegion.RegionFigures
+ Nix.Eval.CRegion: instance GHC.Internal.Classes.Eq Nix.Eval.CRegion.Regions
+ Nix.Eval.CRegion: instance GHC.Internal.Classes.Eq Nix.Eval.CRegion.SizeClass
+ Nix.Eval.CRegion: instance GHC.Internal.Classes.Eq Nix.Eval.CRegion.Tenure
+ Nix.Eval.CRegion: instance GHC.Internal.Classes.Eq Nix.Eval.CRegion.Threshold
+ Nix.Eval.CRegion: instance GHC.Internal.Show.Show Nix.Eval.CRegion.RegionFigures
+ Nix.Eval.CRegion: instance GHC.Internal.Show.Show Nix.Eval.CRegion.Regions
+ Nix.Eval.CRegion: instance GHC.Internal.Show.Show Nix.Eval.CRegion.SizeClass
+ Nix.Eval.CRegion: instance GHC.Internal.Show.Show Nix.Eval.CRegion.Tenure
+ Nix.Eval.CRegion: instance GHC.Internal.Show.Show Nix.Eval.CRegion.Threshold
+ Nix.Eval.CRegion: regionFigures :: IO (Either CStatusError RegionFigures)
+ Nix.Eval.CRegion: regionsRunning :: IO Regions
+ Nix.Eval.CRegion: renderRegionFigures :: RegionFigures -> ByteString
+ Nix.Eval.CRegion: withRegions :: Regions -> IO a -> IO a
+ Nix.Eval.CRoots: crootsAddEnv :: MonadCData m => Ptr NnEnv -> m ()
+ Nix.Eval.CRoots: crootsAddThunk :: MonadCData m => CThunkPtr -> m ()
+ Nix.Eval.CRoots: crootsMark :: IO RootsMark
+ Nix.Eval.CRoots: crootsRelease :: RootsMark -> IO ()
+ Nix.Eval.CRoots: data RootsMark
+ Nix.Eval.CStats: Census :: PerKind Figures -> PerKind Figures -> Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> Double -> Double -> Map Word32 Word64 -> Maybe SiteCounts -> Census
+ Nix.Eval.CStats: EnvSiteFigures :: Word64 -> Word64 -> Word64 -> EnvSiteFigures
+ Nix.Eval.CStats: EnvSlots :: Word32 -> EnvSize
+ Nix.Eval.CStats: EnvSlotsAtLeast :: Word32 -> EnvSize
+ Nix.Eval.CStats: Figures :: Maybe Word64 -> Word64 -> Figures
+ Nix.Eval.CStats: PerKind :: a -> a -> a -> a -> a -> a -> a -> a -> a -> a -> PerKind a
+ Nix.Eval.CStats: RootAttrSet :: AttrSet -> CRoot
+ Nix.Eval.CStats: RootCtxStr :: CCtxStrPtr -> CRoot
+ Nix.Eval.CStats: RootEnv :: Env -> CRoot
+ Nix.Eval.CStats: RootList :: CList -> CRoot
+ Nix.Eval.CStats: RootRegistered :: CRoot
+ Nix.Eval.CStats: RootString :: CStrPtr -> CRoot
+ Nix.Eval.CStats: RootThunk :: Thunk -> CRoot
+ Nix.Eval.CStats: SetSiteFigures :: Word64 -> Word64 -> Word64 -> SetSiteFigures
+ Nix.Eval.CStats: SiteCounts :: Map EnvSite EnvSiteFigures -> Map EnvSize Word64 -> Map SetSite SetSiteFigures -> Word64 -> SiteCounts
+ Nix.Eval.CStats: [censusAllocated] :: Census -> PerKind Figures
+ Nix.Eval.CStats: [censusCodeBytes] :: Census -> Word64
+ Nix.Eval.CStats: [censusIndexSeconds] :: Census -> Double
+ Nix.Eval.CStats: [censusMarkSeconds] :: Census -> Double
+ Nix.Eval.CStats: [censusOverheadBytes] :: Census -> Word64
+ Nix.Eval.CStats: [censusReached] :: Census -> PerKind Figures
+ Nix.Eval.CStats: [censusSetSizes] :: Census -> Map Word32 Word64
+ Nix.Eval.CStats: [censusSites] :: Census -> Maybe SiteCounts
+ Nix.Eval.CStats: [censusUnplaced] :: Census -> Word64
+ Nix.Eval.CStats: [censusVisitedBytes] :: Census -> Word64
+ Nix.Eval.CStats: [censusVisitedObjects] :: Census -> Word64
+ Nix.Eval.CStats: [envSiteBytes] :: EnvSiteFigures -> Word64
+ Nix.Eval.CStats: [envSiteEnvs] :: EnvSiteFigures -> Word64
+ Nix.Eval.CStats: [envSiteSlots] :: EnvSiteFigures -> Word64
+ Nix.Eval.CStats: [figuresBytes] :: Figures -> Word64
+ Nix.Eval.CStats: [figuresCount] :: Figures -> Maybe Word64
+ Nix.Eval.CStats: [kindApps] :: PerKind a -> a
+ Nix.Eval.CStats: [kindAttrSets] :: PerKind a -> a
+ Nix.Eval.CStats: [kindCtxStrs] :: PerKind a -> a
+ Nix.Eval.CStats: [kindEnvs] :: PerKind a -> a
+ Nix.Eval.CStats: [kindLambdas] :: PerKind a -> a
+ Nix.Eval.CStats: [kindLists] :: PerKind a -> a
+ Nix.Eval.CStats: [kindPrimopApps] :: PerKind a -> a
+ Nix.Eval.CStats: [kindStrings] :: PerKind a -> a
+ Nix.Eval.CStats: [kindSymbols] :: PerKind a -> a
+ Nix.Eval.CStats: [kindThunks] :: PerKind a -> a
+ Nix.Eval.CStats: [setSiteBytes] :: SetSiteFigures -> Word64
+ Nix.Eval.CStats: [setSiteSets] :: SetSiteFigures -> Word64
+ Nix.Eval.CStats: [setSiteShareable] :: SetSiteFigures -> Word64
+ Nix.Eval.CStats: [sitesEnvSizes] :: SiteCounts -> Map EnvSize Word64
+ Nix.Eval.CStats: [sitesEnvs] :: SiteCounts -> Map EnvSite EnvSiteFigures
+ Nix.Eval.CStats: [sitesSets] :: SiteCounts -> Map SetSite SetSiteFigures
+ Nix.Eval.CStats: [sitesUpdateCopied] :: SiteCounts -> Word64
+ Nix.Eval.CStats: countSites :: IO ()
+ Nix.Eval.CStats: data CRoot
+ Nix.Eval.CStats: data Census
+ Nix.Eval.CStats: data EnvSiteFigures
+ Nix.Eval.CStats: data EnvSize
+ Nix.Eval.CStats: data Figures
+ Nix.Eval.CStats: data PerKind a
+ Nix.Eval.CStats: data SetSiteFigures
+ Nix.Eval.CStats: data SiteCounts
+ Nix.Eval.CStats: envSitesCounted :: IO Word32
+ Nix.Eval.CStats: instance GHC.Internal.Base.Applicative Nix.Eval.CStats.PerKind
+ Nix.Eval.CStats: instance GHC.Internal.Base.Functor Nix.Eval.CStats.PerKind
+ Nix.Eval.CStats: instance GHC.Internal.Classes.Eq Nix.Eval.CStats.Census
+ Nix.Eval.CStats: instance GHC.Internal.Classes.Eq Nix.Eval.CStats.EnvSiteFigures
+ Nix.Eval.CStats: instance GHC.Internal.Classes.Eq Nix.Eval.CStats.EnvSize
+ Nix.Eval.CStats: instance GHC.Internal.Classes.Eq Nix.Eval.CStats.Figures
+ Nix.Eval.CStats: instance GHC.Internal.Classes.Eq Nix.Eval.CStats.SetSiteFigures
+ Nix.Eval.CStats: instance GHC.Internal.Classes.Eq Nix.Eval.CStats.SiteCounts
+ Nix.Eval.CStats: instance GHC.Internal.Classes.Eq a => GHC.Internal.Classes.Eq (Nix.Eval.CStats.PerKind a)
+ Nix.Eval.CStats: instance GHC.Internal.Classes.Ord Nix.Eval.CStats.EnvSize
+ Nix.Eval.CStats: instance GHC.Internal.Data.Foldable.Foldable Nix.Eval.CStats.PerKind
+ Nix.Eval.CStats: instance GHC.Internal.Data.Traversable.Traversable Nix.Eval.CStats.PerKind
+ Nix.Eval.CStats: instance GHC.Internal.Show.Show Nix.Eval.CStats.Census
+ Nix.Eval.CStats: instance GHC.Internal.Show.Show Nix.Eval.CStats.EnvSiteFigures
+ Nix.Eval.CStats: instance GHC.Internal.Show.Show Nix.Eval.CStats.EnvSize
+ Nix.Eval.CStats: instance GHC.Internal.Show.Show Nix.Eval.CStats.Figures
+ Nix.Eval.CStats: instance GHC.Internal.Show.Show Nix.Eval.CStats.SetSiteFigures
+ Nix.Eval.CStats: instance GHC.Internal.Show.Show Nix.Eval.CStats.SiteCounts
+ Nix.Eval.CStats: instance GHC.Internal.Show.Show a => GHC.Internal.Show.Show (Nix.Eval.CStats.PerKind a)
+ Nix.Eval.CStats: renderCensus :: Census -> ByteString
+ Nix.Eval.CStats: setSitesCounted :: IO Word32
+ Nix.Eval.CStats: siteCounts :: IO (Maybe SiteCounts)
+ Nix.Eval.CStats: takeCensus :: [CRoot] -> IO (Either CStatusError Census)
+ Nix.Eval.CStats: valueRoots :: NixValue -> [CRoot]
+ Nix.Eval.CStr: cstrBytes :: MonadCData m => CStrPtr -> m ByteString
+ Nix.Eval.CStr: cstrFromText :: MonadCData m => Text -> m CStrPtr
+ Nix.Eval.CStr: cstrNew :: MonadCData m => ByteString -> m CStrPtr
+ Nix.Eval.CStr: cstrText :: MonadCData m => CStrPtr -> m Text
+ Nix.Eval.CStr: data NnStr
+ Nix.Eval.CStr: type CStrPtr = Ptr NnStr
+ Nix.Eval.CThunk: cthunkApplyCell :: MonadCData m => CThunkPtr -> Word32 -> m CThunkPtr
+ Nix.Eval.CThunk: cthunkEmptyList :: CThunkPtr
+ Nix.Eval.CThunk: cthunkGetPrimop :: MonadCData m => CThunkPtr -> m Word32
+ Nix.Eval.CThunk: cthunkNewApply1 :: MonadCData m => CThunkPtr -> CThunkPtr -> m CThunkPtr
+ Nix.Eval.CThunk: cthunkNewApply2 :: MonadCData m => CThunkPtr -> CThunkPtr -> CThunkPtr -> m CThunkPtr
+ Nix.Eval.CThunk: cthunkNewComputedPrimop :: MonadCData m => Word32 -> m CThunkPtr
+ Nix.Eval.CThunk: cthunkNewComputedPrimopApp :: MonadCData m => Ptr () -> m CThunkPtr
+ Nix.Eval.CThunk: cthunkPendingForm :: MonadCData m => CThunkPtr -> m Word8
+ Nix.Eval.CThunk: cthunkPrimop :: MonadCData m => Word32 -> m CThunkPtr
+ Nix.Eval.CThunk: cthunkSetComputedPrimop :: MonadCData m => CThunkPtr -> Word32 -> m Bool
+ Nix.Eval.CThunk: cthunkSetComputedPrimopApp :: MonadCData m => CThunkPtr -> Ptr () -> m Bool
+ Nix.Eval.CThunk: noCode :: Word32
+ Nix.Eval.Compile: BcBindingCounts :: Int -> Int -> BcBindingCounts
+ Nix.Eval.Compile: BcBindings :: BcBindingCounts -> BcShares -> Int -> Word32 -> BcBindings
+ Nix.Eval.Compile: BcCapturedSlots :: Int -> Word32 -> BcCapturedSlots
+ Nix.Eval.Compile: BcCaptures :: BcCapturedSlots -> BcCaptureInfo
+ Nix.Eval.Compile: BcCapturesWithScopes :: BcCapturedSlots -> BcCaptureInfo
+ Nix.Eval.Compile: BcDynamic :: PosIdx -> Word32 -> Word32 -> BcBinding
+ Nix.Eval.Compile: BcInheritedNames :: Int -> Word32 -> BcInheritedNames
+ Nix.Eval.Compile: BcNoCaptureInfo :: BcCaptureInfo
+ Nix.Eval.Compile: BcShares :: Int -> Word32 -> BcShares
+ Nix.Eval.Compile: SiblingVar :: Symbol -> k -> k -> SiblingVar k
+ Nix.Eval.Compile: compileParsed :: ParsedSource -> IO Word32
+ Nix.Eval.Compile: data BcBindingCounts
+ Nix.Eval.Compile: data BcBindings
+ Nix.Eval.Compile: data BcCaptureInfo
+ Nix.Eval.Compile: data BcCapturedSlots
+ Nix.Eval.Compile: data BcInheritedNames
+ Nix.Eval.Compile: data BcShares
+ Nix.Eval.Compile: data SiblingVar k
+ Nix.Eval.Compile: decodeBinaryOp :: Word8 -> Maybe BinaryOp
+ Nix.Eval.Compile: decodeUnaryOp :: Word8 -> Maybe UnaryOp
+ Nix.Eval.Compile: encodeBinaryOp :: BinaryOp -> Word8
+ Nix.Eval.Compile: encodeUnaryOp :: UnaryOp -> Word8
+ Nix.Eval.Compile: foldBcBindings :: MonadCData m => (Word32 -> m acc) -> (acc -> BcBinding -> m acc) -> acc -> BcBindings -> m acc
+ Nix.Eval.Compile: foldBcCapturedSlots :: MonadCData m => (acc -> Word32 -> Word32 -> m acc) -> acc -> BcCapturedSlots -> m acc
+ Nix.Eval.Compile: foldBcInheritedNames :: MonadCData m => (acc -> BcInheritedName -> m acc) -> acc -> BcInheritedNames -> m acc
+ Nix.Eval.Compile: foldBcShares :: MonadCData m => (acc -> Word32 -> Word32 -> m acc) -> acc -> BcShares -> m acc
+ Nix.Eval.Compile: formalDefaultFromWords :: Word32 -> Word32 -> Maybe FormalDefault
+ Nix.Eval.Compile: formalDefaultWords :: FormalDefault -> (Word32, Word32)
+ Nix.Eval.Compile: siblingShares :: Ord k => (k -> Maybe Symbol) -> [SiblingVar k] -> [(k, k)]
+ Nix.Eval.Context: contextRequest :: StringContext -> ContextRequest
+ Nix.Eval.Context: encodedElement :: StringContextElement -> Text
+ Nix.Eval.Context: firstContextDisplayed :: StringContext -> Maybe Text
+ Nix.Eval.Context: inUpstreamOrder :: StringContext -> [StringContextElement]
+ Nix.Eval.EvalFormals: AnonymousLambda :: LambdaName
+ Nix.Eval.EvalFormals: Default :: Word32 -> FormalDefault
+ Nix.Eval.EvalFormals: NamedLambda :: Symbol -> LambdaName
+ Nix.Eval.EvalFormals: NoDefault :: FormalDefault
+ Nix.Eval.EvalFormals: SharedDefault :: Word32 -> FormalDefault
+ Nix.Eval.EvalFormals: data FormalDefault
+ Nix.Eval.EvalFormals: data LambdaName
+ Nix.Eval.EvalFormals: hasDefault :: FormalDefault -> Bool
+ Nix.Eval.EvalFormals: instance GHC.Internal.Classes.Eq Nix.Eval.EvalFormals.FormalDefault
+ Nix.Eval.EvalFormals: instance GHC.Internal.Classes.Eq Nix.Eval.EvalFormals.LambdaName
+ Nix.Eval.EvalFormals: instance GHC.Internal.Show.Show Nix.Eval.EvalFormals.FormalDefault
+ Nix.Eval.EvalFormals: instance GHC.Internal.Show.Show Nix.Eval.EvalFormals.LambdaName
+ Nix.Eval.EvalFormals: lambdaNameFromSymbol :: Word32 -> LambdaName
+ Nix.Eval.EvalFormals: lambdaNameSymbol :: LambdaName -> Word32
+ Nix.Eval.EvalFormals: lambdaNameText :: LambdaName -> Text
+ Nix.Eval.IO: ReadOnlySession :: StoreQueries IO -> StoreOps IO -> SessionStore
+ Nix.Eval.IO: ReadWriteSession :: StoreOps IO -> SessionStore
+ Nix.Eval.IO: SessionSettings :: EvalPolicy -> IO [Thunk] -> StoreDir -> FilePath -> Regions -> SessionStore -> Logger -> SessionSettings
+ Nix.Eval.IO: SourceCopy :: StorePath -> Text -> SourceCopy
+ Nix.Eval.IO: [scSource] :: SourceCopy -> Text
+ Nix.Eval.IO: [scStorePath] :: SourceCopy -> StorePath
+ Nix.Eval.IO: [sessionBaseDir] :: SessionSettings -> FilePath
+ Nix.Eval.IO: [sessionLogger] :: SessionSettings -> Logger
+ Nix.Eval.IO: [sessionPolicy] :: SessionSettings -> EvalPolicy
+ Nix.Eval.IO: [sessionRegions] :: SessionSettings -> Regions
+ Nix.Eval.IO: [sessionSearchPath] :: SessionSettings -> IO [Thunk]
+ Nix.Eval.IO: [sessionStoreDir] :: SessionSettings -> StoreDir
+ Nix.Eval.IO: [sessionStore] :: SessionSettings -> SessionStore
+ Nix.Eval.IO: data SessionSettings
+ Nix.Eval.IO: data SessionStore
+ Nix.Eval.IO: data SourceCopy
+ Nix.Eval.IO: evalBaseEnv :: EvalState -> Env
+ Nix.Eval.IO: evalSearchPath :: EvalState -> [Thunk]
+ Nix.Eval.IO: instance GHC.Internal.Classes.Eq Nix.Eval.IO.SourceCopy
+ Nix.Eval.IO: instance GHC.Internal.Show.Show Nix.Eval.IO.SourceCopy
+ Nix.Eval.IO: instance Nix.Eval.CData.MonadCData Nix.Eval.IO.EvalIO
+ Nix.Eval.IO: newEvalStateWith :: Logger -> EvalPolicy -> [Thunk] -> SessionStore -> StoreDir -> FilePath -> IO EvalState
+ Nix.Eval.IO: nixPathSearchPath :: IO [Thunk]
+ Nix.Eval.IO: nixPathValue :: IO ByteString
+ Nix.Eval.IO: readImportTarget :: (FilePath, FilePath) -> EvalIO ByteString
+ Nix.Eval.IO: resolveImportTarget :: FilePath -> Text -> EvalIO (FilePath, FilePath)
+ Nix.Eval.IO: sourceCopies :: Map Text SourceCopy -> Map StorePath Text
+ Nix.Eval.IO: withEvalSession :: SessionSettings -> (EvalState -> IO a) -> IO a
+ Nix.Eval.Operator: evalUpdateChain :: MonadEval m => NonEmpty (m NixValue) -> m NixValue
+ Nix.Eval.Operator: expectedFailure :: MonadEval m => Text -> NixValue -> m a
+ Nix.Eval.Policy: AbsoluteTarget :: [Text] -> LinkTarget
+ Nix.Eval.Policy: AllowImportFromDerivation :: ImportFromDerivation
+ Nix.Eval.Policy: PosixPaths :: PathRules
+ Nix.Eval.Policy: RefuseImportFromDerivation :: ImportFromDerivation
+ Nix.Eval.Policy: RelativeTarget :: [Text] -> LinkTarget
+ Nix.Eval.Policy: ResolveAncestors :: SymlinkResolution
+ Nix.Eval.Policy: ResolveFull :: SymlinkResolution
+ Nix.Eval.Policy: TraceImportFromDerivation :: ImportFromDerivation
+ Nix.Eval.Policy: WalkLoops :: WalkStop e
+ Nix.Eval.Policy: WalkRefused :: e -> WalkStop e
+ Nix.Eval.Policy: WindowsPaths :: PathRules
+ Nix.Eval.Policy: [epExperimentalFeatures] :: EvalPolicy -> FeatureSet
+ Nix.Eval.Policy: [epImportFromDerivation] :: EvalPolicy -> ImportFromDerivation
+ Nix.Eval.Policy: data ImportFromDerivation
+ Nix.Eval.Policy: data LinkTarget
+ Nix.Eval.Policy: data PathRules
+ Nix.Eval.Policy: data SymlinkResolution
+ Nix.Eval.Policy: data WalkStop e
+ Nix.Eval.Policy: fileUrlPath :: StoreDir -> Text -> Maybe (Either Text Text)
+ Nix.Eval.Policy: hostPathRules :: PathRules
+ Nix.Eval.Policy: instance GHC.Internal.Classes.Eq Nix.Eval.Policy.ImportFromDerivation
+ Nix.Eval.Policy: instance GHC.Internal.Classes.Eq Nix.Eval.Policy.LinkTarget
+ Nix.Eval.Policy: instance GHC.Internal.Classes.Eq Nix.Eval.Policy.PathRules
+ Nix.Eval.Policy: instance GHC.Internal.Classes.Eq Nix.Eval.Policy.SymlinkResolution
+ Nix.Eval.Policy: instance GHC.Internal.Classes.Eq e => GHC.Internal.Classes.Eq (Nix.Eval.Policy.WalkStop e)
+ Nix.Eval.Policy: instance GHC.Internal.Show.Show Nix.Eval.Policy.ImportFromDerivation
+ Nix.Eval.Policy: instance GHC.Internal.Show.Show Nix.Eval.Policy.LinkTarget
+ Nix.Eval.Policy: instance GHC.Internal.Show.Show Nix.Eval.Policy.PathRules
+ Nix.Eval.Policy: instance GHC.Internal.Show.Show Nix.Eval.Policy.SymlinkResolution
+ Nix.Eval.Policy: instance GHC.Internal.Show.Show e => GHC.Internal.Show.Show (Nix.Eval.Policy.WalkStop e)
+ Nix.Eval.Policy: linkTarget :: PathRules -> Text -> Maybe LinkTarget
+ Nix.Eval.Policy: storeRootPrefix :: [Text] -> [Text] -> Bool
+ Nix.Eval.Policy: walkPath :: Monad m => PathRules -> SymlinkResolution -> ([Text] -> Text -> Either e ()) -> (Text -> m (Maybe Text)) -> Text -> m (Either (WalkStop e) Text)
+ Nix.Eval.Policy: windowsLinkTargetJoins :: Text -> Bool
+ Nix.Eval.Print: instance GHC.Internal.Classes.Eq Nix.Eval.Print.Entered
+ Nix.Eval.Print: instance GHC.Internal.Classes.Ord Nix.Eval.Print.Entered
+ Nix.Eval.Print: printSymbol :: Text -> Text
+ Nix.Eval.RealiseContext: Computed :: PendingOrigin
+ Nix.Eval.RealiseContext: ContextRequest :: [StorePath] -> [(StorePath, Text)] -> ContextRequest
+ Nix.Eval.RealiseContext: Fetched :: PendingOrigin
+ Nix.Eval.RealiseContext: ImportFromDerivationOff :: StorePath -> Text -> ContextRefusal
+ Nix.Eval.RealiseContext: PathNotValid :: StorePath -> ContextRefusal
+ Nix.Eval.RealiseContext: Plan :: Bool -> [(StorePath, Set Text)] -> [StorePath] -> Maybe Text -> Plan
+ Nix.Eval.RealiseContext: ReadOnly :: SessionMode
+ Nix.Eval.RealiseContext: ReadWrite :: SessionMode
+ Nix.Eval.RealiseContext: RealisationFailed :: Text -> ContextRefusal
+ Nix.Eval.RealiseContext: [crOutputs] :: ContextRequest -> [(StorePath, Text)]
+ Nix.Eval.RealiseContext: [crPaths] :: ContextRequest -> [StorePath]
+ Nix.Eval.RealiseContext: [planAdd] :: Plan -> Bool
+ Nix.Eval.RealiseContext: [planBuilds] :: Plan -> [(StorePath, Set Text)]
+ Nix.Eval.RealiseContext: [planOutputs] :: Plan -> [StorePath]
+ Nix.Eval.RealiseContext: [planWarning] :: Plan -> Maybe Text
+ Nix.Eval.RealiseContext: contextRefusalMessage :: ContextRefusal -> Text
+ Nix.Eval.RealiseContext: data ContextRefusal
+ Nix.Eval.RealiseContext: data ContextRequest
+ Nix.Eval.RealiseContext: data PendingOrigin
+ Nix.Eval.RealiseContext: data Plan
+ Nix.Eval.RealiseContext: data SessionMode
+ Nix.Eval.RealiseContext: findFileRefusalMessage :: Text -> ContextRefusal -> Text
+ Nix.Eval.RealiseContext: firstInvalidPath :: SessionMode -> Map StorePath PendingOrigin -> Set StorePath -> ContextRequest -> Maybe StorePath
+ Nix.Eval.RealiseContext: instance GHC.Internal.Classes.Eq Nix.Eval.RealiseContext.ContextRefusal
+ Nix.Eval.RealiseContext: instance GHC.Internal.Classes.Eq Nix.Eval.RealiseContext.ContextRequest
+ Nix.Eval.RealiseContext: instance GHC.Internal.Classes.Eq Nix.Eval.RealiseContext.PendingOrigin
+ Nix.Eval.RealiseContext: instance GHC.Internal.Classes.Eq Nix.Eval.RealiseContext.Plan
+ Nix.Eval.RealiseContext: instance GHC.Internal.Classes.Eq Nix.Eval.RealiseContext.SessionMode
+ Nix.Eval.RealiseContext: instance GHC.Internal.Show.Show Nix.Eval.RealiseContext.ContextRefusal
+ Nix.Eval.RealiseContext: instance GHC.Internal.Show.Show Nix.Eval.RealiseContext.ContextRequest
+ Nix.Eval.RealiseContext: instance GHC.Internal.Show.Show Nix.Eval.RealiseContext.PendingOrigin
+ Nix.Eval.RealiseContext: instance GHC.Internal.Show.Show Nix.Eval.RealiseContext.Plan
+ Nix.Eval.RealiseContext: instance GHC.Internal.Show.Show Nix.Eval.RealiseContext.SessionMode
+ Nix.Eval.RealiseContext: planRealisation :: ImportFromDerivation -> SessionMode -> Map StorePath PendingOrigin -> Set StorePath -> Map (StorePath, Text) StorePath -> ContextRequest -> Either ContextRefusal Plan
+ Nix.Eval.RealiseContext: readableIn :: SessionMode -> Map StorePath PendingOrigin -> Set StorePath -> StorePath -> Bool
+ Nix.Eval.RealiseContext: referenceClosure :: Monad m => (StorePath -> m (Either Text (Set StorePath))) -> [StorePath] -> m (Either Text (Set StorePath))
+ Nix.Eval.SourcePos: printPos :: MonadCData m => PosIdx -> m Text
+ Nix.Eval.StartupSymbols: startupSymbols :: [Text]
+ Nix.Eval.Symbol: invalidSymbolId :: Word32
+ Nix.Eval.Types: CtxStrCell :: CCtxStrPtr -> StringCell
+ Nix.Eval.Types: HeldCtxStr :: CCtxStrPtr -> HeldBytes
+ Nix.Eval.Types: HeldStr :: CStrPtr -> HeldBytes
+ Nix.Eval.Types: NotHeld :: HeldBytes
+ Nix.Eval.Types: PendingApply :: Thunk -> Thunk -> Pending
+ Nix.Eval.Types: PendingApply2 :: Thunk -> Thunk -> Thunk -> Pending
+ Nix.Eval.Types: PendingCode :: Env -> Word32 -> Pending
+ Nix.Eval.Types: PrimopAppCell :: CPrimopAppPtr -> PrimopCell
+ Nix.Eval.Types: PrimopCell :: Word32 -> PrimopCell
+ Nix.Eval.Types: StrCell :: CStrPtr -> StringCell
+ Nix.Eval.Types: VPathHeld :: Text -> HeldBytes -> NixValue
+ Nix.Eval.Types: VStrHeld :: ByteString -> StringContext -> HeldBytes -> NixValue
+ Nix.Eval.Types: [epExperimentalFeatures] :: EvalPolicy -> FeatureSet
+ Nix.Eval.Types: [epImportFromDerivation] :: EvalPolicy -> ImportFromDerivation
+ Nix.Eval.Types: addEvaluatedTrace :: MonadEval m => (Text -> Text) -> m Text -> m a -> m a
+ Nix.Eval.Types: attrSetAllPairs :: MonadCData m => ((Symbol, Thunk) -> (Symbol, Thunk) -> m Bool) -> AttrSet -> AttrSet -> m Bool
+ Nix.Eval.Types: attrSetFindName :: MonadCData m => (Symbol -> Bool) -> AttrSet -> m (Maybe Symbol)
+ Nix.Eval.Types: attrSetFoldM :: MonadCData m => (a -> Symbol -> AttrEntry -> m a) -> a -> AttrSet -> m a
+ Nix.Eval.Types: attrSetFromSymbolEntries :: MonadCData m => SetSite -> Map Symbol AttrEntry -> m AttrSet
+ Nix.Eval.Types: attrSetFromSymbolEntriesSizedFor :: MonadCData m => SetSite -> Int -> Map Symbol AttrEntry -> m AttrSet
+ Nix.Eval.Types: attrSetFromSymbols :: MonadCData m => SetSite -> Map Symbol Thunk -> m AttrSet
+ Nix.Eval.Types: attrSetLookupSymbol :: MonadCData m => Symbol -> AttrSet -> m (Maybe Thunk)
+ Nix.Eval.Types: attrSetLookupSymbolEntry :: MonadCData m => Symbol -> AttrSet -> m (Maybe AttrEntry)
+ Nix.Eval.Types: attrSetMemberSymbol :: MonadCData m => Symbol -> AttrSet -> m Bool
+ Nix.Eval.Types: buildBcCaptureEnv :: MonadCData m => EnvSite -> Env -> BcCaptureInfo -> m Env
+ Nix.Eval.Types: buildCaptureEnv :: MonadCData m => EnvSite -> Env -> CaptureInfo -> m Env
+ Nix.Eval.Types: compile :: MonadCData m => Expr -> m Word32
+ Nix.Eval.Types: compileSource :: MonadCData m => ParsedSource -> m Word32
+ Nix.Eval.Types: data FlatCAttrSet
+ Nix.Eval.Types: data HeldBytes
+ Nix.Eval.Types: data Pending
+ Nix.Eval.Types: data PrimopCell
+ Nix.Eval.Types: data StringCell
+ Nix.Eval.Types: emptyAttrSet :: AttrSet
+ Nix.Eval.Types: envSlotCells :: MonadCData m => Env -> Int -> m [Thunk]
+ Nix.Eval.Types: fetchArchiveToStore :: MonadEval m => Text -> Text -> Maybe (ByteString, ByteString -> Text) -> m (Either FetchFailure Text)
+ Nix.Eval.Types: fetchUrlBytes :: MonadEval m => Text -> m (Either Text ByteString)
+ Nix.Eval.Types: flatCAttrSet :: FlatCAttrSet -> CAttrSet
+ Nix.Eval.Types: frameThunkBc :: MonadCData m => Env -> Word32 -> m Thunk
+ Nix.Eval.Types: heldString :: MonadCData m => CStrPtr -> m NixValue
+ Nix.Eval.Types: instance GHC.Internal.Classes.Eq Nix.Eval.Types.HeldBytes
+ Nix.Eval.Types: instance GHC.Internal.Show.Show Nix.Eval.Types.HeldBytes
+ Nix.Eval.Types: instance Nix.Eval.CData.MonadCData Nix.Eval.Types.PureEval
+ Nix.Eval.Types: mkApply2Thunk :: MonadCData m => Thunk -> Thunk -> Thunk -> m Thunk
+ Nix.Eval.Types: mkApplyThunk :: MonadCData m => Thunk -> Thunk -> m Thunk
+ Nix.Eval.Types: newEnv :: MonadCData m => EnvSite -> Maybe Env -> [Thunk] -> m Env
+ Nix.Eval.Types: newScopeEnv :: MonadCData m => EnvSite -> Maybe Env -> AttrSet -> m Env
+ Nix.Eval.Types: pathCell :: MonadCData m => Text -> HeldBytes -> m CStrPtr
+ Nix.Eval.Types: pattern VPath :: Text -> NixValue
+ Nix.Eval.Types: pattern VStr :: ByteString -> StringContext -> NixValue
+ Nix.Eval.Types: pinnedFetchHeld :: MonadEval m => StorePath -> m Bool
+ Nix.Eval.Types: primopCell :: MonadCData m => Builtin -> [BuiltinArg] -> m PrimopCell
+ Nix.Eval.Types: pushLazyWithScope :: MonadCData m => Thunk -> Env -> m Env
+ Nix.Eval.Types: readComputed :: MonadCData m => CThunkPtr -> m NixValue
+ Nix.Eval.Types: readPending :: MonadCData m => CThunkPtr -> m Pending
+ Nix.Eval.Types: realiseContext :: MonadEval m => StringContext -> m (Either ContextRefusal ())
+ Nix.Eval.Types: resolveWithScopeAt :: MonadCData m => Ptr (Ptr ()) -> Int -> AttrSet -> m ()
+ Nix.Eval.Types: shareSlot :: MonadCData m => (Word32 -> m ()) -> Env -> Word32 -> Word32 -> m ()
+ Nix.Eval.Types: stringCell :: MonadCData m => ByteString -> StringContext -> HeldBytes -> m StringCell
+ Nix.Eval.Types: tieFrame :: MonadCData m => EnvSite -> Maybe Env -> Int -> (Env -> m [Thunk]) -> m (Env, [Thunk])
+ Nix.Eval.Types: warnMessage :: MonadEval m => Text -> m ()
+ Nix.Eval.Types: withScopeAt :: MonadCData m => Ptr (Ptr ()) -> Int -> m (Either Thunk AttrSet)
+ Nix.ExperimentalFeature: addFeatures :: FeatureSet -> FeatureSet -> FeatureSet
+ Nix.ExperimentalFeature: data ExperimentalFeature
+ Nix.ExperimentalFeature: data FeatureSet
+ Nix.ExperimentalFeature: featureEnabled :: ExperimentalFeature -> FeatureSet -> Bool
+ Nix.ExperimentalFeature: featureName :: ExperimentalFeature -> Text
+ Nix.ExperimentalFeature: featureSetWarnings :: FeatureSet -> [Text]
+ Nix.ExperimentalFeature: flakesFeature :: ExperimentalFeature
+ Nix.ExperimentalFeature: instance GHC.Internal.Classes.Eq Nix.ExperimentalFeature.ExperimentalFeature
+ Nix.ExperimentalFeature: instance GHC.Internal.Classes.Eq Nix.ExperimentalFeature.FeatureSet
+ Nix.ExperimentalFeature: instance GHC.Internal.Classes.Ord Nix.ExperimentalFeature.ExperimentalFeature
+ Nix.ExperimentalFeature: instance GHC.Internal.Show.Show Nix.ExperimentalFeature.ExperimentalFeature
+ Nix.ExperimentalFeature: instance GHC.Internal.Show.Show Nix.ExperimentalFeature.FeatureSet
+ Nix.ExperimentalFeature: missingFeatureMessage :: ExperimentalFeature -> Text
+ Nix.ExperimentalFeature: noFeatures :: FeatureSet
+ Nix.ExperimentalFeature: parseFeatures :: ByteString -> FeatureSet
+ Nix.ExperimentalFeature: replaceFeatures :: FeatureSet -> FeatureSet -> FeatureSet
+ Nix.ExperimentalFeature: requireFeature :: ExperimentalFeature -> FeatureSet -> Either Text ()
+ Nix.ExperimentalFeature: verifiedFetchesFeature :: ExperimentalFeature
+ Nix.Expr.Types: EPos :: SrcPos -> Expr
+ Nix.Expr.Types: instance GHC.Internal.Enum.Bounded Nix.Expr.Types.BinaryOp
+ Nix.Expr.Types: instance GHC.Internal.Enum.Bounded Nix.Expr.Types.UnaryOp
+ Nix.Expr.Types: instance GHC.Internal.Enum.Enum Nix.Expr.Types.BinaryOp
+ Nix.Expr.Types: instance GHC.Internal.Enum.Enum Nix.Expr.Types.UnaryOp
+ Nix.Fetch.Archive: ArchiveDirectory :: ArchiveNode blob
+ Nix.Fetch.Archive: ArchiveEntry :: ByteString -> ArchiveNode blob -> ArchiveEntry blob
+ Nix.Fetch.Archive: ArchiveFile :: Bool -> blob -> ArchiveNode blob
+ Nix.Fetch.Archive: ArchiveHardLink :: ByteString -> ArchiveNode blob
+ Nix.Fetch.Archive: ArchiveSpecial :: Int -> ArchiveNode blob
+ Nix.Fetch.Archive: ArchiveSymlink :: ByteString -> ArchiveNode blob
+ Nix.Fetch.Archive: FetchFailure :: [Text] -> Text -> FetchFailure
+ Nix.Fetch.Archive: [entryNode] :: ArchiveEntry blob -> ArchiveNode blob
+ Nix.Fetch.Archive: [entryPath] :: ArchiveEntry blob -> ByteString
+ Nix.Fetch.Archive: [fetchMessage] :: FetchFailure -> Text
+ Nix.Fetch.Archive: [fetchTraces] :: FetchFailure -> [Text]
+ Nix.Fetch.Archive: data ArchiveEntry blob
+ Nix.Fetch.Archive: data ArchiveNode blob
+ Nix.Fetch.Archive: data ArchiveSink blob
+ Nix.Fetch.Archive: data FetchFailure
+ Nix.Fetch.Archive: drainFile :: Monad m => m (Either Text ByteString) -> (ByteString -> m ()) -> FileStep -> m (Either FetchFailure TarStep)
+ Nix.Fetch.Archive: emptySink :: ArchiveSink blob
+ Nix.Fetch.Archive: finishSink :: ArchiveSink blob -> Either FetchFailure (Tree blob)
+ Nix.Fetch.Archive: instance GHC.Internal.Classes.Eq Nix.Fetch.Archive.ArchivePath
+ Nix.Fetch.Archive: instance GHC.Internal.Classes.Eq Nix.Fetch.Archive.FetchFailure
+ Nix.Fetch.Archive: instance GHC.Internal.Classes.Eq blob => GHC.Internal.Classes.Eq (Nix.Fetch.Archive.ArchiveEntry blob)
+ Nix.Fetch.Archive: instance GHC.Internal.Classes.Eq blob => GHC.Internal.Classes.Eq (Nix.Fetch.Archive.ArchiveNode blob)
+ Nix.Fetch.Archive: instance GHC.Internal.Classes.Ord Nix.Fetch.Archive.ArchivePath
+ Nix.Fetch.Archive: instance GHC.Internal.Show.Show Nix.Fetch.Archive.ArchivePath
+ Nix.Fetch.Archive: instance GHC.Internal.Show.Show Nix.Fetch.Archive.FetchFailure
+ Nix.Fetch.Archive: instance GHC.Internal.Show.Show blob => GHC.Internal.Show.Show (Nix.Fetch.Archive.ArchiveEntry blob)
+ Nix.Fetch.Archive: instance GHC.Internal.Show.Show blob => GHC.Internal.Show.Show (Nix.Fetch.Archive.ArchiveNode blob)
+ Nix.Fetch.Archive: readArchive :: Monad m => m (Either Text ByteString) -> (Int -> Word64 -> FileStep -> m (Either FetchFailure (blob, TarStep))) -> m ([Text], Either FetchFailure (Tree blob))
+ Nix.Fetch.Archive: sinkEntry :: ArchiveSink blob -> ArchiveEntry blob -> (Either FetchFailure (ArchiveSink blob), [Text])
+ Nix.Fetch.Archive: unpackArchive :: FilePath -> IO ByteString -> IO ([Text], Either FetchFailure (Tree Blob))
+ Nix.Fetch.Attrs: AttrBool :: Bool -> AttrValue
+ Nix.Fetch.Attrs: AttrInt :: Word64 -> AttrValue
+ Nix.Fetch.Attrs: AttrString :: ByteString -> AttrValue
+ Nix.Fetch.Attrs: attrsJson :: Attrs -> Json
+ Nix.Fetch.Attrs: attrsJsonText :: Attrs -> Text
+ Nix.Fetch.Attrs: attrsToQuery :: Attrs -> Map ByteString ByteString
+ Nix.Fetch.Attrs: data AttrValue
+ Nix.Fetch.Attrs: instance GHC.Internal.Classes.Eq Nix.Fetch.Attrs.AttrValue
+ Nix.Fetch.Attrs: instance GHC.Internal.Classes.Ord Nix.Fetch.Attrs.AttrValue
+ Nix.Fetch.Attrs: instance GHC.Internal.Show.Show Nix.Fetch.Attrs.AttrValue
+ Nix.Fetch.Attrs: maybeBoolAttr :: Text -> Attrs -> Checked (Maybe Bool)
+ Nix.Fetch.Attrs: maybeIntAttr :: Text -> Attrs -> Checked (Maybe Word64)
+ Nix.Fetch.Attrs: maybeStrAttr :: Text -> Attrs -> Checked (Maybe ByteString)
+ Nix.Fetch.Attrs: strAttr :: Text -> Attrs -> Checked ByteString
+ Nix.Fetch.Attrs: type Attrs = Map Text AttrValue
+ Nix.Fetch.Download: LocalFile :: FilePath -> DownloadSource
+ Nix.Fetch.Download: RemoteUrl :: Text -> DownloadSource
+ Nix.Fetch.Download: data DownloadSource
+ Nix.Fetch.Download: downloadBytes :: Logger -> FetchRetryPolicy -> Text -> DownloadSource -> IO (Either Text ByteString)
+ Nix.Fetch.Download: instance GHC.Internal.Classes.Eq Nix.Fetch.Download.DownloadSource
+ Nix.Fetch.Download: instance GHC.Internal.Show.Show Nix.Fetch.Download.DownloadSource
+ Nix.Fetch.Download: withUrlBody :: Logger -> FetchRetryPolicy -> Text -> DownloadSource -> (IO ByteString -> IO a) -> IO (Either Text a)
+ Nix.Fetch.Input: AllowFile :: TreeRequirement
+ Nix.Fetch.Input: Input :: Maybe Scheme -> Attrs -> Input
+ Nix.Fetch.Input: InputContext :: FeatureSet -> PathRules -> InputContext
+ Nix.Fetch.Input: RequireTree :: TreeRequirement
+ Nix.Fetch.Input: SchemeFile :: Scheme
+ Nix.Fetch.Input: SchemeGit :: Scheme
+ Nix.Fetch.Input: SchemeGitHub :: Scheme
+ Nix.Fetch.Input: SchemeGitLab :: Scheme
+ Nix.Fetch.Input: SchemeIndirect :: Scheme
+ Nix.Fetch.Input: SchemeMercurial :: Scheme
+ Nix.Fetch.Input: SchemePath :: Scheme
+ Nix.Fetch.Input: SchemeSourceHut :: Scheme
+ Nix.Fetch.Input: SchemeTarball :: Scheme
+ Nix.Fetch.Input: [icFeatures] :: InputContext -> FeatureSet
+ Nix.Fetch.Input: [icPathRules] :: InputContext -> PathRules
+ Nix.Fetch.Input: [inputAttrs] :: Input -> Attrs
+ Nix.Fetch.Input: [inputScheme] :: Input -> Maybe Scheme
+ Nix.Fetch.Input: data Input
+ Nix.Fetch.Input: data InputContext
+ Nix.Fetch.Input: data Scheme
+ Nix.Fetch.Input: data TreeRequirement
+ Nix.Fetch.Input: inputFromAttrs :: InputContext -> Attrs -> Checked Input
+ Nix.Fetch.Input: inputFromUrl :: InputContext -> TreeRequirement -> ParsedUrl -> Checked Input
+ Nix.Fetch.Input: inputToUrl :: PathRules -> Input -> Checked ParsedUrl
+ Nix.Fetch.Input: inputToUrlString :: PathRules -> [(ByteString, ByteString)] -> Input -> Checked ByteString
+ Nix.Fetch.Input: instance GHC.Internal.Classes.Eq Nix.Fetch.Input.Input
+ Nix.Fetch.Input: instance GHC.Internal.Classes.Eq Nix.Fetch.Input.Scheme
+ Nix.Fetch.Input: instance GHC.Internal.Classes.Eq Nix.Fetch.Input.TreeRequirement
+ Nix.Fetch.Input: instance GHC.Internal.Classes.Ord Nix.Fetch.Input.Scheme
+ Nix.Fetch.Input: instance GHC.Internal.Enum.Bounded Nix.Fetch.Input.Scheme
+ Nix.Fetch.Input: instance GHC.Internal.Enum.Enum Nix.Fetch.Input.Scheme
+ Nix.Fetch.Input: instance GHC.Internal.Show.Show Nix.Fetch.Input.Input
+ Nix.Fetch.Input: instance GHC.Internal.Show.Show Nix.Fetch.Input.Scheme
+ Nix.Fetch.Input: instance GHC.Internal.Show.Show Nix.Fetch.Input.TreeRequirement
+ Nix.Fetch.Input: isLegalRefName :: ByteString -> Bool
+ Nix.Fetch.Input: schemeName :: Scheme -> Text
+ Nix.Fetch.Tar: FileAwait :: (ByteString -> FileStep) -> FileStep
+ Nix.Fetch.Tar: FileChunk :: ByteString -> FileStep -> FileStep
+ Nix.Fetch.Tar: FileEnd :: TarStep -> FileStep
+ Nix.Fetch.Tar: FileFail :: TarFailure -> FileStep
+ Nix.Fetch.Tar: TarAwait :: (ByteString -> TarStep) -> TarStep
+ Nix.Fetch.Tar: TarDataFailure :: Text -> TarFailure
+ Nix.Fetch.Tar: TarDirectory :: TarNode
+ Nix.Fetch.Tar: TarDone :: TarStep
+ Nix.Fetch.Tar: TarEntry :: ByteString -> Bool -> Maybe Text -> TarEntry
+ Nix.Fetch.Tar: TarFail :: TarFailure -> TarStep
+ Nix.Fetch.Tar: TarFile :: TarEntry -> Word64 -> FileStep -> TarStep
+ Nix.Fetch.Tar: TarHardLink :: ByteString -> TarNode
+ Nix.Fetch.Tar: TarHeaderFailure :: Maybe ByteString -> Text -> TarFailure
+ Nix.Fetch.Tar: TarOther :: TarEntry -> TarNode -> TarStep -> TarStep
+ Nix.Fetch.Tar: TarSpecial :: Int -> TarNode
+ Nix.Fetch.Tar: TarSymlink :: ByteString -> TarNode
+ Nix.Fetch.Tar: TarUnrecognized :: TarFailure
+ Nix.Fetch.Tar: [tarExecutable] :: TarEntry -> Bool
+ Nix.Fetch.Tar: [tarPath] :: TarEntry -> ByteString
+ Nix.Fetch.Tar: [tarWarning] :: TarEntry -> Maybe Text
+ Nix.Fetch.Tar: data FileStep
+ Nix.Fetch.Tar: data TarEntry
+ Nix.Fetch.Tar: data TarFailure
+ Nix.Fetch.Tar: data TarNode
+ Nix.Fetch.Tar: data TarStep
+ Nix.Fetch.Tar: instance GHC.Internal.Classes.Eq Nix.Fetch.Tar.TarEntry
+ Nix.Fetch.Tar: instance GHC.Internal.Classes.Eq Nix.Fetch.Tar.TarFailure
+ Nix.Fetch.Tar: instance GHC.Internal.Classes.Eq Nix.Fetch.Tar.TarNode
+ Nix.Fetch.Tar: instance GHC.Internal.Show.Show Nix.Fetch.Tar.TarEntry
+ Nix.Fetch.Tar: instance GHC.Internal.Show.Show Nix.Fetch.Tar.TarFailure
+ Nix.Fetch.Tar: instance GHC.Internal.Show.Show Nix.Fetch.Tar.TarNode
+ Nix.Fetch.Tar: tarReader :: TarStep
+ Nix.Fetch.Tree: Blob :: Int -> Word64 -> Blob
+ Nix.Fetch.Tree: NarBytes :: ByteString -> NarPiece blob
+ Nix.Fetch.Tree: NarContents :: Word64 -> blob -> NarPiece blob
+ Nix.Fetch.Tree: TreeDirectory :: Map ByteString (Tree blob) -> Tree blob
+ Nix.Fetch.Tree: TreeFile :: Bool -> blob -> Tree blob
+ Nix.Fetch.Tree: TreeSymlink :: ByteString -> Tree blob
+ Nix.Fetch.Tree: [blobNumber] :: Blob -> Int
+ Nix.Fetch.Tree: [blobSize] :: Blob -> Word64
+ Nix.Fetch.Tree: blobFile :: FilePath -> Blob -> FilePath
+ Nix.Fetch.Tree: data Blob
+ Nix.Fetch.Tree: data NarPiece blob
+ Nix.Fetch.Tree: data Tree blob
+ Nix.Fetch.Tree: dereferenceSingleton :: Tree blob -> Tree blob
+ Nix.Fetch.Tree: instance GHC.Internal.Classes.Eq Nix.Fetch.Tree.Blob
+ Nix.Fetch.Tree: instance GHC.Internal.Classes.Eq blob => GHC.Internal.Classes.Eq (Nix.Fetch.Tree.NarPiece blob)
+ Nix.Fetch.Tree: instance GHC.Internal.Classes.Eq blob => GHC.Internal.Classes.Eq (Nix.Fetch.Tree.Tree blob)
+ Nix.Fetch.Tree: instance GHC.Internal.Show.Show Nix.Fetch.Tree.Blob
+ Nix.Fetch.Tree: instance GHC.Internal.Show.Show blob => GHC.Internal.Show.Show (Nix.Fetch.Tree.NarPiece blob)
+ Nix.Fetch.Tree: instance GHC.Internal.Show.Show blob => GHC.Internal.Show.Show (Nix.Fetch.Tree.Tree blob)
+ Nix.Fetch.Tree: narPieces :: (blob -> Word64) -> Tree blob -> [NarPiece blob]
+ Nix.Fetch.Tree: treeNarBytes :: FilePath -> Tree Blob -> IO ByteString
+ Nix.Fetch.Tree: treeNarHash :: FilePath -> Tree Blob -> IO NixHash
+ Nix.Fetch.Tree: withTreeNarSource :: FilePath -> Tree Blob -> (IO ByteString -> IO a) -> IO a
+ Nix.Fetch.Url: Authority :: HostType -> ByteString -> Maybe ByteString -> Maybe ByteString -> Maybe Word16 -> Authority
+ Nix.Fetch.Url: HostIPv4 :: HostType
+ Nix.Fetch.Url: HostIPv6 :: HostType
+ Nix.Fetch.Url: HostIPvFuture :: HostType
+ Nix.Fetch.Url: HostName :: HostType
+ Nix.Fetch.Url: Lenient :: Leniency
+ Nix.Fetch.Url: ParsedUrl :: ByteString -> Maybe Authority -> [ByteString] -> Map ByteString ByteString -> ByteString -> ParsedUrl
+ Nix.Fetch.Url: Strict :: Leniency
+ Nix.Fetch.Url: UrlScheme :: Maybe ByteString -> ByteString -> UrlScheme
+ Nix.Fetch.Url: [authHostType] :: Authority -> HostType
+ Nix.Fetch.Url: [authHost] :: Authority -> ByteString
+ Nix.Fetch.Url: [authPassword] :: Authority -> Maybe ByteString
+ Nix.Fetch.Url: [authPort] :: Authority -> Maybe Word16
+ Nix.Fetch.Url: [authUser] :: Authority -> Maybe ByteString
+ Nix.Fetch.Url: [urlAuthority] :: ParsedUrl -> Maybe Authority
+ Nix.Fetch.Url: [urlFragment] :: ParsedUrl -> ByteString
+ Nix.Fetch.Url: [urlPath] :: ParsedUrl -> [ByteString]
+ Nix.Fetch.Url: [urlQuery] :: ParsedUrl -> Map ByteString ByteString
+ Nix.Fetch.Url: [urlScheme] :: ParsedUrl -> ByteString
+ Nix.Fetch.Url: [utApplication] :: UrlScheme -> Maybe ByteString
+ Nix.Fetch.Url: [utTransport] :: UrlScheme -> ByteString
+ Nix.Fetch.Url: bytesToTextLossy :: ByteString -> Text
+ Nix.Fetch.Url: data Authority
+ Nix.Fetch.Url: data HostType
+ Nix.Fetch.Url: data Leniency
+ Nix.Fetch.Url: data ParsedUrl
+ Nix.Fetch.Url: data UrlScheme
+ Nix.Fetch.Url: decodeQuery :: Leniency -> ByteString -> Checked (Map ByteString ByteString)
+ Nix.Fetch.Url: emptyAuthority :: Authority
+ Nix.Fetch.Url: encodeQuery :: Map ByteString ByteString -> ByteString
+ Nix.Fetch.Url: encodeUrlPath :: [ByteString] -> ByteString
+ Nix.Fetch.Url: fixGitUrl :: PathRules -> ByteString -> Checked ParsedUrl
+ Nix.Fetch.Url: instance GHC.Internal.Classes.Eq Nix.Fetch.Url.Authority
+ Nix.Fetch.Url: instance GHC.Internal.Classes.Eq Nix.Fetch.Url.HostType
+ Nix.Fetch.Url: instance GHC.Internal.Classes.Eq Nix.Fetch.Url.Leniency
+ Nix.Fetch.Url: instance GHC.Internal.Classes.Eq Nix.Fetch.Url.ParsedUrl
+ Nix.Fetch.Url: instance GHC.Internal.Classes.Eq Nix.Fetch.Url.UrlScheme
+ Nix.Fetch.Url: instance GHC.Internal.Show.Show Nix.Fetch.Url.Authority
+ Nix.Fetch.Url: instance GHC.Internal.Show.Show Nix.Fetch.Url.HostType
+ Nix.Fetch.Url: instance GHC.Internal.Show.Show Nix.Fetch.Url.Leniency
+ Nix.Fetch.Url: instance GHC.Internal.Show.Show Nix.Fetch.Url.ParsedUrl
+ Nix.Fetch.Url: instance GHC.Internal.Show.Show Nix.Fetch.Url.UrlScheme
+ Nix.Fetch.Url: isAbsoluteHostPath :: PathRules -> ByteString -> Bool
+ Nix.Fetch.Url: parseUrl :: Leniency -> ByteString -> Checked ParsedUrl
+ Nix.Fetch.Url: parseUrlScheme :: ByteString -> UrlScheme
+ Nix.Fetch.Url: pathToUrlPath :: PathRules -> ByteString -> [ByteString]
+ Nix.Fetch.Url: percentDecode :: ByteString -> Checked ByteString
+ Nix.Fetch.Url: percentEncode :: ByteString -> ByteString -> ByteString
+ Nix.Fetch.Url: refuse :: Text -> Checked a
+ Nix.Fetch.Url: renderAuthority :: Authority -> ByteString
+ Nix.Fetch.Url: renderUrl :: ParsedUrl -> ByteString
+ Nix.Fetch.Url: runChecked :: Checked a -> (Either Text a, [Text])
+ Nix.Fetch.Url: type Checked = ExceptT Text Writer [Text]
+ Nix.Fetch.Url: urlPathSegments :: ParsedUrl -> [ByteString]
+ Nix.Fetch.Url: urlPathToPath :: PathRules -> [ByteString] -> Checked ByteString
+ Nix.Fetch.Url: warn :: Text -> Checked ()
+ Nix.Flake.Ref: FlakeRef :: Input -> ByteString -> FlakeRef
+ Nix.Flake.Ref: [flakeInput] :: FlakeRef -> Input
+ Nix.Flake.Ref: [flakeSubdir] :: FlakeRef -> ByteString
+ Nix.Flake.Ref: data FlakeRef
+ Nix.Flake.Ref: flakeRefAttrs :: FlakeRef -> Attrs
+ Nix.Flake.Ref: flakeRefFromAttrs :: InputContext -> Attrs -> Checked FlakeRef
+ Nix.Flake.Ref: flakeRefToString :: InputContext -> FlakeRef -> Checked ByteString
+ Nix.Flake.Ref: instance GHC.Internal.Classes.Eq Nix.Flake.Ref.FlakeRef
+ Nix.Flake.Ref: instance GHC.Internal.Show.Show Nix.Flake.Ref.FlakeRef
+ Nix.Flake.Ref: parseFlakeRef :: InputContext -> ByteString -> Checked FlakeRef
+ Nix.Flake.Ref: parseFlakeRefWithFragment :: InputContext -> ByteString -> Checked (FlakeRef, ByteString)
+ Nix.Hash: FlatIngestion :: FileIngestionMethod
+ Nix.Hash: NarIngestion :: FileIngestionMethod
+ Nix.Hash: base64ToBytes :: Text -> Maybe ByteString
+ Nix.Hash: data FileIngestionMethod
+ Nix.Hash: data ModuloHash
+ Nix.Hash: digestByLength :: Text -> Text -> Either Text ByteString
+ Nix.Hash: fileIngestionPrefix :: FileIngestionMethod -> Text
+ Nix.Hash: instance GHC.Internal.Classes.Eq Nix.Hash.FileIngestionMethod
+ Nix.Hash: instance GHC.Internal.Show.Show Nix.Hash.FileIngestionMethod
+ Nix.Hash: makeSourcePath :: Text -> ByteString -> Set StorePath -> Either BadStorePath StorePath
+ Nix.Hash: moduloHashFinalize :: ModuloHash -> ByteString
+ Nix.Hash: moduloHashInit :: Text -> ByteString -> Maybe ModuloHash
+ Nix.Hash: moduloHashUpdate :: ModuloHash -> ByteString -> ModuloHash
+ Nix.Hash: parseAnyHash :: Maybe Text -> Text -> Either Text (Text, ByteString)
+ Nix.Hash: parseHashAlgo :: Text -> Either Text Int
+ Nix.Hash: parseNarHash :: Text -> Either Text ByteString
+ Nix.Hash: parseSriHash :: Text -> Either Text (Text, ByteString)
+ Nix.Hash: sha256LazyHex :: ByteString -> Text
+ Nix.Hash: sriDigest :: Text -> Text -> Either Text ByteString
+ Nix.Hash: unknownHashAlgo :: Text -> Text
+ Nix.HostPath: absolutePath :: OsPath -> OsPath -> OsPath
+ Nix.HostPath: hostPathBytes :: OsPath -> Maybe ByteString
+ Nix.Http: defaultDownloadAttempts :: Word32
+ Nix.Http: downloadUrlWith :: Text -> (BodyReader -> IO (Either AttemptFailure a)) -> IO (Either AttemptFailure a)
+ Nix.Http: exceptionFailure :: (String -> Text) -> HttpException -> AttemptFailure
+ Nix.Http: fileUrlFailure :: Text -> String -> AttemptFailure
+ Nix.Json: JsonBuilder :: a -> (Bool -> a) -> (Integer -> a) -> (Double -> a) -> (Text -> a) -> ([a] -> a) -> ([(Text, a)] -> a) -> JsonBuilder a
+ Nix.Json: [buildArray] :: JsonBuilder a -> [a] -> a
+ Nix.Json: [buildBool] :: JsonBuilder a -> Bool -> a
+ Nix.Json: [buildFloat] :: JsonBuilder a -> Double -> a
+ Nix.Json: [buildInt] :: JsonBuilder a -> Integer -> a
+ Nix.Json: [buildNull] :: JsonBuilder a -> a
+ Nix.Json: [buildObject] :: JsonBuilder a -> [(Text, a)] -> a
+ Nix.Json: [buildString] :: JsonBuilder a -> Text -> a
+ Nix.Json: data JsonBuilder a
+ Nix.Json: expectJson :: Text -> (Json -> Maybe a) -> Json -> Either Text a
+ Nix.Json: jsonText :: Json -> Text
+ Nix.Json: parseJsonInto :: IntegerRange -> JsonBuilder a -> Text -> Either Text a
+ Nix.Key: ColonBase64BadCharacter :: Word8 -> ColonBase64Refusal
+ Nix.Key: ColonBase64Corrupt :: ColonBase64Refusal
+ Nix.Key: KeyUnreadable :: ColonBase64Refusal -> KeyRefusal
+ Nix.Key: PublicKeyNotValid :: KeyRefusal
+ Nix.Key: SecretKeyNotValid :: KeyRefusal
+ Nix.Key: colonBase64Message :: Text -> ColonBase64Refusal -> Text
+ Nix.Key: data ColonBase64Refusal
+ Nix.Key: data KeyRefusal
+ Nix.Key: data SecretKey
+ Nix.Key: generateSecretKey :: ByteString -> IO SecretKey
+ Nix.Key: instance GHC.Internal.Classes.Eq Nix.Key.ColonBase64Refusal
+ Nix.Key: instance GHC.Internal.Classes.Eq Nix.Key.KeyRefusal
+ Nix.Key: instance GHC.Internal.Show.Show Nix.Key.ColonBase64Refusal
+ Nix.Key: instance GHC.Internal.Show.Show Nix.Key.KeyRefusal
+ Nix.Key: keyRefusalMessage :: KeyRefusal -> ByteString
+ Nix.Key: keyRefusalReason :: KeyRefusal -> Text
+ Nix.Key: parseColonBase64 :: ByteString -> Either ColonBase64Refusal (ByteString, ByteString)
+ Nix.Key: parsePublicKey :: ByteString -> Either KeyRefusal (ByteString, ByteString)
+ Nix.Key: parseSecretKey :: ByteString -> Either KeyRefusal SecretKey
+ Nix.Key: renderColonBase64 :: ByteString -> ByteString -> ByteString
+ Nix.Key: renderPublicKey :: SecretKey -> ByteString
+ Nix.Key: renderSecretKey :: SecretKey -> ByteString
+ Nix.Key: trustedKeys :: [PublicKey] -> [ByteString] -> IO (Either KeyRefusal [PublicKey])
+ Nix.Key: verifyingKey :: (ByteString, ByteString) -> Maybe PublicKey
+ Nix.Logger: Building :: StorePath -> ActivityStart
+ Nix.Logger: Checking :: StorePath -> ActivityStart
+ Nix.Logger: DropEscapes :: EscapeFilter
+ Nix.Logger: KeepColour :: EscapeFilter
+ Nix.Logger: LevelError :: Level
+ Nix.Logger: LevelInfo :: Level
+ Nix.Logger: LevelWarn :: Level
+ Nix.Logger: Logger :: (Level -> Text -> IO ()) -> (ByteString -> IO ()) -> (ActivityStart -> IO (ByteString -> IO (), IO ())) -> Logger
+ Nix.Logger: Substituting :: StorePath -> Text -> ActivityStart
+ Nix.Logger: [logActivity] :: Logger -> ActivityStart -> IO (ByteString -> IO (), IO ())
+ Nix.Logger: [logAt] :: Logger -> Level -> Text -> IO ()
+ Nix.Logger: [logBuildLine] :: Logger -> ByteString -> IO ()
+ Nix.Logger: data ActivityStart
+ Nix.Logger: data EscapeFilter
+ Nix.Logger: data Level
+ Nix.Logger: data Logger
+ Nix.Logger: escapeFilterFor :: Handle -> IO EscapeFilter
+ Nix.Logger: filterLogLine :: EscapeFilter -> ByteString -> ByteString
+ Nix.Logger: handleLogger :: EscapeFilter -> Handle -> Logger
+ Nix.Logger: instance GHC.Internal.Classes.Eq Nix.Logger.ActivityStart
+ Nix.Logger: instance GHC.Internal.Classes.Eq Nix.Logger.EscapeFilter
+ Nix.Logger: instance GHC.Internal.Classes.Eq Nix.Logger.EscapeKind
+ Nix.Logger: instance GHC.Internal.Classes.Eq Nix.Logger.Level
+ Nix.Logger: instance GHC.Internal.Show.Show Nix.Logger.ActivityStart
+ Nix.Logger: instance GHC.Internal.Show.Show Nix.Logger.EscapeFilter
+ Nix.Logger: instance GHC.Internal.Show.Show Nix.Logger.Level
+ Nix.Logger: logMessage :: Logger -> Text -> IO ()
+ Nix.Logger: logWarning :: Logger -> Text -> IO ()
+ Nix.Logger: plainLogger :: (Level -> Text -> IO ()) -> (ByteString -> IO ()) -> Logger
+ Nix.Logger: withActivity :: Logger -> ActivityStart -> (Logger -> IO a) -> IO a
+ Nix.Parser: data ParsedSource
+ Nix.Parser: instance GHC.Internal.Show.Show Nix.Parser.ParsedSource
+ Nix.Parser: parsedExpr :: ParsedSource -> Expr
+ Nix.Parser: parsedNames :: ParsedSource -> [Text]
+ Nix.Parser.Expr: instance GHC.Internal.Classes.Eq Nix.Parser.Expr.Level
+ Nix.Parser.Expr: instance GHC.Internal.Classes.Ord Nix.Parser.Expr.Level
+ Nix.Parser.Internal: [psNames] :: ParseState -> [Text]
+ Nix.Parser.Internal: recordName :: Text -> Parser ()
+ Nix.Profile.Generation: Changed :: Manifest -> Change
+ Nix.Profile.Generation: DatedGeneration :: Generation -> EpochSeconds -> DatedGeneration
+ Nix.Profile.Generation: Days :: Int32 -> Days
+ Nix.Profile.Generation: DryRun :: Changes
+ Nix.Profile.Generation: EpochSeconds :: Int64 -> EpochSeconds
+ Nix.Profile.Generation: ForeignGeneration :: OsPath -> OsPath -> ProfileFailure
+ Nix.Profile.Generation: Generation :: GenerationNumber -> OsPath -> Generation
+ Nix.Profile.Generation: GenerationAt :: GenerationNumber -> RollbackTarget
+ Nix.Profile.Generation: GenerationNumber :: Word64 -> GenerationNumber
+ Nix.Profile.Generation: HomeProfileLink :: ProfileLinkPlace
+ Nix.Profile.Generation: KeepNewerGeneration :: GenerationNumber -> WipeStep
+ Nix.Profile.Generation: LocalAppDataHome :: OsPath -> StateHome
+ Nix.Profile.Generation: MakeChanges :: Changes
+ Nix.Profile.Generation: ManifestFailed :: OsPath -> ManifestError -> ProfileFailure
+ Nix.Profile.Generation: NewGeneration :: GenerationNumber -> NextGeneration
+ Nix.Profile.Generation: NixEnvProfile :: OsPath -> ProfileFailure
+ Nix.Profile.Generation: NixStateHome :: OsPath -> StateHome
+ Nix.Profile.Generation: NoOlderGeneration :: Maybe GenerationNumber -> ProfileFailure
+ Nix.Profile.Generation: NoSuchGeneration :: GenerationNumber -> ProfileFailure
+ Nix.Profile.Generation: NothingChanged :: Updated
+ Nix.Profile.Generation: PreviousGeneration :: RollbackTarget
+ Nix.Profile.Generation: ProfileEnvironment :: StateHome -> OsPath -> ProfileEnvironment
+ Nix.Profile.Generation: ProfileIOFailed :: Text -> ProfileFailure
+ Nix.Profile.Generation: RemoveGeneration :: GenerationNumber -> WipeStep
+ Nix.Profile.Generation: ReuseGeneration :: Generation -> NextGeneration
+ Nix.Profile.Generation: SlashedTargets :: NarTargets
+ Nix.Profile.Generation: StateProfileLink :: ProfileLinkPlace
+ Nix.Profile.Generation: StoreRefused :: Text -> ProfileFailure
+ Nix.Profile.Generation: SwitchedTo :: Generation -> Updated
+ Nix.Profile.Generation: TargetBytes :: NarTargets
+ Nix.Profile.Generation: TreeConflict :: Conflict -> ProfileFailure
+ Nix.Profile.Generation: TreeFailed :: BuildEnvFailure -> ProfileFailure
+ Nix.Profile.Generation: Unchanged :: Change
+ Nix.Profile.Generation: WipeEveryOld :: WipeScope
+ Nix.Profile.Generation: WipeOlderThan :: EpochSeconds -> WipeScope
+ Nix.Profile.Generation: XdgStateHome :: Maybe OsPath -> StateHome
+ Nix.Profile.Generation: [datedGeneration] :: DatedGeneration -> Generation
+ Nix.Profile.Generation: [datedTime] :: DatedGeneration -> EpochSeconds
+ Nix.Profile.Generation: [generationNumber] :: Generation -> GenerationNumber
+ Nix.Profile.Generation: [generationPath] :: Generation -> OsPath
+ Nix.Profile.Generation: [peHome] :: ProfileEnvironment -> OsPath
+ Nix.Profile.Generation: [peStateHome] :: ProfileEnvironment -> StateHome
+ Nix.Profile.Generation: absolutePath :: OsPath -> OsPath -> OsPath
+ Nix.Profile.Generation: checkProfileStore :: StoreDir -> OsPath -> IO (Either ProfileFailure ())
+ Nix.Profile.Generation: currentEpochSeconds :: IO EpochSeconds
+ Nix.Profile.Generation: currentGeneration :: OsPath -> Maybe OsPath -> Maybe GenerationNumber
+ Nix.Profile.Generation: cutoffBefore :: EpochSeconds -> Days -> EpochSeconds
+ Nix.Profile.Generation: data Change
+ Nix.Profile.Generation: data Changes
+ Nix.Profile.Generation: data DatedGeneration
+ Nix.Profile.Generation: data Generation
+ Nix.Profile.Generation: data NarTargets
+ Nix.Profile.Generation: data NextGeneration
+ Nix.Profile.Generation: data ProfileEnvironment
+ Nix.Profile.Generation: data ProfileFailure
+ Nix.Profile.Generation: data ProfileLinkPlace
+ Nix.Profile.Generation: data RollbackTarget
+ Nix.Profile.Generation: data StateHome
+ Nix.Profile.Generation: data Updated
+ Nix.Profile.Generation: data WipeScope
+ Nix.Profile.Generation: data WipeStep
+ Nix.Profile.Generation: defaultProfilePath :: ProfileEnvironment -> OsPath
+ Nix.Profile.Generation: findGenerations :: OsPath -> IO (Either ProfileFailure ([DatedGeneration], Maybe GenerationNumber))
+ Nix.Profile.Generation: generationDate :: EpochSeconds -> Text
+ Nix.Profile.Generation: generationName :: OsPath -> GenerationNumber -> OsPath
+ Nix.Profile.Generation: generationNar :: NarTargets -> Tree -> ByteString -> Either Text NarEntry
+ Nix.Profile.Generation: generationStoreName :: Text
+ Nix.Profile.Generation: generationsIn :: OsPath -> [OsPath] -> [Generation]
+ Nix.Profile.Generation: hostNarTargets :: NarTargets
+ Nix.Profile.Generation: instance GHC.Internal.Classes.Eq Nix.Profile.Generation.Change
+ Nix.Profile.Generation: instance GHC.Internal.Classes.Eq Nix.Profile.Generation.Changes
+ Nix.Profile.Generation: instance GHC.Internal.Classes.Eq Nix.Profile.Generation.DatedGeneration
+ Nix.Profile.Generation: instance GHC.Internal.Classes.Eq Nix.Profile.Generation.Days
+ Nix.Profile.Generation: instance GHC.Internal.Classes.Eq Nix.Profile.Generation.EpochSeconds
+ Nix.Profile.Generation: instance GHC.Internal.Classes.Eq Nix.Profile.Generation.Generation
+ Nix.Profile.Generation: instance GHC.Internal.Classes.Eq Nix.Profile.Generation.GenerationNumber
+ Nix.Profile.Generation: instance GHC.Internal.Classes.Eq Nix.Profile.Generation.NarTargets
+ Nix.Profile.Generation: instance GHC.Internal.Classes.Eq Nix.Profile.Generation.NextGeneration
+ Nix.Profile.Generation: instance GHC.Internal.Classes.Eq Nix.Profile.Generation.ProfileEnvironment
+ Nix.Profile.Generation: instance GHC.Internal.Classes.Eq Nix.Profile.Generation.ProfileFailure
+ Nix.Profile.Generation: instance GHC.Internal.Classes.Eq Nix.Profile.Generation.ProfileLinkPlace
+ Nix.Profile.Generation: instance GHC.Internal.Classes.Eq Nix.Profile.Generation.RollbackTarget
+ Nix.Profile.Generation: instance GHC.Internal.Classes.Eq Nix.Profile.Generation.StateHome
+ Nix.Profile.Generation: instance GHC.Internal.Classes.Eq Nix.Profile.Generation.Updated
+ Nix.Profile.Generation: instance GHC.Internal.Classes.Eq Nix.Profile.Generation.WipeScope
+ Nix.Profile.Generation: instance GHC.Internal.Classes.Eq Nix.Profile.Generation.WipeStep
+ Nix.Profile.Generation: instance GHC.Internal.Classes.Ord Nix.Profile.Generation.EpochSeconds
+ Nix.Profile.Generation: instance GHC.Internal.Classes.Ord Nix.Profile.Generation.GenerationNumber
+ Nix.Profile.Generation: instance GHC.Internal.Show.Show Nix.Profile.Generation.Change
+ Nix.Profile.Generation: instance GHC.Internal.Show.Show Nix.Profile.Generation.Changes
+ Nix.Profile.Generation: instance GHC.Internal.Show.Show Nix.Profile.Generation.DatedGeneration
+ Nix.Profile.Generation: instance GHC.Internal.Show.Show Nix.Profile.Generation.Days
+ Nix.Profile.Generation: instance GHC.Internal.Show.Show Nix.Profile.Generation.EpochSeconds
+ Nix.Profile.Generation: instance GHC.Internal.Show.Show Nix.Profile.Generation.Generation
+ Nix.Profile.Generation: instance GHC.Internal.Show.Show Nix.Profile.Generation.GenerationNumber
+ Nix.Profile.Generation: instance GHC.Internal.Show.Show Nix.Profile.Generation.NarTargets
+ Nix.Profile.Generation: instance GHC.Internal.Show.Show Nix.Profile.Generation.NextGeneration
+ Nix.Profile.Generation: instance GHC.Internal.Show.Show Nix.Profile.Generation.ProfileEnvironment
+ Nix.Profile.Generation: instance GHC.Internal.Show.Show Nix.Profile.Generation.ProfileFailure
+ Nix.Profile.Generation: instance GHC.Internal.Show.Show Nix.Profile.Generation.ProfileLinkPlace
+ Nix.Profile.Generation: instance GHC.Internal.Show.Show Nix.Profile.Generation.RollbackTarget
+ Nix.Profile.Generation: instance GHC.Internal.Show.Show Nix.Profile.Generation.StateHome
+ Nix.Profile.Generation: instance GHC.Internal.Show.Show Nix.Profile.Generation.Updated
+ Nix.Profile.Generation: instance GHC.Internal.Show.Show Nix.Profile.Generation.WipeScope
+ Nix.Profile.Generation: instance GHC.Internal.Show.Show Nix.Profile.Generation.WipeStep
+ Nix.Profile.Generation: listGenerations :: OsPath -> IO (Either ProfileFailure [Generation])
+ Nix.Profile.Generation: narLinkTarget :: NarTargets -> ByteString -> ByteString
+ Nix.Profile.Generation: newtype Days
+ Nix.Profile.Generation: newtype EpochSeconds
+ Nix.Profile.Generation: newtype GenerationNumber
+ Nix.Profile.Generation: nextGeneration :: Maybe (Generation, OsPath) -> OsPath -> NextGeneration
+ Nix.Profile.Generation: parseGenerationName :: OsPath -> OsPath -> Maybe GenerationNumber
+ Nix.Profile.Generation: parseOlderThan :: String -> Either Text Days
+ Nix.Profile.Generation: profileLinkPath :: ProfileLinkPlace -> ProfileEnvironment -> OsPath
+ Nix.Profile.Generation: profilesDirectory :: ProfileEnvironment -> OsPath
+ Nix.Profile.Generation: readGenerationNumber :: String -> Either Text GenerationNumber
+ Nix.Profile.Generation: readManifest :: OsPath -> IO (Either ProfileFailure Manifest)
+ Nix.Profile.Generation: readProfileEnvironment :: Logger -> IO (Either Text ProfileEnvironment)
+ Nix.Profile.Generation: resolveDefaultProfile :: ProfileLinkPlace -> ProfileEnvironment -> IO (Either Text OsPath)
+ Nix.Profile.Generation: rollbackPlan :: RollbackTarget -> Maybe GenerationNumber -> [Generation] -> Either ProfileFailure Generation
+ Nix.Profile.Generation: stateDirectory :: ProfileEnvironment -> OsPath
+ Nix.Profile.Generation: switchGeneration :: Logger -> OsPath -> RollbackTarget -> Changes -> IO (Either ProfileFailure ())
+ Nix.Profile.Generation: updateProfile :: Logger -> StoreOps IO -> StoreDir -> OsPath -> (Manifest -> IO Change) -> IO (Either ProfileFailure Updated)
+ Nix.Profile.Generation: wipeHistory :: Logger -> OsPath -> WipeScope -> Changes -> IO (Either ProfileFailure ())
+ Nix.Profile.Generation: wipePlan :: WipeScope -> Maybe GenerationNumber -> [DatedGeneration] -> [WipeStep]
+ Nix.Profile.Manifest: Conflict :: ConflictSide -> ConflictSide -> Int -> Conflict
+ Nix.Profile.Manifest: ConflictSide :: OsPath -> Text -> Set Text -> ConflictSide
+ Nix.Profile.Manifest: Element :: Set StorePath -> Activity -> Int -> Maybe FlakeSource -> Element
+ Nix.Profile.Manifest: ElementAdded :: Text -> Text -> ElementChange
+ Nix.Profile.Manifest: ElementRemoved :: Text -> Text -> ElementChange
+ Nix.Profile.Manifest: ElementUpgraded :: Text -> Text -> Text -> ElementChange
+ Nix.Profile.Manifest: FlakeSource :: Text -> Text -> Text -> Maybe OutputsSpec -> FlakeSource
+ Nix.Profile.Manifest: MalformedElement :: Text -> Text -> ManifestError
+ Nix.Profile.Manifest: Manifest :: Map Text Element -> Manifest
+ Nix.Profile.Manifest: ManifestNotJson :: Text -> ManifestError
+ Nix.Profile.Manifest: MatchName :: Text -> Matcher
+ Nix.Profile.Manifest: MatchRegex :: Text -> Regex -> Matcher
+ Nix.Profile.Manifest: MatchStorePath :: StorePath -> Matcher
+ Nix.Profile.Manifest: SelectAll :: Selector
+ Nix.Profile.Manifest: SelectSome :: NonEmpty Matcher -> Selector
+ Nix.Profile.Manifest: Selection :: Set Text -> [Text] -> Selection
+ Nix.Profile.Manifest: UnnamedFlakeElement :: Text -> ManifestError
+ Nix.Profile.Manifest: UnsupportedVersion :: Integer -> ManifestError
+ Nix.Profile.Manifest: [conflictExisting] :: Conflict -> ConflictSide
+ Nix.Profile.Manifest: [conflictNew] :: Conflict -> ConflictSide
+ Nix.Profile.Manifest: [conflictPriority] :: Conflict -> Int
+ Nix.Profile.Manifest: [elementActivity] :: Element -> Activity
+ Nix.Profile.Manifest: [elementPaths] :: Element -> Set StorePath
+ Nix.Profile.Manifest: [elementPriority] :: Element -> Int
+ Nix.Profile.Manifest: [elementSource] :: Element -> Maybe FlakeSource
+ Nix.Profile.Manifest: [manifestElements] :: Manifest -> Map Text Element
+ Nix.Profile.Manifest: [selectedNames] :: Selection -> Set Text
+ Nix.Profile.Manifest: [selectionWarnings] :: Selection -> [Text]
+ Nix.Profile.Manifest: [sourceAttrPath] :: FlakeSource -> Text
+ Nix.Profile.Manifest: [sourceOriginalUrl] :: FlakeSource -> Text
+ Nix.Profile.Manifest: [sourceOutputs] :: FlakeSource -> Maybe OutputsSpec
+ Nix.Profile.Manifest: [sourceUrl] :: FlakeSource -> Text
+ Nix.Profile.Manifest: addElement :: Text -> Element -> Manifest -> Manifest
+ Nix.Profile.Manifest: attributeConflict :: StoreDir -> StoreDir -> Manifest -> OsPath -> OsPath -> Int -> Maybe Conflict
+ Nix.Profile.Manifest: changeLine :: ElementChange -> Text
+ Nix.Profile.Manifest: data Conflict
+ Nix.Profile.Manifest: data ConflictSide
+ Nix.Profile.Manifest: data Element
+ Nix.Profile.Manifest: data ElementChange
+ Nix.Profile.Manifest: data FlakeSource
+ Nix.Profile.Manifest: data ManifestError
+ Nix.Profile.Manifest: data Matcher
+ Nix.Profile.Manifest: data Selection
+ Nix.Profile.Manifest: data Selector
+ Nix.Profile.Manifest: defaultPriority :: Int
+ Nix.Profile.Manifest: drvNameName :: Text -> Text
+ Nix.Profile.Manifest: elementIdentifier :: Element -> Text
+ Nix.Profile.Manifest: elementVersions :: Element -> Text
+ Nix.Profile.Manifest: emptyManifest :: Manifest
+ Nix.Profile.Manifest: flakeAttribute :: FlakeSource -> Text
+ Nix.Profile.Manifest: instance GHC.Internal.Classes.Eq Nix.Profile.Manifest.Conflict
+ Nix.Profile.Manifest: instance GHC.Internal.Classes.Eq Nix.Profile.Manifest.ConflictSide
+ Nix.Profile.Manifest: instance GHC.Internal.Classes.Eq Nix.Profile.Manifest.Element
+ Nix.Profile.Manifest: instance GHC.Internal.Classes.Eq Nix.Profile.Manifest.ElementChange
+ Nix.Profile.Manifest: instance GHC.Internal.Classes.Eq Nix.Profile.Manifest.FlakeSource
+ Nix.Profile.Manifest: instance GHC.Internal.Classes.Eq Nix.Profile.Manifest.Manifest
+ Nix.Profile.Manifest: instance GHC.Internal.Classes.Eq Nix.Profile.Manifest.ManifestError
+ Nix.Profile.Manifest: instance GHC.Internal.Classes.Eq Nix.Profile.Manifest.Selection
+ Nix.Profile.Manifest: instance GHC.Internal.Show.Show Nix.Profile.Manifest.Conflict
+ Nix.Profile.Manifest: instance GHC.Internal.Show.Show Nix.Profile.Manifest.ConflictSide
+ Nix.Profile.Manifest: instance GHC.Internal.Show.Show Nix.Profile.Manifest.Element
+ Nix.Profile.Manifest: instance GHC.Internal.Show.Show Nix.Profile.Manifest.ElementChange
+ Nix.Profile.Manifest: instance GHC.Internal.Show.Show Nix.Profile.Manifest.FlakeSource
+ Nix.Profile.Manifest: instance GHC.Internal.Show.Show Nix.Profile.Manifest.Manifest
+ Nix.Profile.Manifest: instance GHC.Internal.Show.Show Nix.Profile.Manifest.ManifestError
+ Nix.Profile.Manifest: instance GHC.Internal.Show.Show Nix.Profile.Manifest.Selection
+ Nix.Profile.Manifest: manifestChanges :: Manifest -> Manifest -> [ElementChange]
+ Nix.Profile.Manifest: manifestErrorText :: OsPath -> ManifestError -> Text
+ Nix.Profile.Manifest: manifestJson :: Manifest -> Json
+ Nix.Profile.Manifest: manifestPackages :: Manifest -> [(StorePath, Int)]
+ Nix.Profile.Manifest: manifestReferences :: Manifest -> Set StorePath
+ Nix.Profile.Manifest: matcherTitle :: Matcher -> Text
+ Nix.Profile.Manifest: newtype Manifest
+ Nix.Profile.Manifest: parseManifest :: ByteString -> Either ManifestError Manifest
+ Nix.Profile.Manifest: regexMatcher :: Text -> Maybe Matcher
+ Nix.Profile.Manifest: renderManifest :: Manifest -> ByteString
+ Nix.Profile.Manifest: selectElements :: Selector -> Manifest -> Selection
+ Nix.Profile.Tree: Built :: [Warning] -> Either BuildEnvFailure Tree -> Built
+ Nix.Profile.Tree: DanglingLink :: OsPath -> Warning
+ Nix.Profile.Tree: Directory :: Tree -> Node
+ Nix.Profile.Tree: DirectoryEntry :: EntryKind
+ Nix.Profile.Tree: Entries :: [OsPath] -> Listing
+ Nix.Profile.Tree: FileConflict :: OsPath -> OsPath -> Int -> BuildEnvFailure
+ Nix.Profile.Tree: FileOverDirectory :: OsPath -> OsPath -> BuildEnvFailure
+ Nix.Profile.Tree: Link :: OsPath -> Int -> Node
+ Nix.Profile.Tree: LinkToNonDirectory :: OsPath -> OsPath -> BuildEnvFailure
+ Nix.Profile.Tree: NonDirectoryEntry :: EntryKind
+ Nix.Profile.Tree: NotADirectory :: Listing
+ Nix.Profile.Tree: NotIncluded :: OsPath -> Warning
+ Nix.Profile.Tree: Package :: OsPath -> Int -> Package
+ Nix.Profile.Tree: ReadFailed :: ReadFailure -> BuildEnvFailure
+ Nix.Profile.Tree: ReadFailure :: Text -> ReadFailure
+ Nix.Profile.Tree: TreeReader :: (OsPath -> m (Either ReadFailure Listing)) -> (OsPath -> m (Either ReadFailure (Maybe EntryKind))) -> (OsPath -> m (Either ReadFailure OsPath)) -> (OsPath -> m (Either ReadFailure [OsPath])) -> TreeReader (m :: Type -> Type)
+ Nix.Profile.Tree: [builtTree] :: Built -> Either BuildEnvFailure Tree
+ Nix.Profile.Tree: [builtWarnings] :: Built -> [Warning]
+ Nix.Profile.Tree: [pkgPath] :: Package -> OsPath
+ Nix.Profile.Tree: [pkgPriority] :: Package -> Int
+ Nix.Profile.Tree: [trEntries] :: TreeReader (m :: Type -> Type) -> OsPath -> m (Either ReadFailure Listing)
+ Nix.Profile.Tree: [trKind] :: TreeReader (m :: Type -> Type) -> OsPath -> m (Either ReadFailure (Maybe EntryKind))
+ Nix.Profile.Tree: [trPropagated] :: TreeReader (m :: Type -> Type) -> OsPath -> m (Either ReadFailure [OsPath])
+ Nix.Profile.Tree: [trResolve] :: TreeReader (m :: Type -> Type) -> OsPath -> m (Either ReadFailure OsPath)
+ Nix.Profile.Tree: buildEnvFailureText :: BuildEnvFailure -> Text
+ Nix.Profile.Tree: buildProfile :: Monad m => TreeReader m -> OsPath -> [Package] -> m Built
+ Nix.Profile.Tree: data BuildEnvFailure
+ Nix.Profile.Tree: data Built
+ Nix.Profile.Tree: data EntryKind
+ Nix.Profile.Tree: data Listing
+ Nix.Profile.Tree: data Node
+ Nix.Profile.Tree: data Package
+ Nix.Profile.Tree: data TreeReader (m :: Type -> Type)
+ Nix.Profile.Tree: data Warning
+ Nix.Profile.Tree: instance GHC.Internal.Classes.Eq Nix.Profile.Tree.BuildEnvFailure
+ Nix.Profile.Tree: instance GHC.Internal.Classes.Eq Nix.Profile.Tree.Built
+ Nix.Profile.Tree: instance GHC.Internal.Classes.Eq Nix.Profile.Tree.EntryKind
+ Nix.Profile.Tree: instance GHC.Internal.Classes.Eq Nix.Profile.Tree.Listing
+ Nix.Profile.Tree: instance GHC.Internal.Classes.Eq Nix.Profile.Tree.Node
+ Nix.Profile.Tree: instance GHC.Internal.Classes.Eq Nix.Profile.Tree.Package
+ Nix.Profile.Tree: instance GHC.Internal.Classes.Eq Nix.Profile.Tree.ReadFailure
+ Nix.Profile.Tree: instance GHC.Internal.Classes.Eq Nix.Profile.Tree.Warning
+ Nix.Profile.Tree: instance GHC.Internal.Show.Show Nix.Profile.Tree.BuildEnvFailure
+ Nix.Profile.Tree: instance GHC.Internal.Show.Show Nix.Profile.Tree.Built
+ Nix.Profile.Tree: instance GHC.Internal.Show.Show Nix.Profile.Tree.EntryKind
+ Nix.Profile.Tree: instance GHC.Internal.Show.Show Nix.Profile.Tree.Listing
+ Nix.Profile.Tree: instance GHC.Internal.Show.Show Nix.Profile.Tree.Node
+ Nix.Profile.Tree: instance GHC.Internal.Show.Show Nix.Profile.Tree.Package
+ Nix.Profile.Tree: instance GHC.Internal.Show.Show Nix.Profile.Tree.ReadFailure
+ Nix.Profile.Tree: instance GHC.Internal.Show.Show Nix.Profile.Tree.Warning
+ Nix.Profile.Tree: newtype ReadFailure
+ Nix.Profile.Tree: propagatedTokens :: ByteString -> [ByteString]
+ Nix.Profile.Tree: storePackagePath :: StoreDir -> ByteString -> IO (Maybe OsPath)
+ Nix.Profile.Tree: storeTreeReader :: StoreDir -> TreeReader IO
+ Nix.Profile.Tree: type Tree = Map OsPath Node
+ Nix.Profile.Tree: warningText :: Warning -> Text
+ Nix.Profile.Tree: writeTree :: OsPath -> Tree -> IO (Either Text ())
+ Nix.Push: [pcPartSize] :: PushConfig -> PartSize
+ Nix.Push: [pcRetry] :: PushConfig -> FetchRetryPolicy
+ Nix.Push: data PartSize
+ Nix.Push: defaultPartSize :: PartSize
+ Nix.Push: instance GHC.Internal.Classes.Eq Nix.Push.PartSize
+ Nix.Push: instance GHC.Internal.Show.Show Nix.Push.PartSize
+ Nix.Push: loadKeyFile :: FilePath -> IO (Either Text Text)
+ Nix.Push: logNar :: Logger -> StorePath -> PushArtifact -> ExceptT Text IO ()
+ Nix.Push: logPushed :: Logger -> StorePath -> ExceptT Text IO ()
+ Nix.Push: logSkipped :: Logger -> Int -> ExceptT Text IO ()
+ Nix.Push: mkPartSize :: Int -> Maybe PartSize
+ Nix.Push: narDirSegment :: Text
+ Nix.Push: narInfoFileName :: StorePath -> Text
+ Nix.Push: partSizeBytes :: PartSize -> Int
+ Nix.Push: preparePath :: PushCompression -> PushSource -> StorePath -> ExceptT Text IO (PushArtifact, NarInfo)
+ Nix.Push: splitParts :: PartSize -> ByteString -> [ByteString]
+ Nix.Push.Directory: DirectoryPush :: FilePath -> SecretKey -> PushCompression -> DirectoryPush
+ Nix.Push.Directory: DirectoryTarget :: FilePath -> FilePath -> PushTarget
+ Nix.Push.Directory: ServerTarget :: Text -> Maybe FilePath -> PushTarget
+ Nix.Push.Directory: [dpCompression] :: DirectoryPush -> PushCompression
+ Nix.Push.Directory: [dpDirectory] :: DirectoryPush -> FilePath
+ Nix.Push.Directory: [dpSecretKey] :: DirectoryPush -> SecretKey
+ Nix.Push.Directory: data DirectoryPush
+ Nix.Push.Directory: data PushTarget
+ Nix.Push.Directory: ed25519SeedBytes :: Int
+ Nix.Push.Directory: instance GHC.Internal.Classes.Eq Nix.Push.Directory.DirectoryPush
+ Nix.Push.Directory: instance GHC.Internal.Classes.Eq Nix.Push.Directory.PushTarget
+ Nix.Push.Directory: instance GHC.Internal.Show.Show Nix.Push.Directory.DirectoryPush
+ Nix.Push.Directory: instance GHC.Internal.Show.Show Nix.Push.Directory.PushTarget
+ Nix.Push.Directory: loadSecretKeyFile :: FilePath -> IO (Either Text SecretKey)
+ Nix.Push.Directory: pushTarget :: String -> Maybe FilePath -> Maybe FilePath -> Either Text PushTarget
+ Nix.Push.Directory: pushToDirectory :: DirectoryPush -> PushSource -> [StorePath] -> IO (Either Text PushSummary)
+ Nix.Push.Directory: signNarInfo :: SecretKey -> NarInfo -> Either Text NarInfo
+ Nix.Push.Source: PushSource :: StoreDir -> CaseHack -> Logger -> (StorePath -> IO (Either Text [StorePath])) -> (StorePath -> IO (Either Text (Maybe PushedPath))) -> IO (Either Text [StorePath]) -> PushSource
+ Nix.Push.Source: PushedPath :: Text -> [StorePath] -> Maybe StorePath -> PushedPath
+ Nix.Push.Source: [ppDeriver] :: PushedPath -> Maybe StorePath
+ Nix.Push.Source: [ppNarHash] :: PushedPath -> Text
+ Nix.Push.Source: [ppReferences] :: PushedPath -> [StorePath]
+ Nix.Push.Source: [psAllValid] :: PushSource -> IO (Either Text [StorePath])
+ Nix.Push.Source: [psCaseHack] :: PushSource -> CaseHack
+ Nix.Push.Source: [psLogger] :: PushSource -> Logger
+ Nix.Push.Source: [psPathInfo] :: PushSource -> StorePath -> IO (Either Text (Maybe PushedPath))
+ Nix.Push.Source: [psReferences] :: PushSource -> StorePath -> IO (Either Text [StorePath])
+ Nix.Push.Source: [psStoreDir] :: PushSource -> StoreDir
+ Nix.Push.Source: data PushSource
+ Nix.Push.Source: data PushedPath
+ Nix.Push.Source: instance GHC.Internal.Classes.Eq Nix.Push.Source.PushedPath
+ Nix.Push.Source: instance GHC.Internal.Show.Show Nix.Push.Source.PushedPath
+ Nix.Push.Source: localPushSource :: Store -> PushSource
+ Nix.Realise: AlwaysAllowSubstitutes :: SubstitutesSetting
+ Nix.Realise: AttrsInEnvironment :: Map Text ByteString -> DerivationAttrs
+ Nix.Realise: AttrsInJson :: Json -> DerivationAttrs
+ Nix.Realise: BuildCheck :: BuildMode
+ Nix.Realise: BuildNormal :: BuildMode
+ Nix.Realise: BuilderStopped :: Text -> FailedBuild
+ Nix.Realise: Checked :: Realised
+ Nix.Realise: DeliveryFailed :: Undelivered
+ Nix.Realise: EveryOutput :: OutputSelection
+ Nix.Realise: FailedLeaving :: RealiseFailure -> StorePath -> NonEmpty StorePath -> RequestsFailure
+ Nix.Realise: FailedWith :: RealiseFailure -> RequestsFailure
+ Nix.Realise: FixedOutputMismatch :: Text -> FailedBuild
+ Nix.Realise: FixedOutputRejected :: Text -> RealiseFailure
+ Nix.Realise: Gone :: Undelivered
+ Nix.Realise: HeedAllowSubstitutes :: SubstitutesSetting
+ Nix.Realise: InvalidDerivation :: Text -> RealiseFailure
+ Nix.Realise: MaySubstitute :: Substitutes
+ Nix.Realise: MissingDerivation :: StorePath -> RealiseFailure
+ Nix.Realise: MissingEffects :: (StorePath -> m Bool) -> (StorePath -> m (Either Text Derivation)) -> (StorePath -> m (Offer s)) -> (s -> (Word64, Word64)) -> MissingEffects s (m :: Type -> Type)
+ Nix.Realise: MissingOutputs :: StorePath -> NonEmpty Text -> RealiseFailure
+ Nix.Realise: MissingPaths :: Set StorePath -> Set StorePath -> Set StorePath -> Word64 -> Word64 -> MissingPaths
+ Nix.Realise: MustBuild :: Substitutes
+ Nix.Realise: NotDeterministic :: StorePath -> StorePath -> DifferingRebuild -> RealiseFailure
+ Nix.Realise: NotFetched :: NonEmpty (StorePath, Undelivered) -> FetchOutcome
+ Nix.Realise: OutputDiffers :: StorePath -> DifferingRebuild -> CheckVerdict
+ Nix.Realise: OutputsMatch :: CheckVerdict
+ Nix.Realise: OutputsNotValid :: StorePath -> RealiseFailure
+ Nix.Realise: RealiseSettings :: Fallback -> SubstitutesSetting -> RealiseSettings
+ Nix.Realise: RebuildDiscarded :: DifferingRebuild
+ Nix.Realise: RebuildKept :: DifferingRebuild
+ Nix.Realise: RegisterAll :: Registration
+ Nix.Realise: RegisterNone :: Registration
+ Nix.Realise: RequestDependencyFailed :: StorePath -> RealiseFailure -> RequestOutcome
+ Nix.Realise: RequestFailed :: RealiseFailure -> RequestOutcome
+ Nix.Realise: RequestRealised :: Realised -> RequestOutcome
+ Nix.Realise: TheseOutputs :: Set Text -> OutputSelection
+ Nix.Realise: WantedOutputs :: StorePath -> OutputSelection -> Wanted
+ Nix.Realise: WantedPath :: StorePath -> Wanted
+ Nix.Realise: [meDerivation] :: MissingEffects s (m :: Type -> Type) -> StorePath -> m (Either Text Derivation)
+ Nix.Realise: [meOffer] :: MissingEffects s (m :: Type -> Type) -> StorePath -> m (Offer s)
+ Nix.Realise: [meSizes] :: MissingEffects s (m :: Type -> Type) -> s -> (Word64, Word64)
+ Nix.Realise: [meValid] :: MissingEffects s (m :: Type -> Type) -> StorePath -> m Bool
+ Nix.Realise: [mpBuild] :: MissingPaths -> Set StorePath
+ Nix.Realise: [mpDownloadSize] :: MissingPaths -> Word64
+ Nix.Realise: [mpNarSize] :: MissingPaths -> Word64
+ Nix.Realise: [mpSubstitute] :: MissingPaths -> Set StorePath
+ Nix.Realise: [mpUnknown] :: MissingPaths -> Set StorePath
+ Nix.Realise: [reCheck] :: RealiseEffects s (m :: Type -> Type) -> Derivation -> StorePath -> m (Either Text CheckVerdict)
+ Nix.Realise: [rsFallback] :: RealiseSettings -> Fallback
+ Nix.Realise: [rsSubstitutes] :: RealiseSettings -> SubstitutesSetting
+ Nix.Realise: [seNextOffer] :: SubstEffects s (m :: Type -> Type) -> StorePath -> s -> m (Offer s)
+ Nix.Realise: checkedOutputPath :: StoreDir -> StorePath -> FilePath
+ Nix.Realise: data BuildMode
+ Nix.Realise: data CheckVerdict
+ Nix.Realise: data DerivationAttrs
+ Nix.Realise: data DifferingRebuild
+ Nix.Realise: data FailedBuild
+ Nix.Realise: data MissingEffects s (m :: Type -> Type)
+ Nix.Realise: data MissingPaths
+ Nix.Realise: data OutputSelection
+ Nix.Realise: data RealiseSettings
+ Nix.Realise: data Registration
+ Nix.Realise: data RequestOutcome
+ Nix.Realise: data RequestsFailure
+ Nix.Realise: data Substitutes
+ Nix.Realise: data SubstitutesSetting
+ Nix.Realise: data Undelivered
+ Nix.Realise: data Wanted
+ Nix.Realise: derivationAttrs :: StorePath -> Derivation -> Either Text DerivationAttrs
+ Nix.Realise: derivationBoolAttr :: StorePath -> Text -> Bool -> DerivationAttrs -> Either Text Bool
+ Nix.Realise: derivationStringAttr :: StorePath -> Text -> DerivationAttrs -> Either Text (Maybe ByteString)
+ Nix.Realise: derivationStringsAttr :: StorePath -> Text -> DerivationAttrs -> Either Text (Maybe [ByteString])
+ Nix.Realise: instance GHC.Internal.Classes.Eq Nix.Realise.BuildMode
+ Nix.Realise: instance GHC.Internal.Classes.Eq Nix.Realise.CheckVerdict
+ Nix.Realise: instance GHC.Internal.Classes.Eq Nix.Realise.DerivationAttrs
+ Nix.Realise: instance GHC.Internal.Classes.Eq Nix.Realise.DifferingRebuild
+ Nix.Realise: instance GHC.Internal.Classes.Eq Nix.Realise.FailedBuild
+ Nix.Realise: instance GHC.Internal.Classes.Eq Nix.Realise.MissingPaths
+ Nix.Realise: instance GHC.Internal.Classes.Eq Nix.Realise.OutputSelection
+ Nix.Realise: instance GHC.Internal.Classes.Eq Nix.Realise.RealiseSettings
+ Nix.Realise: instance GHC.Internal.Classes.Eq Nix.Realise.Registration
+ Nix.Realise: instance GHC.Internal.Classes.Eq Nix.Realise.RequestOutcome
+ Nix.Realise: instance GHC.Internal.Classes.Eq Nix.Realise.RequestsFailure
+ Nix.Realise: instance GHC.Internal.Classes.Eq Nix.Realise.Substitutes
+ Nix.Realise: instance GHC.Internal.Classes.Eq Nix.Realise.SubstitutesSetting
+ Nix.Realise: instance GHC.Internal.Classes.Eq Nix.Realise.Undelivered
+ Nix.Realise: instance GHC.Internal.Classes.Eq Nix.Realise.Wanted
+ Nix.Realise: instance GHC.Internal.Classes.Eq s => GHC.Internal.Classes.Eq (Nix.Realise.Offer s)
+ Nix.Realise: instance GHC.Internal.Classes.Ord Nix.Realise.OutputSelection
+ Nix.Realise: instance GHC.Internal.Classes.Ord Nix.Realise.Wanted
+ Nix.Realise: instance GHC.Internal.Show.Show Nix.Realise.BuildMode
+ Nix.Realise: instance GHC.Internal.Show.Show Nix.Realise.CheckVerdict
+ Nix.Realise: instance GHC.Internal.Show.Show Nix.Realise.DerivationAttrs
+ Nix.Realise: instance GHC.Internal.Show.Show Nix.Realise.DifferingRebuild
+ Nix.Realise: instance GHC.Internal.Show.Show Nix.Realise.FailedBuild
+ Nix.Realise: instance GHC.Internal.Show.Show Nix.Realise.MissingPaths
+ Nix.Realise: instance GHC.Internal.Show.Show Nix.Realise.OutputSelection
+ Nix.Realise: instance GHC.Internal.Show.Show Nix.Realise.RealiseSettings
+ Nix.Realise: instance GHC.Internal.Show.Show Nix.Realise.Registration
+ Nix.Realise: instance GHC.Internal.Show.Show Nix.Realise.RequestOutcome
+ Nix.Realise: instance GHC.Internal.Show.Show Nix.Realise.RequestsFailure
+ Nix.Realise: instance GHC.Internal.Show.Show Nix.Realise.Substitutes
+ Nix.Realise: instance GHC.Internal.Show.Show Nix.Realise.SubstitutesSetting
+ Nix.Realise: instance GHC.Internal.Show.Show Nix.Realise.Undelivered
+ Nix.Realise: instance GHC.Internal.Show.Show Nix.Realise.Wanted
+ Nix.Realise: instance GHC.Internal.Show.Show s => GHC.Internal.Show.Show (Nix.Realise.Offer s)
+ Nix.Realise: noWriteAccessMessage :: StorePath -> Text
+ Nix.Realise: planMissing :: Monad m => SubstitutesSetting -> MissingEffects s m -> [Wanted] -> m (Either Text MissingPaths)
+ Nix.Realise: realiseEach :: Monad m => RealiseSettings -> BuildMode -> RealiseEffects s m -> DepGraph -> [(StorePath, Set Text)] -> m (Either RealiseFailure (Map StorePath RequestOutcome))
+ Nix.Realise: realiseFailureStatus :: RealiseFailure -> Int
+ Nix.Realise: realiseRequests :: Monad m => RealiseSettings -> RealiseEffects s m -> DepGraph -> [(StorePath, Set Text)] -> m (Either RequestsFailure ())
+ Nix.Realise: requestsFailureMessage :: StoreDir -> RequestsFailure -> Text
+ Nix.Realise: requestsFailureStatus :: RequestsFailure -> Int
+ Nix.Realise: substitutesAllowed :: SubstitutesSetting -> StorePath -> DerivationAttrs -> Either Text Substitutes
+ Nix.Signals: interruptOnTermination :: IO ()
+ Nix.Store: AtEndOfInput :: ArchiveEnd
+ Nix.Store: AtRootClose :: ArchiveEnd
+ Nix.Store: MakesAnotherPath :: AddressedPath
+ Nix.Store: MakesItsPath :: AddressedPath
+ Nix.Store: MakesNoPath :: Text -> AddressedPath
+ Nix.Store: NarEnded :: NixHash -> Int -> ByteString -> NarFed
+ Nix.Store: NarGoesOn :: NarFeed -> NarFed
+ Nix.Store: RequireSignature :: [PublicKey] -> SignatureRequirement
+ Nix.Store: SignaturesNotRequired :: SignatureRequirement
+ Nix.Store: addSourceTree :: Store -> Text -> Set StorePath -> NarEntry -> IO (Either Text StorePath)
+ Nix.Store: addressMakesPath :: StorePath -> [StorePath] -> ContentAddress -> AddressedPath
+ Nix.Store: addressRegistrable :: Logger -> StorePath -> [StorePath] -> ContentAddress -> IO (Either Text ())
+ Nix.Store: canonicalizeMetadata :: FilePath -> IO ()
+ Nix.Store: checkNarClaim :: Text -> NixHash -> Integer -> NixHash -> Integer -> Either Text ()
+ Nix.Store: closeNarUnpack :: NarUnpackSink -> IO (Either Text NarLinks)
+ Nix.Store: data AddressedPath
+ Nix.Store: data ArchiveEnd
+ Nix.Store: data NarFed
+ Nix.Store: data NarFeed
+ Nix.Store: data NarLinks
+ Nix.Store: data SignatureRequirement
+ Nix.Store: drvReferences :: Derivation -> [StorePath]
+ Nix.Store: endNar :: NarUnpackSink -> NarFeed -> IO (Either NarStreamFailure (NixHash, Int))
+ Nix.Store: feedNar :: NarUnpackSink -> NarFeed -> ByteString -> IO (Either NarStreamFailure NarFed)
+ Nix.Store: fixedReferencesRefusal :: Text -> Text
+ Nix.Store: freshCopyPath :: FilePath -> FilePath
+ Nix.Store: instance GHC.Internal.Classes.Eq Nix.Store.AddressedPath
+ Nix.Store: instance GHC.Internal.Classes.Eq Nix.Store.ArchiveEnd
+ Nix.Store: instance GHC.Internal.Show.Show Nix.Store.AddressedPath
+ Nix.Store: instance GHC.Internal.Show.Show Nix.Store.ArchiveEnd
+ Nix.Store: moveNarUnpack :: FilePath -> FilePath -> NarLinks -> IO (Either Text ())
+ Nix.Store: moveOutput :: FilePath -> FilePath -> IO ()
+ Nix.Store: narHashMismatch :: Text -> NixHash -> NixHash -> Text
+ Nix.Store: narSizeMismatch :: Text -> Integer -> Integer -> Text
+ Nix.Store: notContentAddressed :: StorePath -> Text
+ Nix.Store: pathCaseHack :: CaseSensitivity -> Text -> CaseHack
+ Nix.Store: replaceWithCopy :: FilePath -> IO ()
+ Nix.Store: rewriteRegularFile :: (ByteString -> ByteString) -> FilePath -> IO ()
+ Nix.Store: startNarFeed :: ArchiveEnd -> NarFeed
+ Nix.Store: useStoreFileMask :: IO ()
+ Nix.Store.Access: AllowEntry :: Word8 -> Word32 -> Sid -> AclEntry
+ Nix.Store.Access: DirSecurity :: Maybe Sid -> Maybe [AclEntry] -> DirSecurity
+ Nix.Store.Access: NoDacl :: Distrust
+ Nix.Store.Access: OtherEntry :: AclEntry
+ Nix.Store.Access: OwnedBy :: Maybe Sid -> Distrust
+ Nix.Store.Access: OwnerAccess :: DirAccess
+ Nix.Store.Access: ParentAccess :: DirAccess
+ Nix.Store.Access: StateAccess :: DirAccess
+ Nix.Store.Access: StoreAccess :: DirAccess
+ Nix.Store.Access: StoreAccounts :: Sid -> Maybe Sid -> StoreAccounts
+ Nix.Store.Access: StoreNotWritable :: StoreWriting
+ Nix.Store.Access: StoreWritable :: StoreWriting
+ Nix.Store.Access: UnknownEntry :: Word8 -> AclEntry
+ Nix.Store.Access: UnreadableDescriptor :: Distrust
+ Nix.Store.Access: UnreadableEntry :: Distrust
+ Nix.Store.Access: ValidDirectory :: ValidNode
+ Nix.Store.Access: ValidLeaf :: ValidNode
+ Nix.Store.Access: WritableBy :: Sid -> Distrust
+ Nix.Store.Access: [dsDacl] :: DirSecurity -> Maybe [AclEntry]
+ Nix.Store.Access: [dsOwner] :: DirSecurity -> Maybe Sid
+ Nix.Store.Access: [saBuilders] :: StoreAccounts -> Maybe Sid
+ Nix.Store.Access: [saService] :: StoreAccounts -> Sid
+ Nix.Store.Access: accessSddl :: StoreAccounts -> DirAccess -> Text
+ Nix.Store.Access: administratorsSid :: Sid
+ Nix.Store.Access: checkStateDirectory :: FilePath -> IO ()
+ Nix.Store.Access: createDirectoryWith :: DirAccess -> FilePath -> IO ()
+ Nix.Store.Access: createStateDirectory :: FilePath -> IO ()
+ Nix.Store.Access: createStoreDirectory :: FilePath -> IO ()
+ Nix.Store.Access: data AclEntry
+ Nix.Store.Access: data DirAccess
+ Nix.Store.Access: data DirSecurity
+ Nix.Store.Access: data Distrust
+ Nix.Store.Access: data Sid
+ Nix.Store.Access: data StoreAccounts
+ Nix.Store.Access: data StoreWriting
+ Nix.Store.Access: data ValidNode
+ Nix.Store.Access: descriptorDistrust :: StoreAccounts -> DirAccess -> ByteString -> Maybe Distrust
+ Nix.Store.Access: distrustMessage :: FilePath -> FilePath -> Distrust -> String
+ Nix.Store.Access: instance GHC.Internal.Classes.Eq Nix.Store.Access.AclEntry
+ Nix.Store.Access: instance GHC.Internal.Classes.Eq Nix.Store.Access.DirAccess
+ Nix.Store.Access: instance GHC.Internal.Classes.Eq Nix.Store.Access.DirSecurity
+ Nix.Store.Access: instance GHC.Internal.Classes.Eq Nix.Store.Access.Distrust
+ Nix.Store.Access: instance GHC.Internal.Classes.Eq Nix.Store.Access.Sid
+ Nix.Store.Access: instance GHC.Internal.Classes.Eq Nix.Store.Access.StoreAccounts
+ Nix.Store.Access: instance GHC.Internal.Classes.Eq Nix.Store.Access.StoreWriting
+ Nix.Store.Access: instance GHC.Internal.Classes.Eq Nix.Store.Access.ValidNode
+ Nix.Store.Access: instance GHC.Internal.Show.Show Nix.Store.Access.AclEntry
+ Nix.Store.Access: instance GHC.Internal.Show.Show Nix.Store.Access.DirAccess
+ Nix.Store.Access: instance GHC.Internal.Show.Show Nix.Store.Access.DirSecurity
+ Nix.Store.Access: instance GHC.Internal.Show.Show Nix.Store.Access.Distrust
+ Nix.Store.Access: instance GHC.Internal.Show.Show Nix.Store.Access.Sid
+ Nix.Store.Access: instance GHC.Internal.Show.Show Nix.Store.Access.StoreAccounts
+ Nix.Store.Access: instance GHC.Internal.Show.Show Nix.Store.Access.StoreWriting
+ Nix.Store.Access: instance GHC.Internal.Show.Show Nix.Store.Access.ValidNode
+ Nix.Store.Access: localSystemSid :: Sid
+ Nix.Store.Access: novaNixServiceSid :: Sid
+ Nix.Store.Access: parseSecurityDescriptor :: ByteString -> Maybe DirSecurity
+ Nix.Store.Access: probeStoreWriting :: FilePath -> IO StoreWriting
+ Nix.Store.Access: securityDistrust :: StoreAccounts -> DirAccess -> DirSecurity -> Maybe Distrust
+ Nix.Store.Access: serviceSid :: Text -> Sid
+ Nix.Store.Access: sidFromText :: Text -> Maybe Sid
+ Nix.Store.Access: sidText :: Sid -> Text
+ Nix.Store.Access: stateDirectories :: FilePath -> [(FilePath, DirAccess)]
+ Nix.Store.Access: storeDirectories :: FilePath -> [(FilePath, DirAccess)]
+ Nix.Store.Access: validPathSddl :: StoreAccounts -> ValidNode -> Text
+ Nix.Store.Access: withValidPathAccess :: ((ValidNode -> FilePath -> IO ()) -> IO a) -> IO a
+ Nix.Store.CaseSensitive: pathCaseHack :: CaseSensitivity -> Text -> CaseHack
+ Nix.Store.DB: NotUltimate :: Ultimate
+ Nix.Store.DB: RegisteredAt :: Int64 -> RegistrationTime
+ Nix.Store.DB: RegisteredNow :: RegistrationTime
+ Nix.Store.DB: Ultimate :: Ultimate
+ Nix.Store.DB: [piContentAddress] :: PathInfo -> Maybe ContentAddress
+ Nix.Store.DB: [piSignatures] :: PathInfo -> Set Signature
+ Nix.Store.DB: [piUltimate] :: PathInfo -> Ultimate
+ Nix.Store.DB: [prContentAddress] :: PathRegistration -> Maybe ContentAddress
+ Nix.Store.DB: [prRegistrationTime] :: PathRegistration -> RegistrationTime
+ Nix.Store.DB: [prSignatures] :: PathRegistration -> Set Signature
+ Nix.Store.DB: [prUltimate] :: PathRegistration -> Ultimate
+ Nix.Store.DB: createStoreDirectories :: StoreDir -> IO ()
+ Nix.Store.DB: data RegistrationTime
+ Nix.Store.DB: data Ultimate
+ Nix.Store.DB: foreignStoreDir :: StoreDir -> Text -> Maybe StoreDir
+ Nix.Store.DB: instance GHC.Internal.Classes.Eq Nix.Store.DB.RegistrationTime
+ Nix.Store.DB: instance GHC.Internal.Classes.Eq Nix.Store.DB.Ultimate
+ Nix.Store.DB: instance GHC.Internal.Show.Show Nix.Store.DB.RegistrationTime
+ Nix.Store.DB: instance GHC.Internal.Show.Show Nix.Store.DB.Ultimate
+ Nix.Store.DB: openStoreDBReadOnly :: StoreDir -> IO StoreDB
+ Nix.Store.DB: queryPathFromHashPart :: StoreDB -> Text -> IO (Either Text (Maybe Text))
+ Nix.Store.DB: queryReferrers :: StoreDB -> StorePath -> IO [Text]
+ Nix.Store.DB: queryValidDerivers :: StoreDB -> StorePath -> IO [Text]
+ Nix.Store.DB: statedRegistrationTime :: Int64 -> RegistrationTime
+ Nix.Store.DB: storeRowRange :: StoreDir -> (Text, Maybe Text)
+ Nix.Store.DB: storeTablesExist :: StoreDB -> IO Bool
+ Nix.Store.ExecBit: serialiseIfReadable :: CaseHack -> FilePath -> IO (Maybe NarEntry)
+ Nix.Store.GC: DeleteOutcome :: Bool -> Bool -> DeleteOutcome
+ Nix.Store.GC: LinkRooting :: (StorePath -> IO (Either Text ())) -> (ByteString -> IO (Either Text ())) -> LinkRooting
+ Nix.Store.GC: [doRowRemoved] :: DeleteOutcome -> Bool
+ Nix.Store.GC: [doTreeRemoved] :: DeleteOutcome -> Bool
+ Nix.Store.GC: [lrHold] :: LinkRooting -> StorePath -> IO (Either Text ())
+ Nix.Store.GC: [lrRecord] :: LinkRooting -> ByteString -> IO (Either Text ())
+ Nix.Store.GC: addIndirectRoot :: Store -> ByteString -> IO ()
+ Nix.Store.GC: data DeleteOutcome
+ Nix.Store.GC: data LinkRooting
+ Nix.Store.GC: data StoreEntryName
+ Nix.Store.GC: deleteSpecificPaths :: Store -> Set StorePath -> Set StorePath -> IO (Either Text GcResults)
+ Nix.Store.GC: deleteStorePathRaw :: Store -> StoreEntryName -> IO (Either Text DeleteOutcome)
+ Nix.Store.GC: deleteStorePaths :: Store -> [StoreEntryName] -> (StoreEntryName -> DeleteOutcome -> IO ()) -> IO (Either Text ())
+ Nix.Store.GC: instance GHC.Internal.Classes.Eq Nix.Store.GC.DeleteOutcome
+ Nix.Store.GC: instance GHC.Internal.Classes.Eq Nix.Store.GC.StoreEntryName
+ Nix.Store.GC: instance GHC.Internal.Show.Show Nix.Store.GC.DeleteOutcome
+ Nix.Store.GC: instance GHC.Internal.Show.Show Nix.Store.GC.StoreEntryName
+ Nix.Store.GC: makeOutLinkRoot :: StoreDir -> LinkRooting -> FilePath -> StorePath -> IO (Either Text FilePath)
+ Nix.Store.GC: referrersFirst :: Map Text [Text] -> Set Text -> [Text]
+ Nix.Store.GC: specificStillAliveMessage :: Text -> Text
+ Nix.Store.GC: storeEntryName :: Text -> Either Text StoreEntryName
+ Nix.Store.GC: storeEntryNameText :: StoreEntryName -> Text
+ Nix.Store.Handle: [stLogger] :: Store -> Logger
+ Nix.Store.Import: NarAlreadyValid :: NarImportStart
+ Nix.Store.Import: NarImportBegun :: NarImport -> NarImportStart
+ Nix.Store.Import: NarImportGoesOn :: NarImport -> NarImportStep
+ Nix.Store.Import: NarImported :: NarImportStep
+ Nix.Store.Import: abandonDumpAdd :: DumpAdd -> IO ()
+ Nix.Store.Import: abandonNarImport :: NarImport -> IO ()
+ Nix.Store.Import: addTextToStore :: Store -> Text -> ByteString -> [StorePath] -> IO (Either Text StorePath)
+ Nix.Store.Import: admitNar :: Store -> SignatureRequirement -> PathRegistration -> IO (Either Text AdmittedNar)
+ Nix.Store.Import: beginDumpAdd :: Store -> Text -> ContentAddressMethod -> Text -> Set StorePath -> IO (Either Text DumpAdd)
+ Nix.Store.Import: beginNarImport :: AdmittedNar -> IO NarImportStart
+ Nix.Store.Import: checkDerivationOutputs :: StoreDir -> StorePath -> Derivation -> IO (Either Text ())
+ Nix.Store.Import: data AdmittedNar
+ Nix.Store.Import: data DumpAdd
+ Nix.Store.Import: data EndedDump
+ Nix.Store.Import: data NarImport
+ Nix.Store.Import: data NarImportStart
+ Nix.Store.Import: data NarImportStep
+ Nix.Store.Import: endDumpAdd :: DumpAdd -> IO (Either Text EndedDump)
+ Nix.Store.Import: endNarImport :: NarImport -> IO (Either Text ())
+ Nix.Store.Import: endedDumpPath :: EndedDump -> StorePath
+ Nix.Store.Import: feedDumpAdd :: DumpAdd -> ByteString -> IO (Either Text DumpAdd)
+ Nix.Store.Import: feedNarImport :: NarImport -> ByteString -> IO (Either Text NarImportStep)
+ Nix.Store.Import: importNar :: Store -> SignatureRequirement -> PathRegistration -> IO ByteString -> IO (Either Text ())
+ Nix.Store.Import: placeDump :: EndedDump -> IO (Either Text ())
+ Nix.Store.Import: replacePath :: Store -> StorePath -> ExceptT Text IO () -> IO (Either Text ())
+ Nix.Store.Metadata: DirectoryNode :: NodeKind
+ Nix.Store.Metadata: NodeMetadata :: NodeKind -> Word32 -> Int64 -> Ownership -> NodeMetadata
+ Nix.Store.Metadata: OwnedByBuildUser :: Word32 -> OutputOwner
+ Nix.Store.Metadata: OwnedByInvoker :: OutputOwner
+ Nix.Store.Metadata: OwnedByOther :: Ownership
+ Nix.Store.Metadata: OwnedByProcess :: Ownership
+ Nix.Store.Metadata: RegularNode :: NodeKind
+ Nix.Store.Metadata: SetModificationTime :: MetadataChange
+ Nix.Store.Metadata: SetPermissions :: Word32 -> MetadataChange
+ Nix.Store.Metadata: SymlinkNode :: NodeKind
+ Nix.Store.Metadata: TakeOwnership :: MetadataChange
+ Nix.Store.Metadata: [nmKind] :: NodeMetadata -> NodeKind
+ Nix.Store.Metadata: [nmModificationTime] :: NodeMetadata -> Int64
+ Nix.Store.Metadata: [nmOwnership] :: NodeMetadata -> Ownership
+ Nix.Store.Metadata: [nmPermissions] :: NodeMetadata -> Word32
+ Nix.Store.Metadata: canonicalPermissions :: Word32 -> Word32
+ Nix.Store.Metadata: canonicalizeMetadata :: FilePath -> IO ()
+ Nix.Store.Metadata: data MetadataChange
+ Nix.Store.Metadata: data NodeKind
+ Nix.Store.Metadata: data NodeMetadata
+ Nix.Store.Metadata: data OutputOwner
+ Nix.Store.Metadata: data Ownership
+ Nix.Store.Metadata: executablePermissions :: Word32
+ Nix.Store.Metadata: foreignOwnedNode :: OutputOwner -> FilePath -> IO (Maybe FilePath)
+ Nix.Store.Metadata: instance GHC.Internal.Classes.Eq Nix.Store.Metadata.MetadataChange
+ Nix.Store.Metadata: instance GHC.Internal.Classes.Eq Nix.Store.Metadata.NodeKind
+ Nix.Store.Metadata: instance GHC.Internal.Classes.Eq Nix.Store.Metadata.NodeMetadata
+ Nix.Store.Metadata: instance GHC.Internal.Classes.Eq Nix.Store.Metadata.OutputOwner
+ Nix.Store.Metadata: instance GHC.Internal.Classes.Eq Nix.Store.Metadata.Ownership
+ Nix.Store.Metadata: instance GHC.Internal.Show.Show Nix.Store.Metadata.MetadataChange
+ Nix.Store.Metadata: instance GHC.Internal.Show.Show Nix.Store.Metadata.NodeKind
+ Nix.Store.Metadata: instance GHC.Internal.Show.Show Nix.Store.Metadata.NodeMetadata
+ Nix.Store.Metadata: instance GHC.Internal.Show.Show Nix.Store.Metadata.OutputOwner
+ Nix.Store.Metadata: instance GHC.Internal.Show.Show Nix.Store.Metadata.Ownership
+ Nix.Store.Metadata: isPlainFile :: FilePath -> IO Bool
+ Nix.Store.Metadata: metadataChanges :: NodeMetadata -> [MetadataChange]
+ Nix.Store.Metadata: nodeModificationTime :: FilePath -> IO Int64
+ Nix.Store.Metadata: ownedByAnother :: OutputOwner -> FilePath -> IO Bool
+ Nix.Store.Metadata: readOnlyPermissions :: Word32
+ Nix.Store.Metadata: storeModificationTime :: Int64
+ Nix.Store.Metadata: writableByOthers :: FilePath -> IO Bool
+ Nix.Store.Ops: AddedAsMade :: MadeOps m -> EvalWrites (m :: Type -> Type)
+ Nix.Store.Ops: BuildStop :: Text -> Int -> BuildStop
+ Nix.Store.Ops: EvalObjects :: Map StorePath Text -> Map Text ([StorePath], StoreWriteMode) -> Map Text ByteString -> EvalObjects
+ Nix.Store.Ops: FixedOutputRefused :: Text -> BuildStop
+ Nix.Store.Ops: FlatWrite :: Text -> ByteString -> EvalWrite
+ Nix.Store.Ops: MadeOps :: (EvalWrite -> m (Either Text StorePath)) -> (StorePath -> m (Either Text ())) -> MadeOps (m :: Type -> Type)
+ Nix.Store.Ops: NarWrite :: Text -> ByteString -> EvalWrite
+ Nix.Store.Ops: StoreOps :: StoreQueries m -> (EvalObjects -> m (Either Text ())) -> (Text -> Set StorePath -> NarEntry -> m (Either Text StorePath)) -> ([(StorePath, Set Text)] -> m (Either BuildStop ())) -> (StorePath -> m (Either BuildStop ())) -> (FilePath -> StorePath -> m (Either Text FilePath)) -> EvalWrites m -> StoreOps (m :: Type -> Type)
+ Nix.Store.Ops: StoreQueries :: (Set StorePath -> m (Set StorePath)) -> (StorePath -> m (Either Text (Set StorePath))) -> StoreQueries (m :: Type -> Type)
+ Nix.Store.Ops: TextWrite :: Text -> Set StorePath -> ByteString -> EvalWrite
+ Nix.Store.Ops: WrittenInDirectory :: EvalWrites (m :: Type -> Type)
+ Nix.Store.Ops: [eoDerivations] :: EvalObjects -> Map Text ByteString
+ Nix.Store.Ops: [eoSources] :: EvalObjects -> Map StorePath Text
+ Nix.Store.Ops: [eoStoreWrites] :: EvalObjects -> Map Text ([StorePath], StoreWriteMode)
+ Nix.Store.Ops: [moAdd] :: MadeOps (m :: Type -> Type) -> EvalWrite -> m (Either Text StorePath)
+ Nix.Store.Ops: [moHold] :: MadeOps (m :: Type -> Type) -> StorePath -> m (Either Text ())
+ Nix.Store.Ops: [soAddEvalObjects] :: StoreOps (m :: Type -> Type) -> EvalObjects -> m (Either Text ())
+ Nix.Store.Ops: [soAddOutLinkRoot] :: StoreOps (m :: Type -> Type) -> FilePath -> StorePath -> m (Either Text FilePath)
+ Nix.Store.Ops: [soAddSourceTree] :: StoreOps (m :: Type -> Type) -> Text -> Set StorePath -> NarEntry -> m (Either Text StorePath)
+ Nix.Store.Ops: [soBuild] :: StoreOps (m :: Type -> Type) -> [(StorePath, Set Text)] -> m (Either BuildStop ())
+ Nix.Store.Ops: [soCheck] :: StoreOps (m :: Type -> Type) -> StorePath -> m (Either BuildStop ())
+ Nix.Store.Ops: [soEvalWrites] :: StoreOps (m :: Type -> Type) -> EvalWrites m
+ Nix.Store.Ops: [soQueries] :: StoreOps (m :: Type -> Type) -> StoreQueries m
+ Nix.Store.Ops: [sqReferences] :: StoreQueries (m :: Type -> Type) -> StorePath -> m (Either Text (Set StorePath))
+ Nix.Store.Ops: [sqValidPaths] :: StoreQueries (m :: Type -> Type) -> Set StorePath -> m (Set StorePath)
+ Nix.Store.Ops: data BuildStop
+ Nix.Store.Ops: data EvalObjects
+ Nix.Store.Ops: data EvalWrite
+ Nix.Store.Ops: data EvalWrites (m :: Type -> Type)
+ Nix.Store.Ops: data MadeOps (m :: Type -> Type)
+ Nix.Store.Ops: data StoreOps (m :: Type -> Type)
+ Nix.Store.Ops: data StoreQueries (m :: Type -> Type)
+ Nix.Store.Ops: evalWriteContents :: EvalWrite -> ByteString
+ Nix.Store.Ops: instance GHC.Internal.Classes.Eq Nix.Store.Ops.EvalWrite
+ Nix.Store.Ops: instance GHC.Internal.Show.Show Nix.Store.Ops.EvalWrite
+ Nix.Store.Ops: localQueries :: StoreDir -> StoreQueries IO
+ Nix.Store.Ops: madeAnotherPath :: StorePath -> StorePath -> Text
+ Nix.Store.Ops: nothingToAdd :: EvalObjects -> Bool
+ Nix.Store.Ops: stopReported :: BuildStop -> (Text, Int)
+ Nix.Store.Ops: withLocalStore :: Logger -> BuildConfig -> (StoreOps IO -> IO a) -> IO a
+ Nix.Store.Ops: withOpenedOnFirstUse :: IO r -> (r -> IO ()) -> (IO r -> IO a) -> IO a
+ Nix.Store.Path: isInStoreText :: Text -> Bool
+ Nix.Store.Path: storeDirDrive :: StoreDir -> Maybe Text
+ Nix.Store.Path: storePathBasename :: StorePath -> Text
+ Nix.Store.Upstream: DeletesUpstreamPaths :: UpstreamHazard
+ Nix.Store.Upstream: ReplacesUpstreamPaths :: UpstreamHazard
+ Nix.Store.Upstream: data UpstreamHazard
+ Nix.Store.Upstream: instance GHC.Internal.Classes.Eq Nix.Store.Upstream.UpstreamHazard
+ Nix.Store.Upstream: instance GHC.Internal.Show.Show Nix.Store.Upstream.UpstreamHazard
+ Nix.Store.Upstream: upstreamDatabasePath :: FilePath -> Maybe FilePath
+ Nix.Store.Upstream: upstreamManagedRefusal :: UpstreamHazard -> StoreDir -> IO (Maybe Text)
+ Nix.Store.Upstream: upstreamStateDir :: FilePath -> Maybe FilePath
+ Nix.Substituter: AcceptUnsigned :: RequireSigs
+ Nix.Substituter: NarInfoTrustFailed :: Text -> NarInfoAnswer
+ Nix.Substituter: NarInfoUnsigned :: NarInfoAnswer
+ Nix.Substituter: RequireSigs :: RequireSigs
+ Nix.Substituter: [ccRequireSigs] :: CacheConfig -> RequireSigs
+ Nix.Substituter: [ccSecretKeyFiles] :: CacheConfig -> [ByteString]
+ Nix.Substituter: cacheRequirement :: CacheConfig -> IO (Either Text SignatureRequirement)
+ Nix.Substituter: checkContentAddress :: CaseHack -> StoreDir -> StorePath -> FilePath -> ContentAddress -> IO (Either Text ())
+ Nix.Substituter: checkStatedAddress :: CaseHack -> StoreDir -> StorePath -> FilePath -> Maybe Text -> IO (Either Text (Maybe ContentAddress))
+ Nix.Substituter: data CacheMemo
+ Nix.Substituter: data RequireSigs
+ Nix.Substituter: data Substitute
+ Nix.Substituter: emptyCacheMemo :: CacheMemo
+ Nix.Substituter: fetchSubstituteWith :: FetchRetryPolicy -> RetryEffects IO -> Store -> Substitute -> IO SubstResult
+ Nix.Substituter: instance GHC.Internal.Classes.Eq Nix.Substituter.CacheTransport
+ Nix.Substituter: instance GHC.Internal.Classes.Eq Nix.Substituter.OpenedCache
+ Nix.Substituter: instance GHC.Internal.Classes.Eq Nix.Substituter.RequireSigs
+ Nix.Substituter: instance GHC.Internal.Classes.Eq Nix.Substituter.Substitute
+ Nix.Substituter: instance GHC.Internal.Show.Show Nix.Substituter.CacheTransport
+ Nix.Substituter: instance GHC.Internal.Show.Show Nix.Substituter.OpenedCache
+ Nix.Substituter: instance GHC.Internal.Show.Show Nix.Substituter.RequireSigs
+ Nix.Substituter: instance GHC.Internal.Show.Show Nix.Substituter.Substitute
+ Nix.Substituter: narStreamFailure :: NarStreamFailure -> AttemptFailure
+ Nix.Substituter: queryNextOfferWith :: Logger -> FetchRetryPolicy -> RetryEffects IO -> Fallback -> Substitute -> StateT CacheMemo IO (Offer Substitute)
+ Nix.Substituter: substituteCache :: Substitute -> CacheConfig
+ Nix.Substituter: substitutePath :: Substitute -> StorePath
+ Nix.Substituter: substituteSizes :: Substitute -> (Word64, Word64)
+ Nix.Substituter: unsignedWarning :: CacheConfig -> StorePath -> Text
+ Nix.Substituter: withXzAttempt :: XzLimits -> IO ByteString -> (IO ByteString -> IO (Either AttemptFailure a)) -> IO (Either AttemptFailure a)
+ Nix.Trust: ArArchive :: CodeKind
+ Nix.Trust: ArchiveMember :: Text -> CodePlace
+ Nix.Trust: BuiltBy :: ByteString -> Provenance
+ Nix.Trust: CoffObject :: CodeKind
+ Nix.Trust: ContentFacts :: [FoundCode] -> [UnreadFile] -> ContentFacts
+ Nix.Trust: ElfImage :: CodeKind
+ Nix.Trust: ElfObject :: CodeKind
+ Nix.Trust: ElfOther :: CodeKind
+ Nix.Trust: FetchedBy :: ByteString -> Provenance
+ Nix.Trust: FetchedFile :: CodePlace
+ Nix.Trust: FixedInput :: StorePath -> StorePath -> Provenance -> [StorePath] -> Map ByteString Int -> Map ByteString Int -> Scan -> FixedInput
+ Nix.Trust: FoundCode :: CodeKind -> CodePlace -> Text -> FoundCode
+ Nix.Trust: HoldsNoPrebuiltCode :: InputClass
+ Nix.Trust: HoldsPrebuiltCode :: InputClass
+ Nix.Trust: MachO :: CodeKind
+ Nix.Trust: MachOUniversal :: CodeKind
+ Nix.Trust: NotFullyRead :: InputClass
+ Nix.Trust: NotInStore :: Scan
+ Nix.Trust: PeImage :: CodeKind
+ Nix.Trust: RunAsBuilder :: InputClass
+ Nix.Trust: Scanned :: ContentFacts -> Scan
+ Nix.Trust: TreeArchiveMember :: Text -> Text -> CodePlace
+ Nix.Trust: TreeFile :: Text -> CodePlace
+ Nix.Trust: TrustReport :: [FixedInput] -> Map ByteString Int -> Map ByteString Int -> Map ByteString Int -> Set StorePath -> Map Text [StorePath] -> TrustReport
+ Nix.Trust: UnreadFile :: Maybe Text -> Text -> UnreadFile
+ Nix.Trust: [cfCode] :: ContentFacts -> [FoundCode]
+ Nix.Trust: [cfUnread] :: ContentFacts -> [UnreadFile]
+ Nix.Trust: [fcKind] :: FoundCode -> CodeKind
+ Nix.Trust: [fcPlace] :: FoundCode -> CodePlace
+ Nix.Trust: [fcSha256] :: FoundCode -> Text
+ Nix.Trust: [inputBuilders] :: FixedInput -> Map ByteString Int
+ Nix.Trust: [inputDrvPath] :: FixedInput -> StorePath
+ Nix.Trust: [inputOutput] :: FixedInput -> StorePath
+ Nix.Trust: [inputProvenance] :: FixedInput -> Provenance
+ Nix.Trust: [inputSameHash] :: FixedInput -> [StorePath]
+ Nix.Trust: [inputScan] :: FixedInput -> Scan
+ Nix.Trust: [inputTreeBuilders] :: FixedInput -> Map ByteString Int
+ Nix.Trust: [trBuilderBytes] :: TrustReport -> Map Text [StorePath]
+ Nix.Trust: [trBuiltinBuilders] :: TrustReport -> Map ByteString Int
+ Nix.Trust: [trInputs] :: TrustReport -> [FixedInput]
+ Nix.Trust: [trOutsideBuilders] :: TrustReport -> Map ByteString Int
+ Nix.Trust: [trSourceBuilders] :: TrustReport -> Map ByteString Int
+ Nix.Trust: [trSources] :: TrustReport -> Set StorePath
+ Nix.Trust: [ufFile] :: UnreadFile -> Maybe Text
+ Nix.Trust: [ufReason] :: UnreadFile -> Text
+ Nix.Trust: codeKindName :: CodeKind -> Text
+ Nix.Trust: data CodeKind
+ Nix.Trust: data CodePlace
+ Nix.Trust: data ContentFacts
+ Nix.Trust: data FixedInput
+ Nix.Trust: data FoundCode
+ Nix.Trust: data InputClass
+ Nix.Trust: data Provenance
+ Nix.Trust: data Scan
+ Nix.Trust: data TrustReport
+ Nix.Trust: data UnreadFile
+ Nix.Trust: fetchedByBuiltin :: Derivation -> Bool
+ Nix.Trust: fixedOutputInputs :: DepGraph -> StorePath -> [(DepNode, StorePath)]
+ Nix.Trust: fixedOutputPath :: Derivation -> Maybe StorePath
+ Nix.Trust: inputClass :: FixedInput -> InputClass
+ Nix.Trust: instance GHC.Internal.Classes.Eq Nix.Trust.CodeKind
+ Nix.Trust: instance GHC.Internal.Classes.Eq Nix.Trust.CodePlace
+ Nix.Trust: instance GHC.Internal.Classes.Eq Nix.Trust.ContentFacts
+ Nix.Trust: instance GHC.Internal.Classes.Eq Nix.Trust.FixedInput
+ Nix.Trust: instance GHC.Internal.Classes.Eq Nix.Trust.FoundCode
+ Nix.Trust: instance GHC.Internal.Classes.Eq Nix.Trust.InputClass
+ Nix.Trust: instance GHC.Internal.Classes.Eq Nix.Trust.Provenance
+ Nix.Trust: instance GHC.Internal.Classes.Eq Nix.Trust.Reach
+ Nix.Trust: instance GHC.Internal.Classes.Eq Nix.Trust.Scan
+ Nix.Trust: instance GHC.Internal.Classes.Eq Nix.Trust.TrustReport
+ Nix.Trust: instance GHC.Internal.Classes.Eq Nix.Trust.UnreadFile
+ Nix.Trust: instance GHC.Internal.Classes.Ord Nix.Trust.CodeKind
+ Nix.Trust: instance GHC.Internal.Classes.Ord Nix.Trust.CodePlace
+ Nix.Trust: instance GHC.Internal.Classes.Ord Nix.Trust.FoundCode
+ Nix.Trust: instance GHC.Internal.Classes.Ord Nix.Trust.InputClass
+ Nix.Trust: instance GHC.Internal.Classes.Ord Nix.Trust.Reach
+ Nix.Trust: instance GHC.Internal.Enum.Bounded Nix.Trust.CodeKind
+ Nix.Trust: instance GHC.Internal.Enum.Bounded Nix.Trust.InputClass
+ Nix.Trust: instance GHC.Internal.Enum.Enum Nix.Trust.CodeKind
+ Nix.Trust: instance GHC.Internal.Enum.Enum Nix.Trust.InputClass
+ Nix.Trust: instance GHC.Internal.Show.Show Nix.Trust.CodeKind
+ Nix.Trust: instance GHC.Internal.Show.Show Nix.Trust.CodePlace
+ Nix.Trust: instance GHC.Internal.Show.Show Nix.Trust.ContentFacts
+ Nix.Trust: instance GHC.Internal.Show.Show Nix.Trust.FixedInput
+ Nix.Trust: instance GHC.Internal.Show.Show Nix.Trust.FoundCode
+ Nix.Trust: instance GHC.Internal.Show.Show Nix.Trust.InputClass
+ Nix.Trust: instance GHC.Internal.Show.Show Nix.Trust.Provenance
+ Nix.Trust: instance GHC.Internal.Show.Show Nix.Trust.Reach
+ Nix.Trust: instance GHC.Internal.Show.Show Nix.Trust.Scan
+ Nix.Trust: instance GHC.Internal.Show.Show Nix.Trust.TrustReport
+ Nix.Trust: instance GHC.Internal.Show.Show Nix.Trust.UnreadFile
+ Nix.Trust: prebuiltKind :: ByteString -> Maybe CodeKind
+ Nix.Trust: renderTrustReport :: TrustReport -> [Text]
+ Nix.Trust: trustReport :: Map StorePath ContentFacts -> DepGraph -> StorePath -> TrustReport
+ Nix.Trust: trustReportJson :: TrustReport -> Json
+ Nix.Trust: trustReportJsonVersion :: Integer
+ Nix.Trust.Fetch: FixedOutputStore :: (DepNode -> m (Either Text ())) -> (StorePath -> m (Either Text ClosureOutcome)) -> (StorePath -> m (Either Text Bool)) -> (StorePath -> m ContentFacts) -> FixedOutputStore (m :: Type -> Type)
+ Nix.Trust.Fetch: [fosFetch] :: FixedOutputStore (m :: Type -> Type) -> DepNode -> m (Either Text ())
+ Nix.Trust.Fetch: [fosHeld] :: FixedOutputStore (m :: Type -> Type) -> StorePath -> m (Either Text Bool)
+ Nix.Trust.Fetch: [fosScan] :: FixedOutputStore (m :: Type -> Type) -> StorePath -> m ContentFacts
+ Nix.Trust.Fetch: [fosSubstitute] :: FixedOutputStore (m :: Type -> Type) -> StorePath -> m (Either Text ClosureOutcome)
+ Nix.Trust.Fetch: data FixedOutputStore (m :: Type -> Type)
+ Nix.Trust.Fetch: fetchAndScan :: Monad m => FixedOutputStore m -> [(DepNode, StorePath)] -> m (Either Text (Map StorePath ContentFacts))
+ Nix.Trust.Scan: scanFetched :: FilePath -> IO ContentFacts
- Nix.Builder: BuildConfig :: StoreDir -> FilePath -> [CacheConfig] -> Fallback -> UnpackLimits -> FetchRetryPolicy -> Map Text FilePath -> Handle -> BuildConfig
+ Nix.Builder: BuildConfig :: StoreDir -> [CacheConfig] -> Fallback -> SubstitutesSetting -> SubstitutionAccess -> BuildMode -> Word32 -> UnpackLimits -> FetchRetryPolicy -> Map Text FilePath -> SandboxConfig -> BuildUsers -> FailedBuilds -> BuildConfig
- Nix.Builder: substitutePaths :: BuildConfig -> Store -> [StorePath] -> IO FetchOutcome
+ Nix.Builder: substitutePaths :: BuildConfig -> Store -> Registration -> NonEmpty Substitute -> IO FetchOutcome
- Nix.Builder.Log: streamBuildLog :: Handle -> Handle -> IO ()
+ Nix.Builder.Log: streamBuildLog :: Handle -> Logger -> IO ()
- Nix.Builtins: builtinEnv :: EvalPolicy -> Int64 -> [Thunk] -> Env
+ Nix.Builtins: builtinEnv :: MonadCData m => EvalPolicy -> Int64 -> [Thunk] -> m Env
- Nix.Builtins: builtinEnvWithScope :: EvalPolicy -> Int64 -> [Thunk] -> [(Text, Thunk)] -> Env
+ Nix.Builtins: builtinEnvWithScope :: MonadCData m => Env -> AttrSet -> m Env
- Nix.Builtins: parseNixPath :: ByteString -> [Thunk]
+ Nix.Builtins: parseNixPath :: MonadCData m => ByteString -> m [Thunk]
- Nix.Builtins: searchPathRoots :: [Thunk] -> [ByteString]
+ Nix.Builtins: searchPathRoots :: MonadCData m => [Thunk] -> m [ByteString]
- Nix.Config: ConfigLocations :: Maybe ByteString -> Maybe OsPath -> Maybe ByteString -> OsPath -> [OsPath] -> ConfigLocations
+ Nix.Config: ConfigLocations :: Maybe ByteString -> Maybe OsPath -> Maybe ByteString -> Maybe ByteString -> OsPath -> [OsPath] -> ConfigLocations
- Nix.Config: NixConfig :: [Text] -> [Text] -> Bool -> Word32 -> [Text] -> Bool -> Bool -> Bool -> NixConfig
+ Nix.Config: NixConfig :: [Text] -> [Text] -> [ByteString] -> Bool -> Bool -> Bool -> Maybe Word32 -> Word32 -> [Text] -> Bool -> Bool -> Bool -> Bool -> Bool -> Maybe SandboxMode -> Bool -> PathSetValue -> ByteString -> ByteString -> Maybe Bool -> Maybe ByteString -> Maybe ByteString -> Maybe ByteString -> Bool -> ByteString -> ByteString -> ByteString -> PathSetValue -> Bool -> Bool -> FeatureSet -> [ByteString] -> [ByteString] -> [Text] -> Word32 -> NixConfig
- Nix.DependencyGraph: DepNode :: StorePath -> Derivation -> [StorePath] -> DepNode
+ Nix.DependencyGraph: DepNode :: StorePath -> Derivation -> Map StorePath (Set Text) -> DepNode
- Nix.DependencyGraph: [dnDeps] :: DepNode -> [StorePath]
+ Nix.DependencyGraph: [dnDeps] :: DepNode -> Map StorePath (Set Text)
- Nix.Eval: EvalPolicy :: Bool -> Bool -> [Text] -> Bool -> EvalPolicy
+ Nix.Eval: EvalPolicy :: Bool -> Bool -> [Text] -> Bool -> ImportFromDerivation -> FeatureSet -> EvalPolicy
- Nix.Eval: VBuiltin :: Text -> [BuiltinArg] -> NixValue
+ Nix.Eval: VBuiltin :: Builtin -> [BuiltinArg] -> NixValue
- Nix.Eval: addFixedOutputFile :: MonadEval m => Text -> ByteString -> m Text
+ Nix.Eval: addFixedOutputFile :: MonadEval m => PendingOrigin -> Text -> ByteString -> m Text
- Nix.Eval: attrSetElems :: AttrSet -> [Thunk]
+ Nix.Eval: attrSetElems :: MonadCData m => AttrSet -> m [Thunk]
- Nix.Eval: attrSetFromMap :: Map Text Thunk -> AttrSet
+ Nix.Eval: attrSetFromMap :: MonadCData m => SetSite -> Map Text Thunk -> m AttrSet
- Nix.Eval: attrSetKeys :: AttrSet -> [Text]
+ Nix.Eval: attrSetKeys :: MonadCData m => AttrSet -> m [Text]
- Nix.Eval: attrSetLookup :: Text -> AttrSet -> Maybe Thunk
+ Nix.Eval: attrSetLookup :: MonadCData m => Text -> AttrSet -> m (Maybe Thunk)
- Nix.Eval: attrSetMember :: Text -> AttrSet -> Bool
+ Nix.Eval: attrSetMember :: MonadCData m => Text -> AttrSet -> m Bool
- Nix.Eval: attrSetNull :: AttrSet -> Bool
+ Nix.Eval: attrSetNull :: MonadCData m => AttrSet -> m Bool
- Nix.Eval: attrSetRemoveKeys :: [Text] -> AttrSet -> AttrSet
+ Nix.Eval: attrSetRemoveKeys :: MonadCData m => SetSite -> [Text] -> AttrSet -> m AttrSet
- Nix.Eval: attrSetSize :: AttrSet -> Int
+ Nix.Eval: attrSetSize :: MonadCData m => AttrSet -> m Int
- Nix.Eval: attrSetToAscList :: AttrSet -> [(Text, Thunk)]
+ Nix.Eval: attrSetToAscList :: MonadCData m => AttrSet -> m [(Text, Thunk)]
- Nix.Eval: attrSetToMap :: AttrSet -> Map Text Thunk
+ Nix.Eval: attrSetToMap :: MonadCData m => AttrSet -> m (Map Text Thunk)
- Nix.Eval: class Monad m => MonadEval (m :: Type -> Type)
+ Nix.Eval: class MonadCData m => MonadEval (m :: Type -> Type)
- Nix.Eval: copyPathToStore :: MonadEval m => Text -> Text -> Maybe (Text, ByteString) -> m Text
+ Nix.Eval: copyPathToStore :: MonadEval m => PendingOrigin -> Text -> Text -> Maybe (ByteString, ByteString -> Text) -> m Text
- Nix.Eval: deferApply :: NixValue -> Thunk -> Thunk
+ Nix.Eval: deferApply :: MonadCData m => NixValue -> Thunk -> m Thunk
- Nix.Eval: evaluated :: NixValue -> Thunk
+ Nix.Eval: evaluated :: MonadCData m => NixValue -> m Thunk
- Nix.Eval: forceThunk :: MonadEval m => (Env -> Word32 -> m NixValue) -> Thunk -> m NixValue
+ Nix.Eval: forceThunk :: MonadEval m => (Pending -> m NixValue) -> Thunk -> m NixValue
- Nix.Eval: listDirectory :: MonadEval m => Text -> m [(Text, Text)]
+ Nix.Eval: listDirectory :: MonadEval m => Text -> m [(Text, Maybe Text)]
- Nix.Eval: readThunkValue :: Thunk -> Maybe NixValue
+ Nix.Eval: readThunkValue :: MonadCData m => Thunk -> m (Maybe NixValue)
- Nix.Eval: scopedImportFile :: MonadEval m => [(Text, Thunk)] -> Text -> m NixValue
+ Nix.Eval: scopedImportFile :: MonadEval m => AttrSet -> Text -> m NixValue
- Nix.Eval.AttrPath: selectAttrPath :: MonadEval m => Text -> NixValue -> m (Either Text NixValue)
+ Nix.Eval.AttrPath: selectAttrPath :: MonadEval m => (NixValue -> m NixValue) -> Text -> NixValue -> m (Either Text NixValue)
- Nix.Eval.CAttrSet: cattrsetFreeze :: CAttrSet -> IO ()
+ Nix.Eval.CAttrSet: cattrsetFreeze :: MonadCData m => CAttrSet -> m ()
- Nix.Eval.CAttrSet: cattrsetIndex :: CAttrSet -> Symbol -> IO (Maybe Word32)
+ Nix.Eval.CAttrSet: cattrsetIndex :: MonadCData m => FlatCAttrSet -> Symbol -> m (Maybe Word32)
- Nix.Eval.CAttrSet: cattrsetInsert :: CAttrSet -> Symbol -> PosIdx -> CThunkPtr -> IO ()
+ Nix.Eval.CAttrSet: cattrsetInsert :: MonadCData m => CAttrSet -> Symbol -> PosIdx -> CThunkPtr -> m ()
- Nix.Eval.CAttrSet: cattrsetLookup :: CAttrSet -> Symbol -> IO (Maybe CThunkPtr)
+ Nix.Eval.CAttrSet: cattrsetLookup :: MonadCData m => CAttrSet -> Symbol -> m (Maybe CThunkPtr)
- Nix.Eval.CAttrSet: cattrsetNew :: Int -> IO CAttrSet
+ Nix.Eval.CAttrSet: cattrsetNew :: MonadCData m => SetSite -> Int -> m CAttrSet
- Nix.Eval.CAttrSet: cattrsetRemoveKeys :: CAttrSet -> [Symbol] -> IO CAttrSet
+ Nix.Eval.CAttrSet: cattrsetRemoveKeys :: MonadCData m => SetSite -> CAttrSet -> [Symbol] -> m CAttrSet
- Nix.Eval.CAttrSet: cattrsetSetValue :: CAttrSet -> Word32 -> CThunkPtr -> IO ()
+ Nix.Eval.CAttrSet: cattrsetSetValue :: MonadCData m => FlatCAttrSet -> Word32 -> CThunkPtr -> m ()
- Nix.Eval.CAttrSet: cattrsetSize :: CAttrSet -> IO Word32
+ Nix.Eval.CAttrSet: cattrsetSize :: MonadCData m => CAttrSet -> m Word32
- Nix.Eval.CAttrSet: cattrsetUnion :: CAttrSet -> CAttrSet -> IO CAttrSet
+ Nix.Eval.CAttrSet: cattrsetUnion :: MonadCData m => SetSite -> CAttrSet -> CAttrSet -> m CAttrSet
- Nix.Eval.CBytecode: cbcArg1 :: Word32 -> IO Word32
+ Nix.Eval.CBytecode: cbcArg1 :: MonadCData m => Word32 -> m Word32
- Nix.Eval.CBytecode: cbcArg2 :: Word32 -> IO Word32
+ Nix.Eval.CBytecode: cbcArg2 :: MonadCData m => Word32 -> m Word32
- Nix.Eval.CBytecode: cbcArg3 :: Word32 -> IO Word32
+ Nix.Eval.CBytecode: cbcArg3 :: MonadCData m => Word32 -> m Word32
- Nix.Eval.CBytecode: cbcCountedPayload :: Word32 -> Word32 -> IO (Int, Word32)
+ Nix.Eval.CBytecode: cbcCountedPayload :: MonadCData m => Word32 -> Word32 -> m (Int, Word32)
- Nix.Eval.CBytecode: cbcData :: Word32 -> IO Word32
+ Nix.Eval.CBytecode: cbcData :: MonadCData m => Word32 -> m Word32
- Nix.Eval.CBytecode: cbcEmit :: Word8 -> Word8 -> Word16 -> Word32 -> Word32 -> Word32 -> IO Word32
+ Nix.Eval.CBytecode: cbcEmit :: MonadCData m => Word8 -> Word8 -> Word16 -> Word32 -> Word32 -> Word32 -> m Word32
- Nix.Eval.CBytecode: cbcEmitData :: Word32 -> IO Word32
+ Nix.Eval.CBytecode: cbcEmitData :: MonadCData m => Word32 -> m Word32
- Nix.Eval.CBytecode: cbcFlags :: Word32 -> IO Word8
+ Nix.Eval.CBytecode: cbcFlags :: MonadCData m => Word32 -> m Word8
- Nix.Eval.CBytecode: cbcOpcode :: Word32 -> IO Word8
+ Nix.Eval.CBytecode: cbcOpcode :: MonadCData m => Word32 -> m Word8
- Nix.Eval.CBytecode: cbcShortArg :: Word32 -> IO Word16
+ Nix.Eval.CBytecode: cbcShortArg :: MonadCData m => Word32 -> m Word16
- Nix.Eval.CCtxStr: cctxstrCtxCount :: CCtxStrPtr -> IO Word32
+ Nix.Eval.CCtxStr: cctxstrCtxCount :: MonadCData m => CCtxStrPtr -> m Word32
- Nix.Eval.CCtxStr: cctxstrElemHash :: CCtxStrPtr -> Word32 -> IO Word32
+ Nix.Eval.CCtxStr: cctxstrElemHash :: MonadCData m => CCtxStrPtr -> Word32 -> m CStrPtr
- Nix.Eval.CCtxStr: cctxstrElemName :: CCtxStrPtr -> Word32 -> IO Word32
+ Nix.Eval.CCtxStr: cctxstrElemName :: MonadCData m => CCtxStrPtr -> Word32 -> m CStrPtr
- Nix.Eval.CCtxStr: cctxstrElemOutput :: CCtxStrPtr -> Word32 -> IO Word32
+ Nix.Eval.CCtxStr: cctxstrElemOutput :: MonadCData m => CCtxStrPtr -> Word32 -> m CStrPtr
- Nix.Eval.CCtxStr: cctxstrElemTag :: CCtxStrPtr -> Word32 -> IO Word8
+ Nix.Eval.CCtxStr: cctxstrElemTag :: MonadCData m => CCtxStrPtr -> Word32 -> m Word8
- Nix.Eval.CCtxStr: cctxstrNew :: Word32 -> Word32 -> IO CCtxStrPtr
+ Nix.Eval.CCtxStr: cctxstrNew :: MonadCData m => CStrPtr -> Word32 -> m CCtxStrPtr
- Nix.Eval.CCtxStr: cctxstrSetAllOutputs :: CCtxStrPtr -> Word32 -> Word32 -> Word32 -> IO ()
+ Nix.Eval.CCtxStr: cctxstrSetAllOutputs :: MonadCData m => CCtxStrPtr -> Word32 -> CStrPtr -> CStrPtr -> m ()
- Nix.Eval.CCtxStr: cctxstrSetDrvOutput :: CCtxStrPtr -> Word32 -> Word32 -> Word32 -> Word32 -> IO ()
+ Nix.Eval.CCtxStr: cctxstrSetDrvOutput :: MonadCData m => CCtxStrPtr -> Word32 -> CStrPtr -> CStrPtr -> CStrPtr -> m ()
- Nix.Eval.CCtxStr: cctxstrSetPlain :: CCtxStrPtr -> Word32 -> Word32 -> Word32 -> IO ()
+ Nix.Eval.CCtxStr: cctxstrSetPlain :: MonadCData m => CCtxStrPtr -> Word32 -> CStrPtr -> CStrPtr -> m ()
- Nix.Eval.CCtxStr: cctxstrText :: CCtxStrPtr -> IO Word32
+ Nix.Eval.CCtxStr: cctxstrText :: MonadCData m => CCtxStrPtr -> m CStrPtr
- Nix.Eval.CEnv: cenvEmpty :: IO (Ptr NnEnv)
+ Nix.Eval.CEnv: cenvEmpty :: Ptr NnEnv
- Nix.Eval.CEnv: cenvLookupResolved :: Ptr NnEnv -> Int -> Int -> IO CThunkPtr
+ Nix.Eval.CEnv: cenvLookupResolved :: MonadCData m => Ptr NnEnv -> Word32 -> Word32 -> m CThunkPtr
- Nix.Eval.CEnv: cenvNew :: Ptr CThunkPtr -> Word32 -> Ptr () -> Ptr NnEnv -> Ptr (Ptr ()) -> Word32 -> IO (Ptr NnEnv)
+ Nix.Eval.CEnv: cenvNew :: MonadCData m => EnvSite -> Word32 -> Ptr NnEnv -> m (Ptr NnEnv)
- Nix.Eval.CEnv: cenvParent :: Ptr NnEnv -> IO (Ptr NnEnv)
+ Nix.Eval.CEnv: cenvParent :: MonadCData m => Ptr NnEnv -> m (Ptr NnEnv)
- Nix.Eval.CEnv: cenvPushWith :: Ptr NnEnv -> Ptr () -> IO (Ptr NnEnv)
+ Nix.Eval.CEnv: cenvPushWith :: MonadCData m => EnvSite -> Ptr NnEnv -> Ptr () -> m (Ptr NnEnv)
- Nix.Eval.CEnv: cenvSlotCount :: Ptr NnEnv -> IO Word32
+ Nix.Eval.CEnv: cenvSlotCount :: MonadCData m => Ptr NnEnv -> m Word32
- Nix.Eval.CEnv: cenvSlots :: Ptr NnEnv -> IO (Ptr CThunkPtr)
+ Nix.Eval.CEnv: cenvSlots :: MonadCData m => Ptr NnEnv -> m (Ptr CThunkPtr)
- Nix.Eval.CEnv: cenvWithCount :: Ptr NnEnv -> IO Word32
+ Nix.Eval.CEnv: cenvWithCount :: MonadCData m => Ptr NnEnv -> m Word32
- Nix.Eval.CEnv: cenvWithScopes :: Ptr NnEnv -> IO (Ptr (Ptr ()))
+ Nix.Eval.CEnv: cenvWithScopes :: MonadCData m => Ptr NnEnv -> m (Ptr (Ptr ()))
- Nix.Eval.CLambda: clambdaAllowExtra :: CLambdaPtr -> IO Word8
+ Nix.Eval.CLambda: clambdaAllowExtra :: MonadCData m => CLambdaPtr -> m Word8
- Nix.Eval.CLambda: clambdaBody :: CLambdaPtr -> IO Word32
+ Nix.Eval.CLambda: clambdaBody :: MonadCData m => CLambdaPtr -> m Word32
- Nix.Eval.CLambda: clambdaEntryDefault :: CLambdaPtr -> Word32 -> IO Word32
+ Nix.Eval.CLambda: clambdaEntryDefault :: MonadCData m => CLambdaPtr -> Word32 -> m Word32
- Nix.Eval.CLambda: clambdaEntryHasDefault :: CLambdaPtr -> Word32 -> IO Word32
+ Nix.Eval.CLambda: clambdaEntryHasDefault :: MonadCData m => CLambdaPtr -> Word32 -> m Word32
- Nix.Eval.CLambda: clambdaEntryName :: CLambdaPtr -> Word32 -> IO Word32
+ Nix.Eval.CLambda: clambdaEntryName :: MonadCData m => CLambdaPtr -> Word32 -> m Word32
- Nix.Eval.CLambda: clambdaEnv :: CLambdaPtr -> IO (Ptr NnEnv)
+ Nix.Eval.CLambda: clambdaEnv :: MonadCData m => CLambdaPtr -> m (Ptr NnEnv)
- Nix.Eval.CLambda: clambdaFormalCount :: CLambdaPtr -> IO Word32
+ Nix.Eval.CLambda: clambdaFormalCount :: MonadCData m => CLambdaPtr -> m Word32
- Nix.Eval.CLambda: clambdaFormalsType :: CLambdaPtr -> IO Word8
+ Nix.Eval.CLambda: clambdaFormalsType :: MonadCData m => CLambdaPtr -> m Word8
- Nix.Eval.CLambda: clambdaNameSym :: CLambdaPtr -> IO Word32
+ Nix.Eval.CLambda: clambdaNameSym :: MonadCData m => CLambdaPtr -> m Word32
- Nix.Eval.CLambda: clambdaNew :: Ptr NnEnv -> Word32 -> Word8 -> Word32 -> Word8 -> Word32 -> IO CLambdaPtr
+ Nix.Eval.CLambda: clambdaNew :: MonadCData m => Ptr NnEnv -> Word32 -> Word8 -> Word32 -> Word32 -> Word8 -> Word32 -> m CLambdaPtr
- Nix.Eval.CLambda: clambdaSetEntry :: CLambdaPtr -> Word32 -> Word32 -> Word32 -> Word32 -> IO ()
+ Nix.Eval.CLambda: clambdaSetEntry :: MonadCData m => CLambdaPtr -> Word32 -> Word32 -> Word32 -> Word32 -> m ()
- Nix.Eval.CList: clistDrop :: Int -> CList -> CList
+ Nix.Eval.CList: clistDrop :: MonadCData m => Int -> CList -> m CList
- Nix.Eval.CList: clistFromThunks :: [CThunkPtr] -> CList
+ Nix.Eval.CList: clistFromThunks :: MonadCData m => [CThunkPtr] -> m CList
- Nix.Eval.CList: clistIndex :: CList -> Int -> Maybe CThunkPtr
+ Nix.Eval.CList: clistIndex :: MonadCData m => CList -> Int -> m (Maybe CThunkPtr)
- Nix.Eval.CList: clistLen :: CList -> Int
+ Nix.Eval.CList: clistLen :: MonadCData m => CList -> m Int
- Nix.Eval.CList: clistThunks :: CList -> [CThunkPtr]
+ Nix.Eval.CList: clistThunks :: MonadCData m => CList -> m [CThunkPtr]
- Nix.Eval.CList: thunkListToCList :: [CThunkPtr] -> IO CListPtr
+ Nix.Eval.CList: thunkListToCList :: MonadCData m => [CThunkPtr] -> m CListPtr
- Nix.Eval.CThunk: cthunkGetBcIdx :: CThunkPtr -> IO Word32
+ Nix.Eval.CThunk: cthunkGetBcIdx :: MonadCData m => CThunkPtr -> m Word32
- Nix.Eval.CThunk: cthunkGetBool :: CThunkPtr -> IO Word8
+ Nix.Eval.CThunk: cthunkGetBool :: MonadCData m => CThunkPtr -> m Word8
- Nix.Eval.CThunk: cthunkGetFloat :: CThunkPtr -> IO Double
+ Nix.Eval.CThunk: cthunkGetFloat :: MonadCData m => CThunkPtr -> m Double
- Nix.Eval.CThunk: cthunkGetInt :: CThunkPtr -> IO Int64
+ Nix.Eval.CThunk: cthunkGetInt :: MonadCData m => CThunkPtr -> m Int64
- Nix.Eval.CThunk: cthunkMarkBlackhole :: CThunkPtr -> IO Bool
+ Nix.Eval.CThunk: cthunkMarkBlackhole :: MonadCData m => CThunkPtr -> m Bool
- Nix.Eval.CThunk: cthunkMarkPending :: CThunkPtr -> IO Bool
+ Nix.Eval.CThunk: cthunkMarkPending :: MonadCData m => CThunkPtr -> m Bool
- Nix.Eval.CThunk: cthunkNewBc :: Word32 -> Ptr () -> IO CThunkPtr
+ Nix.Eval.CThunk: cthunkNewBc :: MonadCData m => Word32 -> Ptr () -> m CThunkPtr
- Nix.Eval.CThunk: cthunkNewComputedAttrs :: Ptr () -> IO CThunkPtr
+ Nix.Eval.CThunk: cthunkNewComputedAttrs :: MonadCData m => Ptr () -> m CThunkPtr
- Nix.Eval.CThunk: cthunkNewComputedCtxStr :: Ptr () -> IO CThunkPtr
+ Nix.Eval.CThunk: cthunkNewComputedCtxStr :: MonadCData m => Ptr () -> m CThunkPtr
- Nix.Eval.CThunk: cthunkNewComputedFloat :: Double -> IO CThunkPtr
+ Nix.Eval.CThunk: cthunkNewComputedFloat :: MonadCData m => Double -> m CThunkPtr
- Nix.Eval.CThunk: cthunkNewComputedInt :: Int64 -> IO CThunkPtr
+ Nix.Eval.CThunk: cthunkNewComputedInt :: MonadCData m => Int64 -> m CThunkPtr
- Nix.Eval.CThunk: cthunkNewComputedLambda :: Ptr () -> IO CThunkPtr
+ Nix.Eval.CThunk: cthunkNewComputedLambda :: MonadCData m => Ptr () -> m CThunkPtr
- Nix.Eval.CThunk: cthunkNewComputedList :: Ptr () -> IO CThunkPtr
+ Nix.Eval.CThunk: cthunkNewComputedList :: MonadCData m => Ptr () -> m CThunkPtr
- Nix.Eval.CThunk: cthunkNewComputedPath :: Word32 -> IO CThunkPtr
+ Nix.Eval.CThunk: cthunkNewComputedPath :: MonadCData m => CStrPtr -> m CThunkPtr
- Nix.Eval.CThunk: cthunkNewComputedStr :: Word32 -> IO CThunkPtr
+ Nix.Eval.CThunk: cthunkNewComputedStr :: MonadCData m => CStrPtr -> m CThunkPtr
- Nix.Eval.CThunk: cthunkPayload :: CThunkPtr -> IO (Ptr ())
+ Nix.Eval.CThunk: cthunkPayload :: MonadCData m => CThunkPtr -> m (Ptr ())
- Nix.Eval.CThunk: cthunkSetComputedAttrs :: CThunkPtr -> Ptr () -> IO Bool
+ Nix.Eval.CThunk: cthunkSetComputedAttrs :: MonadCData m => CThunkPtr -> Ptr () -> m Bool
- Nix.Eval.CThunk: cthunkSetComputedBool :: CThunkPtr -> Word8 -> IO Bool
+ Nix.Eval.CThunk: cthunkSetComputedBool :: MonadCData m => CThunkPtr -> Word8 -> m Bool
- Nix.Eval.CThunk: cthunkSetComputedCtxStr :: CThunkPtr -> Ptr () -> IO Bool
+ Nix.Eval.CThunk: cthunkSetComputedCtxStr :: MonadCData m => CThunkPtr -> Ptr () -> m Bool
- Nix.Eval.CThunk: cthunkSetComputedFloat :: CThunkPtr -> Double -> IO Bool
+ Nix.Eval.CThunk: cthunkSetComputedFloat :: MonadCData m => CThunkPtr -> Double -> m Bool
- Nix.Eval.CThunk: cthunkSetComputedInt :: CThunkPtr -> Int64 -> IO Bool
+ Nix.Eval.CThunk: cthunkSetComputedInt :: MonadCData m => CThunkPtr -> Int64 -> m Bool
- Nix.Eval.CThunk: cthunkSetComputedLambda :: CThunkPtr -> Ptr () -> IO Bool
+ Nix.Eval.CThunk: cthunkSetComputedLambda :: MonadCData m => CThunkPtr -> Ptr () -> m Bool
- Nix.Eval.CThunk: cthunkSetComputedList :: CThunkPtr -> Ptr () -> IO Bool
+ Nix.Eval.CThunk: cthunkSetComputedList :: MonadCData m => CThunkPtr -> Ptr () -> m Bool
- Nix.Eval.CThunk: cthunkSetComputedNull :: CThunkPtr -> IO Bool
+ Nix.Eval.CThunk: cthunkSetComputedNull :: MonadCData m => CThunkPtr -> m Bool
- Nix.Eval.CThunk: cthunkSetComputedPath :: CThunkPtr -> Word32 -> IO Bool
+ Nix.Eval.CThunk: cthunkSetComputedPath :: MonadCData m => CThunkPtr -> CStrPtr -> m Bool
- Nix.Eval.CThunk: cthunkSetComputedStr :: CThunkPtr -> Word32 -> IO Bool
+ Nix.Eval.CThunk: cthunkSetComputedStr :: MonadCData m => CThunkPtr -> CStrPtr -> m Bool
- Nix.Eval.CThunk: cthunkState :: CThunkPtr -> IO Word8
+ Nix.Eval.CThunk: cthunkState :: MonadCData m => CThunkPtr -> m Word8
- Nix.Eval.CThunk: cthunkValueTag :: CThunkPtr -> IO Word8
+ Nix.Eval.CThunk: cthunkValueTag :: MonadCData m => CThunkPtr -> m Word8
- Nix.Eval.Compile: BcInheritFrom :: Word32 -> [BcInheritedName] -> BcBinding
+ Nix.Eval.Compile: BcInheritFrom :: Word32 -> BcInheritedNames -> BcBinding
- Nix.Eval.Compile: BcNamed :: PosIdx -> BcAttrKey -> Word32 -> BcBinding
+ Nix.Eval.Compile: BcNamed :: PosIdx -> Word32 -> Word32 -> BcBinding
- Nix.Eval.Compile: decodeBcBindings :: Int -> Word32 -> IO [BcBinding]
+ Nix.Eval.Compile: decodeBcBindings :: MonadCData m => Int -> Word32 -> m BcBindings
- Nix.Eval.Compile: decodeBcCaptureInfo :: Word32 -> IO CaptureInfo
+ Nix.Eval.Compile: decodeBcCaptureInfo :: MonadCData m => Word32 -> m (Either Word32 BcCaptureInfo)
- Nix.Eval.Compile: decodeBcFormals :: Word8 -> Word32 -> IO EvalFormals
+ Nix.Eval.Compile: decodeBcFormals :: MonadCData m => (Word32 -> m FormalDefault) -> Word8 -> Word32 -> m (Maybe EvalFormals)
- Nix.Eval.EvalFormals: EFName :: Text -> EvalFormals
+ Nix.Eval.EvalFormals: EFName :: Symbol -> EvalFormals
- Nix.Eval.EvalFormals: EFNamedSet :: Text -> [EvalFormal] -> Bool -> EvalFormals
+ Nix.Eval.EvalFormals: EFNamedSet :: LambdaName -> Symbol -> [EvalFormal] -> Bool -> EvalFormals
- Nix.Eval.EvalFormals: EFSet :: [EvalFormal] -> Bool -> EvalFormals
+ Nix.Eval.EvalFormals: EFSet :: LambdaName -> [EvalFormal] -> Bool -> EvalFormals
- Nix.Eval.EvalFormals: EvalFormal :: Text -> Maybe Word32 -> EvalFormal
+ Nix.Eval.EvalFormals: EvalFormal :: Symbol -> FormalDefault -> EvalFormal
- Nix.Eval.EvalFormals: [efDefault] :: EvalFormal -> Maybe Word32
+ Nix.Eval.EvalFormals: [efDefault] :: EvalFormal -> FormalDefault
- Nix.Eval.EvalFormals: [efName] :: EvalFormal -> Text
+ Nix.Eval.EvalFormals: [efName] :: EvalFormal -> Symbol
- Nix.Eval.Policy: EvalPolicy :: Bool -> Bool -> [Text] -> Bool -> EvalPolicy
+ Nix.Eval.Policy: EvalPolicy :: Bool -> Bool -> [Text] -> Bool -> ImportFromDerivation -> FeatureSet -> EvalPolicy
- Nix.Eval.Print: printAmbiguous :: NixValue -> Builder
+ Nix.Eval.Print: printAmbiguous :: MonadCData m => NixValue -> m Builder
- Nix.Eval.Print: printValue :: PrintOptions -> NixValue -> Text
+ Nix.Eval.Print: printValue :: MonadCData m => PrintOptions -> NixValue -> m Text
- Nix.Eval.SourcePos: lookupPos :: PosIdx -> Maybe RecordedPos
+ Nix.Eval.SourcePos: lookupPos :: MonadCData m => PosIdx -> m (Maybe RecordedPos)
- Nix.Eval.Symbol: symbolIntern :: Text -> IO Symbol
+ Nix.Eval.Symbol: symbolIntern :: MonadCData m => Text -> m Symbol
- Nix.Eval.Types: EFName :: Text -> EvalFormals
+ Nix.Eval.Types: EFName :: Symbol -> EvalFormals
- Nix.Eval.Types: EFNamedSet :: Text -> [EvalFormal] -> Bool -> EvalFormals
+ Nix.Eval.Types: EFNamedSet :: LambdaName -> Symbol -> [EvalFormal] -> Bool -> EvalFormals
- Nix.Eval.Types: EFSet :: [EvalFormal] -> Bool -> EvalFormals
+ Nix.Eval.Types: EFSet :: LambdaName -> [EvalFormal] -> Bool -> EvalFormals
- Nix.Eval.Types: EvalFormal :: Text -> Maybe Word32 -> EvalFormal
+ Nix.Eval.Types: EvalFormal :: Symbol -> FormalDefault -> EvalFormal
- Nix.Eval.Types: EvalPolicy :: Bool -> Bool -> [Text] -> Bool -> EvalPolicy
+ Nix.Eval.Types: EvalPolicy :: Bool -> Bool -> [Text] -> Bool -> ImportFromDerivation -> FeatureSet -> EvalPolicy
- Nix.Eval.Types: VBuiltin :: Text -> [BuiltinArg] -> NixValue
+ Nix.Eval.Types: VBuiltin :: Builtin -> [BuiltinArg] -> NixValue
- Nix.Eval.Types: [efDefault] :: EvalFormal -> Maybe Word32
+ Nix.Eval.Types: [efDefault] :: EvalFormal -> FormalDefault
- Nix.Eval.Types: [efName] :: EvalFormal -> Text
+ Nix.Eval.Types: [efName] :: EvalFormal -> Symbol
- Nix.Eval.Types: addFixedOutputFile :: MonadEval m => Text -> ByteString -> m Text
+ Nix.Eval.Types: addFixedOutputFile :: MonadEval m => PendingOrigin -> Text -> ByteString -> m Text
- Nix.Eval.Types: attrSetElems :: AttrSet -> [Thunk]
+ Nix.Eval.Types: attrSetElems :: MonadCData m => AttrSet -> m [Thunk]
- Nix.Eval.Types: attrSetFromEntries :: Map Text AttrEntry -> AttrSet
+ Nix.Eval.Types: attrSetFromEntries :: MonadCData m => SetSite -> Map Text AttrEntry -> m AttrSet
- Nix.Eval.Types: attrSetFromMap :: Map Text Thunk -> AttrSet
+ Nix.Eval.Types: attrSetFromMap :: MonadCData m => SetSite -> Map Text Thunk -> m AttrSet
- Nix.Eval.Types: attrSetKeys :: AttrSet -> [Text]
+ Nix.Eval.Types: attrSetKeys :: MonadCData m => AttrSet -> m [Text]
- Nix.Eval.Types: attrSetLookup :: Text -> AttrSet -> Maybe Thunk
+ Nix.Eval.Types: attrSetLookup :: MonadCData m => Text -> AttrSet -> m (Maybe Thunk)
- Nix.Eval.Types: attrSetLookupEntry :: Text -> AttrSet -> Maybe AttrEntry
+ Nix.Eval.Types: attrSetLookupEntry :: MonadCData m => Text -> AttrSet -> m (Maybe AttrEntry)
- Nix.Eval.Types: attrSetMapWithKey :: (Text -> Thunk -> Thunk) -> AttrSet -> AttrSet
+ Nix.Eval.Types: attrSetMapWithKey :: MonadCData m => SetSite -> (Symbol -> Thunk -> m Thunk) -> AttrSet -> m AttrSet
- Nix.Eval.Types: attrSetMember :: Text -> AttrSet -> Bool
+ Nix.Eval.Types: attrSetMember :: MonadCData m => Text -> AttrSet -> m Bool
- Nix.Eval.Types: attrSetNull :: AttrSet -> Bool
+ Nix.Eval.Types: attrSetNull :: MonadCData m => AttrSet -> m Bool
- Nix.Eval.Types: attrSetRemoveKeys :: [Text] -> AttrSet -> AttrSet
+ Nix.Eval.Types: attrSetRemoveKeys :: MonadCData m => SetSite -> [Text] -> AttrSet -> m AttrSet
- Nix.Eval.Types: attrSetSize :: AttrSet -> Int
+ Nix.Eval.Types: attrSetSize :: MonadCData m => AttrSet -> m Int
- Nix.Eval.Types: attrSetToAscList :: AttrSet -> [(Text, Thunk)]
+ Nix.Eval.Types: attrSetToAscList :: MonadCData m => AttrSet -> m [(Text, Thunk)]
- Nix.Eval.Types: attrSetToMap :: AttrSet -> Map Text Thunk
+ Nix.Eval.Types: attrSetToMap :: MonadCData m => AttrSet -> m (Map Text Thunk)
- Nix.Eval.Types: buildCAttrSetKeys :: [Text] -> CAttrSet
+ Nix.Eval.Types: buildCAttrSetKeys :: MonadCData m => [Symbol] -> m FlatCAttrSet
- Nix.Eval.Types: cheapThunk :: Env -> Expr -> Thunk
+ Nix.Eval.Types: cheapThunk :: MonadCData m => Env -> Expr -> m Thunk
- Nix.Eval.Types: cheapThunkBc :: Env -> Word32 -> Thunk
+ Nix.Eval.Types: cheapThunkBc :: MonadCData m => Env -> Word32 -> m Thunk
- Nix.Eval.Types: class Monad m => MonadEval (m :: Type -> Type)
+ Nix.Eval.Types: class MonadCData m => MonadEval (m :: Type -> Type)
- Nix.Eval.Types: clistFromThunks :: [CThunkPtr] -> CList
+ Nix.Eval.Types: clistFromThunks :: MonadCData m => [CThunkPtr] -> m CList
- Nix.Eval.Types: clistLen :: CList -> Int
+ Nix.Eval.Types: clistLen :: MonadCData m => CList -> m Int
- Nix.Eval.Types: clistThunks :: CList -> [CThunkPtr]
+ Nix.Eval.Types: clistThunks :: MonadCData m => CList -> m [CThunkPtr]
- Nix.Eval.Types: copyPathToStore :: MonadEval m => Text -> Text -> Maybe (Text, ByteString) -> m Text
+ Nix.Eval.Types: copyPathToStore :: MonadEval m => PendingOrigin -> Text -> Text -> Maybe (ByteString, ByteString -> Text) -> m Text
- Nix.Eval.Types: envLookup :: Text -> Env -> Maybe Thunk
+ Nix.Eval.Types: envLookup :: MonadCData m => Symbol -> Env -> m (Maybe Thunk)
- Nix.Eval.Types: envLookupResolved :: Int -> Int -> Env -> Thunk
+ Nix.Eval.Types: envLookupResolved :: MonadCData m => Word32 -> Word32 -> Env -> m Thunk
- Nix.Eval.Types: envWithScopesRaw :: Env -> (Ptr (Ptr ()), Word32)
+ Nix.Eval.Types: envWithScopesRaw :: MonadCData m => Env -> m (Ptr (Ptr ()), Word32)
- Nix.Eval.Types: evaluated :: NixValue -> Thunk
+ Nix.Eval.Types: evaluated :: MonadCData m => NixValue -> m Thunk
- Nix.Eval.Types: fillCAttrSetValues :: CAttrSet -> Map Text Thunk -> ()
+ Nix.Eval.Types: fillCAttrSetValues :: MonadCData m => FlatCAttrSet -> Map Symbol Thunk -> m ()
- Nix.Eval.Types: forceThunk :: MonadEval m => (Env -> Word32 -> m NixValue) -> Thunk -> m NixValue
+ Nix.Eval.Types: forceThunk :: MonadEval m => (Pending -> m NixValue) -> Thunk -> m NixValue
- Nix.Eval.Types: listDirectory :: MonadEval m => Text -> m [(Text, Text)]
+ Nix.Eval.Types: listDirectory :: MonadEval m => Text -> m [(Text, Maybe Text)]
- Nix.Eval.Types: marshalLambda :: Ptr NnEnv -> EvalFormals -> Word32 -> IO (Ptr ())
+ Nix.Eval.Types: marshalLambda :: MonadCData m => Ptr NnEnv -> EvalFormals -> Word32 -> m (Ptr ())
- Nix.Eval.Types: mkThunkBc :: Env -> Word32 -> Thunk
+ Nix.Eval.Types: mkThunkBc :: MonadCData m => Env -> Word32 -> m Thunk
- Nix.Eval.Types: readThunkValue :: Thunk -> Maybe NixValue
+ Nix.Eval.Types: readThunkValue :: MonadCData m => Thunk -> m (Maybe NixValue)
- Nix.Eval.Types: scopedImportFile :: MonadEval m => [(Text, Thunk)] -> Text -> m NixValue
+ Nix.Eval.Types: scopedImportFile :: MonadEval m => AttrSet -> Text -> m NixValue
- Nix.Eval.Types: storePathOrThrow :: MonadEval m => Either BadStorePath StorePath -> m StorePath
+ Nix.Eval.Types: storePathOrThrow :: MonadEval m => Either BadStorePath a -> m a
- Nix.Eval.Types: thunkUnderEvaluation :: Thunk -> Bool
+ Nix.Eval.Types: thunkUnderEvaluation :: MonadCData m => Thunk -> m Bool
- Nix.Hash: makeFixedOutputPath :: Text -> Text -> Text -> ByteString -> Either BadStorePath StorePath
+ Nix.Hash: makeFixedOutputPath :: Text -> Text -> FileIngestionMethod -> ByteString -> Either BadStorePath StorePath
- Nix.Http: FetchRetryPolicy :: Int -> Int -> FetchRetryPolicy
+ Nix.Http: FetchRetryPolicy :: Word32 -> Int -> FetchRetryPolicy
- Nix.Http: [frpAttempts] :: FetchRetryPolicy -> Int
+ Nix.Http: [frpAttempts] :: FetchRetryPolicy -> Word32
- Nix.Http: ioRetryEffects :: RetryEffects IO
+ Nix.Http: ioRetryEffects :: Logger -> RetryEffects IO
- Nix.Http: retryDelayMs :: FetchRetryPolicy -> Int -> Double -> Int
+ Nix.Http: retryDelayMs :: FetchRetryPolicy -> Word32 -> Double -> Int
- Nix.Parser: parseNix :: FilePath -> SourceOrigin -> ByteString -> Either SourceError Expr
+ Nix.Parser: parseNix :: FilePath -> SourceOrigin -> ByteString -> Either SourceError ParsedSource
- Nix.Parser: parseNixWithScope :: Set Text -> FilePath -> SourceOrigin -> ByteString -> Either SourceError Expr
+ Nix.Parser: parseNixWithScope :: Set Text -> FilePath -> SourceOrigin -> ByteString -> Either SourceError ParsedSource
- Nix.Parser.Internal: ParseState :: [Located] -> SourceOrigin -> ParseState
+ Nix.Parser.Internal: ParseState :: [Located] -> SourceOrigin -> [Text] -> ParseState
- Nix.Push: PushConfig :: Text -> Maybe Text -> PushCompression -> PushConfig
+ Nix.Push: PushConfig :: Text -> Maybe Text -> PushCompression -> PartSize -> FetchRetryPolicy -> PushConfig
- Nix.Push: checkRecordedNarHash :: Maybe PathInfo -> Text -> StorePath -> Either Text ()
+ Nix.Push: checkRecordedNarHash :: Maybe PushedPath -> Text -> StorePath -> Either Text ()
- Nix.Push: computeClosure :: Store -> [StorePath] -> IO (Either Text [StorePath])
+ Nix.Push: computeClosure :: PushSource -> [StorePath] -> IO (Either Text [StorePath])
- Nix.Push: pushPaths :: PushConfig -> Store -> [StorePath] -> IO (Either Text PushSummary)
+ Nix.Push: pushPaths :: PushConfig -> PushSource -> [StorePath] -> IO (Either Text PushSummary)
- Nix.Realise: NotOffered :: Offer
+ Nix.Realise: NotOffered :: Offer s
- Nix.Realise: Offered :: [StorePath] -> Offer
+ Nix.Realise: Offered :: s -> [StorePath] -> Offer s
- Nix.Realise: QueryFailed :: Text -> Offer
+ Nix.Realise: QueryFailed :: Text -> Offer s
- Nix.Realise: RealiseEffects :: SubstEffects m -> (Derivation -> m Bool) -> (Derivation -> StorePath -> m (Either Text ())) -> (Realised -> Derivation -> m ()) -> RealiseEffects (m :: Type -> Type)
+ Nix.Realise: RealiseEffects :: SubstEffects s m -> (Derivation -> StorePath -> Set Text -> m (Either FailedBuild ())) -> (Derivation -> StorePath -> m (Either Text CheckVerdict)) -> (Realised -> Derivation -> m ()) -> RealiseEffects s (m :: Type -> Type)
- Nix.Realise: SubstEffects :: (StorePath -> m Bool) -> (StorePath -> m Offer) -> ([StorePath] -> m FetchOutcome) -> SubstEffects (m :: Type -> Type)
+ Nix.Realise: SubstEffects :: (StorePath -> m Bool) -> (StorePath -> m (Offer s)) -> (StorePath -> s -> m (Offer s)) -> (Registration -> NonEmpty (StorePath, s) -> m FetchOutcome) -> SubstEffects s (m :: Type -> Type)
- Nix.Realise: [reBuild] :: RealiseEffects (m :: Type -> Type) -> Derivation -> StorePath -> m (Either Text ())
+ Nix.Realise: [reBuild] :: RealiseEffects s (m :: Type -> Type) -> Derivation -> StorePath -> Set Text -> m (Either FailedBuild ())
- Nix.Realise: [reReport] :: RealiseEffects (m :: Type -> Type) -> Realised -> Derivation -> m ()
+ Nix.Realise: [reReport] :: RealiseEffects s (m :: Type -> Type) -> Realised -> Derivation -> m ()
- Nix.Realise: [reSubst] :: RealiseEffects (m :: Type -> Type) -> SubstEffects m
+ Nix.Realise: [reSubst] :: RealiseEffects s (m :: Type -> Type) -> SubstEffects s m
- Nix.Realise: [seFetch] :: SubstEffects (m :: Type -> Type) -> [StorePath] -> m FetchOutcome
+ Nix.Realise: [seFetch] :: SubstEffects s (m :: Type -> Type) -> Registration -> NonEmpty (StorePath, s) -> m FetchOutcome
- Nix.Realise: [seReferences] :: SubstEffects (m :: Type -> Type) -> StorePath -> m Offer
+ Nix.Realise: [seReferences] :: SubstEffects s (m :: Type -> Type) -> StorePath -> m (Offer s)
- Nix.Realise: [seValid] :: SubstEffects (m :: Type -> Type) -> StorePath -> m Bool
+ Nix.Realise: [seValid] :: SubstEffects s (m :: Type -> Type) -> StorePath -> m Bool
- Nix.Realise: data Offer
+ Nix.Realise: data Offer s
- Nix.Realise: data RealiseEffects (m :: Type -> Type)
+ Nix.Realise: data RealiseEffects s (m :: Type -> Type)
- Nix.Realise: data SubstEffects (m :: Type -> Type)
+ Nix.Realise: data SubstEffects s (m :: Type -> Type)
- Nix.Realise: realise :: Monad m => Fallback -> RealiseEffects m -> DepGraph -> StorePath -> m (Either RealiseFailure ())
+ Nix.Realise: realise :: Monad m => RealiseSettings -> BuildMode -> RealiseEffects s m -> DepGraph -> StorePath -> m (Either RealiseFailure ())
- Nix.Realise: realiseFailureMessage :: RealiseFailure -> Text
+ Nix.Realise: realiseFailureMessage :: StoreDir -> RealiseFailure -> Text
- Nix.Realise: substituteClosure :: Monad m => SubstEffects m -> [StorePath] -> m ClosureOutcome
+ Nix.Realise: substituteClosure :: Monad m => SubstEffects s m -> [StorePath] -> m ClosureOutcome
- Nix.Store: materializeEvalSources :: Store -> Map Text Text -> IO ()
+ Nix.Store: materializeEvalSources :: Store -> Map StorePath Text -> IO ()
- Nix.Store: resolveDeleteTarget :: StoreDir -> Text -> Either Text Text
+ Nix.Store: resolveDeleteTarget :: StoreDir -> Text -> Either Text StoreEntryName
- Nix.Store: sinkNarStream :: NarUnpackSink -> IO ByteString -> IO (Either NarStreamFailure (NixHash, Int))
+ Nix.Store: sinkNarStream :: ArchiveEnd -> NarUnpackSink -> IO ByteString -> IO (Either NarStreamFailure (NixHash, Int))
- Nix.Store.DB: PathInfo :: Text -> Text -> Int -> Maybe Text -> Int -> PathInfo
+ Nix.Store.DB: PathInfo :: Text -> Text -> Int -> Maybe Text -> Int -> Ultimate -> Set Signature -> Maybe ContentAddress -> PathInfo
- Nix.Store.DB: PathRegistration :: StorePath -> Text -> Int -> Maybe Text -> [StorePath] -> PathRegistration
+ Nix.Store.DB: PathRegistration :: StorePath -> Text -> Int -> Maybe Text -> [StorePath] -> Ultimate -> Set Signature -> Maybe ContentAddress -> RegistrationTime -> PathRegistration
- Nix.Store.GC: collectGarbage :: Store -> IO (Either Text GcResults)
+ Nix.Store.GC: collectGarbage :: Store -> Set StorePath -> IO (Either Text GcResults)
- Nix.Store.GC: findingRootsMessage :: String
+ Nix.Store.GC: findingRootsMessage :: Text
- Nix.Store.GC: indirectRootRecordName :: FilePath -> FilePath
+ Nix.Store.GC: indirectRootRecordName :: ByteString -> FilePath
- Nix.Store.Handle: Store :: StoreDir -> StoreDB -> MVar PathLock -> CaseSensitivity -> Store
+ Nix.Store.Handle: Store :: StoreDir -> StoreDB -> MVar PathLock -> CaseSensitivity -> Logger -> Store
- Nix.Store.Handle: openStore :: StoreDir -> IO Store
+ Nix.Store.Handle: openStore :: Logger -> StoreDir -> IO Store
- Nix.Store.Lock: acquireLockFileWith :: LockMode -> String -> FilePath -> IO PathLock
+ Nix.Store.Lock: acquireLockFileWith :: Logger -> LockMode -> Text -> FilePath -> IO PathLock
- Nix.Store.Lock: acquirePathLock :: StoreDir -> StorePath -> IO PathLock
+ Nix.Store.Lock: acquirePathLock :: Logger -> StoreDir -> StorePath -> IO PathLock
- Nix.Store.Lock: waitingForLockMessage :: FilePath -> String
+ Nix.Store.Lock: waitingForLockMessage :: FilePath -> Text
- Nix.Store.Lock: withLockFile :: FilePath -> (PathLock -> IO a) -> IO a
+ Nix.Store.Lock: withLockFile :: Logger -> FilePath -> (PathLock -> IO a) -> IO a
- Nix.Store.Lock: withLockFileWith :: LockMode -> String -> FilePath -> (PathLock -> IO a) -> IO a
+ Nix.Store.Lock: withLockFileWith :: Logger -> LockMode -> Text -> FilePath -> (PathLock -> IO a) -> IO a
- Nix.Store.Lock: withPathLock :: StoreDir -> StorePath -> (PathLock -> IO a) -> IO a
+ Nix.Store.Lock: withPathLock :: Logger -> StoreDir -> StorePath -> (PathLock -> IO a) -> IO a
- Nix.Substituter: CacheConfig :: Text -> [Text] -> Int -> CacheConfig
+ Nix.Substituter: CacheConfig :: Text -> [Text] -> [ByteString] -> RequireSigs -> Int -> CacheConfig
- Nix.Substituter: cappedBodySource :: Int -> BodyReader -> IO (IO ByteString)
+ Nix.Substituter: cappedBodySource :: Int -> IO ByteString -> IO (IO ByteString)
- Nix.Substituter: judgeNarInfo :: CacheConfig -> StorePath -> NarInfo -> NarInfoAnswer
+ Nix.Substituter: judgeNarInfo :: Either Text SignatureRequirement -> StorePath -> NarInfo -> ([Text], NarInfoAnswer)
- Nix.Substituter: queryReferencesWith :: FetchRetryPolicy -> RetryEffects IO -> Fallback -> [CacheConfig] -> StorePath -> IO Offer
+ Nix.Substituter: queryReferencesWith :: Logger -> FetchRetryPolicy -> RetryEffects IO -> Fallback -> [CacheConfig] -> StorePath -> StateT CacheMemo IO (Offer Substitute)
- Nix.Substituter: readBodyCapped :: Int -> BodyReader -> IO (Maybe ByteString)
+ Nix.Substituter: readBodyCapped :: Int -> IO ByteString -> IO (Maybe ByteString)
- Nix.Substituter: verifySigs :: CacheConfig -> NarInfo -> Either Text ()
+ Nix.Substituter: verifySigs :: [PublicKey] -> NarInfo -> Bool

Files

CHANGELOG.md view
@@ -1,5 +1,360 @@ # Changelog +## 0.11.0.0 - 2026-12-04++`nova-nix daemon` serves a store in upstream Nix's worker protocol, over a Unix socket on Linux and macOS and a named pipe on Windows, and builds, substitutes and adds paths for its clients. A command that cannot write its store goes through a daemon when one is there, `push` and `trust` included. `nova-nix profile` keeps profiles of generations, with history, rollback and wipe-history, and on Linux and macOS `nova-nix develop` starts a shell in a derivation's build environment, which `print-dev-env` prints. Builds run in a sandbox by default on Linux and under a macOS sandbox profile with `sandbox = true`, and as root on Linux and macOS they run as members of `build-users-group`. On Windows, the package set's stdenv takes its shell, tools and toolchain from the seed ladder, which builds them from stage0-pe32's seed through GNU Mes, TinyCC and GCC 4.6.4, 10 and 16 to a native x86_64 GCC, and `pkgs/windows` no longer downloads a prebuilt compiler or shell. `builtins.fetchTarball` unpacks in process, so a tarball's tree and its store path are the archive's own. Evaluation spends less of its time collecting garbage: a pending thunk holds its environment's C pointer where it held a GHC stable pointer, and in that change's measurement the drvPaths of firefox, git, python3 and gimp from nixpkgs evaluated in 6.7 seconds where they took 24.5. The Library API section lists the breaking changes.++### Library API++Breaking changes for code that uses nova-nix as a library:++- **`Nix.Realise.realise` takes a `RealiseSettings`, holding `rsFallback` and `rsSubstitutes`, where it took a `Fallback`.** `RealiseFailure` gains `InvalidDerivation`, `BuildConfig` gains `bcSubstitutes` and `NixConfig` gains `ncAlwaysAllowSubstitutes`, so a record built without a default needs the new field. `Nix.Realise` exports `derivationAttrs` and `substitutesAllowed` with their types, and `storePathBasename` is defined in `Nix.Store.Path`, which exports it as `Nix.Push` still does. (#421)+- **`Nix.Realise.realise` also takes a `BuildMode`, `BuildNormal` or `BuildCheck`, after its `RealiseSettings`; `RealiseEffects` gains `reCheck`, which answers a `CheckVerdict`; `Realised` gains `Checked`; and `RealiseFailure` gains `OutputsNotValid`, `NotDeterministic` and `MissingDerivation`, the last for a check whose root the graph does not hold, which is a failure where a build of such a root realises nothing and succeeds.** A record built without a default needs the new field, a call to `realise` the mode, and a total match the new constructors. `realiseFailureMessage` takes the directory the store's files are in before the failure, to name the output that differs where it is, and `realiseFailureStatus` gives the status a failure exits with. `BuildConfig` gains `bcMode`, and `buildWithDeps` answers a `BuildFailure` with that status, 104 for a check that found a difference, where it answered 1 for every failure. `Nix.Builder` exports `checkDerivation`, the rebuild and comparison alone for a derivation whose outputs are valid and whose inputs are realised. (#425)+- **`Nix.Eval.Types` drops `mkSyntheticThunk`, whose callers use `mkThunkBc`, and `allocCSlots` and `fillCSlots`, which `tieFrame :: (MonadCData m) => EnvSite -> Maybe Env -> Int -> (Env -> m [Thunk]) -> m (Env, [Thunk])` replaces: it allocates a frame of that many empty slots at a site under a parent or none, makes its thunks against it, and fills the slots last.** A pending thunk's cell holds its env's C pointer, so `mkThunkBc`, and `cheapThunkBc` and `cheapThunk` where they make a pending thunk, take the env when they run; a frame whose slots hold thunks that point back at it is built with `tieFrame`. `cthunkNewBc` in `Nix.Eval.CThunk` takes the pending payload as an `nn_env_t *`, which both evaluators' force paths read back, and arena teardown no longer frees it, so a caller passing a StablePtr there leaks it and crashes when the thunk is forced. `cthunkPayload` answers that env pointer for a pending thunk of code. `Nix.Eval.CThunk` drops `cthunkSetPayload`. (#428)+- **`Nix.Config.NixConfig` gains `ncCores :: Maybe Word32`, `Nothing` when no source sets it, and `Nix.Builder.BuildConfig` gains `bcCores :: Word32`, which `defaultBuildConfig` sets to 1, what setup.sh takes an unset `NIX_BUILD_CORES` to mean, and which a builder is told of as it is, `settingsBuildConfig` giving it the machine's default where `ncCores` is `Nothing` or `Just 0`; a record built with the constructor needs the new field.** The new module `Nix.Builder.Cores` gives upstream's default: `defaultCores` chooses it from a cgroup limit and a hardware count, `hardwareConcurrency` reads the hardware count, `cgroupCoreLimit` finds the limit over a file-reading effect (`ReadKernelFile`), and `cgroup2MountPoint`, `parseCgroups` and `cpuMaxCores` parse the three files it reads. (#436)+- **`Nix.Store.GC` adds `deleteStorePaths :: Store -> [StoreEntryName] -> (StoreEntryName -> DeleteOutcome -> IO ()) -> IO (Either Text ())`, which deletes the named entries in order under one collector lock and one live set, runs the action after each deletion, and stops at the first refusal, which it returns; it refuses whatever `deleteStorePathRaw` refuses.** `LiveSet`, `withLiveSet` and `isLive` are removed from `Nix.Store.GC`, and `deleteStorePathChecked` from `Nix.Store`: a batch delete calls `deleteStorePaths`. `DeleteOutcome` and `deleteStorePathRaw` move from `Nix.Store` to `Nix.Store.GC`, which `Nix.Store` re-exports, so an import from `Nix.Store` is unchanged. (#446)+- **`Nix.Builder.BuildConfig` has no `bcTmpDir`; a build's directory follows from `bcStoreDir`.** The new module `Nix.Builder.BuildDir` names a build's directory (`buildDirFor`), creates one (`createBuildDir`) and runs a build in one (`withBuildDir`). (#449)+- **`deleteStorePathRaw` takes a `StoreEntryName` where it took `Text`, as `deleteStorePaths` does.** `Nix.Store.GC`, which `Nix.Store` re-exports, adds `StoreEntryName` without its constructor, `storeEntryName :: Text -> Either Text StoreEntryName`, the only way to make one, and `storeEntryNameText`. `resolveDeleteTarget` returns a `StoreEntryName`. (#457)+- **`Nix.Expr.Types.Expr` gains `EPos`, the position `__curPos` is written at, which the parser gives where it gave `EVar "__curPos"`; a match on `Expr` needs the case.** `Nix.Eval.CBytecode` adds the opcode `OpPos`. (#468)+- **`Nix.Store.setReadOnly` is replaced by `canonicalizeMetadata`, from the new module `Nix.Store.Metadata`; `Nix.Store` re-exports it.** The module also exports the canonical form: `metadataChanges` gives the `MetadataChange`s a node's `NodeMetadata` needs, and `canonicalPermissions`, `readOnlyPermissions`, `executablePermissions` and `storeModificationTime` are its constants. `writeDrvAterm` keeps a `.drv` that already holds its bytes rather than writing it again. On Windows the `Win32` floor rises to 2.12, the first whose `setFileTime` leaves a time it is not given as it is. (#477)+- **`Nix.Eval.Types.MonadEval`'s `listDirectory` returns `[(Text, Maybe Text)]`, `Nothing` for an entry whose `lstat` is refused, where it returned `[(Text, Text)]`; an instance gives `Nothing` for such an entry, and a caller that needs every entry's type reads it with `getFileType`.** (#491)+- **`Nix.Eval.Compile.decodeBcFormals` answers a `Maybe EvalFormals` and `decodeBcCaptureInfo` an `Either` whose `Left` holds the unknown tag, where each answered the decoded value alone.** `Nix.Eval.Compile` exports each operator's tag pair, `encodeUnaryOp` with `decodeUnaryOp :: Word8 -> Maybe UnaryOp` and `encodeBinaryOp` with `decodeBinaryOp :: Word8 -> Maybe BinaryOp`, and `Nix.Expr.Types.UnaryOp` and `BinaryOp` derive `Bounded` and `Enum`. (#502)+- **`Nix.DependencyGraph.DepNode`'s `dnDeps` maps each dependency's `.drv` path to the outputs wanted of it, a `Map StorePath (Set Text)`, where it was a `[StorePath]`; `directDeps` still answers the paths.** `Nix.Realise.RealiseEffects` drops `reAllValid`: whether the outputs wanted of a derivation are valid is asked of `reSubst`'s `seValid`. Its `reBuild` also takes the names of the outputs the request that led to the build asks for, a `Set Text`, which a build that makes every output may leave unread. `Nix.Realise.RealiseFailure` gains `MissingOutputs`, naming the derivation and the outputs it lacks, a `NonEmpty Text`. (#503)+- **`Nix.Eval.Types.MonadEval`'s `copyPathToStore` takes its pin as the digest the copy must have and the refusal of a copy with another, given the digest it has (`Maybe (ByteString, ByteString -> Text)`), where it took the refusal's subject and the digest (`Maybe (Text, ByteString)`).** (#500)+- **`Nix.Eval.Types.MonadEval`'s `addErrorTrace` method is replaced by `addEvaluatedTrace :: (Text -> Text) -> m Text -> m a -> m a`, which makes its line, an action, only when the action it wraps fails, and when making the line fails keeps the action's failure with the line its first argument makes of the line's own failure.** `addErrorTrace :: (MonadEval m) => Text -> m a -> m a` is a function of `Nix.Eval.Types` taking a line that is already made, which `MonadEval (..)` no longer brings in and `Nix.Eval` does not export, so a caller imports it from `Nix.Eval.Types` by name, and an instance defines `addEvaluatedTrace`. (#517, #706)+- **`Nix.Realise.SubstEffects` and `RealiseEffects` take the type of a substitute, which `Offered` carries beside the references; `SubstEffects` gains `seNextOffer`, and `seFetch` takes a `Registration`, `RegisterAll` or `RegisterNone`, and each path with its substitute, as a `NonEmpty`.** `FetchOutcome` is `Fetched` or `NotFetched`, which names each path that did not arrive with an `Undelivered`, `Gone` or `DeliveryFailed`, in place of `FetchMissed` and `FetchFailed`. `Nix.Substituter.queryReferencesWith` runs in `StateT CacheMemo IO` and answers an `Offer Substitute`, which names the path it was checked for (`substitutePath`) and the cache it comes from (`substituteCache`); `queryNextOfferWith` asks the caches after a substitute's, `fetchSubstituteWith` fetches a substitute's path, and a run starts from `emptyCacheMemo`. `trySubstitute`, `trySubstituteWith` and `tryCachesWith` are removed: a path is fetched from the substitute a reference query offered, `queryReferencesWith` and then `fetchSubstituteWith`, whose `SubstResult` is about that one cache. `Nix.Builder.substitutePaths` takes a `Registration` and the substitutes. (#518)+- **`Nix.Hash.makeFixedOutputPath` takes the method as a `FileIngestionMethod` (`FlatIngestion` or `NarIngestion`, exported from `Nix.Hash` with `fileIngestionPrefix`), where it took `"flat"` or `"recursive"` as `Text` and read every other text as flat.** (#528)+- **`Nix.Parser.parseNix` and `parseNixWithScope` return a `ParsedSource`, whose expression `parsedExpr` reads and whose names, in upstream's interning order, `parsedNames` reads.** `Nix.Eval.evalParsed` evaluates one in the environment an action builds, interning its names first and running the action once the source has compiled, and `Nix.Eval.Compile.compileParsed` compiles one; `eval` on its expression interns the names in the order the compiler meets them. `Nix.Parser.Internal.ParseState` gains `psNames`, the names noted so far, latest first, which a state built outside the parser starts as `[]`, and `recordName` notes one. (#525)+- **Every constructor of an environment or attribute set takes, first, the `EnvSite` or `SetSite` (`Nix.Eval.AllocSite`, new) it allocates for: `attrSetFromMap`, `attrSetFromEntries`, `attrSetMapWithKey` and `attrSetRemoveKeys`, and in `Nix.Eval.CAttrSet` and `Nix.Eval.CEnv` `cattrsetNew`, `cattrsetUnion`, `cattrsetRemoveKeys` and `cenvPushWith`.** `Nix.Eval.AllocSite` gives each site's name in the census (`envSiteName`, `setSiteName`) and its index in the C counts (`envSiteIndex`, `setSiteIndex`). `Nix.Eval.CStats` also has `countSites`, which turns counting by site on, `siteCounts`, which reads the `SiteCounts` (an `EnvSiteFigures` for each environment site, a `SetSiteFigures` for each set site, and the environments by `EnvSize`), `envSitesCounted` and `setSitesCounted`, and the census's `censusSites`. `attrSetUnionWith` and `pushWithScope`, which nothing called, are removed. (#539)+- **`Nix.Eval.EvalFormals.EFSet` and `EFNamedSet` take the function's `LambdaName` (`AnonymousLambda`, or `NamedLambda` holding the name's `Symbol`) as their first field, which `lambdaNameText`, `lambdaNameSymbol` and `lambdaNameFromSymbol` read.** `Nix.Eval.StartupSymbols.startupSymbols` lists the names an evaluation session interns first, and `Nix.Eval.Symbol.invalidSymbolId` is exported. `Nix.Eval.CLambda.clambdaNew` takes the function's name symbol after the binding's and refuses a formals type or count its closure cannot hold, `clambdaLambdaNameSym` reads the name, and `clambdaShape`, `clambdaShapeFormalsType`, `clambdaShapeAllowExtra` and `clambdaShapeFormalCount` pack and unpack the one word a closure keeps its formals type, ellipsis flag and formal count in. `Nix.Eval.Print.printSymbol` prints a name as upstream writes a symbol into a message. `Nix.Eval.runPureEval` reports an abort with its message alone, as `Nix.Eval.IO.runEvalIO` does, where it prefixed `evaluation aborted: `. (#540)+- **`MonadEval` has `MonadCData` (in the new `Nix.Eval.CData`) as a superclass, so an instance needs `liftCData`, which runs a `CData` action; `IO` is an instance.** The C accessors and allocators are `MonadCData` actions where they were pure: in `Nix.Eval.Types` the attribute set, list, environment and thunk functions (`attrSetLookup`, `attrSetFromMap`, `evaluated`, `readThunkValue`, `mkThunkBc` and the rest), `Nix.Eval.CList`'s `clistFromThunks`, `clistThunks`, `clistLen`, `clistIndex` and `clistDrop`, `Nix.Eval.SourcePos.lookupPos`, `Nix.Eval.Print.printValue` and `printAmbiguous`, `Nix.Eval.deferApply`, and `Nix.Builtins`'s `builtinEnv`, `builtinEnvWithScope`, `parseNixPath` and `searchPathRoots`; the `IO` accessors of the C binding modules (`Nix.Eval.CThunk`, `CAttrSet`, `CEnv`, `CLambda`, `CList`, `CCtxStr`, `CBytecode`), `Nix.Eval.Compile`'s `decodeBcFormals`, `decodeBcCaptureInfo` and `decodeBcBindings`, and `Nix.Eval.Symbol.symbolIntern` are too, so their `IO` callers are unchanged; each environment and set constructor keeps the site it takes first, and `buildCaptureEnv` takes one too. `attrSetMapWithKey` takes an action where it took a function, `Nix.Eval.CEnv.cenvEmpty` is a value, and `Nix.Eval` exports `compileSource`; `NIX_PATH`'s entries are built and interned as a session starts rather than when an entry is first used, and `Nix.Eval.IO.nixPathValue` reads `NIX_PATH`'s bytes. `Nix.Eval.Types` no longer exports the unused `lookupWithScopes`, nor `checkedCPtr`, which `Nix.Eval.CStatus` exports; it exports `compile`, `compileSource`, `readComputed`, `pushLazyWithScope`, `buildCaptureEnv`, `withScopeAt` and `resolveWithScopeAt`. `Eq` on `Thunk` and `AttrSet` compares identity, as on `Env` and `CList`, where it compared what they held, so two `NixValue`s holding equal sets in different C objects are unequal; `Show` on the four gives the address. `Nix.Eval.Types.thunkSameRef` is gone, since `==` on `Thunk` is what it was. `Nix.Eval.CData` exports `cdataIO`, which runs a binding's `IO` action as a `CData` one, `runCData`, which runs a `CData` action in `IO`, and the two reads outside a monad, `readImmutable` and `runCDataPure`; `Nix.Eval.Operator` exports `expectedFailure`, upstream's refusal of a value of the wrong type. (#552)+- **In `Nix.Eval.Types`, `newEnv`, which takes a site, a parent or none and the thunks for the slots, and `newScopeEnv`, which takes a site, a parent or none and a name table, replace `buildCSlots`, `newMinimalEnv`, `envFromSlots` and `newCEnv`.** In `Nix.Eval.CEnv`, `cenvNew` takes a site, a slot count and a parent, `cenvNewScoped` and `cenvWithOwner` are new, `cenvSlots` answers the environment's own slots, `cenvWithScopes` and `cenvWithCount` read the with-scopes an environment has of its own (`envWithScopesRaw` answers those it sees), and `cenvAllocSlots`, `cenvFromSlots` and `cenvNewMinimal` are removed. (#559)+- **`Nix.Eval.CStr` (new) binds the string arena: `cstrNew`, `cstrFromText`, `cstrBytes` and `cstrText` over a `CStrPtr`.** `Nix.Eval.Symbol` no longer exports `symbolInternBytes` or `symbolBytes`. The string and path functions of `Nix.Eval.CThunk` (`cthunkNewComputedStr`, `cthunkNewComputedPath`, `cthunkSetComputedStr`, `cthunkSetComputedPath`) and the text, hash, name and output functions of `Nix.Eval.CCtxStr` take and answer a `CStrPtr` where they took a symbol's `Word32`. `Nix.Eval.CBytecode` exports `cbcEmitString`, `cbcEmitText`, `cbcString`, `cbcStringBytes` and `cbcStringText` for the compiled code's strings, and `Nix.Eval.CStats.PerKind` has a `kindStrings` field and `CRoot` the roots `RootString` and `RootCtxStr`. `NixValue`'s string and path constructors are `VStrHeld` and `VPathHeld`, which carry the `HeldBytes` their bytes already are in C; `VStr` and `VPath` are bidirectional pattern synonyms bundled with `NixValue`, which match one whatever it holds and build one held in Haskell only, so code that matches and builds strings and paths is unchanged. `Nix.Eval.Types` exports `heldString`, `stringCell`, `pathCell` and `StringCell`. (#559)+- **`Nix.Push.PushConfig` gains `pcPartSize`, a `PartSize` (from `mkPartSize`, or `defaultPartSize` for 64 MiB), and `pcRetry`, a `Nix.Http.FetchRetryPolicy` (`defaultFetchRetryPolicy` for upstream's); a caller that builds a `PushConfig` sets both.** `splitParts` cuts a NAR into the parts of an upload, and `partSizeBytes` gives the bytes a part size allows. `Nix.Http.exceptionFailure` classifies a client failure as `fetchExceptionFailure` does, with the caller's message. (#560)+- **`NixValue`'s `VBuiltin` holds a `Builtin` from the new `Nix.Eval.Builtin`, one constructor per builtin, where it held the builtin's name; `builtinName` and `builtinNamed` convert, and `builtinIndex` and `builtinAtIndex` give the index the C data layer holds.** `VCompiledRegex` and `CompiledRegex` are removed. `Nix.Eval` exports `listedBuiltins`, the builtins `builtins` lists, where it exported `builtinNames` and `builtinRegistry`. `Nix.Eval.CPrimop` (new) binds the partial application object. `Nix.Eval.CThunk` loses `cthunkNewComputed` and `cthunkSetComputed`, which stored a StablePtr, and gains `cthunkPrimop`, a builtin's static cell, with `cthunkNewComputedPrimop`, `cthunkNewComputedPrimopApp`, `cthunkSetComputedPrimop`, `cthunkSetComputedPrimopApp` and `cthunkGetPrimop`. `Nix.Eval.Types` exports `PrimopCell` and `primopCell`. `Nix.Eval.CStats.PerKind` has a `kindPrimopApps` field. (#565)+- **`Nix.Eval.IO.EvalState` no longer exports its constructor or `esPolicy`, `esTimestamp`, `esSearchPaths` and `esImportCache`, which the session fixes as it starts, and `evalBaseEnv` gives the environment to evaluate a file in.** `Nix.Builtins.builtinEnvWithScope` takes the base environment to overlay in place of the policy, the timestamp and the search path. `Nix.Eval.CRoots` (new) registers roots, `Nix.Eval.CStats.CRoot` has `RootRegistered`, and `Nix.Eval.CThunk` exports `cthunkEmptyList`. (#567)+- **`Nix.Eval.IO` exports `SessionSettings`, `withEvalSession`, `nixPathSearchPath` and `evalSearchPath`, and no longer exports `newEvalState`: `newEvalStateWith :: Logger -> EvalPolicy -> [Thunk] -> SessionStore -> StoreDir -> FilePath -> IO EvalState` makes a state, with its base environment built over the policy and the search path, in the session already open.** `Nix.Eval.Arena` is no longer exposed, so `arenaInit` and `arenaDestroy` leave the public API; `CStatusError` and `arenaLive` are in `Nix.Eval.CStatus`. `ArenaNotInitialized` names `withEvalSession` in its message. (#574)+- **`Nix.Eval.Types.MonadEval`'s `forceThunk` takes the action that runs a `Pending`, a pending thunk's code in an environment (`PendingCode`) or its deferred application (`PendingApply`, `PendingApply2`), where it took one running code in an environment; `readPending` reads it from a cell, and `mkApplyThunk` and `mkApply2Thunk` make an application's cell.** `Nix.Eval.CBytecode` loses `reservedApply1`, `reservedApply2`, `appDirect` and `appDeferred`: the bytecode store no longer opens with reserved instructions. `Nix.Eval.CThunk` gains `cthunkNewApply1`, `cthunkNewApply2`, `cthunkPendingForm`, `cthunkApplyCell` and `noCode`, the index of no instruction, which `cthunkGetBcIdx` answers for an application and `cthunkNewBc` must not be given; `Nix.Eval.CStats.PerKind` has a `kindApps` field. (#575)+- **The C data layer's lifecycle is internal to the library, as an evaluation session owns it (`Nix.Eval.IO.withEvalSession`): `Nix.Eval.Symbol` no longer exports `symbolInit` and `symbolDestroy`, `Nix.Eval.CThunk` `cthunkInit` and `cthunkDestroy`, `Nix.Eval.CEnv` `cenvInit` and `cenvDestroy`, `Nix.Eval.CBytecode` `cbcInit` and `cbcDestroy`, and `Nix.Eval.CCtxStr`, `Nix.Eval.CLambda` and `Nix.Eval.CList` `cctxstrFreeAll`, `clambdaFreeAll` and `clistFreeAll`, any of which, called inside a session, freed the session's memory under it.** Names nothing outside their module uses are no longer exported: from `Nix.Eval.Types`, `marshalStringContext`, `unmarshalStringContext`, `unmarshalLambdaValue`, `withScopesForCapture` and `mkThunk`; from `Nix.Eval`, `BuiltinDef` and `ArgMode`; from `Nix.Eval.IO`, `EvalErrorKind`, `NixEvalError` and `NixAbortError`, which `runEvalIO` and `runEvalIOTraced` catch before a caller can meet them; from `Nix.Eval.Policy`, `modeInformation` and `forbiddenUriMessage`; from `Nix.Eval.CallDepth`, `maxCallDepthExceeded`; and from `Nix.Eval.CList`, `clistNew`, which made a list whose cells nothing exported could fill, `clistCount`, `clistGet`, `clistSet` and `clistToThunkList`: a list is built with `clistFromThunks` or `thunkListToCList` and read with `clistLen`, `clistIndex` and `clistThunks`. `Nix.Eval.Types.thunkToCPtr`, which was `unThunk`, is gone, and so are `Nix.Eval.CThunk.cthunkCount` and `cthunkGet`, with the count of thunks the arena kept for them. (#589)+- **`Nix.Eval.CThunk` no longer exports `cthunkGetStr`, `cthunkGetPath`, `cthunkGetList`, `cthunkGetAttrs`, `cthunkGetCtxStr` and `cthunkGetLambda`, each of which answered the payload `cthunkPayload` answers, which a caller casts.** `Nix.Eval.CEnv` renames `cenvLazyScope` to `cenvNameTable`, the set of names an environment binds. `cenvLookupResolved` takes `Word32` coordinates and raises `CInvariantViolated` where it answered `nullPtr`, and `Nix.Eval.Types.envLookupResolved` takes `Word32` coordinates. `Nix.Eval.CEnv`'s `cenvNew` and `cenvPushWith`, `Nix.Eval.CLambda.clambdaNew` and `Nix.Eval.CCtxStr.cctxstrNew` raise a `CStatusError` where they answered `nullPtr`. `Nix.Eval.CLambda` exports `FormalsName`, `FormalsSet` and `FormalsNamedSet`, and `Nix.Eval.CCtxStr` exports `ScePlain`, `SceDrvOutput` and `SceAllOutputs`, the tags their C structs hold. (#595)+- **`Nix.Eval.CEnv` removes `cenvRootScope` and `cenvAllocWithScopes`, which built a trimmed closure's copy of its scopes.** (#595)+- **`Nix.Expr.Types.Expr` loses `ESearchPath` and `Nix.Eval.CBytecode` loses `OpSearchPath`.** `Nix.Parser` no longer exports `parseNixFile`, which nothing called: a caller reads the file and passes its bytes to `parseNix`. (#597)+- **`Nix.Eval.Types.envLookup` takes the name it looks up as a `Symbol` where it took `Text`.** `Nix.Eval.Types` exports `attrSetLookupSymbol`, which looks a name up in a set by its `Symbol`. (#599)+- **`Nix.Eval.Types.buildCAttrSetKeys` takes a name table's names as `Symbol`s and `fillCAttrSetValues` takes a `Map Symbol Thunk`, where each took `Text` names.** `Nix.Eval.Types` exports `attrSetFromSymbolEntriesSizedFor`, which builds, from names already interned, a set upstream sizes before it knows what it holds, and `Nix.Eval.SourcePos` exports `printPos`, which writes a position as upstream's messages write one. (#604)+- **`Nix.Eval.Types.attrSetMapWithKey` passes each name to its action as a `Symbol` where it passed `Text`.** `MonadEval`'s `scopedImportFile` takes the scope as an `AttrSet` where it took a list of names and values, and `Nix.Builtins.builtinEnvWithScope` takes that set, which becomes the environment's name table, in place of the list. `Nix.Eval.Types` exports `attrSetFoldM`, which folds an action over a set's attributes in the order the set holds them, and `attrSetLookupSymbolEntry`, which looks an attribute up with its position by the `Symbol` of its name. (#605)+- **`Nix.Eval.Compile.decodeBcBindings` answers `BcBindings`, a binding list's `BcBindingCounts` with its count and offset, where it answered a list of `BcBinding`; `foldBcBindings` folds over the bindings, handing a binding tag the compiler never writes to the function it is given, and `foldBcInheritedNames` folds over an `inherit (from)`'s names.** `BcAttrKey` is gone: `BcNamed` holds a static name's symbol, the new `BcDynamic` holds the bytecode index a dynamic name is computed by, and `BcInheritFrom` holds `BcInheritedNames`, the names' count and offset, where it held a list. The capture info `decodeBcCaptureInfo` answers is a `BcCaptureInfo`, whose `BcCaptures` and `BcCapturesWithScopes` hold the `BcCapturedSlots` that `foldBcCapturedSlots` reads, where it was a `CaptureInfo`, and `Nix.Eval.Types.buildBcCaptureEnv` builds a closure's env from one. A binding list's bytecode starts with the two counts. (#608)+- **`Nix.Eval.EvalFormals.EvalFormal`'s `efName`, the argument name `EFName` holds and the `@` name `EFNamedSet` holds are each a `Symbol` where they were `Text`, so `Nix.Eval.Compile.decodeBcFormals` answers, and `Nix.Eval.Types.marshalLambda` stores, the symbols the bytecode and a closure hold, and `Nix.Eval.Compile.compileFormalsToEval` interns each name it compiles.** (#611)+- **`Nix.Eval.Types.cheapThunkBc` answers the value of a variable the resolver left to a name table, where it answered a thunk of its own, and `Nix.Eval.Types.frameThunkBc` makes a value in a frame that is being tied; `shareSlot` gives a slot of such a frame the cell another slot holds, handing a slot past the frame's, as `Nix.Eval.CEnv.cenvSlotCount` counts them, to the function it is given, `envSlotCells` reads a frame's cells, and `attrSetMemberSymbol` says whether a set binds a symbol, a name table's entry not filled yet included.** `Nix.Eval.EvalFormals.EvalFormal`'s `efDefault` is a `FormalDefault`, which tells a default that shares a slot's cell apart, where it was a `Maybe Word32`; `hasDefault` says whether there is one. `Nix.Eval.Compile.decodeBcFormals` takes the function a default kind the compiler never writes is handed to, and `formalDefaultWords` and `formalDefaultFromWords` write and read a default as the kind and code words a set pattern's entries hold. A binding list's words hold the count of its frame's shares and the shares after its two counts, which `Nix.Eval.Compile.decodeBcBindings` reads into a field of `BcBindings` and `foldBcShares` folds over, and `Nix.Eval.Compile.siblingShares` decides them. `Nix.Eval.CBytecode` exports `attrsPlain`, `attrsRec` and `attrsRecOverrides`, the flags an `OpAttrs` instruction holds, and `formalNoDefault`, `formalDefault` and `formalSharedDefault`, the kinds of a formal's default. Bytecode holding an `OpAttrs` flag or a default kind the compiler never writes, a share naming a slot past its frame or a name its frame does not bind, or shared defaults that form a cycle is corrupt bytecode, where any `OpAttrs` flag but 0 made a recursive set and any default kind but 0 made a default. (#616)+- **`SessionSettings` has a field `sessionRegions`, what the session runs regions for (`Nix.Eval.CRegion`): `RegionsCollect` the collector, `RegionsCensus` the census, which frees nothing, or `RegionsOff` neither.** `withRegions` runs an arena's setup and teardown with them running, `regionsRunning` reads what they run for, and `inRegion` runs a force in a region of its own. (#622)+- **`Nix.Eval.CAttrSet` has `cattrsetUpdate`, which makes the set `cattrsetUnion` makes and counts its entries as copied.** `SiteCounts` in `Nix.Eval.CStats` has a field `sitesUpdateCopied`, the count. (#637)+- **`Nix.Push.Directory` is new: `pushToDirectory` writes a closure to a directory cache as `DirectoryPush` describes it, `loadSecretKeyFile` reads a signing key, and `pushTarget` tells a server's URL from a directory's.** `Nix.Push.loadApiKeyFile` is renamed `loadKeyFile`, since it reads either kind of key, and `narInfoFileName` and `narDirSegment` are exported. (#639)+- **`Nix.Builder.attrsDelivery` takes the build directory and outputs where the builder sees them, and the `adFiles` of the `AttrsDelivery` it gives name each file in the build directory, where they held its path there.** `Nix.Builder` exports `BuildPlace`, a path as the builder is told of it and on disk, `BuildLayout`, a build's directory and outputs as places, and `builderInvocation`, which gives the `BuilderInvocation` a spawned builder starts with: the program and arguments, the environment and the ambient variables copied into it, the files written before it starts and the directory it starts in. (#646)+- **`Nix.Eval.Types` has `attrSetFindName`, which walks a set in order and stops at the first name a test holds for, and `attrSetAllPairs`, which walks two sets in lockstep and stops at the first pair an action fails.** `Nix.Eval.CAttrSet` drops `cattrsetKeys`, `cattrsetGetKey`, `cattrsetGetPos` and `cattrsetGetValue`: a set is walked in symbol order with the new `cattrsetWalk` and `cattrsetWalkNext`, a `CAttrSetStep` at a time, and read by name with the new `cattrsetFind`, which gives an entry's position and value and finds a value not yet written, and `cattrsetMember`. `cattrsetIndex` and `cattrsetSetValue` take a `FlatCAttrSet`, the name table `cattrsetFromNames` makes, whose set `flatCAttrSet` gives; `buildCAttrSetKeys` gives one and `fillCAttrSetValues` takes one. (#650)+- **`Nix.Eval.AttrPath.selectAttrPath` takes, first, the action the value each component selects from is passed through, `pure` for none.** `Nix.Eval.AutoCall` is new, with `autoCallFunction` and `AutoArgs`; `Nix.Eval` exports `findInSearchPath`, the lookup `builtins.findFile` makes; `Nix.Eval.IO` exports `resolveImportTarget` and `readImportTarget`, which find and read a file as `import` does; and `Nix.Environment` exports `argumentBytes`. (#644)+- **`Nix.Eval.Types.MonadEval` has a new method with no default, `realiseContext :: StringContext -> m (Either ContextRefusal ())`; `PureEval` answers `Right ()`, and an instance with no store answers the same.** Its `copyPathToStore` and `addFixedOutputFile` take a `PendingOrigin` first, `Fetched` from a fetcher and `Computed` from `builtins.path`. The new module `Nix.Eval.RealiseContext` holds `ContextRequest`, `SessionMode`, `PendingOrigin`, `Plan`, `planRealisation`, `firstInvalidPath`, `referenceClosure`, `ContextRefusal` and its messages, and `Nix.Eval.Context` gives a context's request (`contextRequest`). `Nix.Eval.IO.SessionSettings` gains `sessionStore`, a `SessionStore` that is `ReadOnlySession` over a `StoreQueries` and a build or `ReadWriteSession` over a `StoreOps`, and `newEvalStateWith` takes one after the search path. `Nix.Store.Ops` exports `StoreQueries` (`sqValidPaths`, `sqReferences`), `StoreOps` gains `soQueries`, and `localQueries` answers for the store in a directory without making or writing it. `Nix.Builder.BuildConfig` gains `bcSubstitution`, whose `RefuseSubstitution` refuses every substitution in upstream's read-only words (`Nix.Realise.noWriteAccessMessage`), and `Nix.Builder.realiseWithoutWriting` realises requests that way where nothing may be opened or written. `Nix.Store.DB` adds `openStoreDBReadOnly` and `storeTablesExist`. The read-only open needs `direct-sqlite >= 2.3.28`, the first release whose `open2` opens a database read-only, and wraps the handle in sqlite-simple's `Connection`, whose two fields arrived in sqlite-simple 0.4.19.0 (a minor release), so the library's bound on sqlite-simple rises from `>= 0.4` to `>= 0.4.19 && < 0.4.20`. `Nix.Store.Path` adds `isInStoreText`, upstream's `isInStore`. (#657)+- **`Nix.Eval.Policy.EvalPolicy` gains `epImportFromDerivation`, an `ImportFromDerivation` that is `RefuseImportFromDerivation`, `AllowImportFromDerivation` (in `unrestrictedPolicy`) or `TraceImportFromDerivation`.** `Nix.Eval.RealiseContext.planRealisation` takes one first, `Plan` gains `planWarning`, and `ContextRefusal` gains `ImportFromDerivationOff`. `Nix.Config.NixConfig` gains `ncAllowImportFromDerivation` and `ncTraceImportFromDerivation`, and `Nix.Eval.Types` exports `warnMessage`, upstream's `warn`. (#665)+- **`Nix.Eval.Types.MonadEval` has a new method with no default, `pinnedFetchHeld :: StorePath -> m Bool`, which `PureEval` answers `False`, and a read-only `SessionStore`, `ReadOnlySession` over a `StoreQueries` and a `StoreOps`, writes and adds only what a fetcher fetches.** `Nix.Store.Ops`'s local `soAddEvalObjects` adds nothing, and refuses nothing, for an evaluation that made nothing. `Nix.Eval.RealiseContext` exports `readableIn`. (#668)+- **`Nix.Builder.BuildConfig` gains `bcSandbox`, a `SandboxConfig` from the new `Nix.Builder.Sandbox`, which also holds the settings' types, the decision (`sandboxUse`, `buildNetwork`), the helper's plan (`sandboxPlan`, `renderPlan`), the chroot (`chrootSkeleton`) and the helper's reports (`parseStatus`, `helperOutcome`); `defaultBuildConfig` leaves the sandbox off (`defaultSandboxConfig`), since finding the helper takes IO.** The new `Nix.Builder.Sandbox.Spawn` probes the system (`sandboxAvailability`), runs the helper (`runHelper`) and makes the chroot (`withChroot`). `Nix.Config.NixConfig` gains `ncSandbox`, `ncSandboxFallback`, `ncSandboxPaths` (a `PathSetValue`), `ncSandboxBuildDir`, `ncSandboxDevShmSize`, `ncRequireDropSupplementaryGroups` and `ncSslCertFile`, so a record built without a default needs them. `Nix.Realise` exports `derivationBoolAttr`, upstream's `getBoolAttr`. `Nix.Builder.BuildLayout` also holds the `HOME` a builder is told of (`layoutHome`). The library's `directory` floor rises to 1.3.9, the first whose `removePathForcibly` works relative to each directory's descriptor and never follows a link, which removing a chroot relies on. (#673)+- **`Nix.Store.Ops.EvalObjects`' `eoSources` is a `Map StorePath Text`, each copy's store path with the path-value text of the tree it is restored from, and `Nix.Store.materializeEvalSources` takes that map.** `Nix.Eval.IO.EvalState`'s `esSourcePathCache` holds a `SourceCopy` per coerced path, and `sourceCopies` gives the map from it. (#676)+- **A caller that makes an attribute set, a lambda, a builtin's partial application or a string with context directly, through `Nix.Eval.CAttrSet`, `Nix.Eval.CLambda`, `Nix.Eval.CPrimop` or `Nix.Eval.CCtxStr`, does so inside `Nix.Eval.IO.withEvalSession`.** (#703)+- **`Nix.Profile.Manifest` reads and writes `manifest.json` and selects its elements as `profile remove` does, and `Nix.Profile.Generation` finds where profiles are from a `ProfileEnvironment`, resolves the default profile, names and lists generations, and changes a profile through `updateProfile`.** `Nix.Store.addSourceTree`, and the `StoreOps` field `soAddSourceTree`, add a tree given as its NAR as the content-addressed path its name and references make. `Nix.Config.NixConfig` gains `ncUseXdgBaseDirectories`, and `Nix.HostPath` exports `hostPathBytes`, the inverse of `hostPathFromBytes`. (#713)+- **`Nix.Develop.Shell` holds what a `develop` shell runs (`shellModeFor`, `shellArguments`, `bashProgram`) and the environment it starts with (`shellEnvironment` over `EnvironmentChanges`), refusing what upstream refuses in its words, and `developHost`, the host's temporary files, environment and exec, which is `Left` on Windows.** `Nix.Eval` exports `inputModuloHashes`, `Nix.Develop.Environment` exports `appendPath`, and `NixConfig` gains `ncBashPrompt`, `ncBashPromptPrefix` and `ncBashPromptSuffix`, which a record built without `defaultNixConfig` needs. (#715)+- **`Nix.Builder.Sandbox` gains macOS's sandbox: `SandboxBackend`, `hostSandboxBackend` and `backendFallback`; the macOS defaults (`darwinSandboxPaths`, `darwinImpureHostPrefixes`); a derivation's `DarwinOptions` (`darwinOptions`); the paths a profile names (`darwinPathsInSandbox`, `darwinPathTarget`, `profileFilter`), the profile itself (`darwinProfile`), the helper's macOS plan (`DarwinPlan`, `darwinParameters`, `renderDarwinPlan`) and its macOS steps (`DarwinStage`, `darwinSetupFailureMessage`).** `sandboxUse` takes the host's backend first, `helperOutcome` takes the backend's stage names and report of a failed step in place of a Linux plan, `unavailableMessage` takes the backend, and `SandboxConfig` has two new strict fields, `scAllowedImpureHostDeps` and `scViolationLog`. `Nix.Builder.Sandbox.Spawn`'s `sandboxAvailability` answers the backend with the helper, and `profileFilters` and `resolvedPath` are added. `Nix.Config.NixConfig` has two new strict fields, `ncAllowedImpureHostDeps` and `ncDarwinLogSandboxViolations`. `Nix.Realise` exports `derivationStringAttr` and `derivationStringsAttr`, upstream's `getStringAttr` and `getStringSetAttr`. `Nix.Json` exports `expectJson`, upstream's `ensureType`, which `Nix.Daemon.Protocol` used privately. (#725)+- **`Nix.Builder.BuildConfig` has a new strict field, `bcFailedBuilds :: FailedBuilds`, which `defaultBuildConfig` sets to `RemoveFailed`.** `Nix.Builder.BuildDir` exports `FailedBuilds`, `WorkDir`, `workDirIn` and `BuildEnding`, and its `withBuildDir` takes, after the first output, where in the directory the builder works, what a failed build keeps, and how the build's result says it ended. `Nix.Realise`'s `OutputDiffers` and `NotDeterministic` carry a new `DifferingRebuild`, `RebuildKept` or `RebuildDiscarded`, and `checkedOutputPath` names where a kept rebuild is. `Nix.Config.NixConfig` has a new strict field, `ncKeepFailed`. `Nix.Store` exports `moveOutput`, the move a build makes into the store. (#733)+- **Library code reports through a `Nix.Logger.Logger` it is given and never writes to standard error itself: a message (a wait on a lock, a collection's progress, a substitution's or a push's progress, a warning, a trace) and each line a builder writes, as the line completes and unfiltered.** `openStore` takes the logger the store's operations report through, which the handle holds as `stLogger`, and a build, a substitution, a collection and a push report through their store's. `withLocalStore`, `newEvalStateWith`, `readProfileEnvironment`, `updateProfile`, `ioRetryEffects`, `queryReferencesWith`, `queryNextOfferWith`, `realiseWithoutWriting`, `withBuildDir`, `clearLeftover`, `runBuiltinBuildenv`, `warnFallback`, `runHelper`, `withChroot`, `streamBuildLog`, Push's `logSkipped`, `logNar` and `logPushed`, and the lock functions of `Nix.Store.Lock` take one, whose busy messages are `Text`, as `Nix.Store.Lock.waitingForLockMessage` and `Nix.Store.GC.findingRootsMessage` are, where they were `String`. `SessionSettings` holds one as `sessionLogger`, and `BuildConfig` no longer has `bcBuildLog`. `handleLogger` writes each report to a handle, a build line filtered for the terminal by `filterLogLine` under `escapeFilterFor`, which move to `Nix.Logger` from `Nix.Builder.Log` with `EscapeFilter`. The command line's output is unchanged. (#741)+- **`Nix.Builder.Sandbox` gains the helper's Windows plan (`WindowsPlan`, `renderWindowsPlan`) and its Windows steps (`WindowsStage`, `windowsStageName`), and `ProbeStage` has `ProbePrivileges`, the probe of the privileges that starting a builder as another account takes.** `Nix.Store.Access` exports `sidText`, a `Sid`'s string form. (#743)+- **`Nix.Profile.Generation` reads a profile's generations with their times and its current one (`findGenerations`), plans a rollback and a wipe as values (`rollbackPlan`, `wipePlan`), carries them out (`switchGeneration`, `wipeHistory`), and reads `--to` and `--older-than` as upstream does (`readGenerationNumber`, `parseOlderThan`); `ProfileFailure` gains `NoSuchGeneration` and `NoOlderGeneration`.** `Nix.Profile.Manifest.manifestChanges` gives what changed from one manifest to the next, as a profile's history prints it, and `Nix.Store.Metadata.nodeModificationTime` reads a node's own modification time, a symlink's rather than its target's. (#744)+- **`Nix.CacheDirectory` holds what is shared by a push to a directory and a substitution from one: `cacheInfoFileName`, `cacheInfoText` and `readCacheInfo`, which returns a `CacheInfo` or a `CacheOpenFailure`.** `Nix.Substituter` no longer exports `sortCaches`, and `readBodyCapped` and `cappedBodySource` take an `IO ByteString` chunk source, the type http-client's `BodyReader` already was. (#745)+- **`Nix.Trust.FoundCode` carries the file's SHA-256 in lowercase base-16 (`fcSha256`), `TrustReport` the builder inputs that are one file, by their SHA-256 (`trBuilderBytes`), and `trustReportJson` and `trustReportJsonVersion` render the report as JSON; `Nix.Hash` exports `sha256LazyHex`.** (#757)+- **`EvalPolicy` has a field `epExperimentalFeatures` and `NixConfig` one `ncExperimentalFeatures`, each a `Nix.ExperimentalFeature.FeatureSet`; a record built with every field lists it.** `parseSriHash` and `parseNarHash` are exported by `Nix.Hash`. (#773)+- **`PathRegistration` has `prUltimate`, `prSignatures` and `prContentAddress`, and `PathInfo` has `piUltimate`, `piSignatures` and `piContentAddress`, with the new `Ultimate` type.** `Nix.Store.DB` has `queryReferrers`, `queryValidDerivers` and `queryPathFromHashPart`. `checkStatedAddress` answers the content address it held the tree to. `indirectRootRecordName` takes the bytes of the link's spelling. `Nix.HostPath` exports `absolutePath`, which `Nix.Profile.Generation` re-exports. `Nix.Daemon.Protocol` exports `parseSignature`, `renderSignature` and `renderContentAddress`, and `Nix.Derivation` exports `drvExtension`. (#749)+- **`Nix.Store.Import` imports a path from its NAR with what it claims of itself (`importNar`), refusing, in upstream's words, a path that must be signed and is neither signed by a key given nor content-addressed, a NAR whose hash or size is not the claim's, a tree that does not reproduce the stated content address, an address that does not make the path, and a derivation whose outputs are not the paths its inputs make (`checkDerivationOutputs`); and adds a text as a client adds a `.drv` (`addTextToStore`).** The NAR arrives from a chunk source that ends where the archive ends. `collectGarbage` takes extra roots, kept alive as upstream's temporary roots are, and `deleteSpecificPaths` deletes named paths as upstream's collector deletes them: each with the paths that reference it, all named, referrers first (`referrersFirst`), stopping at the first that stays alive with upstream's refusal. `Nix.Substituter` exports `checkContentAddress`, `Nix.Store.Upstream` exports `upstreamStateDir`, and `Nix.Derivation` exports `fixedOutputModulo` and `inputAddressedModulo`, the modulo-hash rules the evaluator and the store share. (#756)+- **The new `Nix.Builder.BuildUser` decides whom builds run as (`buildUsersFor`, `defaultBuildUsersGroup`, `userPoolDir`), chooses a member over a capability record of the user database (`acquireBuildUser`, `UserDatabase`, `Member`), holds one for a build (`withBuildUser`, which alone makes a `BuildUser`, and only in a process that runs as root), kills a member's processes (`killBuildUser`, which the C shim refuses for a caller that is not root) and runs a builder as one (`runAsBuildUser`), and answers whether a daemon is to refuse a peer for its primary group (`peerInBuildUsersGroup`), which `Nix.Daemon.Auth` asks.** `BuildConfig` gains `bcBuildUsers`, so a record built without a default needs it; `defaultBuildConfig` builds as the user nova-nix runs as. `Nix.Config.NixConfig` gains `ncBuildUsersGroup`. `Nix.Store.Metadata.foreignOwnedNode` takes whom the output belongs to (`OutputOwner`), and `ownedByAnother` tests an output's root. In `Nix.Builder.Sandbox`, `PlanInputs` and `SandboxPlan` carry the ids the builder runs as (`BuilderIds`), `DarwinPlan` the build user, `darwinParameters` the build's temporary directory, and the chroot's store directory is a `SkeletonStoreDir`; the plan's format is version 5, which a helper of an earlier release refuses. `Nix.Builder.Sandbox` also exports `setupContext` and `errnoSuffix`, and `Nix.Builder.Sandbox.Spawn.withChroot` takes the build users' group. (#770)+- **`Nix.Eval.Context.firstContextEncoded` is replaced by `firstContextDisplayed`, which names a context's first element as upstream 2.34.0 and later display it.** (#776)+- **`Nix.Store.Access` gains `StoreAccounts`, the account that keeps the store and the build accounts' group where there is one, which `accessSddl`, `securityDistrust` and `descriptorDistrust` now take in place of a `Sid`, the last two with the `DirAccess` of the directory checked; `StateAccess`, the state directory's access, which `StoreAccess` no longer stands for; `validPathSddl`, a registered path's security descriptor for a node of a `ValidNode` kind, a directory's entries passed down and a file's or a link's with no inheritance flags, which Windows keeps on no such node; and `withValidPathAccess`, the step `Nix.Store.canonicalizeMetadata` takes for each node.** `AllowEntry` carries the entry's flags. (#758)+- **`ConfigLocations` has a field `clNixConfigHome`, `NIX_CONFIG_HOME`'s bytes when it is set; a record built with every field lists it.** (#775)+- **`Nix.Store.sinkNarStream` takes an `ArchiveEnd` first: `AtEndOfInput` for the archive that ends its input, as it always read one, and `AtRootClose` for one that stops at its root node's close, leaving the rest of the input unread.** Either way the digest and size are of the bytes the parser consumed. `Nix.Store.Import.importNar` reads to the root node's close, as upstream's daemon reads an imported NAR, and pulls no chunk after it, leaving the rest of its source to the caller. (#761)+- **`Nix.Daemon.Listen` listens on a socket and serves each admitted client on its own thread (`openListener`, `serveListener`), `Nix.Daemon.Auth` decides admission over a user database it is given (`admitPeer`), and `Nix.Daemon.LocalStore` serves the local store to each connection (`serveLocal`).** `NixConfig` has `ncTrustedUsers`, `ncAllowedUsers` and `ncTrustedSubstituters`, and `Nix.Store.GC` exports `addIndirectRoot`. The library depends on `network`. (#772)+- **`Nix.Http.FetchRetryPolicy`'s `frpAttempts` and the retry number `Nix.Http.retryDelayMs` takes are `Word32` where they were `Int`, and `Nix.Config.NixConfig` has a new strict field, `ncDownloadAttempts :: Word32`, which a record built with the constructor needs.** `Nix.Http` exports `defaultDownloadAttempts`, upstream's default number of attempts, and `fileUrlFailure`, the failure of a `file://` URL a fetch cannot read; `Nix.Eval.Policy` exports `fileUrlPath`, the path a `file://` URL names; and `Nix.Store.Path` exports `storeDirDrive`, the drive a store directory is on. (#782)+- **A `Nix.Logger.Logger`'s messages have a level (`logAt`, with `LevelWarn` and `LevelInfo`), and a build, a check and a substitution are activities of it (`withActivity`, `ActivityStart`), whose builders' lines are the activity's, so a daemon can pass each on to its client as upstream's daemon passes on its logger's calls.** `logMessage` reports at the info level, and `plainLogger` makes a logger from a message sink and a build-line sink. The command line writes what it wrote before. (#780)+- **`Nix.Realise.realiseEach` realises several requests and says how each ended (`RequestOutcome`), or the failure that ended the call, and `planMissing` works out what realising some paths would take (`Wanted`, `MissingPaths`) over the queries it is given (`MissingEffects`).** `Nix.Builder` exports `buildRequestsEach`, `planMissingPaths`, `substitutablePaths` and `readDrvFromStore`, `Nix.Substituter` exports `substituteSizes`, and `Nix.Daemon.Ops` exports `logVerbosity` and `storeActivity`. `Nix.Daemon.LocalStore.newServedStore` takes the machine's defaults. `Nix.Realise.RealiseEffects.reBuild` answers a `FailedBuild`, a builder that stopped or a fixed output refused, and `RealiseFailure` has `FixedOutputRejected` for the second; `Nix.Builder.BuildStop` has `FixedOutputRefused`, which exits as any other stop does, and `stopReported` gives any stop's message and exit code. (#780)+- **`Nix.Store.Import` takes a NAR and a dump a chunk at a time: `admitNar`, `beginNarImport`, `feedNarImport`, `endNarImport` and `abandonNarImport` import a NAR, and `beginDumpAdd`, `feedDumpAdd`, `endDumpAdd`, `endedDumpPath`, `placeDump` and `abandonDumpAdd` add a dump as the path its content address makes.** `importNar` is built on them, so it unpacks into a staging directory and moves the tree to its path under the lock, and refuses a reference that is not valid with upstream's message; `replacePath` is exposed for testing. `Nix.Store.DB`'s `PathRegistration` states when its path is registered (`prRegistrationTime`, a `RegistrationTime`), and `statedRegistrationTime` reads a time a path's info states as upstream does. `Nix.Store` feeds a NAR to a sink a chunk at a time (`NarFeed`, `NarFed`, `startNarFeed`, `feedNar`, `endNar`), which `sinkNarStream` now drives, and closes an unpack without making its links (`closeNarUnpack`, `NarLinks`), so its tree can be moved and its links made where it stays (`moveNarUnpack`). `Nix.Key` reads a public key as upstream does (`parsePublicKey`, refused with `PublicKeyNotValid`), and `Nix.Daemon.Protocol` exports `grammarText`. (#799)+- **`NixConfig` has `ncRequireSigs` and `ncSecretKeyFiles`, and `CacheConfig` carries them as `ccRequireSigs` (a `RequireSigs`) and `ccSecretKeyFiles`.** `Nix.Substituter.cacheRequirement` reads what a cache's narinfos are held to, and `judgeNarInfo` takes it and answers, beside its verdict, the lines it warns of at the error level; a narinfo no trusted key signed is `NarInfoUnsigned`, warned of with `unsignedWarning`, a trust check that cannot be made is `NarInfoTrustFailed`, and `verifySigs` takes the keys and answers a `Bool`, where it took a `CacheConfig` and answered `Either Text ()`. `Nix.Key` gathers the keys a store trusts (`trustedKeys`, `verifyingKey`) and words a key's refusal (`keyRefusalReason`). `Nix.Logger.Level` has `LevelError`. `Nix.Store` says what a path copied in must be signed by (`SignatureRequirement`) and what a content address makes of a path (`addressMakesPath`, `AddressedPath`, `fixedReferencesRefusal`), and words upstream's warning of one that makes another (`notContentAddressed`) and its refusal to register the path (`addressRegistrable`). (#800)+- **`Nix.Daemon.Pipe`, built on Windows alone, makes the daemon's pipe and its instances (`listenPipe`, `nextInstance`, `awaitClient`), reads a client's account (`clientAccount`), connects a client (`connectPipe`), says whether a pipe is there without connecting to it (`pipePresent`), gives the owner a daemon's pipe has (`PipeOwner`, `processPipeOwner`, `pipeOwnerOf`) and its descriptor (`pipeSddl`, `clientPipeAccess`, `daemonPipeAccess`), and resolves accounts (`systemAccounts`); each end's connection is a `Nix.Daemon.Connection.Transport`.** `Nix.Daemon.Auth` admits a Windows account by SID (`admitAccount`, over an `AccountDatabase` that resolves names of an `AccountKind` and computes an account's groups, given an `AccountPeer`), says which pipe owners a client trusts (`trustsPipeOwner`), and `acceptedMessage` takes the peer's process. `Nix.Store.Access` exports the SIDs of SYSTEM and Administrators and derives a service's SID from its name as Windows does (`serviceSid`, `novaNixServiceSid`). The library links `authz` on Windows. (#803)+- **The new `Nix.Daemon.StoreChoice` reads a store reference (`parseStoreTarget`, `storeReference`) and chooses whether a command opens the store or goes through a daemon (`chooseStore`, over a `StoreProbe`).** `Nix.Daemon.Dial.addressPresence` says whether anything is at a daemon's address, `Nix.Store.Access.probeStoreWriting` and `StoreWriting` whether a process can keep a store's state directory, `Nix.Daemon.StoreChoice.storeOverride` and `StoreFlag` what a daemon is told of the `store` setting, `NixConfig` has `ncStore`, and `AssignedSettings` and `HowAssigned` are semigroups, so the record of a command line's settings joins the record of the files'. (#810)+- **`Nix.Push.Source` is new and holds `PushSource`, `PushedPath` and `localPushSource`, which `Nix.Push` does not re-export.** A `PushSource` gives `psReferences`, the only record `computeClosure` asks, and `psPathInfo`, which `preparePath` asks for a path it sends, so a damaged row of a path the cache already holds does not fail a push. `computeClosure`, `preparePath`, `pushPaths` and `Nix.Push.Directory.pushToDirectory` take a `PushSource` in place of a `Store`, and `checkRecordedNarHash` takes a `PushedPath`. `Nix.Trust.Fetch` is new (`FixedOutputStore`, `fetchAndScan`), and `Nix.Daemon.ClientStore` has `withDaemonPushSource` and `withDaemonFixedOutputs`. (#815)+- **`MonadEval` has the methods `fetchUrlBytes` and `fetchArchiveToStore`, so an instance defines them.** `Nix.Http` exports `downloadUrlWith`, the request `builtin:fetchurl` and the fetchers share. The new modules `Nix.Fetch.Tar`, `Nix.Fetch.Tree`, `Nix.Fetch.Archive`, `Nix.Fetch.Download` and `Nix.Compression.Stream` hold the tar reader, fetched trees and their NARs, the tar sink, the downloads, and the decoders. (#816)+- **The new module `Nix.Store.Upstream`, which `Nix.Store` re-exports, holds `upstreamDatabasePath`, the database upstream would keep for a store directory, when upstream keeps stores in a directory of that name, and `collectGarbage` and `deleteStorePathRaw` return `Left` for a store with one.** (#442)+- **`Nix.Store.Upstream` also holds `upstreamManagedRefusal`, which gives the reason an operation is refused for a store directory upstream Nix's database may also manage, worded for what the operation would do to upstream's paths (`UpstreamHazard`).** For such a store, before they write anything, `Nix.Builder.buildDerivation` and `buildWithDeps` return `BuildFailure`, and `checkDerivation` returns `Left`. `Nix.Substituter.unpackAndVerify` and `fetchSubstituteWith` return `SubstError`, so `Nix.Builder.substitutePaths` returns `NotFetched`, each path `DeliveryFailed`. `Nix.Store.materializeEvalSources` throws an `IOException`, and the `Nix.Eval.IO` evaluator's store writes (`writeToStore`, `copyPathToStore`, `addSourceNar`, `addFixedOutputFile`) fail the evaluation with an error `builtins.tryEval` does not catch. (#452)+- **The new module `Nix.Trust` classifies the fixed-output derivations of a `DepGraph` from the graph and from content facts it is given, and renders the report; `Nix.Trust.Scan` reads a fetched output's bytes for those facts.** `Nix.Builder` adds `substituteFromCaches :: BuildConfig -> Store -> [StorePath] -> IO ClosureOutcome`, which substitutes paths from the caches a build uses, each after the paths it references, and builds nothing. (#458)+- **`Nix.Hash` exports the decoder, `base64ToBytes :: Text -> Maybe ByteString`.** (#469)+- **`Nix.Push` exports `preparePath`, the NAR and the narinfo a push uploads for one store path.** (#473)+- **`Nix.Eval` exports `deepForce :: MonadEval m => NixValue -> m ()`, the deep force behind `builtins.deepSeq`, which `nova-nix eval --strict` now runs too.** (#488)+- **`Nix.Substituter` exports `narStreamFailure`, the retry class of a streamed NAR's failure, and `withXzAttempt`, which runs a consumer over an xz-decompressed chunk source and ends the attempt with the class of a decoder failure.** (#501)+- **`Nix.Store.Metadata` exports `isPlainFile`, whether a node is a regular file its owner may not execute.** (#501)+- **`Nix.Eval.CStats` takes a census and renders it: `takeCensus :: [CRoot] -> IO (Either CStatusError Census)`, with the roots a value holds from `valueRoots :: NixValue -> [CRoot]`, and `renderCensus :: Census -> ByteString`.** (#531)+- **`Nix.Store.ExecBit` exports `serialiseIfReadable`, which answers `Nothing` for a tree that cannot be read into an archive.** (#561)+- **`Nix.Eval.Types` exports `attrSetFromSymbols` and `attrSetFromSymbolEntries`, which build a set from names already interned.** `Nix.Json` exports `parseJsonInto`, which hands each value it reads to a `JsonBuilder`, an object's members in document order with a repeated name each time it appears, as nlohmann's SAX interface does. (#564)+- **`Nix.Eval.Types` exports `emptyAttrSet`, the shared set.** `attrSetFromMap`, `attrSetFromEntries` and `attrSetRemoveKeys` give `emptyAttrSet` for an empty result, except a removal from a set with attributes, which makes a set of its own. `Nix.Eval.CAttrSet` exports `cattrsetEmpty`, and `cattrsetInsert` raises on a frozen set, the shared one among them. (#568)+- **`Nix.Eval.CEnv` exports `cenvResolveWith`, which resolves the entry at an index of a with-scopes array to the set its thunk evaluated to.** It is the one write into the array after its creation, which a census of regions records. (#617)+- **`Nix.Derivation` exports `fixedOutput :: Derivation -> Maybe DerivationOutput`, the one output of a fixed-output derivation.** (#642)+- **`Nix.Realise` exports `realiseRequests`, which realises several derivations in one call, each for the outputs a request asks of it, with one record of what is realised, as upstream's `Store::buildPaths` runs a goal for each request with one worker (entry-points.cc at 2.24.9, `Worker::buildPaths` there at 2.36.0).** Requests that name one derivation are realised as one request for every output any of them asks, as they share one goal upstream. Every request is assessed before any is realised, so one whose outputs are valid is realised first, and one whose derivation's attributes cannot be read or that asks for an output its derivation does not have stops the call before anything is substituted or built, as in upstream's first pass over its goals. The requests are realised and never checked, as import from derivation builds under upstream's `bmNormal` (`EvalState::realiseContext` in primops.cc); a check is of one derivation, through `realise`. The first failure stops the call, as upstream's does without `keep-going`. It answers a `RequestsFailure`: `FailedWith` a failure reported as it is, or `FailedLeaving` a request's failure with the requests it left unrealised, which `requestsFailureMessage` reports as upstream's `build of '<drv>', '<drv>' failed`; `requestsFailureStatus` gives the status the call exits with, the one failure's. (#647)+- **The new module `Nix.Store.Ops` gives the store a command works against as a record of its operations, `StoreOps`: adding what an evaluation wrote or named, an `EvalObjects` of its sources, written trees and derivations, references first (`soAddEvalObjects`); realising several derivations, each for the outputs a request names (`soBuild`); checking one derivation, every output of it, as `nova-nix build --check` does (`soCheck`); and rooting an out-link (`soAddOutLinkRoot`).** `withLocalStore` runs an action with the operations of the store in a `BuildConfig`'s `bcStoreDir`, which it opens at the first operation and closes once, when the action ends; an add, a build or a check in a store upstream Nix's database manages is refused before the store is opened, since opening it would make this store's database there. `withOpenedOnFirstUse` is the bracket it opens the store with. `nova-nix build` adds, builds or checks, and roots through these operations. `Nix.Builder` exports `buildRequests`, which reads the requested derivations and their inputs from the store and realises them through `Nix.Realise.realiseRequests`, `checkStored`, which reads one derivation from the store and checks it as `buildWithDeps` does under `BuildCheck`, and `BuildStop`, the message and status of a stopped build. `Nix.DependencyGraph` exports `buildDepGraphFrom`, the graph of several roots read as their inputs are. (#653)+- **`Nix.Eval.Operator` exports `evalUpdateChain`, which evaluates the operands of a chain of `//` and merges them as upstream's update queue does.** (#656)+- **The new module `Nix.Store.Access` creates a directory open to whom a `DirAccess` says (`StoreAccess`, `ParentAccess` or `OwnerAccess`, with `createDirectoryWith`) and a store's state directory with the store directory it is in and any missing parent (`createStateDirectory`), and gives the SDDL a directory is created with on Windows (`accessSddl`), for a `Sid` that `sidFromText` makes only from a SID's string form, `S-1-I-S...`, so no trustee can carry another entry into the DACL.** `Nix.Store.DB` exports `createStoreDirectories`, which `openStore` and `openStoreDB` create a store's directories with. (#659)+- **`Nix.Builder.BuildDir` exports `clearLeftover`, which removes what an earlier build left at a path or moves it aside.** (#673)+- **`Nix.Store` exports `useStoreFileMask`, which a program building through the library calls to give its builders upstream's mask, `replaceWithCopy` and `freshCopyPath`, and, for testing, `rewriteRegularFile`; `Nix.Store.Metadata` exports `writableByOthers` and `foreignOwnedNode`; and `Nix.Builder.BuildDir` exports `sandboxedBuildDir`, where a sandboxed build's own directory is.** `Nix.Store`'s `placeInStore` and `addToStore` move a path by a rename that fails, rather than copies, except across volumes. (#673)+- **`Nix.Store.CaseSensitive` exports `pathCaseHack`, the case-hack mode a read of path-value text runs under given the store volume's sensitivity.** `Nix.Eval.Policy` exports the walk of a path through its symlinks, `walkPath`, pure over path-value text with the read of a link as an argument, and its rules: `PathRules` and `hostPathRules`, `SymlinkResolution`, `LinkTarget` and `linkTarget`, `WalkStop`, `storeRootPrefix` and `windowsLinkTargetJoins`. (#676)+- **`Nix.Derivation` exports `inputAddressed`, which makes every output of a derivation input-addressed from the derivation's name and its inputs' modulo hashes and gives the `.drv` file it is written as, as upstream's `fillInOutputPaths` and `writeDerivation` do (derivations.cc), and `drvFile`, the `.drv` file of a derivation as it stands.** A `DrvFile` holds the derivation, its ATerm and its store path (`drvFileDerivation`, `drvFileATerm`, `drvFilePath`). `derivationStrict` fills in an input-addressed derivation through `inputAddressed`, and every drvPath and output path is the one it gave before. `Nix.Eval.Types.storePathOrThrow` unwraps the result of any construction that makes a store path, not only a store path itself. (#694)+- **The new modules `Nix.Daemon.Wire` and `Nix.Daemon.Protocol` read and write the worker protocol upstream's `nix-daemon` speaks, as upstream 2.35.4 reads and writes it at every protocol version its serialisers distinguish.** `Nix.Daemon.Wire` is the framing: 64-bit little-endian numbers, each refused above the largest value of the type upstream reads it into; strings padded with zeros to a multiple of eight, refused when the padding is not zeros; lists; and framed streams, read a chunk at a time. Its `Decoder` reads incrementally (`startDecoding`, `feedInput`), so a connection can hand it each read as it arrives. `Nix.Daemon.Protocol` holds the values the protocol carries and their serialisers: versions and features, the handshake's words and what a daemon tells its client after it, store paths, a path's info with its NAR hash, signatures and content address, derived paths, realisations, build results, a collection's action and paths, and the messages and errors a daemon sends while it works. Each reader refuses what upstream refuses, and each writer refuses what upstream's does, in upstream's words, but for a malformed hash, which is worded as `Nix.Hash` words it, after 2.24.9. Realisations and a build's outputs follow 2.35's `realisation-with-path-not-hash` feature where both sides list it, and the older JSON form of a build's outputs where they do not, as 2.35.4 does. `Nix.Hash` exports `parseAnyHash`, `parseHashAlgo`, `digestByLength`, `sriDigest` and `unknownHashAlgo`, which `Nix.Eval` held privately, and the library depends on `binary`. (#695)+- **`Nix.Profile.Tree` builds the tree as a value over a `TreeReader`, the capability that reads the packages, so it runs over any store, an in-memory one included: `buildProfile`, `storeTreeReader` for a store on disk, and `writeTree`.** `Nix.Builder.Buildenv` exports the builtin's name, `runBuiltinBuildenv`, and `parseDerivations`, which reads the `derivations` attribute. (#696)+- **`Nix.Develop.Environment` holds the build environment upstream's `nix develop` captures and the scripts made from it, as upstream's `BuildEnvironment`, `makeRcScript` and `CmdDevelop::run` make them (develop.cc at 2.35.4).** `parseBuildEnvironment` reads the JSON `get-env.sh` writes, dropping a variable of a kind it does not know as upstream does, and `buildEnvironmentJson` writes it back. `environmentScript` gives the script `print-dev-env` prints, each output's path moved under the working directory, with the structured attributes' files to write; `renderRcfile` wraps it for an interactive shell, `--command` or `--phase`. `ignoreVars` and `escapeShellArgAlways` are upstream's. Where upstream asserts that a variable is set, or replaces a path forever because the text replacing it holds it, these return an error. (#702)+- **`Nix.Develop.Capture` makes the derivation upstream's `nix develop` builds to capture a target's build environment (`getDerivationEnvironment`, develop.cc at 2.35.4).** `captureDerivation` refuses a builder whose base name is not `bash`, makes upstream's `get-env.sh` the builder's one argument and an input source, removes the checks on what the outputs refer to (under structured attributes, `outputChecks`, with `__json` written again as nlohmann's `dump()` writes it), names the capture `NAME-env`, and fills its outputs in input-addressed, so a fixed-output target's capture is input-addressed too. `getEnvScriptPath` gives the script's store path, `/nix/store/hyhh9rhzxhzmfspllmpf75xzkzns109r-get-env.sh`, since upstream stores the file after a newline its build puts in front of it; the file ships as `data/develop/get-env.sh`, upstream's 2.35.4 copy under its LGPL-2.1 license. `environmentOutput` picks the output the environment is read from, the first in name order that is a regular file of at least one byte. (#705)+- **`Nix.Hash` exports `makeSourcePath`, the path of a tree added by the SHA-256 of its NAR together with the store paths it references, as upstream's `makeFixedOutputPath` makes one under `NixArchive` and SHA-256: the type it hashes is `source` followed by each reference after a colon, in path order (`makeType`, store-dir-config.cc at 2.35.4), which upstream's own fixture for such a path pins.** `makeFixedOutputPath` gives that path with no references for a NAR SHA-256 hash, as it did. (#707)+- **`Nix.Hash` exports `ModuloHash`, `moduloHashInit`, `moduloHashUpdate` and `moduloHashFinalize`, a digest modulo a hash part; `Nix.Daemon.Protocol` exports `parseContentAddress`; and `Nix.Substituter` exports `checkStatedAddress`.** (#738)+- **`Nix.Derivation` exports `impureOutputHash`.** (#738)+- **The local store's `soAddSourceTree` (`Nix.Store.Ops.withLocalStore`) refuses a store directory that upstream Nix's database also manages before it opens the store, as its other adds, builds and checks do, so it no longer makes this store's database there on the way to the refusal.** `nova-nix profile add` and `profile remove`, which add a generation's tree through it, refuse such a store before evaluating anything and are unchanged. (#739)+- **`Nix.Eval.Context` exports `inUpstreamOrder`, a context's elements in the order upstream keeps them, and `encodedElement`, an element in the encoding upstream prints.** (#736)+- **On Windows `Nix.Store.Access.createStateDirectory`, and through it `Nix.Store.DB.createStoreDirectories`, `openStoreDB` and `Nix.Store.openStore`, refuse a store with a directory another account owns or can change with a `userError`, `Nix.Store.DB.openStoreDBReadOnly` does through the new `checkStateDirectory`, and the new `createStoreDirectory` makes and checks a store's directory as they do, less the state directory, for an evaluation's write.** `Nix.Store.Access` gives the rule as pure functions that work on every platform: `storeDirectories` and `stateDirectories` list the directories checked, `parseSecurityDescriptor` reads a self-relative security descriptor into a `DirSecurity` of `AclEntry` values, `securityDistrust` and `descriptorDistrust` give the `Distrust` that refuses one, and `distrustMessage` words the refusal. `Sid` equality compares the accounts two SIDs name, so the hexadecimal digits of a wide authority may differ in case. (#742)+- **`Nix.DrvName` (new) holds the split, `drvNameDash`, which takes the `uncons` of the string it reads, so it counts bytes for `builtins.parseDrvName` and characters for `Nix.Profile.Manifest.drvNameName`.** (#750)+- **The new modules `Nix.Flake.Ref`, `Nix.Fetch.Input` and `Nix.Fetch.Attrs` read and write flake references, fetcher inputs and their attributes as upstream 2.36.0 does.** (#773)+- **The new modules `Nix.Daemon.Ops` and `Nix.Daemon.Connection` are a daemon's side of upstream's worker protocol, over a store and a transport they are given.** `Nix.Daemon.Connection.serveConnection` runs one connection: upstream's handshake, from 1.18, then each operation the client asks, until its input ends. `Nix.Daemon.Ops` holds what each operation reads before its work begins (`getRequest`), what a client the daemon does not trust may not ask (`authorize`), what a client's settings change for its connection (`applyClientSettings`), and the store the operations run over (`DaemonStore`), a record of upstream's store calls in the protocol's own terms. The operations are those upstream's clients send to build, substitute, copy, query and collect through a daemon; another code is refused as upstream refuses one it does not know, and AddToStore before protocol 1.25 and AddToStoreNar before 1.23, whose uploads are not framed, are refused as their requests begin. A failure before an operation's work closes the connection and one during it is sent and the connection goes on, where upstream's daemon does each; what the store reports as it works reaches the client as upstream's daemon forwards its logger's calls; and an upload's frames are read past after its store stops, as upstream drains them, so the next operation starts at its first byte. Upstream's messages are kept without the colours its formatter adds. `Nix.Daemon.Ops` also writes each request and a client's settings as upstream's client writes them (`putRequest`, `putClientSettings`, `putUploadPathInfo`), refusing in upstream's words a request the agreed version cannot carry, and names the versions the requests change at. `Nix.Daemon.Protocol` reads and writes the replies the operations give (`Missing`, `GCResult`, a derivation's outputs, the roots, build results with the paths they answer) and names the build and substitution activities and the two log-line results. `Nix.Daemon.Wire.DecodeFailed` carries the input after the bytes a refused read took, and `Nix.Daemon.Protocol` exports `parseContentAddressMethod`, `featureDeleteDeadSpecificReferrers` and `defaultExitStatus`. (#755)+- **`Nix.Key` reads, makes and spells signing keys, and `Nix.Daemon.Protocol` reads and spells signatures through `Nix.Key`'s `parseColonBase64` and `renderColonBase64`, so a byte outside base64 that is not ASCII in a signature the daemon receives is named as the character of its value, where it was named as the UTF-8 character it began.** (#765)+- **The new `Nix.Signals.interruptOnTermination` has SIGTERM and SIGHUP throw `UserInterrupt` to the calling thread, as the runtime does at SIGINT, and does nothing on Windows.** (#778)+- **`Nix.Builder.Settings` gives the build configuration a store's settings give (`settingsBuildConfig`): the caches, fallback, the `allowSubstitutes` setting, how many times a download is tried (`settingsFetchRetry`, from `download-attempts`), cores, the sandbox, the build users and what a failed build keeps, each with upstream's default where no setting gives it.** The defaults only the machine can tell (`MachineDefaults`: the cores, the sandbox helper and bundled shell, whether the process is root, the user pool's directory, the certificate bundle) are found once (`machineDefaults`), so a daemon gives each operation the configuration its connection's settings give without looking again. The command line applies its flags to the settings first, as upstream's flags set settings, and builds as it did. (#780)+- **`Nix.Builder.Unpack.envOmit` is new.** (#762)+- **The new `Nix.Daemon.Client` is a client of a daemon that speaks upstream's worker protocol, as upstream's remote store is one, over a transport it is given (`Nix.Daemon.Connection.Transport`).** `runClient` makes upstream's client handshake, offering the newest version and the features the codec carries (`offeredVersion`) and refusing a daemon older than 1.18, then runs a session's operations (`ClientT`): `setOptions`, the queries (`isValidPath`, `queryValidPaths`, `querySubstitutablePaths`, `queryReferrers`, `queryValidDerivers`, `queryDerivationOutputMap`, `queryAllValidPaths`, `queryPathInfo`, `queryMissing`), the framed uploads `addToStore` and `addToStoreNar`, `buildPaths`, `buildPathsWithResults`, `ensurePath`, `addTempRoot` and `addIndirectRoot`. What the daemon says while it works goes to a report the caller gives. A daemon's error is a `DaemonFailed` that `attempt` catches, the session going on; a request the agreed version does not carry is not sent (`NotSent`), so a daemon older than 1.19 is not asked `queryMissing`, one older than 1.22 `queryDerivationOutputMap` and one older than 1.34 `buildPathsWithResults`, whose answers upstream's client works out itself; a broken connection is a `ConnectionLost`. Requests are written as `Nix.Daemon.Ops.putRequest` writes them, so below 1.27 `queryValidPaths` sends no substitute flag, as upstream's client sends none. (#781)+- **`Nix.Store` exports `checkNarClaim`, which holds an archive's hash and then its size to what a path's info claims, and `narHashMismatch` and `narSizeMismatch`, upstream's refusal of each.** (#768)+- **The new `Nix.Daemon.ClientStore` gives a command's store operations (`StoreOps`) through a daemon, as upstream's remote store does for its commands.** `withDaemonStore` runs an action over a connection made at the first operation that asks the daemon something and closed when the action ends, so a command that asks nothing of the store never connects. After the handshake the client sends its settings as upstream's remote store does, unless the daemon grants `disable-set-options`, which `Nix.Daemon.Client.offeredVersion` offers as upstream's client does. `clientSettings` builds them from the configuration: keep-failed, fallback and cores as set, cores 0 where nothing sets them as upstream's client sends its own default, and upstream's defaults for the rest. A daemon takes a client's cores as upstream's does, so a client's 0 gives a build the default count of the machine it runs on, whatever the daemon's own `cores` says. Queries ask the daemon which paths are valid and what a path references. An evaluation's copies of paths and its derivations are sent to the daemon as upstream's client sends them, each derivation after every source and derivation it refers to, because a daemon needs each reference valid first, and the path the daemon answers must be the one evaluation computed. Each copy and derivation is given a temporary root before the daemon is asked which it holds, and so is a fetched path evaluation adopts, as upstream roots a path before it skips sending it, so a collection between the question and the use cannot remove what the client relies on. A daemon's refusal fails the operation with its message and the connection goes on. A connection that cannot be opened, in its connecting, its handshake or its settings, fails the operation that tried, and every operation after fails with upstream's `opening a connection to remote store '...' previously failed` without trying again. Only a failed handshake is worded `cannot open connection to remote store '...': ...`, as upstream words one; an error from making the connection, or from the settings, is reported as it is. A store is named `daemon` at the default socket and otherwise `unix://` and the path with each segment percent-encoded as upstream's `encodeUrlPath` encodes it (`Nix.Fetch.Url.encodeUrlPath` is exported for it). A connection that breaks, or whose upload fails reading a local file, is closed and the next operation opens another, which holds none of the earlier one's temporary roots. A source an add cannot read (a file or directory the process may not open, which the archive walk reports as `NovaCache.NAR.NarWalkError`) fails the add with the access's words, on a store over a daemon and on the local store alike, where `soAddEvalObjects` answers `Left` as it does for any refusal. A framed upload (`addToStore` and `addToStoreNar`, which run in `ClientT IO`) reads the daemon's messages on a thread of its own while it sends, so a daemon that answers each chunk with more output than the connection holds cannot stall it. A session that outlives one call is `openSession` and `continueSession` in `Nix.Daemon.Client`. `Nix.Daemon.Dial` connects to the daemon's Unix socket, or on Windows to its named pipe, and a refused connection to either is worded as upstream words it, with the address in double quotes. `soEvalWrites` lets a store take each tree evaluation writes as it is made (`builtins.toFile`, a fetcher's result, a copy of a path) where the store's directory cannot be written: it is handed an `EvalWrite`, a `TextWrite` (the only write that names references), a `FlatWrite` or a `NarWrite`, and answers whether it holds a path evaluation adopts. A read-only session hands over only what a fetcher fetched, and never adds what evaluation made. `Nix.Store.drvReferences` is exported. (#805)+- **A store through a daemon (`Nix.Daemon.ClientStore.withDaemonStore`) builds, checks and roots out-links, as upstream's remote store does.** `soBuild` asks the daemon to build each derivation's named outputs, and a request that names no output is not asked; `soCheck` asks it to build every output of a derivation again under the check mode. A build the daemon fails stops with the daemon's message and its status, which from protocol 1.26 on is 1 because the daemon does not send it, as upstream's client reads it; a connection that cannot be used stops it with the reason and status 1. `soAddOutLinkRoot` makes the link in the client, refusing a link inside the store before the daemon is asked anything and a file in its place once the daemon holds the path with a temporary root, as the local store refuses them, and records the link's absolute spelling with the daemon as an indirect root; `Nix.Store.GC.makeOutLinkRoot` does it over a `LinkRooting`, which says how a store holds the path while the link is made and records the link, and `addOutLinkRoot` is that over a local store, whose lease already holds collection off. A daemon on Windows records a link by its drive-qualified or share spelling, collapsed over the host's separators and roots, and refuses a link that is not absolute before any work begins, as it has no directory to take one from; a daemon on POSIX takes a relative link from `/`, as upstream's does. The store settings a source set are sent as overrides, each under its own name whichever alias or `extra-` spelling set it, spelled as `nix.conf` spells it, and none that was left at its default. Only the settings nova-nix's configuration reads can be sent, so a store setting it does not read (`builders` and `connect-timeout`, for example) is not, whatever a source says. `clientSettings` takes the `Nix.Config.AssignedSettings` that `Nix.Config.loadConfigAssigned` reports beside the configuration (`assignedSettings` reads them from assignments), which records for each setting whether a plain assignment replaced it or only `extra-` assignments added to it, and `storeSettingOverrides` writes them. A list is sent in full under its own name, as upstream's client sends it. The default of `substituters` and of `trusted-public-keys` is empty here and names cache.nixos.org and its key in upstream's client, which sends a daemon the default and then the entries added to it, so a list that only `extra-` assignments built is sent with those two defaults before its entries (`https://cache.nixos.org/` and `cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=`), none merged and none dropped, and so is one whose `extra-` assignments added nothing. A list a plain assignment replaced is sent as it resolved. A daemon at upstream's defaults then keeps cache.nixos.org, and an untrusted client's added cache that the daemon trusts passes its filter, which takes the plain `substituters` name from such a client. A trusted client of nova-nix's own daemon that only extends either list turns on cache.nixos.org and its key there, as upstream's client would, and one that is not trusted has cache.nixos.org dropped from its list with upstream's warning unless that daemon's `substituters` or `trusted-substituters` names it. A set of paths that keeps its default is sent as an `extra-` assignment of the paths a source added, and not at all when it added none, because its default (the sandbox shell the binary was built with, the system paths of macOS) is not held here and is the daemon's to apply. A setting upstream declares on some systems only is sent from those alone, as upstream's client has it there alone: `sandbox-dev-shm-size` from Linux, `sandbox-build-dir` from Linux and FreeBSD, `darwin-log-sandbox-violations` from macOS, and `require-drop-supplementary-groups` from every system but Windows. Upstream's client takes the settings the options message carries as fields (keep-failed, fallback and cores), `experimental-features` and `use-xdg-base-directories` out of its overrides and sends only its store library's and its file transfer's settings, so the evaluator's settings, `develop`'s prompt and the daemon command's `trusted-users` and `allowed-users` are not sent. What the daemon says while it works reaches the command's logger as the calls the local store makes for the same work: a message as a message at the error level, as upstream's client reports one, a build or a substitution as an activity of the logger that its builder's lines and its stop belong to, and a post-build hook's line as a message, through `Nix.Daemon.Client.Relay`. `Nix.Daemon.Ops.activityStart` reads an activity a daemon starts as the store's own, the inverse of `storeActivity`, and a build on a machine or a repair as a build. An activity a failed operation leaves open is stopped when the operation ends, before another operation on the same store starts. `Nix.Builder.Sandbox.renderSandboxMode` is the spelling `parseSandboxMode` reads back. (#807)+- **`Nix.Store.DB.openStoreDB` and `openStoreDBReadOnly`, and `Nix.Store.openStore` through the first, refuse a store whose paths all lie under another directory with a `userError`.** `Nix.Store.DB.foreignStoreDir` gives the directory a row was recorded under when it is not the one given, and `storeRowRange` gives the range of row text that lies under a store directory. (#818)++### CLI++- **`nova-nix --help` lists each flag under the commands that take it, and each nix.conf setting with what it does, printed from one reference of the CLI that `docs/cli.json` also renders.** The help named the command for some flags and not for others, so `--strict`, which `build` refuses, read as a flag of every command. Two entries said what the code does not do: `--trusted-key` was the key for the substituter, but a trusted key is checked against the signatures of every substituter, those nix.conf configures included; and `--pure-eval` left no search path, but the bundled `<nix/*>` expressions stay on it, as upstream still resolves `<nix/*>` from its built-in copy. `--expr` and `--cache`, which appeared only in the command lines, have entries of their own; `push` has a line for `PATH...` and one for `--all`, one of which it requires; the usage line is `nova-nix COMMAND [FLAG...]`, where it named `--nix-path` alone of the flags that may come before a command; the system nix.conf directory is given for both platforms; and the text wraps at 80 columns. The test suite checks the reference against the parser, that every command it lists for a flag accepts the flag and that a flag takes a value exactly when its entry names one, and runs each example that shows its output. (#413)+- **`nova-nix build --check` builds a derivation again beside its valid outputs and fails when one comes out different, as `nix-build --check` does.** A path that came from a binary cache was only ever trusted; a check holds it to a build. The rules are those of upstream's build mode `bmCheck` at 2.24.9. The mode covers the derivation the build was asked for and no other: its inputs are substituted or built as ever (`DerivationGoal::gaveUpOnSubstitution` gives each input's goal `bmNormal`), since the rebuild needs them and a path that was substituted never fetched them. An output that is not valid is substituted first, as under any mode, and a derivation still short of an output stops with upstream's `some outputs of '<drv>' are not valid, so checking is not possible`, before any input is looked at (`outputsSubstitutionTried`). The derivation itself is then built here and never substituted. Its builder writes each output to a scratch path while the valid one stays where it is, the scratch path's hash is rewritten to the output's own in what the builder wrote, so that an output holding its own path or a sibling's compares equal, and the NAR hash of the result is compared with the one the store recorded, which is all upstream compares (`registerOutputs`, local-derivation-goal.cc). The first output that differs stops the check with upstream's `derivation '<drv>' may not be deterministic: output "<path>" differs`, after nova-nix's own `build failed (exit 104):`, and the command exits with upstream's status for it, 104 (`Worker::failingExitStatus`), so a caller can tell it from a build that broke; every other failure still exits 1, where upstream's status for a failed builder is usually 100. Whatever the comparison finds, the rebuild registers nothing, the outputs it is compared with are as they were, and what it wrote is removed, unless `keep-failed` keeps the rebuild of an output that differs; the substitutions and builds before it add to the store as in any build. A fixed output is held to its declared hash first, and a reference cycle between the rebuilt outputs fails a check as it fails a build. A check that passes is logged as `[check]`. Five things differ from upstream. Its `run-diff-hook` and `diff-hook` settings, which run a program on the valid output and the rebuilt one before the check fails, are not implemented. It marks a path it has checked as ultimately trusted and signs it; nova-nix's check does neither. A check here wants every output of the derivation valid, where upstream's wants only the outputs the build asked for, which for `nix-build` is the one it prints. nova-nix checks as upstream does outside a Linux sandbox, through the scratch path and the rewrite, in its own Linux sandbox too: an output that holds its own path where a rewrite of the hash cannot reach it, compressed for one, differs under a check here, as it does under upstream's on macOS, and not under upstream's in a Linux sandbox, which builds at the output's own path inside a chroot. And a builder is handed its output under the directory its store's files are in, as before, where upstream builds a store kept outside its own directory only in a Linux chroot that shows it there: an output that records its whole path therefore checks equal here only against one built in a store kept in the same directory. (#425)+- **`nova-nix trust` reports what a derivation's closure relies on: its fixed-output derivations, those a build runs as builders and those holding prebuilt code, each file named with its kind, those not fully read, and the builders and sources the closure takes from outside itself.** Every closure bottoms out in fixed-output derivations, whose bytes a hash pins whatever fetches or builds them, but which of them are readable source and which are prebuilt code was not visible anywhere. The classification rests on facts, never on a name or a URL's suffix, which this repository's own recipes disprove: stage0-pe32's source archive also holds the `hex0-seed.exe` its chain starts from. One fact is in the graph: a fixed-output derivation runs as a builder when a derivation's builder is inside its output, or inside the tree a builtin such as `builtin:unpack`, which runs nothing from the closure, makes from it and any others. Each entry says whether a builtin fetched it or the closure built it, and names any other fixed-output derivation pinned to the same hash, as stage0-pe32's `hex0.exe`, built by running the seed, is pinned to the seed's. The other fact is in the bytes: prebuilt code found by its header, a PE image, an ELF file (an image or an object), a Mach-O file, a COFF object in the plain or the bigobj form, or an ar archive such as a static library, whose members are not read. The scan looks in a fetched file, in each file of a fetched tree, and in each file of a tar archive, plain or compressed with gzip, bzip2, xz or zstd, the format told by the bytes. An archive inside another is not opened, and a file in another archive format the scan knows, such as zip or an MSI installer, is reported as not read rather than as holding no prebuilt code. A fixed-output derivation that a builtin fetches with no input of its own is fetched first, or substituted, so that its bytes can be read; any other is only substituted, with the paths it references, from a cache that holds it, since making it would run its builder, so nixpkgs' `fetchurl` and `fetchFromGitHub`, which run `curl` or `git`, are read when a cache holds their outputs. Such a substitute is taken whatever the derivation's `allowSubstitutes` says, since the attribute chooses between building and substituting and trust builds none of these. A failed substitute of such an input stops the command, as upstream's substitution of a path fails when a substituter fails, whatever `fallback` says (`PathSubstitutionGoal::init` at 2.24.9), and a fetch that fails stops it too. nixpkgs' `meta.sourceProvenance` is not read: it is a maintainer's claim, made during evaluation and absent from the `.drv`. The report says what the closure relies on, not whether any of it is safe. (#458)+- **`--help` and `--version` are answered after every command, as they were after `build` and `trust`, and a run whose stdout has lost its reader, as `nova-nix --help | head -1`, reports nothing and ends with the status its work gives it.** `eval --help`, `push --help`, `store --help`, `store delete --help` and `store gc --help` failed with the parser's `unknown ... flag: --help` and status 1. A write to stdout after its reader had gone, such as the help's second line once `head -1` had read the first, failed with `error: <stdout>: hFlush: resource vanished (Broken pipe)` and status 1, and `store delete`, which prints each path as it deletes it, stopped after the first. Upstream's main thread blocks SIGPIPE (`startSignalHandlerThread`, libutil/unix/signals.cc at 2.24.9), so a write through `std::cout` to a pipe with no reader fails with EPIPE, which only sets the stream's error state: nix-instantiate writes its result that way (`processExpr` in nix-instantiate.cc), nothing is reported, and the command goes on to its own exit status. nova-nix now drops the rest of a write to stdout once its reader has gone, and still reports any other failure of a write. (#471)+- **A Boolean setting given a value it cannot take is refused naming the setting, where it named the alias it was set through: `build-fallback = maybe` is refused as `Boolean setting 'fallback' has invalid value 'maybe'`, as upstream refuses it.** Upstream's `BaseSetting<bool>::parse` (config.cc at 2.24.9, configuration.cc at 2.36.0) throws with the setting's own name, which `Config::set` reaches through the alias's entry in the same table, and nova-nix's integer settings already named theirs that way. `fallback` is the only Boolean setting nova-nix reads that has an alias. (#472)+- **`push` uploads a NAR larger than 64 MiB in parts of 64 MiB through nova-cache's multipart upload, so a cache behind a proxy that refuses a large request body takes it.** Each NAR went in one `PUT /nar/<file>`, which Cloudflare, in front of cache.novavero.ai, refuses with 413 for a body over 100 MB. Upstream's `HttpBinaryCacheStore` also sends each file in one PUT (`upsertFile` in http-binary-cache-store.cc), so the parts follow nova-cache's protocol: `POST /nar/<file>/uploads` begins an upload, `PUT /nar/<file>/uploads/<id>/<n>` sends each part in order, and `POST /nar/<file>/uploads/<id>` completes it with the part count and the total size. A NAR of 64 MiB or less still goes in one PUT, and so does a larger one when the cache answers the beginning with 404, as a nova-cache without the multipart upload does, so a push to such a cache works as before. A part, or the request that begins an upload, that fails as upstream's transfer layer retries a transfer, its response lost or an error status such as 503, is sent again with upstream's attempts and backoff, which it applies to an upload as to a download (`TransferItem::finish` in filetransfer.cc): the server replaces a part it holds, so a part that did arrive is not doubled. A part answered 404 or 409 means the server no longer holds the parts before it, and a new upload begins. A completion answered with anything but 200, or not at all, may still have joined the NAR, so the push goes on and the narinfo decides: the server checks its FileSize and FileHash against the stored NAR, and a narinfo it refuses then uploads the NAR again. The narinfo is sent in the second phase with the others, so a path is still never announced before its references. A push begins at most three uploads of one NAR, then fails naming the request and the server's answer. A push request that gets no response is reported with the client's failure alone, where it printed the client's whole request record, and a refused `narinfo-hashes` request carries the server's message. The compressed NAR is still held in memory whole, as for one PUT: nova-cache's zstd encoder is one-shot, and an upload is begun under the object's name, which for zstd is the hash of the whole compressed file. (#560)+- **`nova-nix build` links its output from `./result` and makes the link a root the garbage collector keeps, as `nix-build` does, and `--no-out-link`, or its other spelling `--no-link`, links nothing.** It linked nothing unless `--out-link` was given. The link is named as nix-build names it (the loop over the built outputs at the end of `main_nix_build` in nix-build.cc): `./result`, or the path `--out-link` gives, for the output `out`, and that path with `-NAME` appended for any other output, so `-A dev` links `./result-dev`. nix-build's `-2`, `-3` and so on for a second and later derivation do not arise, since `build` builds one. The link is made and registered as an `--out-link` was, by upstream's `addPermRoot` rules: a link already there that points into the store is replaced, and anything else at the path fails the command after the build, with no path printed. A build that fails, or a check that finds an output different, links nothing, since upstream's `Store::buildPaths` throws before nix-build links (`main_nix_build` in nix-build.cc, and build/entry-points.cc at 2.24.9, where 2.36.0 has `Worker::buildPaths`). nix-build's `--no-out-link` links into a temporary directory it deletes on exit (the `tmpDir` and the `--no-out-link` case of `main_nix_build` in nix-build.cc), which leaves a dangling record that its next collection removes with a `removing stale link` line (`LocalStore::findRoots` in gc.cc); here nothing is linked or recorded, which leaves the store as upstream leaves it, less that record. Of several link flags on one command line the later wins, as nix-build's does, since it sets its link as it reads each flag (the `--no-out-link` and `--out-link` cases of `main_nix_build` in nix-build.cc): `-o a --no-out-link` links nothing, `--no-out-link -o a` links `a`, and `-o a -o b` links `b`, where a second `--out-link` was refused. A script that runs `build` now leaves `./result` in its working directory, and since a link into another store is replaced only when that store is the platform store, a script that builds into two scratch stores from one directory fails at the second build's link; `--no-out-link` keeps such a script as it was. On Windows the link is a symlink, which needs Developer Mode or an elevated shell, so without either a build fails at its link unless `--no-out-link` is given. (#638)+- **`push --cache file:///DIR --secret-key-file KEY` writes a binary cache to a directory, as upstream's `nix copy --to file:///DIR` does, so builds can be shared from any static web server or file share.** `push` reached only a nova-cache server, which signs what it receives. The directory gets the layout upstream's `LocalBinaryCacheStore` writes at 2.24.9: `nix-cache-info` holding `StoreDir: /nix/store` (`BinaryCacheStore::init` in binary-cache-store.cc), without which upstream's HTTP substituter reads no cache, a `<hash>.narinfo` for each path, and its NAR under `nar/`, named by the hash of the file (`BinaryCacheStore::addToStoreCommon` in binary-cache-store.cc). It also gets the empty `realisations`, `build-trace-v2` and `log` directories. Upstream's `file://` store creates `nar`, its realisations directory and `log` whenever it opens a cache, to read it as well (`LocalBinaryCacheStore::init` in local-binary-cache-store.cc), and a reader that cannot create them, without write access to the directory, drops the cache with only a warning (`getDefaultSubstituters` in store-api.cc at 2.24.9, store-registration.cc at 2.36.0). The realisations directory is `realisations` through Nix 2.34.9 and `build-trace-v2` from 2.35.4, so both are made. Each narinfo is signed with the secret key, a file in the form `nix-store --generate-binary-cache-key` writes, as upstream's binary cache store signs every narinfo with the key its `secret-key` setting names (`BinaryCacheStore::addToStoreCommon` in binary-cache-store.cc at 2.24.9, `BinaryCacheStore::uploadNarInfo` at 2.36.0). A key file whose second half is not the public key of its seed is refused, since upstream's signer, libsodium's, signs with that half as the public key, and what it signs with such a key verifies under no key. A path whose narinfo is in the directory is skipped and a NAR whose file is there is not written again, as upstream skips them; every NAR is written before any narinfo; each file is written beside its name and renamed onto it, with the permissions the umask leaves, so a web server running as another user can read it; and a `nix-cache-info` naming another store directory is refused in upstream's words. The NARs are uncompressed unless `--compression zstd` is given, where upstream's default is xz: nova-cache decodes xz but has no encoder. A `file://` cache needs `--secret-key-file`, since a substituter refuses a narinfo with no signature, nova-nix's and upstream's alike, unless `require-sigs` is off, the path is content-addressed, or, for upstream's, the cache is marked trusted; it refuses `--key-file`, a server's API key, and a server refuses `--secret-key-file`. A `file://` URL names an absolute path after an empty host, as upstream requires, and not a filesystem root such as `file:///`, which a variable that expanded to nothing leaves; one with a query, a fragment or a percent-escape is refused, since upstream reads the query as store settings and decodes escapes, and on Windows `file:///C:/DIR` names `C:/DIR`. A `--cache` that is no `http://`, `https://` or `file://` URL is refused before the store is opened, where it failed at the first request. (#639)+- **`nova-nix eval`, `build` and `trust` take a directory, a `<NAME>` the search path finds, and `--arg` and `--argstr`, and call a function the target evaluates to, as `nix-instantiate --eval` and `nix-build` do.** They took a file or `--expr` alone, and kept a function as the value it is. A directory stands for its `default.nix` (`resolveExprPath`, eval.cc). An argument longer than two characters and written in angle brackets is found and read as `import <NAME>` finds and reads its file (`lookupFileArg`, common-eval-args.cc): a name the search path does not hold fails with the same message, and a file found in the store keeps its store path, so a path literal in it names a place in that store path and the target gives the derivation `import <NAME>` gives. `--arg NAME EXPR` passes an expression, parsed with its relative paths against the working directory before the target is read and evaluated only when the function uses it, and `--argstr NAME STRING` a string; a later flag for a name replaces an earlier one (the `--arg` and `--argstr` flags of the `MixEvalArgs` constructor and `MixEvalArgs::getAutoArgs` in common-eval-args.cc). The expression, the string and a `<NAME>` are the bytes the command line gives, as upstream reads them; a name is an attribute name, which is text here, so one whose bytes have no UTF-8 reading is refused. A function with a set pattern is called as upstream's `autoCallFunction` calls it (eval.cc): one that takes `...` with every argument, any other with the arguments its formals name, its defaults filling the rest, and a set with `__functor` as the function its functor gives. A formal with neither an argument nor a default fails with upstream's `cannot evaluate a function that has an argument without a value` message, which upstream follows with the formal's position and nova-nix, whose formals carry none, does not. `eval` calls the value only when an argument is given, as `nix-instantiate --eval` does (`processExpr` in nix-instantiate.cc). `eval --aterm` takes any of these targets, where it took only `--expr`, and calls the value whether or not an argument is given, as `nix-instantiate` does before it writes a derivation (`getDerivations` in get-drvs.cc). `build` and `trust` call it before each component of the `-A` path is selected from it and once the path has selected it, as `nix-build` does through `findAlongAttrPath` and `getDerivations` (attr-path.cc, get-drvs.cc), so `build '<nixpkgs>' -A hello` calls nixpkgs' function before it selects `hello`. A URL or `channel:` target, which upstream downloads, `--arg-from-file` and `--arg-from-stdin` are not accepted, and a command given no target still asks for one, where upstream reads `default.nix` in the working directory. (#644)+- **`nova-nix eval`, `build` and `trust` read `--expr` as the bytes the command line gives, as upstream does.** The expression was decoded as text first, so a byte with no reading in the file-system encoding, such as a Latin-1 byte in a string literal, became U+FFFD and could change a derivation without a word. On Windows, where the command line is UTF-16, an expression holding an unpaired surrogate, which has no UTF-8 form, is refused. (#644)+- **`nova-nix eval` computes the store paths of `builtins.toFile`, `builtins.path` and `builtins.filterSource` without writing them, as `nix-instantiate --eval` does, and `--read-write-mode` writes them as `eval` did before.** `eval` wrote each such object into the store, making the store if there was none, so evaluating `builtins.path { path = ./f; }` changed the store and, in a store upstream Nix also manages, failed where upstream prints the path. `nix-instantiate --eval` runs read-only (`main_nix_instantiate` in nix-instantiate.cc): it copies with `FetchMode::DryRun` (`addPath` in primops.cc) and names a `toFile` result without adding the text (`prim_toFile`), and `eval` now gives the same paths and writes none of them. `trust` evaluates the same way, so in a store upstream Nix manages it no longer fails on a `toFile` or `builtins.path` the evaluation makes. What a fetcher fetches is still written, and now registered as it lands, making the store's database if there is none, since upstream's fetchers add their results in any mode (`fetch` in fetchTree.cc, `downloadFile` in tarball.cc and `Input::fetchToStore` in fetchers.cc at 2.24.9); a fetch pinned by a `sha256` whose path the store already holds returns that path without downloading or writing, as upstream's does (`fetch` in fetchTree.cc at 2.24.9, and at 2.34.9, whose ensurePath returns at once for a valid path), so a second evaluation of the same pinned fetch does not download it again. `--read-write-mode` evaluates as `build` does: it writes what evaluation makes, adds it and every derivation it recorded to the store once evaluation succeeds, so a later evaluation finds them valid, and adds nothing, and so is refused nothing in a store upstream Nix manages, when evaluation made nothing, and builds or substitutes what an import from derivation names, through `--substituter`, `--trusted-key`, `--fallback` and `--exec-wrapper`, which `eval` now takes. `nova-nix build` writes as before. (#668)+- **`nova-nix profile add`, `profile remove` and `profile list` keep a profile of generations in upstream's layout, each generation a root the garbage collector keeps, so a package added to the default profile puts its programs under `~/.nix-profile/bin`.** They are `nix profile`'s commands of those names at 2.35.4. A profile is a link to one of its generations, `PROFILE-1-link`, `PROFILE-2-link` and on beside it, and each generation is a store path named `profile` holding the packages' files linked into one tree, as `builtin:buildenv` links them, and a `manifest.json`, version 3, written byte for byte as upstream writes it, added as a NAR-hashed path whose references are every package's paths, as upstream adds it, so its store path is computed the way upstream computes one. A new generation is one past the highest, unless the highest already names the path, and each is linked as `build` links its output, so it is an indirect root `store gc` follows and `store gc --print-roots` lists. The default profile is upstream's for a user who is not root: `profiles/profile` under `$NIX_STATE_HOME`, else `$XDG_STATE_HOME/nix`, else `~/.local/state/nix`, and on Windows `nix\state` under the Local AppData folder, linked from `~/.nix-profile`, or from `profile` in the state directory when nix.conf's `use-xdg-base-directories` is on; every profile command makes the directory and the link when they are missing, as upstream's do, and `--profile` names another profile. `profile add` takes what `build` takes and builds the outputs upstream installs (the one `outputSpecified` selects, else those `meta.outputsToInstall` names, else every output), or a store path, or a link into the store such as `./result`; names the package after its paths' names without their versions, with `-1`, `-2` and on appended to a name already taken; gives it `--priority`, 5 by default; and fails a file two packages of one priority hold with upstream's message, its hints naming nova-nix's commands. `profile remove` takes a name, a store path, `--regex` (a POSIX extended regular expression matching the whole name, ignoring case) or `--all`, prints upstream's lines, and refuses a line that selects nothing, or `--all` beside another selector, as usage errors, reported as nova-nix reports its other usage errors. It refuses a number as upstream refuses an index, in words of its own, `does not support indices`: upstream's say it no longer supports them, which describes upstream's history, and nova-nix never took one. `profile list` prints upstream's lines, a name in bold and `(inactive)` in red where 2.36.0 styles stdout, on a terminal whose `TERM` is not `dumb` or wherever `CLICOLOR_FORCE` or `FORCE_COLOR` is set, and never under `NO_COLOR` or `NOCOLOR` (a name holding an escape sequence of its own keeps it there, where 2.36.0 takes every escape out of the line), or with `--json` the manifest, indented when stdout is a terminal unless `--pretty` or `--no-pretty`, upstream's flags, say otherwise. Manifests of versions 1 to 3 are read. Where nova-nix differs from upstream: a change reads the profile's link, makes the new generation's store path, then takes the profile's lock, `PROFILE.lock`, and starts again with upstream's `changed while we were busy; restarting` if the link moved meanwhile, as `nix-env` does; upstream's `nix profile` takes no lock, so two changes at once there can both start from one manifest and the later drop what the earlier added. The lock file stays once released, as every nova-nix lock file does. Every profile command refuses a profile whose current generation is outside the store it uses, the store and the profile compared with their links resolved, and names `--store` and `--profile`, since a user with upstream Nix installed shares `~/.nix-profile` with it while nova-nix's store is elsewhere, and a generation read against the wrong store names paths that store does not hold; upstream has one store, and its `profile list` lists any profile. And a profile only `nix-env`'s `manifest.nix` describes is refused rather than read, a version 1 or 2 manifest's flake element, which upstream names from its URL, is refused, a flake element of version 3 keeps the fields it was read with where upstream parses and renders them again, and `--priority` takes an int with no binary unit suffix, where upstream takes a suffix and narrows a 64-bit value. Root's profile is where any user's is, where upstream keeps root's under its state directory. On Windows every link is a symlink, which needs Developer Mode or an elevated shell, and a switch removes the profile's link and makes it again, since a rename cannot replace a directory link there. (#713)+- **`nova-nix develop` starts `bash` with the build environment of a derivation, and `nova-nix print-dev-env` prints that environment, as upstream's `nix develop` and `nix print-dev-env` do, on Linux and macOS.** Both take `build`'s targets and its evaluation, store and sandbox flags. A derivation whose builder is not `bash` is refused in upstream's words. The environment is captured as upstream captures it: a copy of the derivation named `NAME-env`, whose builder runs upstream's 2.35.4 `get-env.sh` to write what bash holds once the stdenv's setup has run, so that the copy's path is upstream's at 2.34.9 and 2.35.4. The copy is built or downloaded with what it depends on, as `build` builds, and a second run builds nothing. The shell runs upstream's rcfile: `--command` runs a command with every argument after it, `--phase` and the phase flags (`--unpack` through `--installcheck`, `--check` among them) run a phase through `runPhase`, and the `bash-prompt`, `bash-prompt-prefix` and `bash-prompt-suffix` settings set an interactive shell's prompt. `--ignore-env`, `--keep-env-var`, `--unset-env-var` and `--set-env-var`, with 2.24.9's spellings as aliases, shape the shell's environment, which also gets `NIX_GCROOT` and `SHELL`; their conflicts are upstream's usage errors, and those upstream finds only once the environment is built are found then here too. nova-nix replaces itself with the shell, as upstream does, so that the shell has the terminal and its signals to itself and the command exits with its status, and no descriptor nova-nix holds, such as a connection a substitution left open, reaches the shell. The shell is `bash` found on the `PATH` of the environment it starts with, which is what upstream starts with flakes off, where `nixpkgs#bashInteractive` cannot resolve. `print-dev-env --json` prints the environment as upstream's does, over several lines when stdout is a terminal and on one otherwise, or as `--pretty` and `--no-pretty` choose. Upstream's `develop` leaves an empty temporary directory behind on every run, and an empty rcfile when it refuses its flags; nova-nix leaves neither. On Windows both commands are refused, since no Windows stdenv's builder is bash yet. The garbage collector does not yet keep the environment while a shell runs. (#715)+- **The command-line reference, which `--help` prints, says what `eval`, `trust`, `store gc`, `develop` and `profile remove` do, where it said otherwise.** `eval` writes `builtins.toFile` and `builtins.path` to the store only under `--read-write-mode`; without it, it builds an output a path's context names only when its derivation's `allowSubstitutes` is false and `always-allow-substitutes` is off, refusing to substitute any other. `trust` in a store upstream Nix's database also manages refuses a closure only when it has a fixed-output input. `store gc --print-roots` lists the roots in such a store too. `--ignore-env` keeps the variables `--set-env-var` sets as well as those `--keep-env-var` names. `profile remove --regex` matches a package's identifier: for one a flake added, its flake reference and attribute, and for any other the names of the store paths it holds, without their versions. (#738)+- **A push that fails on an exception, such as a path whose tree cannot be read, says `push failed:` once, where it said it twice.** `Nix.Push.pushPaths` put the prefix on an exception's message, and `nova-nix push` put it on every failure it was given, so such a failure read `push failed: push failed: ...`. `pushPaths` now reports an exception as it reports its other failures, unprefixed. (#738)+- **`Nix.Develop.Capture.captureDerivation` captures a derivation with a fixed output beside others, or under another name than `out`, input-addressed, as upstream's `nix develop` does, and refuses only a floating content-addressed or impure output, the one reason its refusal gives.** Upstream's `getDerivationEnvironment` (develop.cc at 2.36.0) defers every input-addressed and fixed output before anything reads the outputs together, and its reading of a `.drv` (derivation/aterm.cc) checks no output against another, so such a derivation is captured; nova-nix refused it with `the derivation has a floating content-addressed or impure output`, which it has not. nova-nix's evaluator makes no such derivation, so `develop` and `print-dev-env` are unchanged. (#738)+- **`nova-nix build` realises only the output it prints, the one the derivation's `outputName` names, as `nix-build` does, so with that output valid it builds and downloads nothing, whatever the state of the derivation's other outputs.** `nix-build` asks for each derivation's `outputName` alone (`main_nix_build` in nix-build.cc, the same at 2.24.9, 2.34.9 and 2.36.0); nova-nix asked for every output, so a missing sibling output, such as a `dev` a collection deleted, was downloaded or built again. A build the requested output needs still builds every output of the derivation, as upstream's does. `--check` still checks every output. (#738)+- **`nova-nix profile history`, `profile rollback` and `profile wipe-history` show a profile's generations, switch it back to an earlier one, and delete the ones it no longer needs, so that the next `store gc` takes what only they kept.** They are `nix profile`'s commands of those names at 2.36.0. `history` prints upstream's lines for each generation in order of number: `Version N (DATE) <- M:`, where the date is the day in UTC its link was made and `M` the generation listed before it, then each package added, removed or at other versions than in that generation, with the empty-set sign for none and an epsilon for an empty version, or `No changes.`; it sets the current generation's number in green and the others' in bold where upstream 2.36.0 styles stdout, on a terminal whose `TERM` is not `dumb` or wherever `CLICOLOR_FORCE` or `FORCE_COLOR` is set, and never under `NO_COLOR` or `NOCOLOR`. `rollback` switches to the newest generation below the current one, or with `--to N` to generation `N`, every `--to` read as upstream reads it, a binary unit after it included, the last winning, and says `switching profile from version M to N`; a change after a rollback makes the generation after the newest, as upstream numbers one. `wipe-history` deletes every generation but the current one, or with `--older-than Nd` those made before its cutoff but the newest of them, which the profile held at the cutoff, and warns of one made after the cutoff that a later one predates, as upstream does; it says `removing profile version N` for each. `--dry-run` on either says what it would do and changes nothing. A generation's time is its link's own modification time, and the next collection removes a deleted generation's root record with upstream's `removing stale link` line. The refusals are upstream's, each one `error:` line: `profile version N does not exist`, `no profile version older than the current (N) exists`, the two `invalid number of days specifier` messages, and those for a `--to` that does not read, which upstream follows with a `Try 'nix --help'` line that nova-nix does not print. Where nova-nix differs: both commands keep the profile's lock file once they release the lock, as every nova-nix lock does, where upstream deletes it; both refuse a profile whose current generation is outside the store in use, as every profile command does, so a profile upstream Nix keeps in another store is neither switched nor wiped; `history` refuses a generation only `nix-env`'s `manifest.nix` describes, as `profile list` refuses such a profile, where upstream reads it; `--older-than` multiplies its days into seconds in 64 bits, where upstream's product is an int that more than 24855 days overflow; and of two links for one number, such as `profile-3-link` and `profile-3-link.tmp`, a rollback takes the later in name order, where upstream takes the later in directory order. (#744)+- **On Windows a variable set to nothing counts as set, as upstream reads it, so an empty `NO_COLOR` turns colour off there as it does elsewhere.** A Windows variable was read through base's `lookupEnv`, which reads a value of no characters as unset. nova-nix now asks `GetEnvironmentVariableW` for the space the value needs first, as upstream does, which is none only for a variable that is not set, so every variable nova-nix reads, `NO_COLOR` and `NIX_STATE_HOME` among them, is set when it is set to nothing. (#744)+- **`nova-nix trust --json` prints the report as one JSON document, and the report names a file of prebuilt code that is a copy of an input the closure runs as a builder as that input.** The lines are for a reader; the JSON is for a check, which can then hold a closure to what it relies on without reading prose. It has a `version`, the fixed-output inputs keyed by output path, each with its `class`, how it comes to be, the inputs pinned to the same hash, the builders inside it, and the prebuilt code and unread files its scan found, then the builders outside the closure, in its input sources and the builtins, each with its count of derivations, and the input sources themselves. Keys are camelCase and store paths full, as upstream's JSON output spells its own, and `--pretty` and `--no-pretty` lay it out as they do `print-dev-env --json`. Every file of prebuilt code now carries its SHA-256, and one whose bytes are those of a fixed-output input a build runs as a builder, hashed flat, is named as that input: `pkgs/windows`' stage0-pe32 source archive holds a copy of the 1,623-byte seed, which the report now gives as the seed rather than as more prebuilt code. (#757)+- **`NIX_CONFIG_HOME` holds the user's `nix.conf`, as upstream 2.36.0 reads it.** Upstream's `getConfigDir` returns `NIX_CONFIG_HOME` itself when the variable is set, the directory `nix.conf` sits in rather than one with a `nix` directory beneath it, and otherwise `nix` under the XDG config home (users.cc at 2.36.0); its user config files are that directory's `nix.conf` and then each `XDG_CONFIG_DIRS` entry's, unless `NIX_USER_CONF_FILES` names others. nova-nix read the XDG config home's file whatever `NIX_CONFIG_HOME` said. An empty `NIX_CONFIG_HOME` is set, as upstream reads it, and names `nix.conf` in the working directory. (#775)+- **`nova-nix key generate-secret --key-name NAME` prints a new Ed25519 secret key for signing a binary cache, and `nova-nix key convert-secret-to-public` prints the public key of the secret key on stdin, byte for byte as upstream's `nix key` commands do.** A cache `push` writes to a directory is signed with a secret key file, and nova-nix had no way to make one: the reference pointed at upstream's `nix-store --generate-binary-cache-key`. The secret key is `NAME`, a colon and the base64 of 64 bytes, a seed from the system's source of randomness and then that seed's public key, as libsodium makes the key upstream prints, with no line feed after it. The public key is the secret key's last 32 bytes under the same name, read off as upstream reads it rather than derived from the seed again, also with no line feed. Stdin is read whole and as it is, as upstream reads it. The base64 is read up to its first `=`, skipping line feeds, so a key echoed with a line feed after it is read, and what follows a padded key is not read at all. A character outside base64 before the padding is refused with upstream's report: an `error:` line, the trace `while decoding key named ''` after an ellipsis on the next, and `error: invalid character in Base64 string: '...'` below it, each line indented by the width of `error: `. A key with no colon, no name or no bytes is refused the same way, with `error: key is corrupt`, and a key that is not 64 bytes with `error: secret key is not valid` alone. Each refusal exits with status 1. The name is the bytes the command line gives, unchecked, as upstream takes it, and the last `--key-name` given wins. Without one the command is refused with upstream's `required argument '--key-name' is missing`. Both commands take `--store` and leave it unused, as upstream's take that setting as every command does. (#765)+- **SIGTERM and SIGHUP interrupt nova-nix on POSIX, as SIGINT does and as upstream takes all three: a command ends saying it was interrupted, and a build running ends its builder's process group.** Each ended the process at once, which, with a builder in a session of its own, left the builder running. (#778)+- **`nova-nix daemon` serves the store to clients over a Unix socket, in upstream Nix's worker protocol, on Linux and macOS.** It listens where upstream's daemon does, at `$NIX_DAEMON_SOCKET_PATH`, else `daemon-socket/socket` in `$NIX_STATE_DIR` or `/nix/var/nix`, or where `--socket-path` says, on a socket every user may write, as upstream's is, so the directory it is in decides who reaches it. It admits and trusts each client as upstream's daemon does, by `trusted-users` and `allowed-users`, which name users, groups as `@GROUP` and everyone as `*`, refusing a member of `build-users-group`, which defaults to `nixbld` for a daemon run as root; `--force-trusted` and `--force-untrusted` decide without asking who a client is, as upstream's flags do. A client the daemon does not trust is limited as upstream limits one: it may not repair, its settings are held to those upstream lets it set, its substituters to `trusted-substituters` and those the daemon uses, and it is shown roots without what holds them. Each connection is served on a thread of its own, with temporary roots of its own that go with it, and the daemon holds the store open while it runs, so a collection waits for it to stop. It answers queries of the store (which paths are valid, their info, referrers and derivers, a derivation's outputs, the roots, a path's NAR), keeps temporary and indirect roots, and builds, substitutes and adds paths, as the entries below describe; a client asking it to add signatures or collect garbage is told it does not do so yet, and one asking it to repair, optimise or verify the store is told nova-nix does not do so. A path too long for a socket address is refused, where upstream binds one from its directory, and on macOS a group's members include those the directory counts, as upstream's do. `trusted-users`, `allowed-users` and `trusted-substituters` (and its older name `trusted-binary-caches`) are read from `nix.conf`. (#772)+- **`nova-nix daemon` builds and substitutes for its clients, and tells them what realising paths would take.** BuildPaths and BuildPathsWithResults realise each derivation's outputs asked for, building them or substituting them from the caches the connection's settings name, and check them when a check is asked for; EnsurePath substitutes a path, failing as upstream does with "path '...' is required, but there is no substituter that can build it"; QueryValidPaths substitutes what it is asked to first, a failure a warning, as upstream's daemon does; QuerySubstitutablePaths says which paths a cache offers; and QueryMissing works out the derivations to build, the paths to substitute with their download and unpacked sizes, and those unknown, as upstream's `queryMissing` does. Each operation runs under its connection's settings, with no cache when the client says not to substitute, as upstream's worker has none then, and a daemon run as root builds as `build-users-group`'s members. The client is told what the store does as upstream's daemon tells it: each message as a line at its level, and each build, check and substitution as the activity upstream's derivation and substitution goals start, each line a builder writes a result of it. Results with a build report one for each derivation that ended, as upstream 2.36.0 reports them: one realised as another's input is built, a failure is reported under the request whose own derivation failed, one whose input no request asked for failed did so with upstream's "Cannot build '...'. Reason: 1 dependency failed.", and one left unrealised when another failed is left out, as upstream leaves out a goal that never finished. A store path asked for that no cache holds has no substituter, and one whose references no cache holds failed for them, in upstream's words. A derivation asked for that the store does not hold is substituted first, and one no cache gives fails its request with upstream's "failed to obtain derivation of '...'", nothing else being realised, as upstream's worker stops then. A fixed-output derivation whose output has other contents than it fixes is reported as upstream reports a hash mismatch, as an output rejected, where a builder that fails is a permanent failure. A failure upstream's goals throw, such as a cache that cannot be asked or an output a derivation does not have, fails the whole call, as upstream's does. A build's start and stop times are not recorded and read as 0. Repairing is refused before anything is done, as nova-nix does not repair. (#780)+- **A daemon client that hangs up has its work stopped.** `nova-nix daemon` watches each connection for its client to hang up, as upstream's daemon does, and stops the work it is doing for that client as an interrupt stops it: its builder is ended with every process it started, and its locks, temporary roots and database connection are released. The sandbox helper closes every descriptor it inherits past the standard ones, as an unsandboxed builder's start closes them, so a sandboxed build holds no other client's connection open. On Windows a build that is stopped waits for its builder's job to end before it unwinds. (#780)+- **`nova-nix daemon` adds paths for its clients: the derivations and sources they send as dumps, and NARs with what their paths claim of themselves, one at a time or several together.** AddToStore makes a dump into the path its content address makes, as upstream's daemon does, and answers the path's info: a text, as a `.drv` is sent, by its SHA-256 with the references sent; a NAR by the algorithm it names, with references only for SHA-256; and a file's contents by the algorithm it names. AddToStoreNar and AddMultipleToStore import a NAR as upstream's store imports one: a path already valid is answered without its NAR being written; a path that is not content-addressed is refused a client the daemon does not trust, whatever it asks, unless a key the daemon trusts signed it, one in `trusted-public-keys` or the public key of one in `secret-key-files`, or `require-sigs` is off, with upstream's "cannot add path '...' because it lacks a signature by a trusted key"; and a NAR whose hash is not its info's, or that ends before the size its info states, a tree that does not reproduce the content address it states, an address that does not make its path, a fixed address other than a NAR's SHA-256 stated with references, a derivation whose outputs are not the paths its inputs make, and a reference that is not valid are refused in upstream's words, as is a `trusted-public-keys` entry or a `secret-key-files` file that does not read. Upstream's warning of a path that "claims to be content-addressed but isn't" reaches the client at upstream's error level, where upstream prints it, so a client that hears errors alone hears it. A NAR that goes on past the size its info states is refused as an archive cut short at that size, where upstream refuses it as a size mismatch. Each path added, or found valid, is a temporary root of the connection, as upstream's store roots what it adds. What a client sends is written to a staging directory in the store and moved to its path under the path's lock once it has been checked, as upstream 2.36.0 stages an import, so a refusal leaves nothing at a store path, and an upload a client abandons or hangs up in is removed. A text hashed other than with SHA-256 is refused, where upstream's daemon stops on an assertion, and so is a dump that goes on past its archive's end, which upstream takes. A NAR's path is registered at the time its info states, or at the time of its import where its info states 0, as upstream registers one. The git-hashing method is still refused, as upstream refuses it without its experimental feature, and so is repairing. `trusted-public-keys` is empty unless nix.conf sets it, where upstream's default holds the key of cache.nixos.org. (#799)+- **The daemon names every path under `/nix/store` to its clients, wherever the store it serves keeps its files, as upstream's daemon names a store's paths by its store directory and not by the physical directory its files are in.** nova-nix computes a store path under `/nix/store` whatever directory `--store` names, but its daemon named paths on the wire under the directory the files are in: a client computing the same paths under `/nix/store` would refuse them as outside its store, and on Windows, where that directory is `C:\nix\store`, the daemon refused every path a client sent as not absolute. The daemon's messages to a client name paths under `/nix/store` too. (#803)+- **`nova-nix daemon` serves the store on Windows, over the named pipe `\\.\pipe\nova-nix-daemon`, and names each client by its Windows account.** Windows has no Unix socket that names its peer, so the daemon listens on a named pipe, or on the `\\.\pipe\NAME` that `$NIX_DAEMON_SOCKET_PATH` or `--socket-path` names. It creates the pipe as its first instance, so it refuses to start where another process already has the pipe rather than join a pipe someone else controls, and the pipe refuses clients on other machines. The pipe's DACL gives SYSTEM and Administrators full control and Users the right to read and write data and nothing more, so while the daemon has the pipe no other user's process can create an instance of it and take a client in its place. A daemon whose token holds Administrators enabled, as an elevated administrator's does, owns the pipe as Administrators and gives its own account no entry: the processes of that account that are not elevated hold Administrators for deny only, so they use the pipe as any user does and can neither create an instance nor rewrite the DACL. A daemon without Administrators owns the pipe as its account and gives the account the access that creating its next instance takes, and no right to delete the pipe or take its owner. A process at Medium integrity or above makes a pipe with no integrity label, which Windows reads as Medium, so clients at Medium integrity write it; a client at Low integrity cannot. (#803)+- **The daemon reads who a client is as the client connects, before it has read a byte, and matches the client's account against `trusted-users` and `allowed-users` by SID.** It impersonates the client, reads its token's user and the groups the token grants by, and stops, in one call, so a client the daemon refuses has sent nothing and holds neither its pipe instance nor a thread. An entry names an account as Windows resolves a name, or by its SID, and a group after `@`. A bare name is an account of this machine, so `root` or `alice` cannot name an account of a domain the machine belongs to; another domain's account is `DOMAIN\NAME` or `NAME@DOMAIN`, and a well-known one is `BUILTIN\Administrators` or `NT AUTHORITY\SYSTEM`. An account whose name holds a space is named by its SID, since the settings are lists split at whitespace. Windows has no root, so `trusted-users` defaults there to `@S-1-5-32-544`, the machine's administrators, whose tokens enable the group only while elevated; elsewhere it stays `root`. `build-users-group` refuses a client by the groups Windows holds for its account, not by the groups its token shows, which a token can set aside, and a client whose group membership or whose build-users group Windows cannot tell is refused where a mistaken answer would let a build account in. A client running with a restricted token is refused rather than taken as its user. (#803)+- **A client of the daemon's pipe checks who made the pipe before it sends anything, and refuses a pipe a trusted account did not make.** `Nix.Daemon.Pipe.connectPipe` reads the owner and the integrity label of the pipe it opened, with the read access it already holds, so a user can check a daemon that is elevated or a service, which a check of the daemon's process could not do. It trusts a pipe owned by its own account, SYSTEM, Administrators or `NT SERVICE\nova-nix`, the virtual account of the service the daemon is to run as, and refuses a pipe made by a process below Medium integrity, naming the pipe. LOCAL SERVICE, NETWORK SERVICE and the other services' accounts are not trusted, since other services share them. Windows lets a process give a pipe it makes only its token's user or a group its token holds enabled with the right to own objects as it, Administrators in an elevated administrator's token, and any other owner only with the restore privilege, so the owner says who made the pipe, and a user who is not elevated, an administrator among them, owns what it makes as itself. The daemon sets the owner itself, since the owner Windows gives by default is a security policy's to change. The client opens the pipe letting the daemon identify it but not act as it, and while every instance is busy it waits for one to free, at most 15 seconds, before it says the pipe is busy. (#803)+- **The daemon's accept loop on Windows waits half a second after a failed accept and stops after ten failures in a row.** A pipe that kept failing would otherwise spin and fill the log. The daemon does not watch a Windows client for its hangup, so the work for a client that has gone ends when the daemon next fails to send to it, and it does not yet run as a Windows service or build as build accounts. (#803)+- **A command reaches the store through a daemon, nova-nix's or upstream's, when it cannot write the store and the daemon is there, and `--store`, nix.conf's `store` and `NIX_REMOTE` choose `auto`, `daemon`, `unix://PATH`, `local` or a store directory, as upstream's do.** A user who cannot write a shared store now evaluates, builds and keeps profiles in it through its daemon, as upstream's `auto` store does. The value is `--store`, else the `store` setting (`NIX_CONFIG` included), else `NIX_REMOTE`, else `auto`, so the setting overrides the variable and the flag overrides both. `auto` opens the store directly when this process can read and write its `.nova-nix` directory, and otherwise goes through the daemon when something is at its socket, or on Windows its pipe, without connecting to find out. The connection is made when a command first needs the store, so a command that never asks it does not fail for a daemon that is not there, and one that does fails with upstream's `cannot connect to socket at "PATH": REASON`. On Windows the probe also asks whether the process may keep the store, since a store the service created is the service's and is refused to other processes. A `unix://PATH` is percent-decoded, split at `/` and folded, and must be absolute, as upstream reads it, `unix:/PATH` with one slash reads the same, a literal space in the address is refused, and `unix://` alone is the default socket. A value that is none of those and has no path separator, such as a misspelt `daemon`, is refused as `Cannot parse Nix store 'VALUE'`, as upstream refuses it, so a directory in the working directory is written `./store`. A store directory is still read as the store itself, where upstream reads a path as the root of a store beneath it, and on Windows so is a drive path or one that starts `\\?\`, where upstream reads a drive path with a `/` as a URL whose scheme is the drive's letter. A store URL's settings and other schemes are refused, since nova-nix opens none of them, and where a Linux system has no `/nix` and no daemon, upstream makes a chroot store under the user's data directory for a user who is not root, which nova-nix does not: it opens the platform store directly, where the opening fails as it would have. `--substituter`, `--trusted-key` and the sandbox flags reach a daemon as the settings they set, as upstream's flags do. A daemon that does not trust the user says it ignored `--trusted-key` and the sandbox flags, and a `--substituter` URL that its `substituters` and `trusted-substituters` do not list, and takes one that they list without a word. The `store` setting is sent when a source set it (`NIX_REMOTE` only gives its default), as upstream's setting renders it: `auto` for the empty reference, and `unix://PATH` with the path as written. `--store` replaces the value that is sent, and for `develop`, `print-dev-env`, `profile add` and `profile remove`, which model upstream's `nix` command, whose flag marks the setting as set, it is sent for `--store` alone, where `build` and `eval`, which model `nix-build` and `nix-instantiate`, send nothing for it. A store directory is opened directly and sends nothing. Upstream's daemon resolves its own `store` setting from `--store`, nix.conf and `NIX_REMOTE`, may serve a store that is itself a daemon, and warns when that store names its own socket; `nova-nix daemon` reads `--store` alone and refuses one that names a daemon, since it serves a store it opens itself and does not proxy to another. Through a daemon the refusal of a store upstream Nix's database manages does not apply, an output that `--check` finds different exits 1, as upstream's client reports its daemon's failure, and `store gc`, `store delete` and `--exec-wrapper` are refused with the reason, since they need the store opened directly. (#810)+- **`push` and `trust` work through the daemon.** `push` asks the daemon for each path's references, NAR hash and deriver and reads its NAR from the store's directory, as upstream's client of a daemon on the same machine reads it: the daemon is asked what it records of the path, never for its NAR. `trust` has the daemon fetch and substitute its fixed-output inputs: a fetch that fails stops the command, and so does a substitution the daemon fails for a reason other than that no substituter offers the path or something it references. A path the daemon holds asks no substituter anything. The daemon's result does not tell a download that failed from a path no substituter offers, so through a daemon an input whose download failed, or whose references' download failed, is left unread and the report names it as not read, where a store opened directly stops the command; everything else matches. `trust` reads what the daemon holds from the store's directory. Each path whose record or files a push or trust relies on is rooted for the connection before the daemon is asked about it, so a collection cannot remove it between the answer and the read of its files; the list `push --all` starts from is not rooted, so a path collected between the listing and its read fails the push. A daemon older than protocol 1.34 cannot say how a substitution ended, so `trust` through one fails for an input the daemon does not hold. `push --all` words a failure to list the store's paths as `push failed: REASON`, for a store opened directly and through a daemon alike. (#815)++### Evaluation++- **Evaluation spends a fraction of the time it did collecting garbage: the drvPaths of firefox, git, python3 and gimp from nixpkgs evaluate in 6.7 seconds where they took 24.5, and a minimal NixOS system's in 19 seconds where it took 149.** A thunk not yet forced reached the environment its code runs in through a GHC stable pointer, freed only when the thunk was forced, and nixpkgs leaves most of the thunks it makes unforced: those two evaluations ended holding about 1.9 million and 3.9 million such pointers. GHC marks every stable pointer on every collection, minor ones included, so collecting took 74% and 87% of the time. A pending thunk now holds its environment's C pointer, as upstream's holds its `Env *`, and collecting takes 9% and 12%. A frame whose bindings refer to it, those of a `let`, a `rec` set or a function's formals, is allocated before the thunks that point at it and its slots are filled after, as upstream builds `env2` in `ExprLet::eval`, `ExprAttrs::eval` and `EvalState::callFunction` (eval.cc at 2.24.9). The peak memory footprint falls by 8% on both evaluations, measured back to back on one machine, and the drvPaths are unchanged. (#428)+- **`__curPos` evaluates to the position it is written at, `{ column; file; line; }` in a file and `null` in an `--expr` argument, where it failed with `undefined variable '__curPos'` when forced.** Upstream's parser reads the identifier as a position, never as a variable, wherever it is an expression (`expr_simple`, parser.y), and `ExprPos::eval` answers `EvalState::mkPos` of it (eval.cc), the set `builtins.unsafeGetAttrPos` gives for an attribute: the file's path as a string and the line and column of the identifier, or `null` for text with no file behind it. The parser here now does the same, so no binding of the name reaches it: `let __curPos = 1; in __curPos` is the position, as it is upstream, where it was `1`, and so is `__curPos` under a function whose argument is named `__curPos` or a `with` whose set has that attribute. `inherit __curPos;` copies a variable, as upstream's `inherit` builds one without that check, so with nothing binding the name it fails as an undefined variable before anything is evaluated, where it failed only when the attribute was forced. nixpkgs' Firefox wrapper sets `pos = __curPos;`, so `firefox-bin` failed to evaluate. The position differs from upstream's where `unsafeGetAttrPos`'s does: the file of a file outside the store reached through a symlinked directory is its path with every symlink resolved, where upstream's is the path as written. (#468)+- **A hash's base64 is read as upstream reads it, up to the first `=`, so an SRI or base64 hash with text after its padding, such as `sha256-HS/n40Ng8S5N14DtEH/upwlxdzwCoOEJA40EMdCcLw4=io`, is the digest spelled before the padding.** The decoder removed every `=`, newline and carriage return and decoded what was left, so a character after the padding became part of the digest, giving a 33rd byte or an encoding it refused, and a last character whose unused bits were not zero was refused. The hashes nixpkgs gives `nmgui` on unstable, and `cosmic-workspaces-epoch`, `guake`, `journalist` and `quintom-cursor-theme` on 24.11, failed this way. Upstream's `base64Decode` (util.cc at 2.24.9, `base64::decode` in base-n.cc at 2.36.0) stops at the first `=` and reads nothing after it, skips a newline, refuses any other character outside the standard alphabet, a carriage return among them, and drops the bits left after the last whole byte whatever their value, and so does the decoder here, for `builtins.convertHash`, a fixed-output derivation's `outputHash`, and the `sha256` of `builtins.fetchurl`, `builtins.fetchTarball` and `builtins.path`. A hash's algorithm tag is split off as upstream's `getParsedTypeAndSRI` splits it (hash.cc at 2.24.9, `parseAnyHelper` at 2.36.0): at the first `:`, else at the first `-`, and a tag that names no known algorithm is an error, so a separator after the padding still decides the tag, and `sha256-...=:x` names the unknown algorithm `sha256-...=`. A hash not in SRI form is read as base16, nix32 or base64 by its length in bytes, as upstream counts it, so a character after the padding that UTF-8 spells in more than one byte makes the length wrong. A base64 digest that is refused or decodes to the wrong length fails with upstream's message for both, `invalid SRI hash '...'` or `invalid base-64 hash '...'`, since upstream catches the decoder's exception without rethrowing it and lets the length check report it (the `Hash` constructor in hash.cc at 2.24.9, `parseLowLevel` at 2.36.0). (#469)+- **Every reader of an attribute name a program computes refuses a name with string context, as upstream's does: `listToAttrs`, a dynamic attribute, a select or `?` path, `getAttr`, `hasAttr`, `removeAttrs`, `catAttrs` and `groupBy`.** Each read the name's text and dropped its context, so `builtins.getAttr (builtins.appendContext "a" { ... }) { a = 1; }` was `1`, and a `derivation` whose `outputs` held such a name passed where upstream's fails, since the wrapper makes its output attributes with `listToAttrs`. Upstream reads each name with `forceStringNoCtx` (`getName` and `ExprAttrs::eval` in eval.cc, and `prim_getAttr`, `prim_hasAttr`, `prim_removeAttrs`, `prim_listToAttrs`, `prim_catAttrs` and `prim_groupBy` in primops.cc), which refuses one with context as `the string 'a' is not allowed to refer to a store path (such as '...')`, naming the context's first element, and now so does nova-nix, with `builtins.unsafeGetAttrPos`'s reader. A name that is not a string is refused with that function's `expected a string but found ...` where each reader had a message of its own; a dynamic attribute whose name is null still binds nothing. (#475)+- **`derivationStrict` forces a derivation's attributes in name order and only then looks for its builder and system, so the error it reports is the one upstream's reports.** It forced `system`, then `builder`, and refused either missing, then checked `outputs` and read `args`, all before the rest of the attributes, so `(derivation { name = "w"; builder = "b"; all = throw "all"; }).drvPath` failed with `required attribute 'system' missing` where upstream fails with `all`, a repeated output was reported ahead of a throwing attribute sorting before `outputs`, and with both `builder` and `system` throwing the error was `system`'s. Upstream reads `__structuredAttrs` and `__ignoreNulls` first, then makes one pass over the other attributes in name order that reads `args`, `builder`, `system` and `outputs` at their keys, and checks that the builder and system are present after it (`derivationStrictInternal` in primops.cc), and nova-nix now does the same, for a structured derivation too. As upstream's does, a derivation that passes its attributes through the environment takes its outputs from the words of the `outputs` entry, so `derivationStrict` given `outputs = "out dev"` has the outputs `out` and `dev`. An output name that is not a valid store path name is refused after that pass. (#486)+- **`builtins.readDir` lists a directory holding an entry it cannot stat, and only forcing that entry's value fails, as `builtins.readFileType` on it fails.** readDir stats every entry, so one entry whose stat the system refused failed the whole call, as it did for a directory that can be read but not searched, where every entry's stat is refused, and on Windows for a directory holding a file with a deny ACE, and for `C:/`. Upstream's `readDirectory` gives an entry whose `lstat` is refused with `EACCES` or `EPERM` no type (posix-source-accessor.cc at 2.24.9), and `prim_readDir` binds such an entry to a deferred application of `builtins.readFileType` to its path under the directory with its symlinks resolved (primops.cc), so the listing names every entry and forcing one fails with readFileType's `getting status of '...': Permission denied`. readDir now does the same; any other failure to stat an entry still fails the listing, as upstream's does. `builtins.path` with a filter and `builtins.filterSource` read such an entry's type with an `lstat` of its own, as upstream's path filter does (`EvalState::callPathFilter` in primops.cc), so they fail on it as `readFileType` does, where they failed as the listing. (#491)+- **Hash strings are parsed as upstream's `Hash::parseAny` and `Hash::parseSRI` parse them, so `builtins.convertHash` refuses a tag that disagrees with `hashAlgo`, a fixed-output derivation whose `outputHashAlgo` names no algorithm upstream knows takes its algorithm from `outputHash`'s tag, and `builtins.fetchGit` accepts a `narHash` that spells the fetched hash with text after its padding.** Five cases differed from upstream 2.24.9. A base16 or nix32 digest that did not decode failed with `hash '...' is not a valid base16 sha256 hash`, where upstream's `Hash` constructor reports `invalid base-16 hash '...'` and `invalid base-32 hash '...'` (hash.cc at 2.24.9). An unknown algorithm, in `builtins.hashString`, `builtins.hashFile`, `builtins.convertHash` or a hash's tag, failed with `unknown hash algorithm '...'`, the first two after the builtin's name, and without the `, expect 'md5', 'sha1', 'sha256', or 'sha512'` upstream's `parseHashAlgo` adds (hash.cc at 2.24.9). `builtins.convertHash` ignored `hashAlgo` when the hash carried a tag; upstream parses `hashAlgo` first and hands it to `Hash::parseAny` (`prim_convertHash` in primops.cc), so an unknown `hashAlgo` is refused whatever the hash, and a tag that names another algorithm fails with `hash '...' should have type '...'` (`Hash::parseAny` in hash.cc). A fixed-output derivation refused an `outputHashAlgo` it did not know; upstream reads it with `parseHashAlgoOpt` (`derivationStrictInternal` in primops.cc), which gives no algorithm for a name it does not know, so `outputHash`'s own tag decides, and an untagged hash fails with `hash '...' does not include a type, nor is the type otherwise known from context` (`Hash::parseAny` in hash.cc), as an untagged hash given to `builtins.convertHash` without `hashAlgo` now does too. A known `outputHashAlgo` that disagrees with the tag is still refused, as upstream refuses it. `builtins.fetchGit` compared a declared `narHash` with the fetched one as text; upstream reads it with `Input::getNarHash` (fetchers.cc) before fetching anything, as an SRI hash that must be SHA-256 or as the empty string for a digest whose every byte is zero, and compares the hashes (`InputScheme::checkLocks` in fetchers.cc at 2.24.9, `Input::checkLocks` at 2.36.0), so a spelling with text after its `=` matches, a prefixed one fails with `hash '...' is not SRI`, a SHA-512 one fails with `narHash must use SHA-256`, and a mismatch names the pin in SRI. The refusal of a tag that disagrees with the algorithm the context expects is upstream's `hash '...' should have type '...'` for `outputHash` and for the `sha256` of `builtins.fetchurl`, `builtins.fetchTarball` and `builtins.path` too, where it added the tag's own algorithm and a `derivation:` or builtin's name. (#490)+- **`builtins.listToAttrs` reads an element's `value` only for the first element of its name, so `builtins.listToAttrs [ { name = "a"; value = 1; } { name = "a"; } ]` is `{ a = 1; }`, where it failed with `builtins.listToAttrs: element missing 'value'`.** Upstream's `prim_listToAttrs` (primops.cc at 2.24.9) forces each element to a set and reads its `name`, first to last, and looks `value` up only for a name it has not seen, since the first element of a name gives its attribute; nova-nix looked `value` up on every element before keeping the first of each name. Its failures are now upstream's, each with the line of context upstream gives it: an element without `name`, or the first element of a name without `value`, is `getAttr`'s `attribute 'name' missing` or `attribute 'value' missing` with the line `in a {name=...; value=...;} pair` (primops.cc at 2.24.9, `EvalState::getAttr` in eval.cc at 2.36.0), an element that is not a set is `expected a set but found ...`, and an argument that is not a list `expected a list but found ...`, where each had a message of its own. (#493)+- **A position's column counts bytes, as upstream's does, so `builtins.unsafeGetAttrPos`, `__curPos` and a syntax error give upstream's column on a line with non-ASCII text before the position, where a character UTF-8 spells in several bytes took one column.** Upstream's lexer advances its location by the length in bytes of everything it reads (`adjustLoc`, lexer-helpers.cc, run for every match by `YY_USER_ACTION`, lexer.l), a position is the byte offset where its token begins (`ParserState::at`, parser-state.hh), and the position table makes its column one past that offset's distance from the start of its line (`PosTable::operator[]`, nixexpr.cc at 2.24.9, pos-table.cc at 2.36.0). The lexer here now counts the same way, so each position after a U+00E9 on its line is a column further than it was, for the character's second byte. A UTF-16 source's syntax error counts the bytes of its UTF-8, which is what the lexer reads. (#494)+- **`==`, `!=` and list `<` force a value both sides share before taking it as equal to itself, so `let x = throw "x"; in [ x ] == [ x ]` fails with `x`, as it does under upstream.** Two references to one thunk were taken as equal without forcing it, so an error inside a shared value never surfaced: a list or set compared with another holding the same values was `true` however those values failed, and so was `d == d.out` for a derivation whose arguments throw, since the two sets hold one `outPath`. Upstream's `eqValues` forces both values first and only then takes a value as equal to itself (eval.cc); it compares two derivations by their `outPath` through the same function (eval.cc), which forces the derivation, and list `<` calls it on each pair of elements (`CompareValues` in primops.cc). A list literal holds a variable's own value under both, so `[ x ]` and `[ x ]` share `x`. A function or NaN that both sides share is still equal to itself, as upstream's is. (#495)+- **`nova-nix eval` prints a derivation and exits, with and without `--strict`, and `builtins.deepSeq` on one returns, where each ran without end: a set or list reached a second time prints as upstream's repeated marker, in the eval result and in error and trace messages.** A derivation's `all` and output attributes hold the derivation itself, and the deep force behind `--strict` and `builtins.deepSeq`, and both printers, followed them each time they were reached. Upstream's `forceValueDeep` enters each value once (eval.cc), `printAmbiguous`, which `nix-instantiate --eval` prints through, prints a set or list it has printed before as the marker (print-ambiguous.cc), and so does the printer behind error and trace messages, whose `trackRepeated` is on by default (`PrintOptions::trackRepeated` in print-options.hh, `Printer::printAttrs` and `Printer::printList` in print.cc); the ones here now do the same. Each goes by identity, never by contents, so two equal sets made apart both print in full; here the identity is the C set, list or thunk cell the value lives in, which nothing frees before evaluation ends. The two printers differ where upstream's do. The result printer never marks an empty set or list, and takes a list of one or two elements as one per cell that holds it and a longer list as one however many cells hold it, since upstream keeps a short list's elements inside the value that holds the list and a longer one's in an array its copies share (`Value::listElems` in value.hh). The message printer takes a list with elements as one per cell that holds it, whatever its length, and marks the one shared empty set when it reaches it again, since upstream allocates a set built with room for no attributes as its one empty set (`EvalState::allocBindings` in attr-set.cc). A traced list that holds itself prints one level deeper than upstream's before the marker: upstream's trace hands its printer the argument's own value (`prim_trace` in primops.cc), and the printer here starts from a value with no cell. `--strict` forces the result in place and prints the result itself, where it printed a copy rebuilt while forcing, which held no set or list twice. (#488)+- **Evaluating bytecode that holds a tag the compiler never writes, an unknown opcode or an unknown operator, formals, capture or binding tag, fails the evaluation with an error that names the tag, such as `corrupt bytecode: unknown binary operator tag 200`, where five of those cases stopped the program with a Haskell `error`.** Such a tag reaches the evaluator only from a corrupt bytecode store or from code built with `Nix.Eval.CBytecode.cbcEmit` rather than by the compiler. The store hands each tag back as a whole byte or word, so no type on the decoding side can rule one out, and each decoder answers a tag outside the set the compiler writes as a failure instead. The error is an evaluation error, which `builtins.tryEval` does not catch, and the one for an unknown opcode, which read `evalBytecode: unknown opcode`, names the opcode too. (#502)+- **A derivation is fixed-output whenever its `outputHash` is set, an empty one or one that is not a string included, a fixed output's outputs must be `out` alone, and an empty hash, in `outputHash` or in the `sha256` of `builtins.fetchurl`, `builtins.fetchTarball` and `builtins.path`, is the all-zero hash upstream warns of.** `derivationStrict` took an empty `outputHash`, and one that was not a string, as absent, so `outputHash = ""` and `outputHash = 5` made an input-addressed derivation, and it wrote a fixed-output `.drv` with the one output `out` whatever `outputs` listed, so `.dev` of one with `outputs = [ "out" "dev" ]` was a missing attribute. Upstream reads `outputHash` in its pass over the attributes, coerced as every environment entry is, or as a string under `__structuredAttrs` (`derivationStrictInternal` in primops.cc), takes the derivation as fixed-output once it is set, refuses any outputs but `out` with `multiple outputs are not supported in fixed-output derivations`, and reads the hash with `newHashAllowEmpty` (`derivationStrictInternal`): an empty hash is the hash of `outputHashAlgo`'s algorithm whose every byte is zero, with `warning: found empty hash, assuming 'sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA='` on stderr, and is refused with `empty hash requires explicit hash algorithm` when `outputHashAlgo` names no algorithm upstream knows (hash.cc). nova-nix now does the same, so `outputHash = 5` fails with `hash '5' has wrong length for hash algorithm 'sha256'` given that algorithm and with `hash '5' does not include a type, nor is the type otherwise known from context` given none, and `outputHash = null` is the empty hash unless `__ignoreNulls` leaves it out. The fetchers read their pins with the same function (`fetch` in fetchTree.cc, `prim_path` in primops.cc), where an empty one failed on its length: it is now the all-zero hash with the same warning, read with the other arguments before anything is fetched, as a pin that does not parse now is too. A fetch whose content does not match its pin fails with upstream's message: `hash mismatch in file downloaded from '...'` with both hashes in nix32 for `fetchurl` (`fetch` in fetchTree.cc at 2.24.9), and `store path mismatch in (possibly filtered) path added from '...'` for `builtins.path` (`addPath` in primops.cc); `fetchTarball` refuses a tree that does not match in 2.36.0's words, as the entry on its in-process unpacking says. The exit status is still 1, where upstream's `fetchurl` and `fetchTarball` exit with 102 (`fetch` in fetchTree.cc). (#500)+- **The builtins that read a plain string refuse one with string context, as upstream's do: the regex of `match` and `split`, `getEnv`, the name of `toFile`, the algorithm of `hashString` and `hashFile`, `fromJSON`, `placeholder`, `parseDrvName`, `splitVersion`, both arguments of `compareVersions`, and the name `findFile` looks up.** Each read the string's text and dropped its context, so `builtins.toFile (builtins.appendContext "a" { ... }) "x"` wrote a file and `builtins.match` of such a regex matched. Upstream reads each with `forceStringNoCtx` (`prim_getEnv`, `prim_placeholder`, `prim_findFile`, `prim_hashFile`, `prim_fromJSON`, `prim_toFile`, `prim_hashString`, `prim_match`, `prim_split`, `prim_parseDrvName`, `prim_compareVersions` and `prim_splitVersion` in primops.cc), which refuses one with context as `the string 'a' is not allowed to refer to a store path (such as '...')`, naming the context's first element (eval.cc), and now so does nova-nix, with the reader that computed attribute names already use. A value that is not a string is refused in those positions with that function's `expected a string but found ...`, where each builtin had a message of its own. `findFile` reads the name after its search path entries, as upstream's does, so a failing entry is reported ahead of the name, and `match` and `split` compile the regex before they look at the subject, as upstream's do, so an invalid regex is reported ahead of a subject that is not a string. (#505)+- **`builtins.split` of a string its regex does not match gives back the string with its context, as upstream's does.** It rebuilt the string without context, so `builtins.hasContext (builtins.head (builtins.split "x" s))` was false for a string `s` with context; upstream returns the argument value itself there (`prim_split` in primops.cc). The pieces of a string the regex matches carry no context under either. (#505)+- **`builtins.addErrorContext` adds its message to the trace of a failure inside it, which `nova-nix eval` prints above the error, and forces the message only when its value fails.** It returned its second argument and added nothing, and it forced both arguments as it was applied, so `builtins.addErrorContext "ctx-marker" (throw "x")` reported `error: x` alone where nix-instantiate prints a line of context, `ctx-marker`, above it, and `builtins.addErrorContext (throw "a") 1` failed with `a` where upstream gives `1`. Upstream's `prim_addErrorContext` forces the value inside a `catch`, and only there coerces the message, as a string, a path or a set with `__toString` or `outPath`, without copying a path into the store, then adds it to the failure's trace and rethrows the failure (primops.cc at 2.24.9), and nova-nix now does the same. The failure keeps its kind, so a throw inside stays catchable by `builtins.tryEval`, and nested contexts are listed outermost first. A message that fails itself, by throwing or by not coercing, leaves the value's failure in place, with a line naming the message's failure, as the entry for upstream 2.36.0's `addErrorContext` below describes, so `builtins.tryEval (builtins.addErrorContext 1 (throw "x"))` catches the throw. An empty message adds no line of its own, as upstream's `showErrorInfo` passes over a trace whose text is empty (error.cc). The parity job compares the line of context `ctx-marker` adds with nix-instantiate's. (#517)+- **Evaluation runs 1.7 to 2.4 times as fast and allocates 40 to 50% less: the evaluator is compiled for the monad `nova-nix` runs it in.** The evaluator in `Nix.Eval` is written over any `MonadEval`, and nothing compiled it for `EvalIO`, the monad the executable and `Nix.Eval.IO` run it in, so every bind and every class method in it was a call through the instance dictionary, which GHC can neither inline nor fuse. The library now builds with `-fspecialise-aggressively -fexpose-all-unfoldings`, and `Nix.Eval.IO` specialises `eval`, `deepForce` and `selectAttrPath` to `EvalIO`, exporting rules that send a call at `EvalIO` in any module to that code. The flags alone would leave the executable's own call of `eval` on the dictionary-passing evaluator, since `eval` is small enough to be inlined into `Nix.Eval.IO` rather than given a rule there. `EvalIO`'s actions are also built one-shot, the trick GHC's own `IOEnv` uses, so an action takes the evaluator state and the IO world as arguments instead of returning a closure that waits for them. On `profiling/stress.nix`, `fib 30`, two million three-level selects and two million `elemAt`s, best of five on an Apple M2, time falls from 0.81, 2.22, 2.34 and 5.21 s to 0.46, 0.93, 1.32 and 2.47 s, with the one-shot actions worth 8 to 12% of it, and the results are unchanged. A clean build of the library takes about 13% longer, 94 s where it took 83 s on the same machine, the executable and test suite about 7% longer, and the stripped executable is 2% larger. The evaluator's source stays polymorphic, and the test suite still runs it in its pure monad. (#521)+- **`outputHashMode = "nar"` hashes a fixed output as a NAR, as `recursive` does, and a mode upstream does not take is refused for every derivation, with or without an `outputHash`.** `derivationStrict` read `recursive` as a NAR hash and every other value as a flat one, so `outputHashMode = "nar"` gave the flat output's path and `outputHashMode = "foo"` was accepted. Upstream's `handleHashMode` reads the mode in its pass over the attributes, whatever else the derivation holds (`derivationStrictInternal` in primops.cc): `recursive`, kept as the older name of `nar`, and `nar` hash a NAR and `flat` the output's bytes (`ContentAddressMethod::parse`, content-address.cc; `parseFileIngestionMethod`, file-content-address.cc), `text` and `git` need the `dynamic-derivations` and `git-hashing` experimental features, and any other value fails with `invalid value '<mode>' for 'outputHashMode' attribute`. nova-nix now does the same. It implements neither feature, so `text` and `git` fail as upstream fails with them off, whatever `experimental-features` says, with `experimental Nix feature 'dynamic-derivations' is disabled; add '--extra-experimental-features dynamic-derivations' to enable it` and its `git-hashing` twin. A refused mode fails at its attribute in name order, under the line `while evaluating attribute 'outputHashMode' of derivation '<name>'`, so before a missing builder or system is reported, and `builtins.tryEval` does not catch it. An empty mode, which `outputHashMode = null` coerces to unless `__ignoreNulls` leaves it out, is refused too. From 2.33.0 upstream's `text` refusal also names the derivation and its mode; nova-nix keeps 2.24.9's words. The parity job compares the paths of `nar`, `recursive` and `flat` and these refusals with nix-instantiate's. (#528)+- **`nova-nix eval` writes a census of its C data layer to the file `NOVA_NIX_C_STATS` names: the objects and bytes of each kind it allocated, those the result, the root environment, the import cache and the search path still reach once evaluation returns, and what finding them cost.** The C data layer holds most of an evaluation's memory, and nothing said where that memory went: a heap profile sees GHC's heap alone. Upstream reports its own figures under `NIX_SHOW_STATS` (`EvalState::maybePrintStats` and `EvalState::printStatistics` in eval.cc), counts of what it allocated; the census gives those counts for the C side and also what is still reached. It reads only what the allocators already keep, and its mark frees and writes nothing. An evaluation that writes it runs without the region collector, so it counts everything the evaluation allocated. What it reaches is exact for those roots. A C object that only a Haskell value outside them holds is counted as unreached. Symbols are reached through the values that hold them and not through the compiled code that names them, and code is counted but never marked, since nothing frees it before the session ends. (#531)+- **A program's names are interned in the order upstream's parser interns them, so a set holds its attributes in upstream's order and `let za = 1; in ({ }: za) { zb = 1; za = 2; }` names `za` as the unexpected argument, as upstream does, where it named `zb`.** Both evaluators hold a set's attributes sorted by symbol (`Bindings`, attr-set.hh at 2.24.9), and a symbol's place is the order its name was interned in, so that order decides which of two failures wins wherever a walk over a set stops at the first: the unexpected argument a call names is the first in symbol order (`EvalState::callFunction` in eval.cc). Upstream's parser interns each name in the action of the rule that reads it (the grammar rules of parser.y), and bison runs a rule's action once the rule's right-hand side is parsed, the deferred actions of its GLR stacks included: a variable where it is read, an attribute path's names before the value bound to it, a `let`'s bindings before its body, a set of formals before the function's body and each formal after its default, an attribute path before its `or` default, and a plain `x:` argument and an `@` name after the function's body. nova-nix interned names as its compiler met them: a `let`'s body before its bindings, a function's body before its formals, an `or` default before its path, a variable bound in scope only where it is bound, and an attribute path written in several places as one set. The parser now notes each name where upstream's interns one, and the evaluator interns them in that order before it compiles. A key whose expression is an indented string of a single literal piece, which upstream's parser makes static, stays dynamic here and is interned only when it evaluates. (#525)+- **`builtins.path { recursive = false; }` copies the one file at the path by its bytes, to the flat fixed-output path upstream gives it, and an argument `builtins.path` does not take is refused.** `builtins.path` never read `recursive`, so `recursive = false` still copied the file as a NAR and gave the NAR's path, and it passed over any argument it did not know, so a misspelt `sha256` left the copy unpinned. Upstream's `prim_path` reads its arguments one at a time in the set's own order (primops.cc at 2.24.9): `recursive` is a Boolean choosing a NAR or a flat copy, and any argument but `path`, `name`, `filter`, `recursive` and `sha256` fails at its turn with `unsupported argument '<name>' to 'addPath'`, before the path is looked for or anything is copied. For a flat copy `addPath` hands `fetchToStore` the path with its symlinks resolved, whose flat dump reads the file's bytes and calls no filter (`addPath` in primops.cc; the flat case of `dumpPath` in file-content-address.cc), so the pin is the SHA-256 of those bytes, a pin that differs fails with `store path mismatch in (possibly filtered) path added from '<path>'` as it does for a NAR copy, and a directory fails that read with `reading from file '<path>': Is a directory` (`PosixSourceAccessor::readFile` in posix-source-accessor.cc). nova-nix now does the same. From 2.26.0 upstream names `builtins.path` in the refusal of an argument where 2.24.9 names `addPath`, and from 2.34.0 it refuses a directory through another read, in other words; nova-nix keeps 2.24.9's. The parity job compares the flat copy's path, pinned and not, and both refusals with nix-instantiate's. (#537)+- **The census `NOVA_NIX_C_STATS` writes counts the environments and attribute sets by the construct or builtin that allocated them, and the environments by number and by size.** Over a nixpkgs slice environments took nearly five times upstream's bytes and attribute sets numbered 1.6 times upstream's (#529, #530), and the census gave each kind's bytes without saying which constructs allocated them, so nothing showed which to make smaller or stop allocating. Every environment and attribute set allocation now names its site: a call, a call with formals, a closure, a `let`, a `rec` set and what each captures, `inherit (from)`, `with`, a set literal, `//`, and each builtin that makes a set. With the variable set the allocators count each allocation under its site from the arena's start: environments with their slots and bytes and by slot count, which also gives the number of environments, and sets with their bytes and how many equal a set that already existed, an empty set or a `//` result with an empty operand, neither of which upstream allocates (`EvalState::allocBindings` in attr-set.cc and `ExprOpUpdate::eval` in eval.cc). Without the variable an allocation tests one flag and counts nothing. `profiling/bench.sh --memory` reports the figures, the environments' slots beside upstream's `envs.elements`. (#539)+- **A key written `${"a"}`, a double-quoted string with no interpolation between `${` and `}`, or a URI there, is the name it spells, as upstream's parser makes it, so `let ${"a"} = 1; in a` is `1` and `let a = 1; in { inherit ${"a"}; }` inherits `a`, where both were syntax errors.** Upstream's `attrpath` and `attrs` rules make a key a name when its expression is a plain string, an `ExprString`, and dynamic only otherwise (parser.y); a double-quoted string with no interpolation is one, and so is a URI (the `URI` case of `expr_simple` and the `string_parts` rule, parser.y), parenthesized or not. nova-nix made a key a name only when it was written as a double-quoted string, so a `${"a"}` key stayed dynamic: refused in a `let` and in an `inherit`, outside a `rec` set's scope, so `rec { ${"a"} = 1; b = a; }` failed as an undefined variable, and apart from the same name written bare, so `{ ${"a"}.b = 1; a.c = 2; }` failed when evaluated where upstream merges the two paths, and `{ b = 1; ${"b"} = 2; }` failed when evaluated where upstream refuses it as it parses. A dynamic key in an `inherit`, `inherit ${x};` or `inherit "${x}";`, fails with upstream's `dynamic attributes not allowed in inherit` at the key's start. A `${ }` key whose string is not UTF-8 is a syntax error at the key, as a double-quoted one already was, where it failed only when its set was evaluated; upstream makes a name of any bytes. A key whose expression is an indented string stays dynamic: upstream makes it a name when `stripIndentation` (parser-state.hh) leaves it a single piece, and this parser holds an indented string as its unstripped pieces until it is evaluated. (#542)+- **A keyword other than `or` is no attribute name, as upstream refuses it, so `{ if = 1; }`, `x.then` and `inherit rec;` are syntax errors at the keyword, where they named an attribute `if`, `then` or `rec`.** Upstream's grammar takes an attribute name, in a binding, a selection, a has-attribute test or an `inherit`, as an identifier or `or` (the `attr` rule, parser.y), and its lexer makes `if`, `then`, `else`, `assert`, `with`, `let`, `in`, `rec` and `inherit` tokens of their own (the keyword rules of lexer.l), so an attribute named like one is written as a string there, `{ "if" = 1; }` and `x."then"`, as it now must be here. `true`, `false` and `null`, which upstream's lexer reads as identifiers, stay attribute names. (#543)+- **The names upstream's evaluator interns as it starts are interned first, in its order, so `({ }: null) { zzz = 1; x = 2; }` names `x` as the unexpected argument, as upstream does, where it named `zzz`.** A set holds its attributes in symbol order, and a symbol's place is the order its name was interned in, so that order decides which failure wins wherever a walk over a set stops at the first. Upstream's `EvalState` interns its static symbols as it is constructed (the `EvalState` constructor in eval.cc at 2.24.9), then every name `createBaseEnv` installs, each followed by that name less a `__` prefix (`EvalState::createBaseEnv` in primops.cc, `EvalState::addConstant` and `EvalState::addPrimOp` in eval.cc), then the names of its `derivation` wrapper, which it parses last (the end of `EvalState::createBaseEnv` in primops.cc, primops/derivation.nix), before it parses a program; `x` is one of the wrapper's. nova-nix interned its builtins' names in name order when a program first used them, after the program's own. The order of the primops is the order their files' static initializers run in: link order at 2.24.9, and the same order at 2.35.0, which compiles the files as one unity build. The release builds of 2.27.0 through 2.34 link under GCC's link-time optimization, which runs the initializers in reverse, so there `getContext` comes before `toString`; nova-nix follows the order 2.24.9 and 2.35.0 share. The order still differs under `pure-eval`, where upstream leaves out `currentTime` and `currentSystem` and their `__` spellings, and with an experimental feature on, whose primops upstream then installs. (#540)+- **A call to a set pattern checks for a missing argument before an unexpected one and words both as upstream does, naming the function, and a select of a missing attribute and `abort` word their failures as upstream does: `({ a }: a) { b = 1; }` fails with `function 'anonymous lambda' called without required argument 'a'`, `let f = { }: 1; in f { a = 1; }` with `function 'f' called with unexpected argument 'a'`, `{ a = 1; }.b` with `attribute 'b' missing` and `abort "boom"` with `evaluation aborted with the following error message: 'boom'`.** An argument's or attribute's name prints as upstream prints a symbol, bare when the lexer reads it as an identifier and otherwise as a string literal (`({ }: null) { "a b" = 1; }` names `'"a b"'`, the empty name `'""'`), as upstream writes a symbol through `printIdentifier` (the `operator<<` for `SymbolStr` in nixexpr.cc); the function's name prints as its binding spells it, as upstream passes it as a plain string. nova-nix named the unexpected argument first, as `unexpected attribute 'b' in function argument`, listed every missing argument and the keys given, named a missing attribute by its whole path with the set's keys, and printed `abort`'s message alone. Upstream's `callFunction` checks each formal in symbol order, which its parser sorts formals into, and stops at the first that has neither an argument nor a default, then names the first attribute in symbol order that no formal names (eval.cc, and `ParserState::validateFormals` in parser-state.hh); both carry the line `from call site`, and an argument that is not a set fails as `expected a set but found ...` with that line and `while evaluating the value passed for the lambda argument` (`EvalState::callFunction` in eval.cc). A function takes the name of the attribute a set or `let` binds it to, as does a function that is its body (`ParserState::addAttr` in parser-state.hh, `ExprLambda::setName` in nixexpr.cc), and is otherwise `anonymous lambda`. A select reads each name before it forces the value it selects from, fails at a value that is not a set as `expected a set but found ...` with `while selecting an attribute`, and names the one name a set lacks (`ExprSelect::eval` in eval.cc); `abort` words its message (`primop_abort` in primops.cc). The wording and the printing of names are the same at 2.34.9 and 2.35.4. Neither the position each of these errors carries upstream nor the `Did you mean` suggestions it prints with an unexpected argument or a missing attribute are printed, and the `from call site` line is not added where forcing the argument itself fails, nor `while evaluating the attribute` to a failure under a select. The traces are upstream's with `show-trace` off, its default, which adds no lines for the calls a failure in a function's body passes through (`EvalState::callFunction` in eval.cc). Upstream also names a function under a dynamic key, with the name the key evaluates to, each time it evaluates the set (`ExprAttrs::eval` in eval.cc); such a function is `anonymous lambda` here. (#540)+- **Evaluation is faster and allocates less, and every read of and allocation in the C data layer runs where the evaluation reaches it: the evaluator reaches C through actions of its own monad.** Thunks, environments, attribute sets, lists, lambdas and the bytecode live in C, and the evaluator reached them through functions that looked pure and made their C call under `unsafePerformIO` whenever GHC demanded the result. Each read of an instruction's field built a lazy thunk and paid `unsafePerformIO`'s duplication check, and an allocation ran whenever its result was first needed rather than where the evaluation made it, which no collector of C memory can work with: a cell made at an unknown moment cannot be assigned to the force or call that made it. Every read, write and allocation is now an action of `MonadCData`, which every `MonadEval` has, so in the executable each one is a direct FFI call at its point in the evaluation. Two reads stay outside a monad, each in `Nix.Eval.CData` with the invariant that makes it sound: an interned symbol's bytes, which do not change once interned and are copied while no intern runs, and a whole computation run as a value, which is how the pure test evaluator runs. The `Show` and `Eq` instances of the C handles read no C memory: two thunks, sets, lists or environments are equal when they are one C object, and each shows as its address. On `profiling/stress.nix`, `fib 30`, two million three-level selects and two million `elemAt`s, best of five on an Apple M2, time falls from 0.54, 1.03, 1.59 and 3.07 s to 0.44, 0.58, 1.13 and 2.25 s and allocation from 2.43, 6.68, 8.08 and 13.07 GB to 1.86, 3.49, 5.48 and 8.15 GB, and two results change, each to upstream's, because the calls behind them now run where the evaluation reaches them; each has an entry of its own. A variable lookup that would read a slot its frame has not filled yet, which only a defect in the resolver or the frame builder makes, raises `CInvariantViolated` naming `nn_env_lookup_resolved` where it handed on a NULL cell that faulted at its first force. (#552)+- **A failed `builtins.tryEval` returns a set of its own, so `nova-nix eval --strict` prints two failed results in full, where it printed the second as upstream's repeated marker.** Upstream's `prim_tryEval` builds the result's bindings on each call, a failed one included (primops.cc), and the printer marks a set as repeated only by identity, so `[ (builtins.tryEval (throw "a")) (builtins.tryEval (throw "b")) ]` prints `{ success = false; value = false; }` twice under both. Every failed `tryEval` here returned the same set. (#552)+- **A type error shows an attribute that is still being forced as the potential infinite recursion marker, as upstream's does, where it showed the thunk marker.** Upstream renders the value a type error names as it builds the error: `forceList` hands the value to the message (eval-inline.hh), and `HintFmt` formats each argument as it is given (fmt.hh), while the attribute is still being forced, and the printer shows such an attribute as that marker (`Printer::printThunk` in print.cc). So `let x = { a = builtins.length x; }; in x.a` fails with `expected a list but found a set`, its `a` printed as the marker, under both. nova-nix rendered the message when it was shown, by which time the failed force had put the attribute back to unevaluated. (#552)+- **Environments take less than half the memory they did: a call's environment of one value takes 16 bytes where it took 56, and one with no parent and no scopes takes 8 bytes and 8 per value, as upstream's does.** An environment was a 48-byte struct in front of a separate array of its values, with room in every one for a name table and with-scopes that only a `with`, a root environment and a frame whose names are not all static use, and over a nixpkgs slice environments took nearly five times upstream's bytes (#529). Upstream's `Env` is a parent pointer and its values (eval.hh). An environment of one to seven values and no scopes is now one word, its parent's address with its value count in the three low bits every environment's 8-byte alignment leaves clear, followed by its values; any other is a header word holding its value count and which fields follow, its values inline, then its parent when it has one and its name table and with-scopes when it has them. Everything an environment points to is found from the environment alone. An environment sees the with-scopes of the nearest environment on its parent chain that has its own, a `with`'s or a trimmed closure's, where each environment carried a copy of its parent's; a `with`'s environment copies the values of the one it is made in, and the census's counts by site and by size count them with it. On `profiling/stress.nix` the environments' bytes fall from 40.6 MB to 15.2 MB, and wall time is unchanged within run-to-run noise. What any program evaluates to is unchanged. (#559)+- **A string value no longer takes a symbol, so the names an evaluation interns keep upstream's order however many strings it makes, and `builtins.seq "zb" (({ }: null) (builtins.listToAttrs [ { name = "za"; value = 1; } { name = "zb"; value = 2; } ]))` names `za` as the unexpected argument, as upstream does, where it named `zb`.** Upstream's symbol table holds names alone (`SymbolTable`, symbol-table.hh at 2.24.9): a string value points at bytes of its own (`Value::mkString`, eval.cc), and a set's attributes are sorted by the order their names were interned in, so that order decides which of two failures a walk over a set stops at first. nova-nix interned every string value in the same table, and so every string, URI, path and search-path literal, every source file's path and every store path and output name in a string's context, each moving the place of every name interned after it. A string's or a path's bytes now live in an arena of their own, made once where the string is made and shared by every cell that comes to hold it, as upstream copies a `Value` with the pointer to its bytes (value.hh at 2.24.9); the value of a string or URI literal, and of a path literal written in canonical form, is the literal's bytes in the compiled code, as upstream's `ExprString` hands out the value it holds (`ExprString::maybeThunk` in eval.cc). Equal strings made apart are two copies, where the symbol table kept one, as upstream's `makeImmutableString` copies the bytes of each string it makes (eval.cc); every empty string is one static, as upstream's is. A string holds at most 4 GiB of bytes, where upstream's has no bound of its own: its length is a `uint32_t`, the per-allocation limit across the C data layer, and a longer one fails evaluation with `CAllocationFailed` naming `nn_str_new`. The order in which a builtin makes the strings it returns no longer shows. The census `nova-nix eval` writes under `NOVA_NIX_C_STATS` counts strings as a kind of their own (`strings.*`), and its `symbols.*` lines count names alone: on `profiling/stress.nix` it counts 10,290 symbols where it counted 350,301, and 530,004 strings of 10.6 MB, and the bytes the allocators hold beyond their objects fall from 17.0 MB to 4.4 MB. (#559)+- **`==` on two sets compares them pair by pair in the order their names were interned, each pair's names and then its values, so `{ zb = 1; za = throw "a"; } == { zb = 2; za = 1; }` is `false` and `{ zq1 = throw "x"; zq2 = 1; } == { zq1 = 1; zq3 = 1; }` fails with `x`, as under upstream.** The two sets' name lists were compared whole before any value, then the values in name order, so the first failed with `a` and the second was `false`. Upstream's `eqValues` compares two derivations by their `outPath`, takes sets of different sizes as unequal without forcing a value, and then walks both sets' `Bindings` together, comparing each pair's names and then its values and stopping at the first difference (the `nAttrs` case of `EvalState::eqValues` in eval.cc). `Bindings` are sorted by `Symbol`, whose order is the order the symbol table interned the name in (attr-set.hh, symbol-table.hh); a set here is sorted by its own symbol table the same way, and nova-nix interns names in upstream's order: its startup names first, then each name where upstream's parser interns it, and no string value at all, so two sets compare in upstream's order. The order decides only which failure wins, never whether two sets are equal. Comparing two sets reads one entry of each at a time, where it copied both sets' names and values first. (#559)+- **`builtins.listToAttrs`, `builtins.groupBy` and `builtins.fromJSON` intern each name of the set they build as they meet it, as upstream's do, so `({ }: null) (builtins.listToAttrs [ { name = "zb"; value = 1; } { name = "za"; value = 2; } ])` names `zb` as the unexpected argument, as upstream does, where it named `za`.** A set holds its attributes in the order their names were interned (`Bindings`, attr-set.hh at 2.24.9), and that order decides which of two failures a walk over a set stops at first: the unexpected argument a call names and the pair `==` forces first. Upstream's `prim_listToAttrs` interns an element's name as it reads it, before the next element (primops.cc), `prim_groupBy` interns the name its function returns before it calls the function on the next element (primops.cc), and `builtins.fromJSON` interns a member's name as the parser reaches it, before the member's value (`JSONObjectState::key` in json-to-value.cc), so a name the document repeats keeps the place its first occurrence gave it and takes its last value. nova-nix collected each builtin's names by name and interned the ones new to its table in name order as it built the set. Each now interns a name where upstream's does, and `builtins.fromJSON` reads an object's members in document order, so `({ }: null) (builtins.fromJSON "{\"zb\": 1, \"za\": 2}")` names `zb`, and `builtins.listToAttrs [ { name = "zb"; value = throw "b"; } { name = "za"; value = 1; } ] == builtins.listToAttrs [ { name = "zb"; value = 1; } { name = "za"; value = throw "a"; } ]` fails with `b`, as under upstream. (#564)+- **Every value lives in the C data layer: a builtin and a builtin applied to some of its arguments are C values, so no value sits in GHC's heap behind a StablePtr, and the census follows the whole value graph in C.** A builtin value and a partial application were the last values a thunk held as a StablePtr to a Haskell value, so a collector in C could not reach the cells a partial application held. A builtin is now its index, inline in its cell, and a partial application is a C object holding the builtin's index and the cells of the arguments it has taken, as upstream's `tPrimOp` and `tPrimOpApp` hold a primop and the values applied to it (value.hh at 2.24.9). The builtin bound under its own name is one static cell per builtin, as upstream binds one value per primop (`EvalState::addPrimOp`, eval.cc), so it is the same value in every file and survives the arena's teardown. `match` and `split` hold their pattern as a string and compile it through the cache keyed by the pattern on each call, as upstream's `RegexCache` does (primops.cc), where a partial application held the compiled regex; the regex engine is unchanged. Applying a builtin now selects its implementation by its constructor rather than by comparing its name with each builtin's: on an Apple M2, best of three, two million saturated builtin calls take 1.40 s where they took 1.74 s, and 200,000 calls through a stored `builtins.elem` and a stored `builtins.match` take 0.47 s where they took 0.53 s. The census `nova-nix eval` writes under `NOVA_NIX_C_STATS` counts partial applications as a kind of their own (`primopapps.*`). What any program evaluates to is unchanged. (#565)+- **The `derivation` wrapper names its values as upstream's does, so `({ }: null) (import ./f.nix)`, where `f.nix` is `{ zz = 1; shared = 2; }`, names `zz` as the unexpected argument, as upstream does, where it named `shared`.** A set holds its attributes in the order their names were interned, and upstream interns its wrapper's names as it starts, before any program's (primops/derivation.nix at 2.24.9). nova-nix's wrapper named four of its values `paths`, `entries`, `shared` and `entry`, which upstream's names `strict`, `outputsList`, `commonAttrs` and `x`, so compiling it interned those four after the first program's names and before every name a file imported later brings. It now uses upstream's names, which nova-nix interns as it starts too, so compiling it interns nothing. Its structure, and every position a program can read from it, is unchanged. (#567)+- **`builtins` no longer holds `fetchTree`, `fetchClosure` or `outputOf`, so `builtins ? fetchTree` is `false` and `builtins.fetchTree` fails as a missing attribute, as under upstream's default settings, where it was a function that failed when called.** Upstream registers the three only with an experimental feature on (`fetch-tree`, `fetch-closure` and `dynamic-derivations`; `primop_fetchTree` in fetchTree.cc, `primop_fetchClosure` in fetchClosure.cc and `primop_outputOf` in primops.cc), and nova-nix implements none of those features, so `builtins` leaves the three out whatever `experimental-features` says, and a program testing for one with `?` takes the branch it takes under upstream's default settings. Their names are no longer interned with the base environment either, where they took their place ahead of a program's own names. (#567)+- **An evaluation builds its base environment once, and evaluates every file it imports in it, as upstream's does, where each imported file built the root environment and the `builtins` set again; and every C value the evaluation keeps from one step to the next is registered as a root.** Upstream's `EvalState` builds one base environment as it is constructed (`createBaseEnv`, primops.cc at 2.24.9), with the `derivation` wrapper in it, and keeps its import cache where its collector scans it (`fileEvalCache`, eval.hh). An evaluation session now builds its base environment as it starts, over the policy and the search path it is given, with the session's own `derivation` wrapper, where the wrapper was one value for the process. The empty list's cell is a C static, like `null`'s. So no constant of the program points into the C data layer's arena, and tearing the arena down and setting it up again starts evaluation afresh. The base environment, with the search path in `builtins.nixPath`, and each value the import cache keeps are registered as roots (`Nix.Eval.CRoots`), which the census `nova-nix eval` writes under `NOVA_NIX_C_STATS` marks from. What any program evaluates to is unchanged. (#567)+- **An empty attribute set is one shared set wherever upstream shares one, and `//` with an empty operand gives the other operand's set, so neither allocates a set.** Upstream's `allocBindings` answers a size of 0 with its one `emptyBindings` (attr-set.cc), which `{ }` and every builtin that sizes its result by what it holds then hold, and `ExprOpUpdate::eval` copies the other operand's value when one is empty (eval.cc). nova-nix allocated a new set for each, and over the first 2,000 attributes of nixpkgs 24.11 the census counted 2,167,080 of its 5,815,653 sets as built empty or as an update with an empty operand (#530). Of the sets nova-nix makes, upstream sizes three before it knows they hold nothing, and gives each bindings of its own: `removeAttrs` of every attribute of a set (`prim_removeAttrs` in primops.cc), `intersectAttrs` of two sets with attributes and no name in common (`prim_intersectAttrs`), and a literal whose every name is a null `${...}` (`ExprAttrs::eval` in eval.cc); each is a set of its own here too. Both printers enter a set by its bindings (`Printer::printAttrs` in print.cc, `printAmbiguous` in print-ambiguous.cc), so these identities show where a value is printed: `let a = { x = 1; }; in [ a (a // { }) ]` prints the update as upstream's repeated marker under `nova-nix eval --strict`, where it printed the set twice, and an error or trace message prints each of the three empty sets of their own in full after the shared one, where it printed it as the marker. The census counts no shared set, and counts as shareable only a set made equal to one that already exists where upstream makes none, so the three are not. (#568)+- **Evaluation runs in a session that owns the C data layer, so no caller sets the data layer up or tears it down: `Nix.Eval.IO.withEvalSession` sets it up when no session holds it, makes the session's state, and tears it down as the outermost session ends, on an exception too.** A library caller had to wrap evaluation in `bracket_ arenaInit arenaDestroy`, and leaving that out raised `ArenaNotInitialized` at the first C call. A session now owns the window: a nested session shares the arena of the one around it and forgets the roots it registered as it ends, so the roots a mark over the C data layer starts from, as the census's does, are what the open sessions hold. `nova-nix build` ends its evaluation's session before it builds, so the evaluation's memory is freed before the build starts. (#574)+- **A builtin's deferred application of a function, one per element of `map`, `genList`, `mapAttrs` and `zipAttrsWith`, holds the function's and the arguments' cells and no environment, as upstream's is an app value: 16 bytes where it took 24, and 24 for a name and a value where it took 32; `concatMap` calls its function on each element and defers nothing.** Over the first 2,000 attributes of nixpkgs 24.11 those builtins allocated 3.87 million environments of 109.3 MiB, a sixth of the environments' bytes, and upstream 2.24.9 allocates none of them: its `prim_map`, `prim_genList`, `prim_mapAttrs` and `prim_zipAttrsWith` make app values holding the function and its argument, and `prim_concatMap` calls `callFunction` on each element (primops.cc at 2.24.9). A pending thunk now holds either code and the environment it runs in, or such an application: the cells of its function and arguments in an array of the environment pages, which forcing it applies in a call frame of its own with the function forced inside it, as upstream's `forceValue` on an app value does, and with a second frame for the first of two arguments, as upstream's two nested app values have. So the call depth at which a callback is refused, the error it raises and what `tryEval` catches are unchanged. The census `NOVA_NIX_C_STATS` writes counts the arrays as a kind of their own (`apps.*`), which the memory report of `profiling/bench.sh` gives a row. On `profiling/stress.nix` environments take 9.8 MB where they took 15.2 MB, beside 3.6 MB of applications' cells; it runs 3% faster, and a sum over a `map` of a `genList` of 100,000 elements 13% faster, while `fib 30`, which makes no such application, runs about 2% slower. What any program evaluates to is unchanged. (#575)+- **The names an `inherit (from)` clause binds select from one environment holding the from-value, where each name had an environment of its own.** Upstream 2.24.9 makes one environment for the from-values of a binding set, in which each inherited name's select runs (`ExprAttrs::buildInheritFromEnv`, eval.cc); over the first 2,000 attributes of nixpkgs 24.11 nova-nix made 505,134 environments for `inherit (from)`, one per name (#529). The clause's from-value was already one thunk for all its names, so each name reads the same value it did. On a program evaluating `let inherit (s) p q r;` 100,000 times, `inherit (from)` makes 100,000 environments where it made 300,000. What any program evaluates to is unchanged. (#575)+- **Reading a symbol id the symbol table does not hold raises `CInvariantViolated` naming `nn_symbol_text` or `nn_symbol_len`, and outside an evaluation session `ArenaNotInitialized`, where it read as an empty name.** Within a session only a defect makes such an id, and an empty name surfaced it as a wrong name far from its cause. The invalid id (`Nix.Eval.Symbol.invalidSymbolId`), an anonymous lambda's name, still reads as no name. (#576)+- **An imported file is evaluated once per evaluation whatever its value, as upstream caches every file: `import ./f.nix == import ./f.nix` is `true` for a file whose set holds a function, and a trace in it prints once, where a file whose value is a set of 1,000 or more attributes was evaluated again by every import.** Upstream's `evalFile` answers a later import of a file from `fileEvalCache`, which keeps every file's value (eval.cc). Leaving a large set out of the cache freed nothing, since a session's values are freed when the session ends. (#582)+- **A resolved variable lookup whose level or index holds nothing, and a code string index no emit returned, raise `CInvariantViolated` naming `nn_env_lookup_resolved` or `nn_bc_string`, where the process aborted; every other C bound aborts in every build, `NDEBUG` or not.** Each of those checks was an assert followed by a fallback for the same condition, commented as what a build under `NDEBUG` does, and no build defines `NDEBUG`, so the assert aborted first; under `NDEBUG` several fallbacks would have answered a plausible wrong value. The two the Haskell boundary already reports now return NULL for it to raise, so the defect is reported with its site, a level read from a corrupt bytecode word past `INT_MAX` among them, and the rest guard indices the library produced itself and keep only their assert. (#587)+- **The library exports what its callers use, and an evaluation session alone sets up and tears down the C data layer.** The binding modules exported the layer's lifecycle, so a library caller could destroy the memory an open session was using, and exported names nothing outside their module used, which a caller could come to depend on. The lifecycle's foreign imports are in the internal `Nix.Eval.Arena`, where an evaluation session (`Nix.Eval.IO.withEvalSession`) calls them. (#589)+- **A closure or string context element holding a tag the C side does not name raises `CInvariantViolated`, where it was read as a set pattern with a name or as a whole derivation's outputs.** A lambda's formals type and a context element's tag are read against the constants the C side names (`NN_FORMALS_*`, `NN_SCE_*`), so memory written past the library is reported with the site that read it rather than evaluated as another value. A with-scope count at its limit, which only corrupt state reaches, aborts at the check that names it, where it was reported as an allocation failure, so a C allocator's NULL means only that it could not allocate. (#595)+- **A variable is looked up only as its kind requires, as upstream's `EvalState::lookupVar` does, and a closure trimmed under a `with` shares the scopes it sees.** A variable a `let`, a recursive set or a global binds was also searched for in the `with` scopes when no name table held it, and a `with` variable no scope held was searched for again in every name table. Neither second search could find anything, since the parser decides each variable's kind before evaluation, and a closure trimmed to its captures under a `with` held a copy of its scopes with the builtins appended for one of them. It now shares the scopes of the environment it is made in, and one made outside every `with` holds none. (#595)+- **The parser makes `<name>` the call `__findFile __nixPath "name"`, as upstream's parser does, so neither the expression tree nor the bytecode has a node of its own for a search path.** The resolver turned that node into the same call before anything evaluated it, so the bytecode's search-path operation ran for no parsed source, and a node a library caller compiled by hand looked `builtins.findFile` up where the parser's call uses the `__findFile` in scope. (#597)+- **A select, a has-attribute test and a variable look their name up by the symbol the compiled code holds for it, so evaluation allocates less, and a select interns a name it computes before it forces the value it selects from, as upstream's does: `builtins.seq ({ s = builtins.listToAttrs [ { name = "z" + "b"; value = 1; } ]; }.s.${"z" + "a"} or null) (({ }: null) (builtins.listToAttrs [ { name = "z" + "b"; value = 1; } { name = "z" + "a"; value = 2; } ]))` names `za` as the unexpected argument, as upstream does, where it named `zb`.** Upstream holds a variable's name and each static name of an attribute path as a symbol from parse to lookup (`ExprVar` and `AttrName`, nixexpr.hh) and finds it in a set by that symbol (`Bindings::get`, attr-set.hh). nova-nix's compiled code holds the same symbols, but each lookup turned its symbol back into text and interned the text again to get the symbol it started from: a variable once for every name table it walked and every `with` scope it tried, and a select or has-attribute test once for every name in its path. Each lookup now passes the symbol on, and a name a select or has-attribute test computes is interned once, where upstream's `getName` interns it (eval.cc): before a select forces the value it selects from (`ExprSelect::eval`), and after a has-attribute test forces the value it tests (`ExprOpHasAttr::eval`). nova-nix interned a select's computed name after that force, so a name the force interned, as `listToAttrs` interns the names of the set it builds, took the earlier symbol, and with it the earlier place in every set holding both. On `profiling/stress.nix` evaluation allocates 1.65 GB where it allocated 1.90 GB. (#599)+- **A set binds its static names before its dynamic ones and checks each dynamic name, in source order, before it evaluates the next, and a name bound twice says where it was first defined, as upstream's does: `{ ${"a" + ""} = 1; ${throw "y"} = 2; a = 3; }` fails on `a` at the line and column of `a = 3`, where it failed with `y`, and `rec { ${"b" + ""} = 1; ${"a" + ""} = 2; a = 3; b = 4; }` names `b`, where it named `a`. Sets are also built with less allocation.** Upstream's `ExprAttrs::eval` binds a set's static attributes, then takes its dynamic ones one at a time in source order: it evaluates the name, in the set's own environment for a recursive set and in the enclosing one otherwise, skips a null, interns the name, and raises `dynamic attribute '%1%' already defined at %2%` for a name already bound, the name written as `printIdentifier` writes an attribute name, before it evaluates the next (`ExprAttrs::eval` in eval.cc). The position is the earlier definition's, as `Pos::print` writes it (position.cc): the file's path, or upstream's string marker for an `--expr` string, then the line and the column. nova-nix bound a non-recursive set's static and dynamic names together in source order, so an error in a later dynamic name could win over an earlier collision, and a recursive set checked each dynamic name against the earlier dynamic ones as it evaluated it, but against its static names only once it had evaluated them all, then named the first such collision in name order; neither message said where the name was defined. It also interned a set's dynamic names only as it built the set, in name order, so they took their places in symbol order, which decides the order of a set's attributes, by name rather than in source order, as upstream's take theirs. In an expression built through `Nix.Expr`, which can hold what the parser refuses, a static name repeated in a set now keeps its last definition, as it did in a recursive set with no dynamic name, where a non-recursive set, a recursive set with a dynamic name and a `let` with one refused it as a dynamic attribute already defined; and a `let` with a dynamic name binds its static names before it evaluates that name, where upstream's `ExprLet::eval` never evaluates one (#602). Each set is now built from the symbols its compiled code holds, where every static name was turned into text and interned again, so on `profiling/stress.nix` evaluation allocates 1.35 GB where it allocated 1.65 GB. (#604)+- **`builtins.deepSeq` and `nova-nix eval --strict` force a set's values in the order the set holds them, by the symbols of their names, as upstream's do: `builtins.deepSeq { zb = throw "b"; za = throw "a"; } null` fails with `b`, where it failed with `a`. `mapAttrs`, `zipAttrsWith`, `intersectAttrs`, `builtins.path` and `scopedImport` read a set by those symbols too, and allocate less.** Upstream's `forceValueDeep` forces a set's values as it walks the set's `Bindings` (eval.cc), which are sorted by `Symbol`, the order the symbol table interned each name in (`Attr::operator<=>` in attr-set.hh, `Symbol::operator<=>` in symbol-table.hh). nova-nix forced them in the order of the names' text, so of two values that fail, the one whose name sorts first failed, where under upstream the one whose name was interned first does; the order decides only which failure wins. The builtins copied a whole set into a map keyed by each name's text and interned every name back into the symbol the set already held it under. Each now walks the set's own array, sorted by symbol, one entry at a time, and turns a name into text only where it is read as text. `intersectAttrs` walks the smaller of its sets and finds each name in the other, as upstream's does (`prim_intersectAttrs` in primops.cc), and `scopedImport` binds its scope's names by the scope set itself, as upstream binds the set's own values in the environment it evaluates the file in (`import` in primops.cc), where nova-nix copied them into a new set. On `profiling/stress.nix`, whose one `mapAttrs` maps 10,000 names, evaluation allocates 1.337 GB where it allocated 1.350 GB. (#605)+- **A set, a `let` and a function allocate less and evaluate faster: their bindings and captured variables are read where the compiled code holds them, and the compiler counts a binding list's names.** Each time a set or a `let` was evaluated, its bindings were decoded into a fresh Haskell list, which was then walked up to five times, once for each thing the evaluator needed from it, such as whether its frame holds its names in slots, how many slots it has and how large the set is. Each time a closure or a frame was made, its captured variables were decoded into a list of pairs. The compiler now writes at the head of each binding list how many names it binds statically and how many of its bindings have a dynamic name, which give a frame's layout, its slot count and a set's size in two reads. The bindings are folded over where the compiled code holds them, a set with no dynamic name skips the pass that binds dynamic names, and a closure's captured slots are written into its env as they are read. Results are unchanged. On `profiling/stress.nix` evaluation allocates 1.18 GB where it allocated 1.34 GB, and its mutator time falls by about 9%. (#608)+- **A function holds the names of its formals, its argument and itself as the symbols the compiled code holds for them, and a call to a set pattern finds each formal in its argument by its symbol and looks for an unexpected argument only when the argument holds attributes no formal takes, as upstream's does, so making, storing, reading and calling a function allocates less.** Upstream holds a formal's name, a function's argument name and the name its binding gives it as symbols from parse to call (`Formal` and `ExprLambda`, nixexpr.hh). Its `callFunction` looks each formal up in the argument by that symbol and counts the formals the argument fills, and only when, with no ellipsis, that count differs from the argument's size does it walk the argument for the first attribute no formal names (eval.cc). nova-nix's compiled code and closures held the same symbols, but each function made from the compiled code and each one read from a cell turned every name into text, each one stored in a cell interned every name again, and each call to a set pattern interned each formal's name to look it up, then, with no ellipsis, turned every attribute of its argument into text and compared it with every formal's name. Results and errors are unchanged. A fold making 600,000 calls to set patterns, with and without defaults, an ellipsis and an `@` name, allocates 3.16 GB where it allocated 4.35 GB, in about 25% less mutator time, and on `profiling/stress.nix` evaluation allocates 1.14 GB where it allocated 1.18 GB. (#611)+- **`builtins.zipAttrsWith` refuses a first argument that is not a function before it forces the list, as upstream's does, so `builtins.zipAttrsWith 1 [ ]` fails with `expected a function but found an integer: 1` where it gave `{ }`.** It never checked its function: given sets, it built a set of applications of the `1` that failed only when one was forced, so `builtins.attrNames (builtins.zipAttrsWith 1 [ { a = 1; } ])` was `[ "a" ]`, and it forced the list as it was applied, so `builtins.zipAttrsWith 1 (throw "b")` failed with `b`. Upstream's `prim_zipAttrsWith` forces its first argument with `forceFunction`, which takes a lambda, a builtin or a set with `__functor`, and only then forces the list (primops.cc and eval.cc), so the function fails first whatever the list holds, and nova-nix now does the same. (#613)+- **A binding, list element, call argument or default whose value is a variable holds that variable's own value wherever upstream's does, so `builtins.catAttrs "g" [ { g = map; } ] == [ map ]` is `true`, where it was `false`.** Upstream's `ExprVar::maybeThunk` binds a variable's own value when the slot it reads is filled and a thunk of its own when it is not, and makes a thunk for a variable only a `with` supplies (`EvalState::lookupVar` and `ExprVar::maybeThunk` in eval.cc), and `==` takes a value as equal to itself before it compares (`EvalState::eqValues` in eval.cc), which a function, never equal to another, shows. nova-nix shared a variable only when it read it by slot, and made each value a recursive set, a `let` or a default gives a name, but an inherited one, a thunk of its own, its frame not being built yet; it now shares a global, a variable of an enclosing scope and a name of a recursive set with a dynamic name as upstream does. A recursive set, a `let` and a set pattern fill their slots in symbol order, from an env whose slots start empty (`ExprAttrs::eval`, `ExprLet::eval` and `EvalState::callFunction` in eval.cc; `allocEnv` in eval-inline.hh), so a variable naming a sibling shares its value only when the sibling's name was interned first: `let s = rec { f = x: x; g = f; }; in builtins.catAttrs "f" [ s ] == builtins.catAttrs "g" [ s ]` is now `true`, as it is with `${"g" + ""} = f`, and with `rec { g = f; f = x: x; }` it stays `false`. A recursive set's dynamic names are bound once its static ones are (`ExprAttrs::eval`). A default naming a formal shares whatever that formal's slot holds, the argument's attribute when the call gives one, and a default naming the @-pattern shares the argument. A recursive set that binds `__overrides` makes every value but an inherited one a thunk of its own (`ExprAttrs::eval`), and does so here too, though nova-nix does not yet apply `__overrides` (#601). A constant in a recursive set, a `let` or a default is now a value rather than a thunk, as upstream's is. The compiler decides which bindings share as it compiles a frame, so a frame that has none pays one read of their count; on `profiling/stress.nix` evaluation allocates 1,134,852,296 bytes where it allocated 1,135,482,952, and a `let` binding a variable of an enclosing scope allocates 6% less over 200,000 evaluations. (#616)+- **`nova-nix eval` writes a census of regions to the file `NOVA_NIX_REGION_STATS` names: at the end of each force of a thunk, the bytes the force allocated and the bytes of them still reachable, and the most bytes collectors freeing at those points would have held.** The census `NOVA_NIX_C_STATS` writes says what is unreachable once evaluation returns, not when it became so. A collector freeing at the end of a force can free only what the force allocated and nothing reaches through the older cells and with-scopes it wrote into or the roots it registered. The census records every such write, marks from them at each force's end, stopping at older objects, and frees nothing. It reports the closes by the bytes their regions allocated, the bytes allocated outside every force, which no such collector frees, and, for collectors that mark only at the regions past a threshold of bytes, the closes that mark, their work and the most bytes held at once, freeing single objects, only whole blocks at the allocators' block sizes and at four smaller ones, or only the lines of 256 or 128 bytes in a block that hold nothing reachable, as a collector reusing a block's free lines in place would. It also counts what a close reached after an earlier close found it unreachable, the pointer a collector would have freed under. And it simulates collectors that tenure what their closes mark: past their threshold each close marks only what no such close of theirs inside it tenured, and a close marks its region whole when it is outermost or, for a collector with a budget of 1, 16 or 256 MiB, when the closes inside have tenured at least that since; their roots are the stores into tenured or older cells, which a mark of the whole reads again for each region they are older than, and the pointers their marks find into untenured objects of regions around. It reports each one's work, the bytes its marks of the whole free and the most bytes it holds beside the collector that marks again at every close, and checks that none frees anything a mark reaches. `profiling/bench.sh --memory` runs it over its slice and reports it. Without the variable an allocation tests one more flag. (#617)+- **The C data layer frees what a force of a thunk allocated once the force returns and nothing reaches it: attribute sets, list headers, lambdas, builtins' partial applications and strings with context one by one, and thunk cells, environments and strings a line of 128 bytes at a time, which later allocations reuse.** The layer freed nothing before its session ended, so one evaluation over nixpkgs held every set it had ever made, and sets are more than half of what it allocates. At the end of each force that allocated at least 16 KiB, a collector marks from the stores the force made into older cells and with-scopes and the roots it registered, entering only what no such close inside it already settled, and marks the force's whole region again once the closes inside have tenured 1 MiB since its last such mark; what the mark leaves unreached is freed. A line of a block of cells, environments or strings is freed once every object in it is, and an allocator that has filled its room next takes a run of free lines, numbered as a room of its own so that its objects are younger than every force under way. An evaluation under `NOVA_NIX_C_STATS` or `NOVA_NIX_REGION_STATS` frees nothing, since those censuses count what the evaluation allocated. A force at the top of an evaluation that allocates less than 16 KiB marks nothing, so what it leaves stays until the session ends. (#622)+- **The census `NOVA_NIX_C_STATS` writes counts the entries `//` copies into the sets it makes, as upstream counts them in `nrOpUpdateValuesCopied`.** Over the first 5,000 attributes of nixpkgs 26.05, sets made at `//` hold 1,786.5 of the 2,378.3 MiB of sets nova-nix allocates, and upstream 2.34 copies fewer entries there than 2.24 does, by layering a small right operand on the left (`ExprOpUpdate::eval` in eval.cc), so the count shows how far nova-nix's `//` is from it. A `//` of two sets that hold entries counts the entries of the set it makes, as upstream adds the merged set's size (`ExprOpUpdate::eval` in eval.cc), and one with an empty operand, which gives the other operand and makes no set, counts none, as upstream's does. `profiling/bench.sh --memory` reports the count beside upstream's. (#637)+- **`//` with a right operand of at most 16 attributes makes a layer on the left operand holding the right operand's attributes alone, as upstream 2.34 does, where it copied both operands into a new set.** Sets made at `//` held most of the bytes of sets nova-nix allocates over a nixpkgs walk (#628), and upstream 2.34 layers such a right operand on the left while the left's chain of layers holds fewer than eight sets, copying the right operand alone (`Bindings::maxLayers`, `eval-attrset-update-layer-rhs-threshold` and `ExprOpUpdate::eval`, in attr-set.hh, eval-settings.hh and eval.cc). A lookup searches the layers top first, and a walk over the set reads each name once, in symbol order, from its topmost layer, so every read answers as the merged set did. A larger right operand, or a left whose chain holds eight sets already, is merged into a new set as before. The census counts the entries a layer copies, the right operand's, as upstream adds them to `nrOpUpdateValuesCopied`, and counts a layer's own bytes, and its own entries among the sizes of the sets it reaches; the census, the object graph and the region collector follow a layer to the set under it. Over the first 2,000 attributes of the memory suite's walk of nixpkgs 26.05, `//` copies 24.5 million entries where it copied 50.1 million, the sets it makes take 433.9 MiB where they took 829.9 MiB, and in runs on macOS peak RSS falls by 287 to 336 MiB. (#652)+- **A chain of `//` merges its operands from the first, as upstream 2.34's update queue does: `a // b // c` layers `b` on `a` and then `c` on that, where it made `b // c` first and merged `a` with it.** `//` groups to the right, so a chain parses as `a // (b // c)`. Upstream 2.34 gathers a chain's operands, descending only into an operand that is itself an update, and once it has evaluated them all folds them into one set from the leftmost (`ExprOpUpdate::eval` and `ExprOpUpdate::evalForUpdate` in eval.cc), so a chain of small sets on a large one copies the small ones alone, once each. A chain one of whose operands fails merges none. (#656)+- **`nova-nix build` builds or substitutes what a path's context names before `import`, `builtins.readFile` and the other builtins that read a path read it, as upstream's import from derivation does, and `nova-nix eval` realises it as upstream's read-only evaluation does.** A path reader read the path as it was on disk with its string context dropped, so importing a derivation's output failed with `path '/nix/store/<hash>-<name>' does not exist` until something else had built it. Each reader now realises its argument's context first, as upstream's `realisePath` does (primops.cc): `import`, `builtins.scopedImport`, `readFile`, `pathExists`, `readDir`, `readFileType` and `hashFile`, `builtins.findFile` for each search path entry, and `builtins.path` and `builtins.filterSource` for a path in the store. Every path the context names must be valid, checked in upstream's order, and then each output it names is realised; when outputs several derivations lack are named, the derivation reported is the first by name, as upstream's worker takes its goals. `nova-nix build` and `nova-nix eval --aterm` add what evaluation has fetched, written or named before that (the sources it coerced, the trees it wrote, the derivations it recorded), so the store holds what upstream's would, and `build` realises through the same store handle its own build uses. `nova-nix eval` and `nova-nix trust` add nothing, as `nix-instantiate --eval` runs read-only (`main_nix_instantiate` in nix-instantiate.cc), and plain `nix-instantiate` does not. A path evaluation computed, a coerced source or a `builtins.toFile`, `builtins.path` or `builtins.filterSource` result or a derivation, is not valid there unless the store already holds it, so `import (derivation { ... })`, and equally `builtins.readFile (builtins.toFile "x" "y")`, fail with upstream's `path '<path>' is not valid`. What a fetcher fetched is readable there, since upstream's fetchers add their results in any mode (`fetch` in fetchTree.cc at 2.24.9). An output of a derivation the store holds is built when it may not be substituted (`allowSubstitutes = false`), and otherwise refused with upstream's `cannot substitute path '<path>' - no write access to the Nix store`, also for whatever that build would substitute; the output refused is the one upstream's worker tries first, by path name and then path, so a derivation's `out` comes before its `dev`. In a store upstream Nix's database manages that realisation opens nothing, so a substitution is refused in upstream's words and only an output that has to be built meets nova-nix's refusal of the store. The read-only queries make no store, metadata, database or lock, and open a store's database read-only, which writes nothing to it; SQLite still makes the `-wal` and `-shm` files a database in WAL mode needs beside one that lacks them. A database without the store's tables, as a first open cut short leaves, reads as holding nothing, as a store upstream's read-only evaluation has just made the tables of does (the new-store case of the `LocalStore` constructor in local-store.cc), and a fetched path is never asked about. What evaluation writes itself, a fetch or a `builtins.toFile` result, still makes the store directory. In a store upstream Nix's database manages, where nova-nix holds no rows, a path counts as valid when its tree exists. A failure carries upstream's line of context, `while realising the context of path '<path>'`, or `while adding path '<path>'` from `builtins.path` and `builtins.filterSource`, which also give it to a failure of the filter or the copy; `builtins.tryEval` does not catch it, and `builtins.pathExists` answers it with the failure rather than `false`. `builtins.hashFile` refuses an unknown algorithm, `builtins.filterSource` a filter that is not a function, and `builtins.path` an argument it does not take, a `filter` that is not a function or a `name` that is not a string without context, before the path's context is realised, as upstream's do; `builtins.path` gives the last two upstream's line of context, and names a copy whose `name` is empty by the path's base name. `builtins.findFile` names the entry and the path's base name, as 2.35.4 does, and where the releases word the refusal differently the newest's words are used. Under `--restrict-eval` and `--pure-eval` the closure of each output realised becomes readable, as 2.34.9 allows it (`EvalState::allowClosure` in eval.cc). (#657)+- **`allow-import-from-derivation` and `trace-import-from-derivation` are read from `nix.conf` and `NIX_CONFIG`, and `--no-allow-import-from-derivation` turns the first off for one run of `eval`, `build` or `trust`.** With it off, a builtin that reads a path whose context names a derivation's output fails with upstream's `cannot build '<drv>^<output>' during evaluation because the option 'allow-import-from-derivation' is disabled`, naming the first output in upstream's order, once every path the context names is valid and before anything is added or built, so an output already valid is refused too (`EvalState::realiseContext` in primops.cc); `builtins.tryEval` does not catch it, as upstream's catches only an assertion, and a read-only `eval` refuses as a `build` does. With `trace-import-from-derivation` on, each such read warns `built '<drv>^<output>' during evaluation due to an import from derivation` before it builds anything, as 2.34.9 does (`EvalState::realiseContext` in primops.cc); the warning has no effect with the first setting off, as upstream's has none. There is no `--allow-import-from-derivation`: as for every setting, a flag only moves the setting from its default, so a machine configured to refuse an import from derivation keeps refusing it whatever the command line says. (#665)+- **`builtins.fetchurl` and `builtins.fetchTarball` return the fetched store path as a string carrying itself as context, and so does the `outPath` of what `builtins.fetchGit` returns, as upstream's do.** Each returned a path value, so `builtins.typeOf` gave `"path"` where upstream gives `"string"`, the result printed unquoted, and `+`, `toString` and `builtins.isPath` treated it as a path. Upstream sets a fetcher's result with `allowAndSetStorePathString` (`fetch` in fetchTree.cc at 2.24.9 and 2.34.9) and fetchGit's `outPath` with `mkStorePathString` (`emitTreeAttrs`), a string whose context is the store path itself, so naming it in a derivation depends on that path rather than copying it to the store again as a path value would be. (#674)+- **A path value inside a store path is copied to the store under its base name when it is coerced, as every other path is, so a derivation in a nixpkgs imported from a store path gets upstream's drvPath and output path.** The path coerced to itself, with the enclosing store path as context, wherever it was interpolated, named in a derivation's `args` or environment, joined by `concatStringsSep` or written by `toJSON`. Upstream's `copyPathToStore` has no store case (eval.cc): it copies the path under `path.baseName()`, so `./build.kaem` in a nixpkgs fetched with `fetchTarball`, from a channel or as a flake input becomes `/nix/store/<hash>-build.kaem`, and a path that is exactly a store path is copied under its `<hash>-<name>` base name. Every derivation naming such a path therefore had a drvPath and output path of its own, nothing above it substituted from cache.nixos.org, its closure took in the whole enclosing tree, and its builder read its source inside that read-only tree: nixpkgs 26.05's `minimal-bootstrap.mescc-tools` now evaluates to `/nix/store/53zd871rgpcvi7qmqkffxhzaiq0is7k4-mescc-tools-1.9.1`, the path cache.nixos.org holds, where nova-nix gave another. drvPaths change for anyone whose nixpkgs lives in the store. The copy is read from the store nova-nix was given, so under `--store` and on Windows it is found where the store text names it, under the case-hack the store's volume keeps. (#676)+- **What a coerced store path now does follows from the copy, as upstream's does.** A read-only `eval` computes the copy's path without writing it, so `import "${/nix/store/<hash>-<name>}/default.nix"` fails with `path '/nix/store/<hash>-<hash>-<name>' is not valid` where it used to import, as upstream's read-only `realisePath` refuses it; `import /nix/store/<hash>-<name>`, which copies nothing, and `--read-write-mode` still import it. Under `--pure-eval` or `--restrict-eval` a path inside a store path that is not allowed is refused when it is coerced, as upstream's accessor refuses the read, where it used to coerce to itself unchecked. (#676)+- **A coerced path that is a symlink is copied as the link, with the links among its ancestors followed, inside a store path and outside it, as 2.34.9 and newer copy it; 2.24.9 copied what the link points to.** Upstream's `copyPathToStore` resolves a path's ancestors only from 2.34.9 (`SymlinkResolution::Ancestors`, eval.cc), where 2.24.9 resolved it in full (eval.cc), and nova-nix follows the newest release: `"${./link}"` gives the copy of the link where it gave the copy of its target. Under `--pure-eval` or `--restrict-eval` the link is read in place, so a link to a path outside the allowed ones is copied rather than refused, as upstream's accessor reads it. `builtins.path` and `builtins.filterSource` still copy what a link points to, as every release does (`addPath` in primops.cc), now inside a store path too, where they copied the link, and `builtins.storePath` of a path inside a store path that is a link names what it points to, as upstream resolves it in full (`prim_storePath` in primops.cc). Every link these follow is read in the store nova-nix was given once a path is in the store, a host link into it and an absolute link inside it included, as upstream resolves a path over the union of the host's file system and the store (`rootFS` in the `EvalState` constructor, eval.cc, from 2.34.9), so under `--store` elsewhere a path through a host link into the store reaches what it names there. The store directory and its ancestors are never taken for links for a path in the store, as upstream's store accessor looks for links only beneath the store directory (`PosixDirectorySourceAccessor::openParent` in posix-source-accessor.cc at 2.35.4 and 2.36.0), so with a `--store` directory that is a symlink store text stays in the store and `readFileType`, `filterSource` and a filtered `builtins.path` of a store path read it. On Windows a reparse point whose target no path value names, a volume mount point or a UNC link, is not walked and is left for the read to cross, as a POSIX read crosses a mount. (#676)+- **Making an attribute set, a lambda, a builtin's partial application or a string with context outside an evaluation session raises `ArenaNotInitialized` naming its C entry point, as every other C data-layer allocation does, where it made an object the next session's end freed.** The arena's teardown frees these objects one by one from a record of each kind, so one made outside every session sat below every region the collector runs and was freed when the next session ended, under whoever still held it. The thunk arena, the env pages, the string arena, the symbol table and the bytecode store already refused outside a session, and a list through its items, which come from the env pages. (#703)+- **A chain of `//` evaluates its operands last to first, as upstream 2.34 and later do, where it evaluated them first to last as 2.24.9 does: of two operands that fail, the later one fails the chain, `1 // "x"` refuses the string, and an operand's traces print after those of the operands after it.** Upstream 2.34's update queue gathers a chain by evaluating each update's right operand and then its left, checking each is a set as it is evaluated (`evalForUpdate`, eval.cc). Where the pinned releases differ, nova-nix follows the newest, and the parity rows whose chains hold two operands that fail run from 2.34.0. (#704)+- **`builtins.addErrorContext` keeps its value's failure when evaluating the message fails too, with a line naming the message's own failure, as upstream 2.36.0 does: `builtins.addErrorContext (throw "a") (throw "b")` fails with `b`, and a throw inside it stays catchable by `builtins.tryEval` whatever the message is.** Up to 2.35.4 upstream lets the message's failure escape in place of the value's. Upstream 2.36.0 rethrows the error it caught after evaluating the message, adding `while evaluating the error message passed to builtins.addErrorContext, another error occurred: ...` to its trace when that fails (`prim_addErrorContext` in primops.cc), so that the type of the value's failure, which decides whether `tryEval` catches it, is kept. nova-nix follows the newest pinned release. (#706)+- **Operators bind as upstream's grammar declares them: `-5 ? a` is `(-5) ? a`, which is `false`, `++` binds tighter than `*` and `+`, `a ? b ? c` is `(a ? b) ? c`, and `!` may stand as the operand of a tighter operator, as in `1 + !x`.** Upstream's grammar (parser.y, the same at 2.24.9, 2.34.9 and 2.36.0) binds, loosest first, `->`, `||`, `&&`, `==` and `!=`, the comparisons, `//`, `!`, `+` and `-`, `*` and `/`, `++`, `?`, and unary `-`, and a prefix operator's operand there runs as far as the operators tighter than it, so `a + !b + c` is `a + !(b + c)`. nova-nix bound unary `-` looser than `?`, so `-5 ? a` failed on negating a Boolean where upstream answers `false`; bound `++` looser than `+`, so `1 * [ ] ++ throw "c"` failed on the product where upstream reaches the throw; refused a second `?`; and refused `!` after a tighter operator, so a file holding `let x = 1 + !true; in 2` did not parse where upstream evaluates it to `2`. `a == b == c` and `a < b > c` are still refused, at the second operator, as upstream refuses them. (#736)+- **`builtins.baseNameOf` drops a single trailing `/` from a string, as upstream does, so `baseNameOf "a//"` is `""` where it was `"a"`.** Upstream's `legacyBaseNameOf` (primops.cc, the same at 2.24.9, 2.34.9 and 2.36.0) removes one final slash, unless it is the whole string, and returns what follows the last slash before it; nova-nix dropped every trailing slash and every empty component. `baseNameOf "a/"` is still `"a"`, and a path value is unchanged. (#736)+- **A set with `__functor` is called as a function by every builtin that calls a function it was given, as upstream's `callFunction` calls one: the predicate of `filter`, `any`, `all` and `partition`, the comparator of `sort`, the function of `groupBy` and `foldl'`, `genericClosure`'s `operator`, and the filter of `builtins.path` and `builtins.filterSource`.** nova-nix applied the functor only where a call is written in source or deferred, as `map`'s are, and these builtins refused a functor with `attempt to call a set, which is not a function`. Upstream's `callFunction` (eval.cc, the same at 2.24.9, 2.34.9 and 2.36.0) applies `__functor` to the set and then to the argument wherever it is called. (#736)+- **`builtins.partition` forces each element before it calls its function on it, as upstream's does, so `builtins.partition (x: true) [ (throw "e") ]` fails with `e`.** Upstream's `prim_partition` (primops.cc, the same at 2.24.9, 2.34.9 and 2.36.0) forces every element in list order as it partitions, where nova-nix passed each one unforced, so an element the function never looked at could hold a failure that never surfaced. `any`, `all`, `filter` and the other higher-order builtins still pass their elements unforced, as upstream's do. (#736)+- **A builtin checks each argument before it forces the next, as upstream's primops do, so of two bad arguments the earlier one's refusal is the error: `builtins.hasAttr 1 (throw "x")` fails with `expected a string but found an integer: 1`, and `builtins.storePath` under pure evaluation is refused before its argument is forced.** nova-nix forced every argument of these builtins as it was applied and checked them only once all were there, so a later argument that failed to evaluate hid an earlier one of the wrong type. Upstream's primops (primops.cc and context.cc, the same at 2.24.9, 2.34.9 and 2.36.0) force and check their arguments one at a time, first to last: `hasAttr`, `getAttr`, `catAttrs`, `match`, `split`, `compareVersions`, `toFile`, `concatStringsSep`, `appendContext`, `removeAttrs`, `intersectAttrs` and `bitAnd`, `bitOr` and `bitXor` check the first before they force the second; `hashString` and `hashFile` refuse an algorithm they do not know before they force what they hash; `substring` checks its start, refusing a negative one with `negative start position in 'substring'`, before it forces the length, and the length before the string; `replaceStrings` compares the lengths of its two lists, refusing a difference in upstream's words, and forces every string it replaces, before it forces the string it works on; `findFile` reads every entry, and realises each one's context, before it forces the name; and `concatMap`, `any`, `all`, `partition`, `groupBy` and `foldl'` force their function with upstream's `forceFunction`, which takes a lambda, a builtin or a set with `__functor`, before they force their list, so `builtins.any 1 [ ]` fails with `expected a function but found an integer: 1` where it was `false`. A first argument of the wrong type is refused with upstream's `expected ... but found ...` where nova-nix had words of its own. `findFile` reads an entry as upstream does: its `prefix` may be absent, and then is empty, its `path` is coerced as a string, so a set with `outPath` is a path, and one without a `path` is refused with `attribute 'path' missing`. A builtin applied to only some of its arguments still forces each as it is applied, where upstream forces none of them until the last. (#736)+- **`builtins.fromTOML` refuses a date or a time with upstream's `while parsing TOML: Dates and times are not supported`, where it returned the text as a string.** Upstream (fromTOML.cc, the same at 2.24.9, 2.34.9 and 2.36.0) turns an offset or local date-time, a local date or a local time into a value only under the `parse-toml-timestamps` experimental feature, and otherwise refuses it once the document has parsed. nova-nix does not implement that feature, so it refuses each one whatever `experimental-features` says, after the rest of the document has parsed, as upstream does with the feature off. (#736)+- **`builtins.toFile` refuses contents that refer to a derivation in upstream's words, naming the file and the reference: `files created by builtins.toFile may not reference derivations, but x references !out!...-d.drv`.** nova-nix refused them with `builtins.toFile: files created by toFile may not reference derivations`, naming neither. Upstream's `prim_toFile` (primops.cc, the same at 2.24.9, 2.34.9 and 2.36.0) names the first element of the contents' context that is no plain store path, in the order it keeps a context: a derivation's every output, `=` and its `.drv`, ahead of one output, `!out!` and its `.drv`; nova-nix names the same one. (#736)+- **`throw` and `abort` coerce their message as string interpolation does, as upstream's do: `throw { __toString = self: "m"; }` throws `m`, a throw `builtins.tryEval` still catches, and `throw 1` fails with `cannot coerce an integer to a string: 1`.** nova-nix took only a string, and refused anything else with `builtins.throw: expected a string` or `builtins.abort: expected a string`. Upstream's `throw` and `abort` (primops.cc, the same at 2.24.9, 2.34.9 and 2.36.0) read their message with `coerceToString` at its defaults, so a set with `__toString` or `outPath` is a message, and a path is one as the store path it is copied to. (#736)+- **`builtins.fetchurl` names the file it fetches as upstream does: by its `name` attribute when one is given and not empty, and otherwise by the base name of the whole URL, a query or fragment included.** nova-nix ignored `name`, and named the file by the URL's last component with any query or fragment cut off, or `source` when that was empty, so `builtins.fetchurl { url = ".../f?x=y"; sha256 = ...; }` and any fetch given a `name` had another store path than upstream's. Upstream's `fetch` (fetchTree.cc, the same at 2.24.9, 2.34.9 and 2.36.0) reads `name` with the other arguments, and when it is empty takes `baseNameOf` of the URL, which drops trailing slashes and keeps everything after the last one, so a URL ending in `/` is named by the component before it. (#736)+- **`builtins.parseDrvName` splits a name at the first dash that something other than an ASCII letter follows, as upstream does: `foo-.1` is `foo` and `.1`, `foo--1` is `foo` and `-1`, and `foo-_1` is `foo` and `_1`.** It split only at a dash a digit follows, so these kept the whole string as the name and an empty version. Upstream's `DrvName` (names.cc, the same at 2.24.9, 2.35.4 and 2.36.0) splits at the first dash whose next character `isalpha` rejects, and upstream 2.36.0 sets no locale, so only `A` to `Z` and `a` to `z` are letters and a dash before a byte outside ASCII splits too. A dash that ends the string splits nothing, so `foo-` stays whole. A profile already named an element by this rule, through a second copy of the split; both now use the same one. (#750)+- **`builtins.parseFlakeRef` and `builtins.flakeRefToString` read and write flake references as upstream 2.36.0 does, and the `experimental-features` setting, with `extra-experimental-features` and the `--extra-experimental-features` flag, turns on what they need.** A reference is read as upstream reads one: as a flake ID such as `nixpkgs/nixos-24.05`, then as a URL (`github:`, `gitlab:`, `sourcehut:`, `git+`, `hg+`, `path:`, `flake:` and tarball or file URLs), then as an absolute path, each input checked as its scheme checks it and refused in its words. The GitHub, GitLab, sourcehut, path and registry forms need `flakes`, as upstream's do, and a reference that names one with the feature off is refused with upstream's `experimental Nix feature 'flakes' is disabled` message; Git, Mercurial, tarball and file references need none. Upstream 2.36.0's `nix` adds `getFlake`, `parseFlakeRef` and `flakeRefToString` to every evaluator whatever the features, so `builtins ? parseFlakeRef` is true with none on; `__getFlake` is bound, as upstream binds it, and a call fails as one of `fetchMercurial` does, until flake evaluation lands, and `builtins` leaves it out, so `builtins ? getFlake` stays false. The names 2.36.0 interns as it starts take the same places here: the internal `fetchFinalTree` among fetchTree.cc's primops, and the three flake primops after every registered one. An unknown feature's name is dropped from the setting with upstream's warning, which is printed as the command starts. (#773)+- **A refusal raised during evaluation reads as the refusal alone, as upstream's does: copying a tree that holds a FIFO fails with `file '<path>' has an unsupported type`, where it failed with `user error (file '<path>' has an unsupported type)`, and a FIFO given as the source itself is no longer reported as a failed read, `opening file '<path>': file '<path>' has an unsupported type`.** The evaluator rendered a refusal that the walk, the store or the database raises in its own words through GHC's display of the exception, which wraps the message in `user error (...)`, and it reworded one raised while reading a source as that read's failure. Upstream prints such refusals bare, and each now reads as its message. A filtered `builtins.path` or `builtins.filterSource` whose tree the NAR parser refuses fails with the parser's refusal, where it was prefixed with `builtins.path: internal NAR round-trip error: `, as upstream's restore of its own dump refuses such an archive in its parser's words. (#760)+- **A filtered `builtins.path` or `builtins.filterSource` refuses an entry 64 levels below the source's root with `path '<path>' exceeds maximum NAR directory depth of 64`, as upstream's dump refuses it.** Upstream archives a filtered tree through the same dump as any other (`SourceAccessor::dumpPath` in archive.cc at 2.36.0), which refuses a node at depth 64, the root at 0, once the filter has kept it and before reading it. nova-nix walks a filtered tree itself to call the filter, and that walk counted no depth, so such a tree was archived and then refused only by the NAR parser, in its words rather than the dump's. (#764)+- **A string a builtin reads without context is refused naming its first context element as upstream 2.34.0 and later display one: a path by its store path, a derivation's outputs by its `.drv`'s store path and ` (deep)`, and one output by the `.drv`'s store path, `^` and the output's name.** Upstream builds the message from `NixStringContextElem::display` (eval.cc at 2.36.0), so `builtins.match`, `builtins.toFile`'s name, `builtins.compareVersions`, a derivation's name and a computed attribute name each say `(such as '/nix/store/...-a')`. nova-nix named the element by its encoding, as 2.24.9 did, which wrote a path by its base name and a derivation's outputs and one output as `=` and `!out!` prefixes. (#776)+- **`builtins.fetchurl` and `builtins.fetchTarball` download through nova-nix's own HTTP client, so a transient failure is retried as `builtin:fetchurl` and the substituter retry one, and `filetransfer-retry-attempts` (or its older name `download-attempts`) in nix.conf sets how many times every download and upload is tried.** The evaluator's fetchers ran `curl -sSfL` once, and `fetchTarball` piped curl into tar through `sh`, so a dropped connection or a 503 failed the evaluation where upstream's fetchers, which go through its one transfer layer, try again: up to `filetransfer-retry-attempts` times, 5 by default, retrying only what a retry can outlive. A 404 and the other refusals are not retried, and neither is a hash mismatch, which upstream checks once the transfer has finished. A failure now reads `builtins.fetchurl: fetch failed: HTTP 404 fetching URL` in the words the rest of nova-nix's downloads use, where it quoted curl's stderr; success and the hash mismatch read as they did. The setting was not read before; upstream's one setting governs every transfer, and here it governs the evaluator's fetchers, `builtin:fetchurl`, the substituter and push alike. Its value error names `filetransfer-retry-attempts` whichever name set it, as upstream's does. (#782)+- **A `file://` URL is read as curl reads it for upstream's `builtins.fetchurl`, and restricted mode admits one only as upstream's does.** The fetch percent-decodes the path, drops a query and a fragment, and accepts an authority that is empty, `localhost` or `127.0.0.1`, as curl does; a URL naming another host fails. Restricted mode checked the URL's remainder as it was spelled, so `file:///allowed/..%2F..%2Fsecret` passed as one name under `/allowed` while curl read `/secret`. It now refuses, as upstream does, a file URL upstream's URL parser does not take: one with an authority (`localhost` included), a character RFC 3986 does not allow unescaped, a malformed escape, or a path segment that decodes to `/` or a NUL. Any other file URL has its decoded, canonical path checked, which is the path the fetch reads. A directory named by a file URL now fails the fetch, where macOS's curl returned an empty file. (#782)+- **`builtins.fetchTarball` unpacks in process as upstream 2.36.0 does, so a tarball's tree, and with it its store path, is the archive's own, and neither it nor `builtins.fetchurl` runs `curl`, `sh` or `tar`.** A tarball is downloaded through nova-nix's own HTTP client, with upstream's retries, or read from the file a `file://` URL names. It is decompressed by what its first bytes announce (gzip, bzip2, xz, zstd or none) and read as libarchive reads tar: ustar with its prefix, GNU long names and pax headers. Its entries are placed by the rules of upstream's tar sink: the last entry at a path wins, a non-empty directory cannot be replaced, and a hard link names what its target is at that point in the archive, with upstream's warning when the target is replaced. The lone top-level directory is the tree only when the archive holds nothing else at its top, so a tarball with two top-level directories keeps both, and a macOS archive's AppleDouble `._` entries are files, as upstream reads them; nova-nix stripped the first path component of every archive and let macOS's `tar` apply AppleDouble entries as metadata. The tree's NAR is streamed into the store's restore, never extracted to a directory first, so a pair of names a case-insensitive volume folds keeps both. A pin the tree does not match is refused in 2.36.0's `NAR hash mismatch in input` words, a `file://` tarball that is missing or a directory in its words, and a failure of the fetch carries upstream's `while fetching the input` line. A tree holding a name that upstream's tree builder refuses, `.git` in any spelling NTFS reads as the same name (`.GIT`, `git~1`, `.git.`), is refused in its words before the store path is computed. A zip archive and a sparse archive member are refused as not yet supported. Upstream's libarchive also decompresses lzip, lzma, lz4, lzop, compress, lrzip, grzip, uuencode and RPM streams, some through an external program, and nova-nix does not: a tarball in one fails with `Failed to open archive (Unrecognized archive format)`, as does any body that is no archive at all. Upstream 2.36.0 copies a fetched tree into the store only when a context needs it; nova-nix writes it at once. (#816)++### Store++- **`store gc` and `store delete` refuse a store directory that upstream Nix's database also manages, such as `/nix/store` where upstream Nix is installed, and name that database.** The collector deletes every entry in the store directory that nova-nix's own roots do not keep, and a path upstream registered has no row in nova-nix's database, so in a store shared with a single-user upstream install, or with nova-nix run as root, `store gc` deleted every upstream path and left upstream's database naming paths that no longer existed; `store delete` removed a named upstream path the same way. The refusal looks for upstream's database where upstream's local store keeps it: `/nix/var/nix/db/db.sqlite` for `/nix/store`, and `<root>/nix/var/nix/db/db.sqlite` for a store upstream opens with a root at `<root>/nix/store` (`LocalFSStoreConfig` and `LocalStore` at 2.24.9). It looks only beside a directory named `nix/store`, the name of upstream's default store and of every store it opens with a root, both as the store is spelled and as its links resolve, so a store of nova-nix's own beside upstream's, such as `/nix/nova-store`, is collected as before. A store is refused too when that path cannot be examined, such as under a directory this user cannot search, since it may be that database. An upstream whose state directory is moved, by `NIX_STATE_DIR` or by its build, is not recognised, nor is a store reached through a bind mount. `store gc --print-roots` still lists the roots. (#442)+- **`deleteStorePaths` replaces `withLiveSet` and `deleteStorePathChecked`, so a delete's live set cannot outlive its collector lock or come from another store.** `withLiveSet` handed its callback a `LiveSet` the callback could return, and `deleteStorePathChecked` took the live set and the store separately, so a library caller could delete with a live set after the collector lock was released, or with another store's: the liveness check then read the roots as they stood when the set was made, or another store's roots, and the delete removed a live path. The live set is now made and consumed inside one call. `store delete` runs on `deleteStorePaths` and prints what it printed. (#446)+- **`build` refuses a store directory that upstream Nix's database also manages, such as `/nix/store` where upstream Nix is installed, and names that database; `eval` refuses one at the evaluation's first write to it.** A path upstream registered has no row in nova-nix's database, so a build that came to build or substitute such a path took upstream's tree for a leftover of its own: it removed the tree before the builder ran, again when the build failed, and before unpacking a substitute, leaving upstream's database recording a NAR hash the new tree need not have, or a path that no longer existed. The build is refused before anything is evaluated, for the same stores `store gc` and `store delete` refuse, so a store of nova-nix's own beside upstream's, such as `/nix/nova-store`, builds as before. An evaluation's own store writes, such as a fetcher's result, clear a tree that does not reproduce its address, which in such a store may be one upstream registered or is writing, so an evaluation stops with an error at its first write there; one that writes nothing, such as `eval` computing a derivation's path, is not refused. `push` and `store gc --print-roots`, which change no path in the store, are not refused. (#452)+- **The library's checked delete refuses a name that is not one entry of the store directory, where it removed a path outside the store, the store directory itself or the store's metadata directory.** `deleteStorePathRaw` and `deleteStorePaths` joined the name they were given to the store directory, and that join keeps an absolute name as it is and follows `..`, so `/etc/x` or `../x` passed the liveness check, found no registration row and was removed as a tree without one, with a lock file left beside it. The empty name joined to the store directory itself, `.` to everything in it, and `.nova-nix` named the metadata directory that holds the store's database and roots. Such a name is now refused before the delete takes a lock or looks for a tree: the empty name, a `/` or a `\`, a dot-leading name, a `:` and a NUL, which are the rules `store delete` already applied to the last component of each argument, with the separators and NUL added. Upstream's delete is never handed a name: `nix-store --delete` resolves each argument to a store path first (`opDelete` and `GCOptions::pathsToDelete`, a `StorePathSet`, at 2.24.9). `store delete` refuses what it refused before; its refusal of an empty name no longer repeats the argument. (#457)+- **A path added to the store takes upstream's canonical metadata: every file and directory is made `0444`, or `0555` when its owner may execute it, and every node, a symlink's own included, has the modification time 1, a second past the epoch, as upstream's `canonicalisePathMetaData` leaves them (posix-fs-canonicalise.cc at 2.24.9).** nova-nix cleared only the owner's write bit, so a path kept the times it was written with and the group and other bits of whatever wrote it: a file a NAR or `builtin:unpack` marked executable could be executed by its owner alone, and a `.drv` stayed writable. Upstream canonicalizes a build's outputs (`registerOutputs`, local-derivation-goal.cc at 2.24.9, derivation-builder-impl.cc at 2.36.0), a substituted or downloaded path (`LocalStore::addToStore`, local-store.cc) and whatever `addToStoreFromDump` adds, which is every other store write an evaluation makes and each `.drv` (local-store.cc). Here that is a build's outputs, a substituted path, each store object an evaluation writes, as it writes it (`builtins.toFile`, `builtins.fetchurl`, `builtins.fetchTarball`, `builtins.fetchGit`, `builtins.path` and `builtins.filterSource`), the sources a build restores, and each `.drv` a build writes, including a tree on disk that already reproduces its address, or that `builtins.fetchGit`'s cache names, and is kept as it is. So `eval` alone leaves a `builtins.fetchTarball` tree as `nix-instantiate` 2.24.9 does: a file `0444` and an executable `0555`, each with the time 1, where nova-nix left what its restore wrote, `0644` and `0744` under the usual umask, with the time of the restore. As upstream's does, the walk drops the setuid, setgid and sticky bits, leaves a symlink's mode alone, keeps a node's access time to the whole second, gives a node another user owns to the process's user and group, and fails a path holding a node that is not a regular file, a directory or a symlink with `file '<path>' has an unsupported type`. A NAR records only the owner's execute bit, which the canonical mode keeps, so no store path or NAR hash changes. Upstream also clears a node's file flags on macOS, which nova-nix does not. On Windows, where upstream sets no times and has no modes, each file and directory is given the read-only attribute, as before, and the same time, and a symlink the time. (#477)+- **On Windows a store directory nova-nix creates, and its `.nova-nix` state directory, can be changed only by the user nova-nix runs as, SYSTEM and Administrators, a directory it creates on the way to the store, such as `C:\nix`, is open to them alone, and a build directory is that user's alone, where each took the permissions of the directory it was made in.** A directory made under a drive root takes the root's permissions, which let every signed-in user (Authenticated Users) modify it, so under the default `C:\nix\store` any user of the machine could change, replace or delete store paths and the store's database, rename a `C:\nix` nova-nix had made and put a store of their own in its place, and change a build's sources and outputs while it ran. nova-nix now creates each of these directories with a protected access control list, which takes nothing from its parent, in the one `CreateDirectoryW` call that makes it, so the directory never exists with its parent's permissions. A store directory and its state directory grant full control to the user, SYSTEM and Administrators and read and execute to Users, the rights, inheritance and principals install-nova-nix sets on `C:\nix`; a parent directory nova-nix creates on the way to the store grants full control to the user, SYSTEM and Administrators and nothing to other users; a build directory grants full control to the user alone, as its mode 0700 does on macOS and Linux. Each grant is inherited by what is made below, so store paths and a build's tree are covered too. A directory that already exists keeps the permissions it has. install-nova-nix accepts a `C:\nix` this release creates, since it grants nothing to an account the installer does not trust, and gives it the installer's own permissions, which add read and execute for Users. A store created inside a private folder, such as a `--store` under the user's profile, now grants Users read and execute, as a store's permissions do wherever it is, where it took the folder's own list before, which under the profile grants other users nothing. Upstream's local store creates its directories with `std::filesystem::create_directories` on every platform and sets no access control list on Windows (`createDirs`, file-system.cc, and the `LocalStore` constructor, local-store.cc, at 2.24.9). macOS and Linux are unchanged. (#659)+- **A derivation whose source is a symlink builds, and a copy is restored from the tree evaluation hashed.** A coerced path that is a link is copied as the link, as 2.34.9 and newer copy it, and the build driver restores it as the link; `src = ./link`, with `link` pointing at a directory or a file, had failed with `refusing to register /nix/store/...-link: .../link changed after evaluation hashed it`, since evaluation hashed what the link pointed to and the restore dumped the link. Evaluation still follows the links among a path's ancestors, so the restore now reads the path evaluation read, those links resolved, rather than the path as written: a coerced path below an absolute link inside a store path, as a NAR carries one into another store path, is restored from the store nova-nix was given rather than through the link on the host, and the tree is read under the case-hack its resolved text calls for, as evaluation read it. A copy `builtins.path` or `builtins.filterSource` makes, of what a link points to, is written by evaluation itself and never restored this way. (#676)+- **On Linux and macOS a file's executable flag in a NAR is the owner-execute bit of its mode, as upstream's dump reads it, where nova-nix asked whether it could execute the file.** Upstream's `PosixSourceAccessor` (posix-source-accessor.cc at 2.36.0) takes `st_mode & S_IXUSR`; nova-nix's `Nix.Store.ExecBit.isExecutable` answered from `access(2)`, which differs for a process running as root, which may execute a file any of whose execute bits is set, and for a file whose access control list refuses execution, so in those cases a path's NAR, and so its NAR hash and any path made from it, differed from upstream's. Windows, which keeps the flag in a stream of the file, is unchanged. (#739)+- **On Windows nova-nix refuses a store when its directory, its `.nova-nix` state directory or a directory on the way to them below the drive root belongs to an account other than the user nova-nix runs as, SYSTEM and Administrators, has no DACL, or lets any other account change it, and the error names the directory and what is wrong with it.** A drive root lets every signed-in user create a folder in it, so on a machine where install-nova-nix never ran another user could create `C:\nix` first; nova-nix then made its protected store inside a folder that user owned, and as its owner they could give themselves the right to delete what it holds, move the store aside and put a store and database of their own in its place, which the next build would run from. nova-nix now holds each of these directories that already exists to install-nova-nix's rule for `C:\nix`: its owner is the user, SYSTEM or Administrators, it has a DACL, and no allow entry of any kind, an inherit-only one included, grants another account a right that changes it. Read and execute for Users is no change. A directory is checked before nova-nix creates anything in it or reads anything from it, an evaluation's write into the store and a read-only command's queries of the database included, since a database another account controls is as dangerous to read as to write; the error says to move the directory aside and let nova-nix or install-nova-nix create it. A `C:\nix` either of them creates passes for the user it was created for, and so does a store under the user's profile; another user's nova-nix refuses it, since it lets its creator change it. A store in a folder that took a drive root's permissions is refused, a `C:\nix` an earlier nova-nix release created among them. The drive root itself is not checked, since its default permissions let other users create a folder in it but not delete or rename one already there. A link is checked as itself, not as what it leads to, so a link the user made stands, where install-nova-nix refuses one at `C:\nix`. A store upstream Nix's database also manages, whose tree answers a read-only command's queries, is checked before the tree is read. Upstream Nix has no such check: on Linux and macOS only root can create a directory in `/`. macOS and Linux are unchanged. (#742)+- **The garbage collector quotes a root, a link or a target in double quotes, as upstream does from 2.35.4 on: `removing stale link from "<record>" to "<out-link>"`, `skipping invalid root from "<link>" to "<target>"`, `cannot read potential root "<path>"`, and the refusals `creating a garbage collector root ("<link>") in the Nix store is forbidden` and `cannot create symlink "<link>"; already exists`.** These lines quoted the path as upstream 2.24.9 does, in single quotes, or, inside the parentheses of the in-store refusal, not at all. Upstream 2.35.4 and 2.36.0 format these paths with `PathFmt`, which writes a path between double quotes and escapes nothing inside, and nova-nix follows the newest pinned release. `deleting '<path>'` and `Cannot delete path '<path>' since it is still alive` keep their single quotes, as upstream's do, since it formats those store paths as strings. (#751)+- **A store path's info records whether this store built it, the signatures it came with and the content address its name was made from, and the store lists each valid derivation's outputs, in the columns and the table upstream's database has.** A built output is ultimately trusted, and a fixed one has the address it was checked against; a substituted path keeps its narinfo's signatures and the address its tree was held to; a source, a write evaluation made and a `.drv` have the address their paths are made from. Upstream records the same (`ultimate`, `sigs` and `ca` in `ValidPaths`, and `DerivationOutputs`), and a daemon answering for the store reads them back. A database an earlier nova-nix made gains the columns, empty in every row it holds, and the table, filled from the derivations it holds, the first time it is opened for writing. (#749)+- **Registering a path whose name ends in `.drv` reads it as a derivation, and one that does not parse is refused with `error parsing derivation '...'`, as upstream's store refuses it.** Upstream lists a derivation's outputs from its file when it registers it, so a `.drv` that is not a derivation never becomes valid there. (#749)+- **A garbage collector root for an out-link whose name has no UTF-8 reading keeps that name: the link is made, recorded and found again under the bytes it was given.** The link's spelling went through text, which replaced each such byte with U+FFFD, so the link was made under a name other than the one asked for, and its record held that name. Upstream keeps a root's path as bytes. (#749)+- **A collection, a checked delete and `store gc --print-roots` read, for a store in a directory upstream's local store uses, the roots under upstream's `gcroots` and `profiles` in its state directory, `/nix/var/nix` for `/nix/store`, beside the store's own.** Upstream's clients keep their profiles and their out-links' roots there, and upstream's collector reads both directories, so a nova-nix store that serves them would otherwise collect what they keep. (#756)+- **On Windows registering a store path gives each of its files and directories the store's account as owner and a protected access control list no build account can change, and where the machine has a local `nixbld` group, the store directory lets that group create entries in it and nothing else.** Builds are to run as build accounts in a local `nixbld` group, as upstream's Linux builds run as `nixbld` users, and a path a build made would otherwise keep the permissions its build gave it, so the account that built it could change or delete it once it was valid. Registration now sets, on every node of the path, a link included and not followed, the account nova-nix runs as as the owner, as upstream gives each node of a path to the store's user, and a protected DACL that grants that account, SYSTEM and Administrators full control, Users and the `nixbld` group read and execute, and the node's owner read-control alone (OWNER RIGHTS), which takes the place of the rights an owner otherwise keeps whatever the DACL says. A node registration cannot read, as one a build gave a DACL that grants the account nova-nix runs as nothing, fails the registration, naming the node, rather than being passed over with the access its build gave it. An access control list is no part of a NAR, so a path's hash is unchanged. Where the machine has a local `nixbld` group, a store directory nova-nix creates grants its entries to itself alone and the group FILE_ADD_FILE, FILE_ADD_SUBDIRECTORY, traverse, read attributes and synchronize, so what a build makes there takes its own token's default DACL rather than one passed down; the check of a store's directories accepts that grant on the store directory alone, and only applying to the directory itself. A machine with no `nixbld` group keeps a single-user store as it was: its store directory passes its entries down as before, and a registered path grants what it would have inherited, with the user as its owner. (#758)+- **A store whose database holds paths, none of them under the directory the store is opened at, is refused, with an error saying where they are, instead of being read as empty and built into again.** nova-nix records each valid path in the store's database as the full path under the directory it was registered at, and the outputs built in the store name that directory too. A store opened under another directory, such as a drive that comes up under another letter or a store moved or renamed on any platform, therefore found none of its paths valid, and a build ran over the outputs already there, which still name the old directory and cannot work from the new one. The open now fails with `store 'NEW' was made at 'OLD', and its paths and the outputs built in it name that directory; use it from there`, for a database opened to write and one opened to read alike, before anything is written to the database. A recorded directory that is not an absolute path on the host, such as a relative spelling, is not named as one to use: the error says the store records its paths under another directory, as in the path it quotes. A store that holds a path under the directory it is opened at opens, so one already built into at its new directory is not locked out, and so does a store with no paths yet, at any directory, and a store moved back to where it was made. (#818)++### Builder++- **A builder's environment holds `NIX_BUILD_CORES`, from the nix.conf setting `cores`, so nixpkgs' `setup.sh` runs `make` for a package with `enableParallelBuilding` with as many jobs as it does under upstream.** nova-nix set no such variable, and setup.sh reads an unset one as 1, so every such package built on one core. Upstream sets it in every builder's environment from `settings.buildCores` (`LocalDerivationGoal::initEnv`, local-derivation-goal.cc at 2.24.9, `UnixDerivationBuilderImpl::initEnv` in unix-derivation-builder.cc at 2.36.0) before it copies in the derivation's environment, so where a derivation's attributes reach the environment, which they do not under `__structuredAttrs`, an attribute of that name wins, as it does here. The setting is read as upstream's `cores` is (`Settings::buildCores` in globals.hh at 2.24.9, `LocalSettings::buildCores` in local-settings.hh at 2.36.0): an unsigned integer under the grammar `max-call-depth` takes, also set through its alias `build-cores`; `0` gives the default count below, as upstream 2.36.0 resolves it when it builds, where 2.24.9 passed it through; a value that does not parse is refused as `setting 'cores' has invalid value '...'`, naming `cores` when it was set through `build-cores`, as upstream's error does; and `extra-cores` is an unknown name. A value past an unsigned 32-bit integer is refused, where upstream multiplies a unit suffix in 64 bits and keeps the low 32 (`string2IntWithUnitPrefix` in util.hh), so that its `cores = 4G` is 0, the default count. With nothing setting it, or with `0`, the value is upstream's default (`Settings::getDefaultCores`, globals.cc). On Linux that is the CPU limit of the process's cgroup when it has one, found as upstream's `getMaxCPU` finds it (current-process.cc): the first `cgroup2` mount in `/proc/mounts`, read as glibc's `getmntent` reads it, joined to the group `/proc/self/cgroup` lists under no name, which is parsed as upstream's `getCgroups` parses it (linux/cgroup.cc), and that group's `cpu.max` quota over its period, rounded up after the division in single precision as upstream divides. A quota past a signed 32-bit integer, which the kernel accepts, is no limit here, where upstream's `std::stoi` throws an exception its `catch (Error &)` does not catch and every command aborts. Otherwise it is the hardware thread count upstream's C++ runtime reports for `std::thread::hardware_concurrency`, at least 1, read through the same call, `sysconf(_SC_NPROCESSORS_ONLN)`: libc++ makes that call on macOS (16.0.6, which nixpkgs 24.05 builds upstream with), and on Linux libstdc++ calls glibc's `get_nprocs`, the function glibc's `sysconf` answers that name with (sysdeps/posix/sysconf.c at glibc 2.39). On Linux the glibc is the host's, where upstream's is nixpkgs' 2.39, and the two count the CPUs online alike on every glibc release but 2.34, whose `get_nprocs` counts the process's affinity mask. On Windows, where upstream has no local builder, the count is GHC's `getNumProcessors`. Upstream's `--cores` flag is not implemented. (#436)+- **A build runs in a directory it creates under the store's state directory, `.nova-nix/builds`, with mode 0700 on macOS and Linux, where it ran in the system temporary directory under its first output's hash.** The build removed that path and then created it with a call that accepts a directory already there, and anyone can compute the name from the derivation, so in a world-writable `/tmp` another local user who created the directory first owned the directory the build ran in and could change its sources and scripts before the outputs were registered. The directory's default mode also let other users read what the build unpacked. The name did not depend on the store either, so two builds of one derivation into two stores at once shared one directory, and the second removed the first's tree mid-build. Upstream creates each build directory with `mkdir` and mode 0700 and never enters one that exists (`createTempDir`, file-system.cc at 2.24.9), and since 2.30.0 roots them at its state directory by default (`LocalBuildStoreConfig::getBuildDir`, local-store.cc), documenting that `build-dir` must not be world-writable. Each store's state directory holds that store's builds, and whoever can write there can already rewrite the store's database. The name is still the first output's hash, where upstream's is `nix-build-<drv name>-<n>`: the build holds that output's path lock throughout, so the name belongs to one build at a time, and a directory a killed build left there is removed before the next build of the derivation creates its own. The directory is removed when the build ends even when the builder left a read-only tree in it, as upstream's `deletePath` removes one. On Windows the directory, which was in the per-user temporary directory, is the user's alone, as the entry on Windows store permissions says. A derivation with no outputs, whose build fails whatever its builder does, fails before its builder runs. (#449)+- **A built output's registration names the `.drv` that built it, so `nova-nix push` writes its narinfo with upstream's `Deriver` field.** Upstream records the derivation as the deriver of every output it registers from a build (`newInfo.deriver = drvPath` in `registerOutputs`, local-derivation-goal.cc at 2.24.9, derivation-builder-impl.cc at 2.36.0), and a narinfo names it by its basename. nova-nix registered a built output with no deriver, so its pushed narinfo had no `Deriver` line, while a substituted path kept the deriver its cache's narinfo named. Upstream's `keep-derivations` and `keep-outputs`, through which its garbage collector reads the deriver, are still not implemented. (#473)+- **`builtin:fetchurl` restores the NAR it downloads when the derivation's `unpack` is true, and makes its output executable when `executable` is true, as upstream's does, so a `<nix/fetchurl.nix>` fetch with either attribute builds.** The bundled `<nix/fetchurl.nix>` declares a recursive hash for either, and nova-nix's builtin refused every recursive hash, so such a fetch evaluated and then failed to build. Upstream's builtin (`builtinFetchurl` in builtins/fetchurl.cc) restores the download as a NAR when `unpack` is `1`, decompressing it with xz first when the URL ends in `.xz` and never otherwise, writes it as the output file when `unpack` is anything else, and then sets the output's mode to `0755` when `executable` is `1`. nova-nix does the same, restoring through the streaming restore the substituter uses and decompressing through nova-cache's xz decoder, so neither the download nor the archive is held whole. Under `executable` it marks a regular file and leaves a directory as it is, since a NAR records no mode for a directory. A restored root that is a symlink fails that URL, and the next is tried, rather than being followed: upstream's `chmod` follows the link, but in the build's child process, after its `chroot` when the build is sandboxed and as the build user when there are build users (`LocalDerivationGoal::runChild` in local-derivation-goal.cc at 2.24.9, `UnixDerivationBuilderImpl::runChild` in unix-derivation-builder.cc at 2.36.0), where a file outside the build is absent or not the build user's to change, so the `chmod` fails the build there, while nova-nix runs a builtin as the invoking user and following the link would change the file it names. The output is held to the hash the derivation declares, in the mode it declares whatever made the output, as upstream's `registerOutputs` holds it: a flat hash needs a regular file its owner may not execute and is of its bytes, and a recursive one is of the output's NAR, the executable flag included. Registration then gives it the store's canonical metadata, so an executable file and every directory are `0555` and every other file `0444`, as upstream leaves them. A fetch of an `.xz` URL without `unpack` keeps the bytes it downloads, as upstream's does. As with a flat hash, each URL a derivation lists is held to the hash before the next is tried, so a mirror that serves the wrong tree is passed over. Three things differ from upstream. nova-nix restores only an archive in the canonical form upstream writes, failing one with bytes after its end or with a file's fields out of order, where upstream's restore stops reading at the archive's end and takes those fields in either order (`parse` in archive.cc at 2.24.9). An archive that fails to parse is retried as a torn transfer is, as the substituter retries one, where upstream fails the build at once. And the xz decoder's memory is bounded at nova-cache's default of 1 GiB, as the substituter's is, where upstream's libarchive decoder has no bound; the largest xz preset needs about 65 MiB. (#501)+- **An output under a flat fixed-output hash must be a regular file its owner may not execute, read without following a symlink, as upstream requires of every build's, and any other fails with upstream's `output path '<path>' should be a non-executable regular file since recursive hashing is not enabled (one of outputHashMode={flat,text} is true)`.** Upstream reads the output with `lstat` and refuses any other form in `registerOutputs` (local-derivation-goal.cc at 2.24.9, derivation-builder-impl.cc at 2.36.0). nova-nix refused only a directory, in words of its own, and followed a symlink: a symlink output was hashed as the file it named and registered as the symlink, and an executable file was registered `0555` under a hash that records no mode. The rule holds for every builder, a spawned one and `builtin:fetchurl` alike, and for the rebuild `nova-nix build --check` compares. (#501)+- **Only a fixed-output derivation's builder sees the variables its `impureEnvVars` lists, as upstream decides by the derivation's type: a floating content-addressed output, an impure one, and a fixed output beside others or not named `out` no longer pass them.** The variables reached any build with an output that names a hash algorithm, which a floating content-addressed output does too. Upstream passes them to a derivation whose type is not sandboxed (`LocalDerivationGoal::initEnv` in local-derivation-goal.cc at 2.24.9, `UnixDerivationBuilderImpl::initEnv` in unix-derivation-builder.cc at 2.36.0), and the type is fixed-output only for one output, `out`, with the hash that fixes it (`BasicDerivation::type` in derivations.cc at 2.24.9, `derivation::type` there at 2.36.0). A floating output, which names an algorithm and no hash, is sandboxed (the same function), and a fixed output beside others or named otherwise makes a derivation upstream refuses (again `BasicDerivation::type`). Upstream also passes them to an impure derivation, which takes the experimental `impure-derivations` feature that nova-nix does not implement. nova-nix makes no floating or impure derivation and reads none upstream writes, since upstream writes such an output with no path (`Derivation::unparse` in derivations.cc at 2.24.9, `unparse` in derivation/aterm.cc at 2.36.0), so one reaches the builder only from the library or a `.drv` written by hand. The rule is the one `nova-nix trust` uses to find a closure's fixed-output derivations. (#642)+- **A builder's program, arguments and environment entries end at their first NUL, as upstream's exec takes them.** Upstream passes each argument and each `NAME=VALUE` entry it builds to `execve` as a C string (`stringsToCharPtrs` in util.cc and `LocalDerivationGoal::runChild` in local-derivation-goal.cc at 2.24.9), so its builder gets each up to the first NUL a derivation's string holds, which `builtins.fromJSON` can put there. nova-nix refused to spawn a builder whose environment held a NUL, since the process library refuses one, and on Windows a NUL in a value started another variable and one in an argument ended the command line. Each is now cut at its first NUL before the spawn, so the builder gets what upstream's gets, with one exception in an unsandboxed build: an entry left with no `=`, by a name holding a NUL, is one the process library cannot pass, and is left out. Upstream passes it, and no `getenv` finds a variable in it. (#673)+- **A build directory, or a sandbox's chroot, that an earlier build left and that cannot be removed is moved aside, with a warning, and the build goes on.** Both are named by the derivation, so a leftover that cannot be removed, such as a directory another user made there through a descriptor a fixed-output builder handed out, which the user may neither empty nor change, failed every later build of the derivation. It now moves to the first free name of its path with `.leftover.` and a number after it, beside it in the store's state directory, and the warning names both paths. Removal that runs out of descriptors on a tree deep enough leaves a chroot the next build moves aside the same way. (#673)+- **A build's output that its group or anyone else may write is refused, every output is made canonical before it is read or changed, and a fixed output is replaced by a fresh copy of itself before it is hashed, as upstream's are.** Upstream refuses such an output with `suspicious ownership or permission on '...' for output '...'; rejecting this build output`, since someone other than the build may have changed it, then makes the output canonical, so nothing in it is setuid, or open to another user's write or swapped link, while it is rewritten and scanned (`registerOutputs`, local-derivation-goal.cc at 2.24.9, derivation-builder-impl.cc at 2.36.0). nova-nix made an output canonical only once it was placed. A fixed output's fresh copy leaves behind the inode the builder wrote, so a descriptor the builder passed out of its build cannot change what is registered (the fresh copy in `registerOutputs`); the copy is made canonical in its turn, and it is the copy that is scanned and hashed, before it leaves the chroot. A fixed output that references a store path, itself included, is refused with upstream's `illegal path references in fixed-output derivation '...'` (the fixed-output reference check in `registerOutputs`), which nova-nix let through; upstream registers such an output under the path its references give it before it fails the build, and nova-nix registers nothing, as for a hash mismatch. On Linux an output's extended attributes, ACLs among them, are removed as it is made canonical, as upstream removes them (`canonicalisePathMetaData_` in posix-fs-canonicalise.cc), but for the three upstream's `ignored-acls` keeps by default, `security.selinux`, `system.nfs4_acl` and `security.csm`. A directory in an output that its owner may not search is given search before it is read, so it ends at 0555 where upstream's canonicalisation gives it 0444 and a single-user upstream build, not run as root, then fails to read beneath it. A sandboxed build's outputs go through all of it in the chroot and move into the store only when registered (the final move in `registerOutputs`), so a check's outputs, and the copy of an output that was already valid, never enter the store. A hash rewrite of an output's file opens it without following a link, and refuses one swapped in. An output holding a node another user owns is refused with upstream's `invalid ownership on file '...'` (`canonicalisePathMetaData_` in posix-fs-canonicalise.cc at 2.24.9) before it is made canonical, which would change that node, a hard link into the output among them. A directory output moves into the store by a rename, given owner write for it as upstream's `movePath` gives it (local-derivation-goal.cc at 2.24.9, unix/file-system.cc at 2.36.0), so it keeps its inodes and hard links, and a rename that fails fails the build, except across volumes, where the move copies. An output that is a symlink is there whatever it names, as upstream reads it with `lstat` (`registerOutputs`), where nova-nix took one naming nothing, or a sibling output not yet in the store, for a missing output. nova-nix now runs with upstream's file-creation mask, 0022, as every upstream command does (`initNix`, shared.cc): everything it creates is made under it, the store and its database, push and fetch caches, garbage-collector roots and out-links among them, and so is everything a builder it starts creates, so no ordinary build's output is refused. (#673)+- **On Linux a build runs in a sandbox by default, as upstream's does: in fresh user, mount, PID, IPC and UTS namespaces, with a chroot that holds the closure of its inputs, and in a network namespace of its own, holding only a loopback interface, unless the derivation is fixed-output.** Upstream sandboxes every build on Linux unless `sandbox` says otherwise (`Settings::sandboxMode` in globals.hh at 2.24.9, `LocalSettings::sandboxMode` in local-settings.hh at 2.36.0), and nova-nix ran every builder with the whole filesystem and the network in reach. A build an evaluation starts for an import from a derivation runs in the sandbox too, whichever command evaluates. The new `nova-nix-sandbox` helper, a C program installed beside `nova-nix`, makes the namespaces and the chroot and executes the builder, following upstream's `startBuilder` and `runChild` (local-derivation-goal.cc at 2.24.9): the setup runs between the namespaces' creation and the builder's exec, where nova-nix can run nothing, since the process library gives no hook between fork and exec and a child forked from the threaded GHC runtime may make only async-signal-safe calls. The helper is spawned with an empty environment, so its dynamic loader reads no variable a derivation sets, such as `LD_PRELOAD`; the builder's environment travels in the helper's plan and is applied only at the builder's `execve`, as upstream's is (`LocalDerivationGoal::runChild` in local-derivation-goal.cc at 2.24.9, `UnixDerivationBuilderImpl::runChild` and `execBuilder` in unix-derivation-builder.cc at 2.36.0). A build sees what upstream's sandboxed build sees: uid 1000 and gid 100, mapped to the invoking user, or as root to the build user and its group, upstream's `/etc/passwd` and `/etc/group`, the host name `localhost`, itself as PID 1, a fresh `/proc`, a tmpfs `/dev/shm`, upstream's `/dev` nodes, a writable `/tmp`, its build directory at `sandbox-build-dir`, `/build`, which `NIX_BUILD_TOP`, `TMPDIR`, `TEMPDIR`, `TMP` and `TEMP` name, and upstream's `HOME`, `/homeless-shelter`. The directory bound there is one inside the build's own, as upstream binds `topTmpDir + "/build"` (`LocalDerivationGoal::startBuilder` in local-derivation-goal.cc at 2.24.9, `ChrootDerivationBuilder::setBuildTmpDir` at 2.36.0), so a builder that opens what it sees to everyone leaves the 0700 directory around it closed to every other user. Its environment still differs from upstream's: `PWD`, `TERM` and `NIX_OUTPUT_CHECKED` are not set, the builder's `argv[0]` is its whole path where upstream's is its base name, and its output reaches the log through a pipe where upstream's goes through a pseudo-terminal. An output that is already valid, or that a check builds again, is still written at a scratch path whose hash is rewritten in it afterwards, as outside the sandbox, where upstream's sandboxed build writes it at its own path, which the chroot leaves free (`LocalDerivationGoal::needsHashRewrite` and `LocalDerivationGoal::startBuilder` in local-derivation-goal.cc at 2.24.9, `ChrootDerivationBuilder::needsHashRewrite` at 2.36.0). A fixed-output build gets the host's network, its `/etc/resolv.conf`, `/etc/services` and `/etc/hosts`, and the `ssl-cert-file` bundle at `/etc/ssl/certs/ca-certificates.crt`; any other gets `/etc/hosts` naming the loopback. Every host path is bound read-only, the build directory alone writable, where upstream binds them plainly: a builder that runs as the invoking user could otherwise change a valid store path, the bundled shell later builds run, an `--exec-wrapper` launcher, or a file of the user's a `sandbox-paths` entry names. The one exception is upstream's too: where the kernel will not mount a devpts of the sandbox's own, the host's `/dev/pts` and `/dev/ptmx` are bound writable instead (`LocalDerivationGoal::runChild` in local-derivation-goal.cc at 2.24.9, `ChrootLinuxDerivationBuilder::enterChroot` at 2.36.0). A `sandbox-paths` target, or `sandbox-build-dir`, that is not absolute or has a `..` component is refused, since joined to the chroot it names a path outside it, and so is one whose path crosses a link in the chroot, such as `/dev/fd` or a link an earlier entry copied in; upstream joins a target to its chroot as it is and follows what it finds. Each directory on the way is opened by its descriptor, which takes search on it and not read, and a bind is made read-only through the descriptor of the mount just made, not by its path. Once the builder has ended, before anything reads an output, the chroot is closed to every other user: the directories from its root down to its store directory become 0700, and every directory in the store directory's subtree, an output's own included, becomes 0700, each read without following a link and changed only once its parent is closed, since a fixed-output builder, which keeps the host's network, could have passed another user a descriptor for one of them. Whether the builder left an output writable by others is read first, so such an output is still refused. A process of the same user, a concurrent build among them, is not kept out. A bind is read-only through every mount beneath its source, which a recursive bind brings along, on any kernel: in one step through `mount_setattr` from Linux 5.12, and before it by remounting each mount `/proc/self/mountinfo` lists there. The builder gains no privileges through its exec, from a setuid program or file capabilities a `sandbox-paths` entry makes reachable, as upstream's builder gains none by default (`allow-new-privileges`, globals.hh at 2.24.9, local-settings.hh at 2.36.0), and it starts with an empty session keyring of its own, so it does not inherit possession of the invoking user's session keyring. That is all the keyring stops: a builder that runs as the invoking user's uid is shown the user's keys in `/proc/keys`, and that uid may link the user keyring into the builder's own, so a builder that tries can read the keys the user keyring holds. Only a filter refusing `keyctl`, `add_key` and `request_key` closes that, as it would for upstream's single-user builds; a builder that runs as a build user, upstream's or nova-nix's as root, has no keys of the invoking user's. An interrupt, or nova-nix's end, makes the helper kill the builder, whose PID namespace the kernel ends with it, and a helper killed outright takes the builder with it unless the builder has cleared its own parent-death signal, which upstream's builder, PID 1 of its namespace too, can as well; nova-nix returns from an interrupt only once the helper has reaped the builder, so no process a builder started outlives the build, and the chroot is removed after them. The helper puts `SIGCHLD` back to its default before it starts a builder, as upstream's `initNix` does (shared.cc), so a nova-nix started with `SIGCHLD` ignored still sees its builder end. The settings are upstream's, under its names, aliases and defaults: `sandbox` (`build-use-chroot`, `build-use-sandbox`) takes `true`, `relaxed` or `false`, and refuses anything else with `option 'sandbox' has invalid value`; `sandbox-paths` (`build-chroot-dirs`, `build-sandbox-paths`, and `extra-` for each) binds `TARGET=SOURCE` entries, with `?` after a source that may be missing and a store source's closure bound beside it; `sandbox-fallback`, `sandbox-build-dir`, `sandbox-dev-shm-size`, `require-drop-supplementary-groups` and `ssl-cert-file` are read too. `build`, `eval` and `trust`, each of which evaluates, take `--sandbox`, `--no-sandbox` and `--relaxed-sandbox`, and upstream's `--build-use-chroot` and `--build-use-sandbox`, which mean `--relaxed-sandbox` as upstream's do: it registers the setting's older names on all three flags, and the last registration holds them (`Args::addFlag` in args.cc). Under `sandbox = true` a derivation setting `__noChroot` fails with upstream's error; under `relaxed` it, and a fixed-output derivation, builds unsandboxed. A setup step that fails is reported with the words of upstream's error for it and the system's text for the errno, after `while setting up the build environment: ` on the same line, where upstream prints that context as a trace line and the error after an `error:` of its own. A derivation whose builder is a host program, such as `/bin/sh`, now needs `--no-sandbox` or a `sandbox-paths` entry binding it: a release archive for Linux carries a static busybox in `libexec/nova-nix/sh`, which `sandbox-paths` names as `/bin/sh` unless an assignment replaces it, as packaged upstream Nix carries its sandbox shell, and a `cabal install` keeps upstream's empty default. BusyBox is GPL-2.0, so each release also carries, beside the archives, the source that busybox was built from, Ubuntu's source package for that version, which the copyright notice beside the binary names. Ubuntu since 24.04 lets an unprivileged process make a user namespace but denies it capabilities there unless an AppArmor profile with a `userns` rule covers the program, so there a build runs unsandboxed unless such a profile names `nova-nix-sandbox`; upstream's root daemon is not restricted that way. A system that cannot make the sandbox builds without it under `sandbox-fallback`, as upstream does, but prints one warning naming the cause, where upstream prints nothing, since nova-nix run by a user other than root falls back on every stock Ubuntu; with `sandbox-fallback = false` the build fails with upstream's `this system does not support the kernel namespaces that are required for sandboxing`. As root a sandboxed build runs as a member of `build-users-group`, as the entry on build users below describes; with `build-users-group` empty it is refused before anything is set up, whatever `sandbox-fallback` says, since the builder would map to root on the host, and `--no-sandbox` builds it unsandboxed. Windows builds are not sandboxed, and `sandbox = true` there falls back the same way. (#673)+- **A derivation whose builder is `builtin:buildenv`, the derivation `nix-env` evaluates for a user environment, builds as upstream's does: its output links every package its `derivations` attribute names into one tree, with `manifest.nix` linked to its `manifest`.** Such a derivation reached the path that spawns a builder, which refused it, since its `system` is `builtin`, with `no way to run a builtin builder on this machine`. The tree is upstream's `buildProfile` (builtins/buildenv.cc at 2.35.4), rule for rule. Packages are taken in order of priority, where the lower number wins, then of path, each path once, and each package's `nix-support/propagated-user-env-packages` queues the packages it names, which follow every package given at priority 1000 and up, one number per queued path in path order. An entry is linked where nothing stands. A directory where a link to a directory stands turns the link into a directory of the tree's own, holding what the link led to, resolved through every link, at the link's priority, and then the new entries at theirs; where the link leads to anything else, the build fails with upstream's `collision between ... and non-directory ...`. A file where a link stands replaces it when its priority number is lower, is passed over when it is higher, and when the two are equal fails the build with upstream's `Unable to build profile. There is a conflict for the following files:`, naming both; a file where a directory of the tree's own stands fails with `collision between non-directory ... and directory ...`. Names starting with `.` are skipped, as are `propagated-build-inputs`, `nix-support`, `perllocal.pod`, `log`, `manifest.nix` and `manifest.json` wherever they are and `dir` inside an `info` directory, an entry whose link leads nowhere, with upstream's `skipping dangling symlink` warning, and a package that is not a directory, with `not including ... in the user environment because it's not a directory`. The `derivations` attribute is read as upstream reads it: whitespace-separated tokens, empty ones dropped, in groups of an activity, a priority, an output count and that many paths, where only `false` makes an element inactive and an inactive element's paths are never read. A priority is read as `stoi` reads one, so a float priority, which `buildenv.nix` writes as `5.500000`, reads as 5. Each link names its package as the store spells it on disk: `/nix/store/...` under the default store on Linux and macOS, which are upstream's bytes, `C:\nix\store\...` on Windows, and the store directory `--store` names otherwise. Three things differ from upstream. A directory is read sorted where upstream reads it in `readdir` order, which does not change the tree but can change which pair a failure names when several entries conflict. Every package path, including those a `propagated-user-env-packages` file names, and the manifest must be a store path, in the canonical spelling or the store's own, where upstream's builder reads whatever path it is given; a sandboxed upstream build can read nothing outside its closure either, and nova-nix runs the builtin in its own process, outside any sandbox. And an attribute that ends inside an element, or a priority or count that `stoi` or `stoul` cannot read, fails with a message of nova-nix's own, where upstream reads past the last token or fails with no more than the function's name. On Windows each link is a symlink, which needs Developer Mode or an elevated shell, as a build's `result` link does. (#696)+- **On macOS, `sandbox = true` runs a build under a profile of macOS's sandbox, as upstream's does: the build reads its inputs and the paths `sandbox-paths` names, writes only its outputs and its build directory, and reaches the network only when it is fixed-output.** `sandbox` stays off by default on macOS, as upstream's does (the `sandbox` setting in local-settings.hh at 2.36.0). The `nova-nix-sandbox` helper, now built and shipped for macOS too, applies the profile with `sandbox_init_with_parameters` in the builder's own process just before its exec, as upstream 2.36.0 applies its profile in the child it forks for the builder (`DarwinDerivationBuilder::setUser`), and passes upstream's parameters: `_NIX_BUILD_TOP`, the build directory; `_GLOBAL_TMP_DIR`, which is the build directory too (see below); and `_ALLOW_LOCAL_NETWORKING` for a derivation that sets `__darwinAllowLocalNetworking`. The profile is nova-nix's own text, written to the rules of upstream's `sandbox-defaults.sb` and `sandbox-network.sb`: everything is refused unless allowed; the build may write `/tmp` itself and its build directory, start processes and signal its own, read the system's version, time zones and locales, use POSIX semaphores and the standard devices, and it may make no file setuid or setgid; a fixed-output build also reaches the network, resolves names and checks certificates; any other reaches no network, or the loopback alone under `__darwinAllowLocalNetworking`. The build sees its build directory and its outputs where they are on disk, and is told upstream's `HOME`, `/homeless-shelter`. The profile names the store directory and the build directory as the kernel resolves them, since macOS's sandbox matches a file by its resolved path, so a store reached through a link, such as one beneath `/var`, still matches; upstream names its store and build directory as given. Each path is escaped in the profile's strings, as upstream escapes it (`sbplQuote`), and the store paths are grouped by the first character of their hash, each group under a guard of its own, as upstream groups them: macOS compiles the path filters of one operation into one table of at most 64 KiB, however many forms hold them, so a closure of some thousands of paths needs the groups. Where upstream lets a build write its inputs and the paths `sandbox-paths` names, under build users who own none of them, a nova-nix builder that runs as the invoking user owns the store and any file a `sandbox-paths` entry may name, so the build may only read and run them, as the Linux sandbox binds every host path read-only. `sandbox-paths` defaults on macOS to upstream's `/System/Library/Frameworks`, `/System/Library/PrivateFrameworks`, `/bin/sh`, `/bin/bash` and `/usr/lib` (the macOS defaults in globals.cc), and an entry there must name one path on both sides of its `=`, as upstream's must. A derivation's `__impureHostDeps` may each name a path at or beneath an entry of the new `allowed-impure-host-deps`, whose macOS default is upstream's `/System/Library`, `/usr/lib`, `/dev` and `/bin/sh`, and its `__sandboxProfile` ends the profile under `relaxed`, where `sandbox = true` refuses it in upstream's words (`makeDerivationBuilder` in unix-derivation-builder.cc). A `__sandboxProfile` that is not a string, or an `__impureHostDeps` that is not a list of strings, in structured attributes is refused in upstream 2.36.0's words, its JSON type error after `while parsing derivation '...': while parsing attribute "...": `. The new `darwin-log-sandbox-violations` sends what a profile refuses to the system log. A path a build may not do without that is missing fails the build in upstream's words, `getting attributes of required path '`, whose quote upstream's format never closes. A profile macOS refuses fails the build as `while setting up the build environment: failed to configure sandbox`, with upstream's line and macOS's reason in the build log, where upstream reports the end of the builder's pipe while it waits for the build environment, that line among the messages before it. A `sandbox-paths` target that is not absolute is refused, where upstream loops forever. The builder leads a session of its own; an interrupt, the end of nova-nix, or the builder's own end kills every process left in its group before the builder is reaped, as upstream kills the group before it waits. The helper checks once per process that macOS takes a profile from it; where it does not, as for a process already in a sandbox, or where the helper is missing, a sandboxed build fails whatever `sandbox-fallback` says, as upstream reads `sandbox-fallback` on Linux alone (`makeDerivationBuilder`) and fails a macOS build whose sandbox cannot be made, in its words, `while setting up the build environment: failed to configure sandbox`. As root a sandboxed build runs as a member of `build-users-group`, as on Linux. An unsandboxed build on macOS runs under no profile: upstream holds one to a profile that refuses setuid and setgid files (`sandbox-minimal.sb`), and it picks a universal builder's architecture from the derivation's system (`DarwinDerivationBuilder::execBuilder`), neither of which nova-nix does yet. (#725)+- **A macOS build reaches none of the invoking user's own files, sockets, terminals or shared memory, and none of its processes outlives it, where upstream's profile assumes a build user of its own.** Upstream runs a macOS build as a build user, who owns nothing beyond the build, and its profile grants what is harmless for that user; nova-nix runs the builder as the invoking user unless it runs as root, so the profile leaves out each grant that would reach that user's own resources, for a build as a build user too. Upstream's `_GLOBAL_TMP_DIR` is the temporary directory Nix runs with, `TMPDIR` or `/tmp`, which the build may write and connect a Unix socket in; nova-nix's is the build's own directory, which the builder's `TMPDIR` names already, so a build reaches none of the user's live sockets and files in the temporary directory; a build as a build user is given upstream's. Upstream's default `sandbox-paths` on macOS also name `/private/tmp` and `/private/var/tmp`; nova-nix's leave them out for the same reason. Upstream allows pseudo-terminals and the terminal devices; nova-nix refuses them and `/dev/console` after every other rule, so `/dev` among a derivation's `__impureHostDeps` reaches none either, since a build that opened one of the user's terminals would read what is typed there and write to it. A build that needs a pseudo-terminal of its own cannot have one. Upstream allows POSIX and System V shared memory and semaphores; nova-nix allows POSIX semaphores alone, which Python's `multiprocessing` takes, since the others would attach the user's own, a PostgreSQL server's System V segment among them. A build that uses System V IPC, PostgreSQL's own tests among them, fails. Upstream ends a build by killing every process of its build user (`UnixDerivationBuilderImpl::killSandbox`, which calls `killUser` in processes.cc); nova-nix's helper, which cannot do that as the invoking user, ends every process that carries the build's mark: a Mach service name, random and made by the helper for that build alone, which the build's profile allows as its last rule, beside a second it refuses. Under `sandbox = true` no other process's sandbox answers the same and the build cannot change the answer; under `relaxed` a derivation's own profile can redefine the forms that state the mark, as `relaxed` already lets a derivation build with no sandbox at all. The helper asks a process about the refused name first, so one that applies a sandbox of its own between the two questions is not taken for the build's. Each time it lists the user's processes it stops every process of the build it finds, those it stopped before included, since one of them may continue another; once a listing finds none new, it kills them, waits for each to end, and lists again, and it reports the build as it ended only when a listing taken after that finds none of the build's left, nor any process that ended before it could be asked. Its listings are bounded, and a build whose processes are still found when they run out, or whose killed processes cannot be watched or do not end in time, fails. It does so after the builder ends and on every way the helper ends: the end of nova-nix, an interrupt, or any terminating signal it can catch, `SIGUSR1` among them. The builder writes its output to a pipe the helper copies into the build log, so the log, and nova-nix's wait for it, ends when the helper does, even when a process of a failed build still holds that pipe; and the helper never blocks on the log, so interrupting a build whose builder writes without pause ends it at once, while a slow or paused reader of the log, such as a pager, never fails a build. So a process of the build that leaves the builder's process group by a session of its own cannot outlive the build and change its output once it is registered, and nova-nix's helper is gone only once the build's processes are, unless it is killed with `SIGKILL`, which no process can catch. A signal the helper inherits ignored, as `SIGHUP` under `nohup`, does not end the build, since the helper runs in nova-nix's process group and upstream's builder, in a session of its own, never sees one sent there. Two exposures remain while the builder runs as the invoking user: a build may create System V shared memory segments and semaphores, which no profile rule refuses, though it can neither use nor remove one, so each outlives the build, counts against the system's limit (`kern.sysv.shmmni` segments) and may hold a key one of the user's programs wants; and a build may read the command lines of the user's other processes (`KERN_PROCARGS2`), which neither `sysctl-read` nor `process-info*` rules reach, where the kernel refuses a build user another user's. A build as a build user cannot read another user's command lines, and the System V objects it leaves are not removed, where upstream removes its build user's. (#725)+- **`--keep-failed`, or `-K`, and the `keep-failed` setting keep the directory of a build that fails and name it, and keep the rebuild of an output that `build --check` finds different as `PATH.check`, as upstream's do.** Without them a failed build's directory and a differing rebuild are removed, as before, so neither what made a build fail nor what a check found different could be read. The flags are `nix-build`'s, and `--keep-failed` is also `nix build`'s; nova-nix takes both on every command that builds (`eval`, `build`, `develop`, `print-dev-env` and `profile add`), and like `--fallback` a flag only turns the setting on. A build that does not succeed, one that stops short of registering its outputs, is interrupted, or is a check that finds an output different, keeps its directory under the store's `.nova-nix/builds` and prints upstream's `note: keeping build directory "DIR"` on stderr before its failure is reported. `DIR` is the directory the builder worked in: for a build in the Linux sandbox, the `build` directory inside the build directory, which the builder saw at `sandbox-build-dir`, as upstream names it. The sandbox's chroot is removed whatever the setting says, as upstream's is. A build whose builder is a builtin keeps nothing, as upstream's does, since a builtin's directory may hold privileged files. A build the sandbox refuses is now refused before its directory is made, as upstream refuses one before it makes one. A check that finds an output different moves that output's rebuild, as it was compared, its scratch hashes rewritten and its metadata canonical, to the output's path with `.check` after it, replacing whatever was there, registers nothing, and fails with upstream's `derivation '<drv>' may not be deterministic: output "<path>" differs from "<path>.check"`; only the first output that differs is kept, since the check stops there, as upstream's does. A collection removes a `.check`, which no row registers, even beside a live path, as upstream's removes one unless its path is in use at the time; a kept build directory is under the state directory, which a collection never reads, as upstream's build directories are outside its store. Without `keep-failed` the check's message is upstream's `output "<path>" differs`, its path now in double quotes as upstream quotes it, where nova-nix used single quotes. Three things differ from upstream. A kept directory keeps mode 0700, where upstream opens it with 0755 because its builder ran as a build user whose files the user who asked could not otherwise read; here the builder ran as that user, or as a build user for root, who can read anything. A kept directory stays until the derivation is next built, which removes it as it removes whatever an earlier build left at the name, where upstream's stays until it is removed by hand, since no later build takes its name: the name is the derivation's first output's, so that a rebuild sees the paths the first build saw, and keeping a directory must not move the next check of that derivation somewhere else. And on Windows a failed build's directory is kept too, where upstream's Windows builds remove theirs whatever the setting says. (#733)+- **On macOS the sandbox helper reports at most one failure, so a build whose setup step fails names that step even when the helper also lost its watch on the build log, where it was refused as a status that cannot be read.** The builder's process reported a failed setup step on the helper's status channel itself, and the helper, after it reaped that process, wrote a second record when it could no longer watch the log; nova-nix refuses a status of two records as one it cannot read, losing the step that failed. The builder's process now reports on a pipe of its own, which its exec closes, and the helper relays what it says, reporting the lost log only when the builder's process reported nothing. Upstream's builder reports a failed step through the one pipe it reads the builder's setup from. (#739)+- **On Linux and macOS a build's `PATH`, unless its derivation sets one, is upstream's `/path-not-set`, so a builder finds no program its derivation does not name, where nova-nix gave it the builder's own directory, that directory's sibling `usr/bin`, `/usr/bin`, `/bin` and `/usr/local/bin`.** Upstream's `initEnv` (unix-derivation-builder.cc at 2.36.0, the same in 2.24.9 and 2.34.9) sets `PATH` to `/path-not-set` before the derivation's own variables, a value naming no directory, so that a shell does not fall back to a search path of its own as it would were `PATH` unset; a derivation reaches a program on the host only by naming it, and nova-nix's builds reached the host's tools unasked, so a derivation that built here could fail upstream. Windows keeps the builder's directory, its sibling `usr\bin` and the system's directories, which `cmd.exe` and a job's environment need; upstream's Windows builder passes on the `PATH` it was started with. (#737)+- **On Windows a builder named relative to the working directory, such as `./tools/bash` or `tools/bash`, puts none of its directories on the build's `PATH`, as a bare name or `./bash` already put none.** The build's working directory is its build directory, so `./tools` on `PATH` would let a file the build writes there resolve ahead of every tool; only a builder whose directory is absolute, or rooted on the working directory's drive, adds its directory and that directory's sibling `usr\bin`. (#737)+- **`nova-nix-sandbox` builds on Windows, with a backend that runs a builder as the build slot's account whose token it is handed: on the window station of that token's logon, with its image opened as the slot, attached to a pseudoconsole the helper owns, in a job that caps each process's memory and lets none of them break away, and with every process of the slot's account ended before the build and after it. Windows builds do not run through it yet, and run as before.** Upstream's builds run as `nixbld` users, and upstream ends every process of its build user before and after each build. On Windows a build account's token is held by the service that logs each slot on and starts the helper, which hands it one slot's token as a handle the plan names, with the slot's SID, and the helper refuses a token that is not a primary token of that account. The builder starts with no window station named, which puts it on the station Windows makes for the slot's logon, since a service running as a virtual account cannot make one and its own is not the slot's to open. CreateProcessAsUserW opens a builder's image with its caller's access, so the helper starts the builder impersonating the slot, and refuses a builder the slot may not read. A process started with a console of its own, as libiberty starts gcc's subprograms when gcc has none, fails to start under a build account's token, where one sharing its parent's console starts, so the builder is attached to a pseudoconsole the helper owns and drains; the build log stays the builder's standard output and error, and its standard input is NUL. The builder starts suspended and joins the build's job before it runs; the job kills its processes when the helper's handle to it closes, however the helper ends, ends a process at an unhandled exception at once, and nests in the process library's job. A process a build has WMI start runs outside the job and outlives it, holding what it copied from the build, the build log among them, so the helper ends every process running as the slot's account before the builder starts and once the job holds no process, listing them again until a listing finds none; a sweep that fails before the build is reported on the status channel, and one that fails after it is said in the build log and fails the build. The helper exits with the builder's exit code once the job holds no process and the sweep is done, ends the job when its lifeline closes, says in the build log which process the memory cap stopped, and reports a step that fails before the builder starts on its status channel, with the Win32 error of the call that failed. Its probe checks that it can enable `SeAssignPrimaryTokenPrivilege` and `SeIncreaseQuotaPrivilege`, which starting a process as another account takes. (#743)+- **builtin:unpack closes an archive once it has read it, where an unpack stopped partway through, by its budget or a refused entry, left the archive open until a garbage collection.** The archive was read lazily, so its handle stayed open until the rest of it was read, which an unpack that stops never does, or until a collection finalized it; on Windows an open file cannot be deleted, so the archive's store path could not be removed in the meantime by the process that unpacked it. The archive is now read whole and its file closed before it is decompressed and decoded. (#771)+- **As root on Linux and macOS, a build runs as a member of `build-users-group`, `nixbld` by default, as upstream's does, so a builder can change neither the store nor another build, and no process it leaves outlives it.** A sandboxed build as root, which nova-nix refused for want of build users, now runs as one; it is refused only with `build-users-group` empty, under which an unsandboxed build runs as root. Each build takes the first member, in the group's order, whose lock file in upstream's user pool, `/nix/var/nix/userpool` or `$NIX_STATE_DIR/userpool`, is free, locked with `flock` as upstream's are, so a build of nova-nix's and one of an upstream daemon's on the same machine never share a user. While every member is taken the build waits, saying `waiting for a free build user ID for '<drv>'` once, and looks again every five seconds, upstream's default `poll-interval`. A group that is missing or has no members, a member that names no user, and a member that is the user nova-nix runs as fail the build in upstream's words. Every process of the member is killed before the build and once its builder ends, before any output is read. The store directory is made root's and the group's with mode 1775, as upstream's store open makes it; the directory the builder works in and the files nova-nix writes there are the member's; and a build is refused when the directory holding build directories, or one above it, is one every user may write, with upstream's `is world-writable or a symlink`. In the Linux sandbox the namespace's uid 1000 and gid 100 map to the member and the group, and the chroot's root and store directory are the group's, as upstream's are. Outside the sandbox, and in macOS's, the builder takes the member's uid, the group and, on Linux, the member's other groups, as upstream keeps them for a group such as `kvm`, set between the fork and the exec by a small C shim, since the process library can drop to another user only by looking it up in the forked child of a threaded process; the groups are looked up beforehand instead. A macOS build as a member is given upstream's temporary directory, `TMPDIR` or `/tmp`, in its profile, where a build as the invoking user keeps its own. An output whose root is not the member's is refused with upstream's `suspicious ownership or permission`, and one holding a node another user owns with `invalid ownership on file`, before it is made canonical; a passing output is made root's and read-only. A builtin builder still runs in nova-nix's own process, as root, where upstream runs it in the build's child as the member. The System V IPC objects upstream removes for a macOS build user are not removed, and `auto-allocate-uids` is not read. (#770)+- **A Windows builder's process that meets an unhandled exception ends at once with the exception's code, and Windows Error Reporting no longer starts WerFault.exe from inside the build.** A configure test that divides by zero, as gettext's check for SIGFPE does, had the reporter start, a program from outside the store that can wait on a dialog. The job each unsandboxed builder runs in now has `JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION`, as the sandbox helper's job has, the counterpart of upstream having a crashing builder dump no core. The limit is the job's, so it holds for a process that sets its own error mode, as busybox-w32 does. The `process` floor rises to 1.6.8, the first release whose process handle holds the process and its job alone, the job the limit is set through. (#777)+- **`builtin:fetchurl` with `unpack` reads a NAR body only to the archive's end, as upstream does, so bytes a server sends after the archive are left unread rather than failing the fetch.** Upstream's builtin restores the download through `parseDump` (fetchurl.cc and archive.cc at 2.36.0), which stops at the root node's close and never reads what follows, so the output is the archive and its hash the archive's. nova-nix parsed the body as an archive that must end with it, and failed a body with any byte after the root node as a malformed NAR. (#761)+- **On Linux and macOS an unsandboxed builder that runs as the user nova-nix runs as starts and ends as upstream's child does: in a session of its own, with `/dev/null` open to read and write as its standard input, every other descriptor closed, upstream's core limit and its program's base name as its first argument, and with every process left in its process group sent SIGKILL once its log ends, or when the build is interrupted.** It started through the process library, which left it nova-nix's controlling terminal, its core limit and its descriptors, and an interrupt sent SIGTERM to the builder alone, so what the builder had started ran on after the build. Upstream's child makes a session of its own, reroutes standard input to `/dev/null`, and sets a soft core limit of 0 with no hard limit, a call a process that is not root is refused where its hard limit is finite, which keeps its soft limit; upstream takes the builder's status by killing its process group, so a builder that closes its log but keeps running now fails on signal 9, as upstream's does, and a build user's builder ends the same way. The builder is executed by its path, with no search of `PATH`; one that cannot be executed fails with exit code 1, with why as the build log's last line, as upstream's child writes it. A failed kill of the group is logged and the builder's own status kept, as upstream's is. (#778)+- **`builtin:unpack` leaves out the archive members its derivation's `omit` names, each by its path from the archive's root.** stage0-pe32's tree is unpacked before any tool exists, so the builtin is what removes the file there. A path that no archive in `srcs` holds fails the build, as does one that leaves the archive or names its root. (#762)++### Substitution++- **A build no longer substitutes the outputs of a derivation whose `allowSubstitutes` attribute is false: it builds them, as upstream does, unless `always-allow-substitutes` is on in nix.conf or `NIX_CONFIG`.** nova-nix did not read the attribute, so such a derivation came from a cache whenever one held its outputs. nixpkgs sets it on the builds that cost less to run than to download, `runCommandLocal` and `writeTextFile` among them. Upstream reads the attribute in `ParsedDerivation::substitutesAllowed` (parsed-derivations.cc at 2.24.9) and starts no substitution for a derivation that forbids it (`DerivationGoal::haveDerivation`), going on to its inputs, which are substituted or built as any other derivation's are. A derivation without the attribute may be substituted. In a derivation's environment only `1` allows it, which is how evaluation writes `true`; with structured attributes it is a JSON Boolean, and any other value there stops the build with upstream's message, `attribute 'allowSubstitutes' of derivation '<hash>-<name>.drv' must be a Boolean`. The rule covers what a derivation's own goal does: a path that another substituted output references still comes from the cache, since upstream's `PathSubstitutionGoal` never reads the attribute. `always-allow-substitutes` lets every derivation be substituted and leaves the attribute unread, as upstream's setting does. Structured attributes that are not JSON now stop the build before the derivation's outputs are looked at, with `cannot process __json attribute of '<hash>-<name>.drv'`, as upstream's `ParsedDerivation` constructor stops it; nova-nix raised that only when it came to build the derivation, and named it by its `name`. Upstream also derives the flags `--always-allow-substitutes` and `--no-always-allow-substitutes` from the setting, which nova-nix does not. (#421)+- **A build realises each input for the outputs its dependent's `.drv` names, so a dependency on one output of a derivation fetches that output and its closure, and an output nothing asks for no longer makes the derivation build.** The dependency graph kept each input's `.drv` path and dropped the output names, and each derivation was checked and substituted for every output it has, so a dependency on `openssl.drv!dev` needed every output of openssl, and one of them missing from every cache rebuilt openssl and what it is built from. Upstream's goal for an input wants the outputs the dependent's `.drv` names (`DerivationGoal::gaveUpOnSubstitution`, derivation-goal.cc at 2.24.9), is valid once those are (`checkPathValidity`) and substitutes those alone (`haveDerivation`); a build makes every output. nova-nix now does the same. A derivation asked later for an output it has not realised, as when one dependent wants its `dev` and another its `out`, is realised again for that output, from a cache or by a build, as upstream's worker drops a goal once it is done (`Goal::amDone`, goal.cc, and `Worker::removeGoal`, worker.cc) and starts a new one for the next request (`Worker::makeDerivationGoalCommon`, worker.cc at 2.24.9). An input asked for an output it does not have, which `builtins.appendContext` can name, fails the build with upstream's `derivation '<drv>' does not have wanted outputs '<name>'` (`DerivationGoal::checkPathValidity` in derivation-goal.cc) before anything is fetched for it, where the build of its dependent refused it after the input was realised. The derivation a build is given is realised for the one output the expression selects, as `nix-build` asks for it (`main_nix_build` in nix-build.cc). Under the output locks a build still adopts a derivation another process finished only when every output is valid, where upstream adopts it once the wanted ones are (`DerivationGoal::tryToBuild` in derivation-goal.cc at 2.24.9). (#503)+- **A build asks each cache for a path's narinfo once, and takes the path's NAR from the cache whose narinfo gave the references it realised first, as upstream does.** A substitution read each path's narinfo to learn its references, then read it again before fetching the NAR, so a closure of N paths cost 2N narinfo requests, and a path no cache holds was asked about again each time a derivation that references it was tried, after its inputs as well as before. The second read could also reach another cache: when the first stopped serving the narinfo or no longer held the NAR, the NAR came from the next cache with that cache's references, which nothing had realised, the store refused the registration, and the build stopped or fell back to building. Upstream's substitution goal queries one substituter's path info, realises the references it declares, and copies the path from that same substituter, and the store's path-info cache answers every later query for the path, one for a path the substituter lacks included (`PathSubstitutionGoal::init` and `tryToRun` in substitution-goal.cc, `Store::queryPathInfo` in store-api.cc at 2.24.9). nova-nix now fetches a path with the narinfo its references came from and remembers what each cache said about each path for the rest of the build, so each narinfo is requested once; a query that failed is not remembered, as upstream caches no failure. A path whose NAR a cache fails to deliver, or no longer holds, goes to the caches after it, as upstream's goal goes to its next substituter: the next cache that serves the path has the references it declares realised first, and the path comes from it. Each output a build wants of a derivation runs its own course, as each of upstream's goals does: once one has no cache left, the others are still fetched from the caches that offer them, registering nothing, and the substitution has failed only when an output ran out of caches after one failed to deliver it, which is when upstream stops the derivation (`DerivationGoal::outputsSubstitutionTried`, derivation-goal.cc at 2.24.9, `DerivationGoal::haveDerivation` at 2.36.0); otherwise the derivation builds. When the outputs wanted of one derivation arrive together and one of them comes from a later cache, the others are fetched again, since none was registered, where upstream registers each output as it arrives. Upstream's cache also expires an entry, after an hour for a path a substituter lacks and a month for one it holds (`narinfo-cache-negative-ttl`, `narinfo-cache-positive-ttl`), and keeps it on disk across runs; nova-nix remembers for one build, or one substitution of a `nova-nix trust` input, and writes nothing to disk. (#518)+- **A substitute whose NAR file is larger than its narinfo's FileSize is downloaded, as upstream downloads it, where the substituter stopped with `NAR body exceeds its download ceiling`.** The download cap was the smaller of a ceiling derived from the signed NarSize and the narinfo's FileSize, which no signature covers. cache.nixos.org names its zstd NARs by their NarHash, so every store path with the same NAR shares one file, and an upload that compresses that NAR again replaces the file whose FileSize and FileHash an earlier narinfo records. In the closure of the x86_64-linux stdenv of nixpkgs 26.05, `/nix/store/s52vdyj97g3adv6qb431v8m2kccs0bzz-linux-headers-6.18.7` declares a FileSize of 1891795 bytes, while the file its URL serves is 1891934 bytes and decompresses to the NAR its signed NarHash and NarSize name, so a build that substituted that stdenv failed. Upstream reads FileSize only for progress and download statistics (`build/substitution-goal.cc` and `misc.cc` at 2.35.4, `build/substitution-goal.cc` and `store-api.cc` at 2.24.9), never compares a download with FileHash, and checks a substituted NAR against NarHash and NarSize alone (`local-store.cc`). The cap is now the ceiling of the signed NarSize, which is NarSize plus the larger of 64 KiB and a 64th of NarSize, so a narinfo whose signature verifies still cannot buy a larger download, and a body past that ceiling still fails at once, without a retry. FileSize is still parsed and validated as before. (#693)+- **A substituted path whose narinfo states a content address is held to it, as upstream holds one: once its NAR's hash and size are checked, the tree is hashed as the address's method reads it, modulo the path's hash part, and a tree that hashes otherwise is removed and refused with upstream's `ca hash mismatch importing path '...'`, both hashes after it.** nova-nix checked a substitute against its narinfo's NarHash and NarSize alone. Upstream's `LocalStore::addToStore` (local-store.cc, the same at 2.24.9, 2.34.9 and 2.36.0) also checks a narinfo's `CA`: a `fixed:r:` address is of the tree's NAR, and a `fixed:` or `text:` address of the bytes of the one file it names, each hashed under the address's algorithm with every occurrence of the path's hash part counted as zeros and the offset of each appended, so a tree that refers to itself does not hash as one with zeros in its place. A narinfo that states no address is still held to its NarHash alone, as upstream's is, so a fixed output a cache supplies without one is not held to its recipe's hash, and `trust`'s reference now says so. (#738)+- **A narinfo whose StorePath has the requested path's hash and another name is passed over, as upstream passes one over, where nova-nix took it for the requested path.** Upstream's `Store::queryPathInfo` (store-api.cc, the same at 2.24.9, 2.34.9 and 2.36.0) holds the path a narinfo names to the requested one by `goodStorePath`, which compares the name as well as the hash, and moves on to the next substituter when they differ; nova-nix compared the hash alone. (#739)+- **A `file://` URL in `substituters` or `--substituter` names a binary cache in a directory, and a build substitutes from it as upstream substitutes from its local binary cache store, so a cache `push` writes to a drive can be carried to another machine and read there with no web server (`file:///D:/cache` on Windows).** The substituter read only HTTP: it handed every URL to its HTTP client, so a `file://` one failed every query. A directory cache's narinfos and NARs now go through the steps an HTTP cache's do: a narinfo must name the path and be signed by a trusted key, unless its content address makes its path or `require-sigs` is off, the NAR is decompressed by the narinfo's `Compression` and held to its `NarHash`, `NarSize` and content address, and caches are asked in priority order. A narinfo the directory lacks is a miss and a NAR it lacks is a substitute gone, as a 404 is for an HTTP cache; a file that cannot be read fails, and is not retried, since upstream retries downloads alone. A narinfo `URL` that is empty, absolute or holds a `.` or `..` segment is refused in upstream's words (`local binary cache path '../x.nar' must not contain '..' or '.' segments`), so a narinfo cannot name a file outside the cache. The first query of a run opens each `file://` cache as upstream's store opens one: it makes the `nar`, `build-trace-v2` and `log` directories, writes a `nix-cache-info` holding `StoreDir: /nix/store` where there is none, and reads the one there. A cache whose `StoreDir` is another store directory is passed over for the run after upstream's warning, `binary cache 'file:///D:/cache' is for Nix stores with prefix '/gnu/store', not '/nix/store'`, as upstream drops a substituter it cannot open, and so is one whose URL `push` would refuse or whose directory cannot be made or read. The cache is asked at the `Priority` its `nix-cache-info` states, or at upstream's default of 0 when it states none, as a `push` writes it, so such a cache comes before the HTTP caches, which nova-nix asks at 50. A `Priority` that is not a 32-bit integer fails the query whatever `fallback` says, as it fails upstream's command, in nova-nix's words, since upstream's are the C++ library's. `WantMassQuery` is not read: it governs only queries about many paths at once, which nova-nix does not make. The URL is read as `push` reads one: an empty host and an absolute path, with no query, fragment or percent-escape, where upstream would read a query such as `?priority=10` as the store's settings. An HTTP cache's `nix-cache-info` is still not read, so its priority is the configured one and its `StoreDir` is not checked: with `substituters = https://cache.nixos.org file:///D:/cache` and `Priority: 45` in the directory's `nix-cache-info`, nova-nix asks the directory first, where upstream asks cache.nixos.org, whose file states 40. A substitution makes only the directories the newest upstream release makes, so it opens a cache that release wrote, which lacks `realisations`, from a drive it cannot write to; a push makes `realisations` as well, for a reader of an older release. Each `file://` cache is opened once a run, where upstream opens it once a process, so `trust`, which makes a run for each fixed-output input, warns of a cache it passes over once for each. (#745)+- **`push` names a cache on Windows as upstream does, `file:///D:/cache`, in its refusal of a `nix-cache-info` for another store directory, names the cache when its directory cannot be made or read, and refuses a `nix-cache-info` whose `Priority` is not a 32-bit integer.** The refusal joined `file://` to the directory, which gave `file://D:/cache`. A push opens the directory as a substitution does, and upstream's `nix copy --to file://` fails on such a `Priority` as its substitution does. (#745)+- **A substituter listed twice, in `substituters`, `extra-substituters` or again with `--substituter`, is asked once, at its first listing, as upstream drops a substituter it already has.** Every listing was kept, so a cache listed twice was asked again for a path whose NAR it had failed to deliver or no longer held, and a narinfo it served that was passed over was reported twice. Two listings are one when they are spelled alike. Upstream compares them once parsed, so spellings that differ only in percent-escapes, the order of a query's parameters, a fragment or a port's leading zeros are one substituter there and two here, while a spelling with a trailing slash and one without are two in both. The library's `containers` floor rises to 0.6.0.1, the first with `nubOrd`. (#766)+- **A substitution reads a cache's NAR only to the archive's end, as upstream does, so a NAR followed by bytes the archive does not hold substitutes as the archive, held to the narinfo's NarHash and NarSize over the archive's bytes alone.** Upstream substitutes a path by importing the NAR it reads from the cache through `restorePath` (`LocalStore::addToStore` in local-store.cc at 2.36.0), whose `parseDump` stops at the root node's close and never reads what follows, and it checks the NarHash and NarSize against the bytes read to there. nova-nix parsed the download as an archive that must end with it, so such a NAR failed as malformed and the attempt was retried. (#763)+- **A substituted NAR whose hash or size is not its narinfo's is refused as upstream refuses it, the hash checked before the size and each in upstream's words: `hash mismatch importing path '<path>';` with the specified and got hashes in SRI form on the lines after, or `size mismatch importing path '<path>';` with the two sizes.** nova-nix checked the size first and worded both its own way, as `NAR size mismatch: narinfo declares <n> bytes but the stream carried <m>` and `NAR hash mismatch: narinfo declares <hash> but downloaded bytes hash to <hash>`. Upstream's `LocalStore::addToStore` (local-store.cc at 2.36.0) checks the hash of the bytes it restored, then their count, and words both so. The streamed and the whole-NAR substitution and the daemon's import of a NAR now share the one check. (#768)+- **nix.conf's `require-sigs` and `secret-key-files` decide what a substituted path must be signed by, as upstream's do, and a narinfo whose content address makes its path is substituted unsigned.** nova-nix read neither setting and asked every narinfo for a signature by a key in `trusted-public-keys`. Now `require-sigs = false` takes a narinfo unsigned, and the public key of the secret key in each file `secret-key-files` names is trusted beside `trusted-public-keys`: a file that cannot be read is passed over, as upstream passes over one a user of a multi-user installation cannot read, and one that holds no secret key, like a `trusted-public-keys` entry that does not read, ends the substitution in upstream's words ("key is corrupt", "secret key is not valid") whatever `fallback` says, as upstream decides trust outside the try that makes a failed query its cache's, so a later cache is not asked and nothing is built from source. Of keys that share a name only the first is trusted, as upstream keeps one key a name. A narinfo whose content address and references make its path needs no signature, as upstream's store counts such a path as signed, and its tree is held to that address once it is fetched. One whose address makes another path is warned of at upstream's error level, "warning: path '...' claims to be content-addressed but isn't", and needs a signature. Once a signature, or `require-sigs = false`, has it fetched, it is refused where upstream refuses to register it, with "cannot add path '...' to the Nix store because it claims to be content-addressed but isn't", and nothing is registered. One whose address makes no path, a fixed address other than a NAR's SHA-256 stated with references, ends the substitution in the same way, in upstream's words. A narinfo no trusted key signed is passed over with upstream's warning, "ignoring substitute for '...' from '...', as it's not signed by any of the keys in 'trusted-public-keys'", where nova-nix logged a line of its own. Upstream also signs each path it builds with the keys in `secret-key-files`, and nova-nix does not. (#800)++### Windows packages++- **The Mes C library compiles with a PE-targeting TinyCC against TinyCC's own `stddef.h` and `stdarg.h`, as `tinycc-boot-mes` compiles it.** Its `wchar_t` is the compiler's `__WCHAR_TYPE__` where the compiler names one, `unsigned short` for a TinyCC that writes PE, where Mes defined `int` whatever the compiler, and a PE TinyCC refused the second, incompatible definition. Its `vfprintf` and `vsnprintf` read a double with `va_arg` when compiled against a `stdarg.h` without Mes's `va_arg8`, where they stopped at `va_arg8`; nixpkgs replaces `va_arg8` with `va_arg` outright, which Mes's own `stdarg.h` defines as reading a long. MesCC names no `__WCHAR_TYPE__` and reads Mes's own `stdarg.h`, so it compiles the same declarations as before. (#401)+- **`pkgs/windows` builds TinyCC's first round on the Mes rung: `tinycc.boot-mes.compiler`, janneke's bootstrappable TinyCC compiled by MesCC into a tcc that writes PE32, and `tinycc.boot-mes.libs`, the Mes C library and TinyCC's runtime compiled by that tcc.** They are nixpkgs' `minimal-bootstrap/tinycc` `tinycc-boot-mes` derivations, each an `i686-windows` `kaem.runCommand` script, from janneke's fork at ea3900f, the commit nixpkgs pins. Four things differ from nixpkgs. tcc is built with `TCC_TARGET_PE`, so it writes PE32 from this round on: it is the one tcc in the chain MesCC links, so a tcc that wrote ELF here would leave every later round with nothing Windows runs. tcc has no include directory built in, and every derivation that runs it names the headers in `C_INCLUDE_PATH`, which tcc reads at startup, where nixpkgs writes them into tcc as a C string: the builder spells a store path `C:\nix\store/...`, and the backslash would start an escape. The library holds `crt1.o` alone of the startup files, since lib/windows has `crt1.c` alone. And nixpkgs' three edits to `x86_64-gen.c` and its PLT relocation in `tccelf.c`, which do not reach an i386 tcc, are not made. `mes.libc` now carries nixpkgs' `CFLAGS`, `-std=c11`, and `mes.baseAddress` is exported, the ImageBase MesCC links tcc at. CI builds it from the seed on x64 and ARM64 Windows, runs the tcc with `-version`, and runs a program it compiled and linked with no import table, checking what it prints and the status it exits with. (#401)+- **`pkgs/windows` builds TinyCC's bootstrappable rounds on the Mes rung: `tinycc.boot0` to `tinycc.boot3` and `tinycc.bootstrappable`, each tcc compiled by the round before it and each compiling the Mes C library the next links with.** They are nixpkgs' `minimal-bootstrap/tinycc` rounds with the options janneke's `boot.sh` gives each, the last repeating boot3's so that its floating point is compiled by a tcc that has it. Four things differ from nixpkgs besides the first round's changes for PE. tcc.c is compiled with `_WIN32` undefined and `__windows__` defined: a PE tcc predefines `_WIN32`, which tcc.c reads as a host with the Win32 API and answers by including `windows.h`, where these tccs run on Mes libc as `tinycc-boot-mes` does, and `__windows__` tells Mes's `fcntl.h` the system in its place. Each round names `crt1.o`, libc and libtcc1 when it links, since a PE tcc adds no startup file or C library of its own and links msvcrt and kernel32 unless told `-nostdlib`. Each round's `tcc.exe` is marked executable by its script, since tcc's PE writer marks nothing. And each round compiles without nixpkgs' `-g`: tcc's debugging information names the directory tcc ran in and each file by the path it opened, a source or header from the store by the store's physical path, so a `tcc.exe` that carried it would differ with the store's drive and with the user whose temporary directory the build ran in, where nixpkgs' builds see one store path and, sandboxed, one build directory. CI builds every round from the seed on x64 and ARM64, runs the last with `-version`, and runs a hello and a program printing the two words of a double it computes, both compiled and linked by the last, checking what each prints and the status it exits with, and checks that no round's `tcc.exe` names the store directory or its own build directory. `printf`'s `%f` is no check at these rounds: Mes's `dtoab` casts the double to `long`, which this tcc compiles as a call to `__fixdfdi`, and Mes's `libtcc1.c`, which nixpkgs copies over TinyCC's for the rounds, stubs it to 0. (#401)+- **`pkgs/windows` builds TinyCC's own source on the Mes rung: `tinycc-mes.prev`, TinyCC at cb41cbfe compiled by `tinycc.bootstrappable`, and `tinycc-mes`, the same source compiled by that, each with the Mes C library and TinyCC's runtime its tcc compiles.** They are nixpkgs' `minimal-bootstrap/tinycc` `tinycc-mes-boot` and `tinycc-mes` derivations, each an `i686-windows` `kaem.runCommand` script, with two of nixpkgs' three edits to the source and its `tccdefs`, tcc's predefined macros compiled into it from `include/tccdefs.h` by `conftest.c`. The archive is TinyCC's GitHub mirror's of that commit, the tree nixpkgs takes from repo.or.cz, whose snapshot does not reach every client as the same gzip stream. Three things differ from nixpkgs besides the changes the rounds before share. nixpkgs' third edit sets `static_link` in every compile, so that an ELF link writes a static executable; a PE tcc reads the flag only where it resolves `-l`, which it then keeps from finding a `.def` import library, so the edit is left out. `tcc.h` keys `PATHSEP`, which splits `C_INCLUDE_PATH`, `-I` and `-L`, on `_WIN32`, the host's macro, where janneke's keys it on `TCC_TARGET_PE`; every round compiles `tcc.c` with `_WIN32` undefined, so a third edit makes it `;`, since an unedited tcc would split a store path at its drive's colon. And `c2str`, which writes `tccdefs_.h`, is linked as every program of a PE round is, with `-nostdlib`, `crt1.o`, libc and libtcc1, where nixpkgs' bare link would pull in msvcrt and kernel32. Each round now carries the `C_INCLUDE_PATH` a script that runs its tcc sets, and a script sets that of the tcc it runs: `tinycc-mes.prev`'s tcc is compiled with janneke's headers and its library with TinyCC's. CI builds both rounds from the seed on x64 and ARM64, runs the last with `-version`, and runs a hello, the double's two words, and a double printed through `printf`'s `%f`, whose cast to `long` this round's libtcc1 has where Mes's stubs it, each compiled and linked by the last, checking what each prints and the status it exits with. (#403)+- **`pkgs/windows` builds TinyCC as a native Windows compiler: `tinycc-native.prev`, TinyCC's own source compiled by `tinycc-mes` with `_WIN32` defined, against TinyCC's `win32/` headers, and `tinycc-native`, the same source compiled by that, each linked against msvcrt.dll and kernel32.dll through the import tables tcc writes from TinyCC's `.def` files.** It is compiled with upstream's `win32/build-tcc.bat` defines, `-DTCC_TARGET_PE -DTCC_TARGET_I386`, as one executable, and each round compiles the thirteen objects `build-tcc.bat` archives as `libtcc1.a` and copies its five import libraries for the next; nothing it builds links Mes. `build-tcc.bat`'s `runmain.o`, `bcheck.o` and `bt-*.o` are not built, so `-run`, `-b` and `-bt` are not available. Where upstream's `tcc.exe` finds `include` and `lib` beside itself, `tinycc-native` reads its headers from `C_INCLUDE_PATH` and its runtime from `-B`, as the rounds before it do, since a store path, spelled with a backslash, cannot be a C string. It predefines `__MINGW32__`, as MinGW's GCC does and TinyCC does nowhere, through `CONFIG_TCC_SWITCHES`, which upstream's `configure --tcc-switches` sets, since Windows sources such as busybox-w32 choose their Windows code by it. A tcc compiled with `_WIN32` adds the Windows system directory to its library paths, so the import libraries it links by default, msvcrt's and kernel32's among them, are read from the DLLs there when the directory a script names lacks their `.def` files; an edit to the TinyCC source removes that call, and such a link fails. `-lkernel32`, `-lws2_32` and the like find their `.def` files in the `-B` directory, as upstream's do, since the source leaves out nixpkgs' edit that makes every link static, which would keep `-l` from finding them. It is built without `-g`, as `build-tcc.bat` builds it, since the debug information names the build directory. CI builds both on x64 and ARM64, checks that `tinycc-native`'s `tcc.exe` is the same bytes as the one `tinycc-mes` compiled, that it searches the `-B` directory alone and predefines `__MINGW32__`, and runs a hello, the double's two words, a double printed through `printf`'s `%f`, and a program linked with `-lws2_32` that calls ws2_32.dll's `htons`, each linked against msvcrt and ending its lines in a carriage return, as msvcrt's text-mode stdout writes them. (#404)+- **`pkgs/windows` builds GNU make 4.4.1 with `tinycc-native`, from make's Windows sources as its `build_w32.bat` compiles them with tcc, in one `i686-windows` `kaem.runCommand` script with no configure and no shell.** It follows nixpkgs' `minimal-bootstrap/gnumake`, which also builds make with tinycc and without configure. make's Windows configuration reads `__MINGW32__` as MinGW's headers being present and turns on headers TinyCC's do not have, so make compiles against TinyCC's own headers, as `build_w32.bat`'s tcc mode does, with `tinycc-native`'s predefined `__MINGW32__` undefined. As in nixpkgs, the directories make searches for an included makefile and for `-l` drop `/usr/gnu/include`, `/usr/local/include`, `/usr/include`, `/lib` and `/usr/lib`, which on Windows resolve against the current drive's root. The link takes `-luser32` and a one-name advapi32 import library, since TinyCC ships no advapi32 `.def`. A make compiled by tcc runs each recipe that needs a shell from a batch file, through `cmd.exe` unless an `sh.exe` is on `PATH`. CI builds it on x64 and ARM64, checks `make --version`, and has make build a target through a pattern rule whose recipe runs mescc-tools-extra's `cp` by its path, which make starts itself, without a shell. (#407)+- **`pkgs/windows` builds busybox-w32 FRP-6354-g5f09fb446 with `tinycc-native`, as upstream's `mingw32_defconfig` build, in one `i686-windows` `kaem.runCommand` script with no shell: the shell and tools the native rungs run configure under.** Upstream compiles busybox-w32 against MinGW-w64's headers and links MinGW-w64's runtime; this compiles it against TinyCC's own headers, with a compatibility layer of the MinGW-w64 declarations busybox-w32 reads and TinyCC's headers lack, and links five mingw-w64-crt v14.0.0 sources for the functions msvcrt.dll lacks. The headers upstream's build generates are written as it writes them: kconfig's `conf`, `applet_tables` and `usage` are compiled and run, and the shell scripts `scripts/gen_build_files.sh` and `applets/usage_compressed` are C programs in the package. Three settings differ from `mingw32_defconfig`, each for something this toolchain lacks: usage text is stored unpacked, since packing it takes bzip2 at build time; the executable carries no version information, manifest or icon, which take a resource compiler; and busybox does not expand wildcards in its own arguments, which MinGW-w64's startup code does and TinyCC's does not, so `busybox --help` reports noglob. Seven edits to the source, as well as those to the configuration, are each checked against the edited file's SHA-256, since `replace` leaves a file unchanged when its match is missing. Three are for what TinyCC does not compile as GCC does: a string literal in parentheses as an array initializer, `bswapl`, which TinyCC's assembler knows as `bswap`, and a call, in code no configuration without Unicode reaches, to a function such a configuration does not define, which TinyCC compiles where GCC drops it. Three supply what upstream's toolchain would: `dirname`, which busybox-w32 carries for newer MinGW-w64 runtimes; `ffs`, a GCC builtin; and the binary file mode MinGW-w64's startup code sets. The seventh keeps `printf`'s exit status 0 for an argument of 128 bytes or more: busybox-w32 formats each directive through msvcrt.dll's `_vsnprintf`, which sets `errno` to `ERANGE` when the output fills or overflows the 128-byte buffer libbb's `vasprintf` tries first, and `printf` takes the `errno` its directives leave for a conversion error, so it wrote such an argument whole and exited 1. GMP 6.2.1's `configure`, whose last command writes a summary that long, failed for it once it had configured. `time_t` is 32 bits, as TinyCC's headers define it for i386; the stack reserve is upstream's 2 MiB; and `busybox.exe` needs the msvcrt.dll of Windows Vista or later, where upstream's i686 build takes `_chsize_s`, `_set_fmode`, `getenv_s` and `strnlen` from MinGW-w64's runtime on older ones. CI builds it on x64 and ARM64, checks `busybox --version`, and has busybox's sh run a script through `sh`, `sed`, `grep`, `awk`, `expr`, `tr`, `cat`, `mkdir`, `rm`, `cp`, `mv`, `test` and `printf`, one of a 200-byte argument among them, checking each line it writes. (#409)+- **`pkgs/windows` has `seedStdenv`, a stdenv made only of tools built from stage0-pe32's seed, with busybox-w32's sh as the builder and its applets as the coreutils, sed, grep and awk, `gnumake` as make, and `tinycc-native`, on msvcrt.dll, as the C compiler and linker, so no MSYS2 or MinGW-w64 package is in the closure of anything it builds.** Its `mkDerivation` takes the attributes the MSYS2 stdenv took and runs the same phases from a `setup.sh` written for POSIX sh, and `pkgs/windows`' GNU Hello package builds with it unchanged. busybox-w32's applets are commands of their own through a launcher beside a copy of `busybox.exe`, as w64devkit installs them, since GNU make runs a recipe line with no shell syntax itself and `busybox --install`'s hard links would each be a copy in a NAR. Every path the stdenv passes on is respelled with forward slashes, since the builder spells the store `C:\nix\store` and a backslash is an escape in the sed scripts and C strings configure writes. The environment gives configure the two things it cannot detect about `PATH`, where every configure reads them whatever site file it is given, GCC's top level among them, which runs the configure of each directory it builds for the build machine, and of each target library, with `CONFIG_SITE=no-such-file`: `PATH_SEPARATOR=';'`, since busybox's sh runs its own `sh` applet whatever `PATH` holds, and `ac_executable_extensions=.exe`, since busybox's `test -x` does not add the suffix. configure is told `--build=i686-pc-mingw32`, since `config.guess` cannot read busybox's `uname`; `LD` is tcc, as nixpkgs' minimal-bootstrap sets it, since the iconv and gettext checks fail with no `ld`; and `BB_OVERRIDE_APPLETS=make` keeps busybox's own make from shadowing GNU make. TinyCC's headers gain MinGW-w64's `sdkddkver.h`, without which gnulib calls Vista's `GetFinalPathNameByHandle`, which they do not declare. The MSYS2 stdenv's fixup phase, which copied each DLL an output imports from a build input beside it, is left out, since nothing built from the seed reads a PE import table. A package that sets `enableParallelBuilding` gets `make -j$NIX_BUILD_CORES` in the build phase and, unless it sets `enableParallelInstalling` to false, in the install phase, with `NIX_BUILD_CORES` read as nixpkgs' `setup.sh` reads it: 1 when unset, and what `nproc` counts for 0. The ladder's rungs build with it, and the package set's `stdenv` runs this `setup.sh` with the ladder's native toolchain. CI builds Hello with the seed stdenv on x64 and ARM64 Windows, runs it and checks that it names neither the store directory nor its own build directory, and a test reads its closure: its leaves are the seed and the sources the ladder fetches. (#411)+- **Every package in `pkgs/windows` states the sources it fetches in `srcs`, and `pkgs/windows/sources.nix` lists them all.** A package names its sources inside its build script, where a walk over attributes such as nixpkgs' `find-tarballs.nix` does not find them, so nothing could fetch a package's sources without building it. CI realises the list from the public cache before each job builds, and a push to main publishes it there, so a source is fetched from its upstream host when the change that brings it is tested and merged, and not on every run. A job fails if the cache cannot be asked, where falling back would send its downloads to the upstream hosts. The test suite checks the list against the fetches in the closure of every derivation in the set. (#417)+- **`pkgs/windows` builds GNU binutils 2.41 for `i686-w64-mingw32` with the seed stdenv, compiled by `tinycc-native`: the assembler, linker, archiver and object tools, running on i686 Windows and writing i686 PE and COFF.** It follows nixpkgs' `minimal-bootstrap/binutils`, which builds the same release with tinycc. The target is the triple MinGW-w64's own build guide configures binutils for and the one under which GCC 4.6.4 takes MinGW-w64's feature set, where any other vendor is mingw.org's; the stdenv's `i686-pc-mingw32` stays the build and the host, so the tools install as `bin/i686-w64-mingw32-<name>.exe` and again under their plain names in `i686-w64-mingw32/bin`. nixpkgs' later `fix-tinycc-attribute.patch` is applied unchanged: `include/ansidecl.h` defines `__attribute__` away for a compiler that is not GCC, and TinyCC's headers spell `__stdcall` as an attribute, so without it a source that reads `ansidecl.h` before `windows.h` calls every Windows API function as cdecl and pops arguments the function has already popped, in bfd on each file it opens. A second patch, of its own, opens in binary mode the temporary file that `ar` and `ranlib`, and `objcopy` and `strip` rewriting a file in place, write their output to and copy into place: without `mkstemp`, which msvcrt.dll lacks, `make_tempname` opens it with no `O_BINARY`, msvcrt treats it as text, and the copy ends at the first 0x1A byte, so an archive of libgcc's objects comes out cut short. MinGW-w64's runtime supplies a `mkstemp` that opens in binary, so its own builds of binutils never reach that open. nixpkgs' `deterministic.patch` is not applied, since the flag it sets is read by the archive and XCOFF writers and not by the PE writer, which stamps an image with the time unless ld is run with `--no-insert-timestamp`. The build leaves out what TinyCC's headers and msvcrt.dll cannot carry: the bundled libintl, whose declaration of `alloca` tcc rejects, plugin support, which reads a directory with `opendir`, and libctf, which includes `sys/param.h`. libbfd is installed, as in nixpkgs' native build, since libtool otherwise unpacks libsframe into libbfd member by member and `tcc -ar` keeps 15 characters of a member's name, which libsframe's three objects share. ld has no built-in search path, as in nixpkgs, and here also because its `genscripts.sh` splits the path at a drive letter's colon. Two compatibility headers add what MinGW-w64's headers have and TinyCC's lack: `alloca` as a macro, and `rpcdce.h` for the `UuidCreate` call behind `--build-id=uuid`. The seed stdenv gains what the build needs of it: a patch phase, nixpkgs' `patches`; `srcs` on what `mkDerivation` returns, as the MSYS2 stdenv stated it; and three `config.site` settings without which libtool takes tcc and its linker for Microsoft's, archives with `lib`, names a static library `.lib` and passes each source through `cygpath`. Since those settings have configure take tcc for GCC, which it gives `-g -O2` where CFLAGS is unset, `config.site` also gives CFLAGS an empty default that a package's own still overrides: tcc's debugging information names the directory tcc ran in and each file by the path it opened, a header from the store by the store's physical path, so a program built with it would differ with the store's drive and with the user whose temporary directory the build ran in, and tcc's `-O` only defines `__OPTIMIZE__`. make runs `$NIX_BUILD_CORES` jobs in one run, where nixpkgs' `minimal-bootstrap/binutils` builds ld on its own for a race between jobs over `ld/.deps/ldwrite.Po`, a file dependency tracking writes and `--disable-dependency-tracking` keeps the compile rule from writing. CI builds binutils on x64 and ARM64 Windows, checks `ld --version`, and has `as` assemble a function, `ar` archive it and `ld` link it into a program that runs and exits with the function's value, and has `ar` archive and extract a file holding a 0x1A byte and a CR LF unchanged. (#423)+- **`pkgs/windows` builds MinGW-w64's headers and GCC 4.6.4's C compiler and libgcc for `i686-w64-mingw32` with the seed stdenv, the compiler compiled by `tinycc-native` and libgcc by that compiler: the driver, `cc1`, `cpp`, `collect2`, GCC's own headers and libgcc, with the binutils rung's assembler and linker.** It follows nixpkgs' `minimal-bootstrap/gcc/4.6.nix`, which builds the same release with tinycc, and builds what MinGW-w64's own build guide builds from one GCC build directory, with `make all-gcc` and `make all-target-libgcc`. The guide builds libgcc once MinGW-w64's runtime is installed, since its shared libgcc links against the runtime; libgcc here is static, as nixpkgs' is, links nothing and needs only the headers, so it is built in the same make, and the runtime, which this compiler compiles, is the next rung. libgcc is compiled without debugging information, which would name the build directory and the store paths the compiler read: `CFLAGS_FOR_TARGET=-O2` replaces the `-g` GCC's top-level configure adds to the target libraries' flags, and `LIBGCC2_DEBUG_CFLAGS=-g0` the `-g` GCC's Makefile adds to every libgcc compile. Its thread model is win32, on the Windows API alone, and its exceptions SJLJ, a 32-bit MinGW target's defaults. make runs `$NIX_BUILD_CORES` jobs, as `minimal-bootstrap/gcc/4.6.nix`'s does. `mingw-w64-headers` installs release v8.0.3, the newest whose runtime calls none of three builtins GCC 4.6.4 lacks, from the project's signed release archive. GCC is given them with `--with-headers`, which copies them into its own output as `i686-w64-mingw32/sys-include`, the directory a cross GCC searches for its target's headers, and its `limits.h` goes on to MinGW-w64's from there. GCC's manual prefers `--with-sysroot`, but GCC's top level hands each option to the configure of every library it builds, and mpc's libtool takes a sysroot for absolute only if it begins with `/`, which a store path on Windows does not; `--with-headers` is read by the top level and by `gcc` alone. The stdenv's `i686-pc-mingw32` stays the build and the host, so GCC is configured as the cross compiler it is: tcc compiles it against TinyCC's headers and msvcrt.dll, and its target has MinGW-w64's. Its programs install as `bin/i686-w64-mingw32-<name>.exe`, and `--with-as` and `--with-ld` compile in the paths of binutils' assembler and linker, which a cross GCC otherwise looks for in its own prefix. gmp, mpfr and mpc are built in the tree, as in nixpkgs. The edit of binutils' `fix-tinycc-attribute.patch` is made to GCC's copy of `include/ansidecl.h`: without it 25 calls in libiberty's `pex-win32.c` and `lrealpath.c` and in `gcc/config/i386/host-mingw32.c` reach the Windows API as cdecl, and pop arguments the function has already popped, on every program the driver starts. Three more settings are for TinyCC. `CFLAGS=-Dalloca=alloca`, since libiberty, gmp and mpfr each declare `alloca` in a way tcc rejects unless it is a macro. `LDFLAGS=-luser32`, since libiberty calls `CharLowerBuff`, and tcc links msvcrt and kernel32 alone where GCC's own MinGW links user32 into every program. And a new package, `mingw-w64-dirent`, MinGW-w64's own `dirent.c` compiled by tcc beside the `dirent.h` it is written for: libcpp reads a directory of precompiled headers with `opendir`, msvcrt.dll has none, and TinyCC's `dirent.h` declares an older `struct dirent`, against which that file compiles without a warning and then copies each name through a pointer nothing sets. The seed stdenv gains what the rung needs of it: `preConfigure`, nixpkgs' hook, which moves `mingw-w64-headers` to the directory its configure is in and unpacks GCC's three libraries where its configure looks for them; `configureScript`, nixpkgs' too, with which GCC configures from a build directory beside its source, as its installation guide recommends, since in the source GCC names the build machine's `fixincl` by two paths that differ and, with the program called `fixincl.exe`, make links `fixincl.o` alone; `configureFlags` joins the variables whose store paths are respelled with forward slashes, since GCC's configure writes the headers' and the two tools' paths into Makefiles and C strings; `config.site` answers that `atoll` exists, since TinyCC's `stdlib.h` defines it inline and `msvcrt.dll` exports none, so a link test finds none and GCC's `read-rtl.c` then defines a second. `tinycc-native`'s runtime gains an empty `libm.a`, as MinGW-w64's runtime has one: TinyCC finds a library only by a file, `msvcrt.dll` holds the math functions, and GCC links its `genautomata` with `-lm`; CI links a program with `-lm` and runs its `sqrt`. `fetchurl` takes nixpkgs' `mirror://sourceforge`. CI builds the three packages on x64 and ARM64 Windows, checks the driver's version line, and has the compiler compile a source to assembly, read `windows.h`, and compile a function that `ld` links and that runs. The assembly is compared with what GCC 4.6.4 built by another compiler writes for the same source, which holds constants `cc1` folds in its 64-bit arithmetic, in its floating point and through MPFR, so a `cc1` that tcc compiled wrongly shows. (#426)+- **`pkgs/windows` builds MinGW-w64's runtime with GCC 4.6.4, and `gcc46`, that compiler with libgcc and the runtime in one prefix, so the ladder now has a compiler that turns a C source into a Windows program that runs.** `mingw-w64-crt` compiles release v8.0.3's runtime, from the archive `mingw-w64-headers` already fetches, with `gcc-core` and binutils' `as`, `ar`, `ranlib` and `dlltool`, for i686 against msvcrt.dll: `crt2.o` and the other start files, `libmingw32.a`, `libmingwex.a`, `libmoldname.a`, `libm.a` and an import library for each DLL. It configures the runtime's own directory from a build directory beside it, as MinGW-w64's build guide does, with `--host=i686-w64-mingw32` so that configure looks the tools up under the target's name, and with the stdenv's `CC`, `AR` and `C_INCLUDE_PATH` unset: configure takes the compiler and archiver the environment names, which in the seed stdenv are tcc's, and GCC reads `C_INCLUDE_PATH` too, which names TinyCC's headers and comes before GCC's own and MinGW-w64's in its search. `--enable-lib32` and `--disable-lib64` are nixpkgs' flags for an i686 host: left to itself, configure decides each by compiling a test, and a compiler that fails the test for another reason would leave a runtime with no libraries and a build that passes. `CFLAGS=-O2` is configure's default for GCC without the `-g` whose debugging information would name the build directory and the store paths the compiler read, and make builds with `$NIX_BUILD_CORES` jobs, as nixpkgs' does, and installs with one, since two of the runtime's install rules write `lib32/libntoskrnl.a`. `gcc46` compiles nothing: it copies `gcc-core`'s output and puts the runtime's in its `i686-w64-mingw32` directory, where the guide installs the runtime in the GCC core's prefix and where GCC's own build looks for its target's libraries. GCC's driver takes its directories relative to the one it runs from when that is not the one it was configured for, so the copy's driver finds `crt2.o`, libgcc and the libraries every link names with no flag, and GCC is not compiled a second time. CI builds both on x64 and ARM64 Windows. One check pins every file the runtime installs and the symbols of `crt2.o`, which defines `__CTOR_LIST__` itself when configure's one link test fails, so that a test failing on Windows for another reason shows instead of changing the runtime quietly. The other has `gcc46` compile and link a program with no flag naming a directory and run it: it prints through msvcrt.dll's `puts` and `printf`, divides 64-bit integers through libgcc's `__divdi3` and `__moddi3`, and imports from msvcrt.dll and kernel32.dll alone. (#439)+- **`pkgs/windows`' Mes is GNU Mes 0.28, with the Windows port merged onto upstream's master.** 0.28 replaces Mes's tree-walking interpreter with a bytecode compiler and interpreter. Mes and MesCC run in the arena and stack MesCC's own script sets, 20,000,000 cells and 60,000 entries: 0.28 asserts that the stack stays under 131,072 entries, where `pkgs/windows` set 6,000,000, and reads no `MES_MAX_ARENA`. A collection copies the cells it keeps into the arena's free third and stops Mes with an out-of-memory error when they do not fit, where 0.27.1 copied them past the arena's end without checking. Upstream fixes `strpbrk` itself, so the fork carries nixpkgs' other i686 C library fixes alone. (#445)+- **`pkgs/windows`' stage0-pe32 links every compiled program against M2libc's Windows runtime, and M2libc's `fseek` returns 0 on success.** The startup, system calls, C library glue and PE-end shim a compiled program links against now live in M2libc's `x86/windows/`, beside its C, as M2libc carries its Linux runtime, so a merge of upstream M2libc shows where the two runtimes need the same change. stage0-pe32 keeps its own copies of the PE header and the ntdll plumbing for the hand-written M0 and cc_x86, as stage0-posix keeps its own ELF header, and one generator writes both. The moved files are byte for byte the ones stage0-pe32 held, and comments that contradicted the code are corrected in both repositories. M2libc's `main` also carries the two fixes it offers upstream: `fseek` returned the new position where ISO C 7.21.9.2 requires 0, and armv7l's `close`, `unlink` and `chroot` passed the kernel their argument's address. No program in the chain reads `fseek`'s result, but hex2-new and kaem link the `stdio.c` that holds it, so their bytes change; every other link is unchanged. (#450)+- **`pkgs/windows` builds `gcc46-cxx`, GCC 4.6.4 with C and C++ for `i686-w64-mingw32`, compiled by `gcc46` in the seed stdenv, with libgcc and libstdc++ compiled by the compiler the same make links, so the ladder has a C++ compiler for the GCC after it.** GCC is written in C++ from 4.8 on, and nixpkgs' `minimal-bootstrap` builds its GCC 10 with the same rung, `gcc/4.6.cxx.nix`, which this follows: gcc-core's sources with GCC's g++ archive unpacked over them, and nixpkgs' flags, `-O1` for the compiler and `-O0` for the target libraries, and `install-strip`. nixpkgs gives its native compiler musl's headers and libraries; here GCC is a cross compiler, as gcc-core is, and is given MinGW-w64's headers and runtime with `--with-headers` and `--with-libs`, the pair GCC's installation guide names for a C library built outside its tree. The top-level configure copies both into GCC's own output, where gcc46 has them and where the build points the compiler it links when it compiles and links libstdc++, whose configure links its tests for a MinGW target and so needs the runtime first. libstdc++ installs beside the runtime, so `i686-w64-mingw32-g++` links a C++ program with no flag naming a directory. The build runs gcc46's driver and binutils' archiver, linker and strip under the target's names, the only names they have on `PATH`, since configure looks the host's tools up under bare names and the seed stdenv's `CC`, `AR` and `LD` are tcc's. `--disable-win32-registry` is not nixpkgs': linked against MinGW-w64's `libadvapi32.a`, a GCC for Windows looks its directories up in the registry under `HKEY_LOCAL_MACHINE\SOFTWARE\Free Software Foundation`, so a machine with a GCC installed there would change where this one looks. `--disable-shared`, as in nixpkgs, keeps libgcc and libstdc++ static, and exceptions are SJLJ, a 32-bit MinGW target's default. No program the rung installs carries the time it was built, so two builds of it at the output's own path are the same bytes. binutils' `ld` writes the time of the link into a PE image's header unless it is given `--no-insert-timestamp`, which GCC 4.6.4's link spec for MinGW never passes and the seed stdenv has no compiler wrapper to add, so `LDFLAGS` passes it to every link `gcc46` makes, of the host's programs and the build machine's. `strip`, which `install-strip` runs on each program, then writes the time over the zero `ld` wrote unless it is run with `-p`, as nixpkgs' strip hook runs it, so the install phase gives make a `STRIP` with `-p`, on make's command line since the stdenv splits `configureFlags` and `makeFlags` at spaces. `nova-nix build --check` of the rung still finds seven programs differ, the five drivers, `cc1` and `cc1plus`: the check builds at a scratch path and rewrites its hash in what the builder wrote, and each of the seven names the output and carries a sum of its own bytes that no rewrite reaches, the PE checksum `ld` and `strip` write and, in `cc1` and `cc1plus`, the MD5 GCC takes of the objects they link, two of which compile the prefix in. CI builds the rung on x64 and ARM64 Windows and has its `g++` compile and link a C++ program that prints through iostream, calls virtual functions through a base pointer, instantiates a template, uses `new` and `delete`, constructs a global and a function-local static, and throws and catches two exceptions, one after unwinding through four frames whose destructors run; the check compares what it prints and its exit status with what the C++ standard defines, and pins that it imports msvcrt.dll and kernel32.dll alone and links libsupc++'s and libgcc's SJLJ exception functions. A second check reads the time stamp in the header of every program and DLL the rung installs and compares the list with one in which each is zero. (#455)+- **`pkgs/windows` builds `gcc10`, GCC 10.4.0 with C and C++ for `i686-w64-mingw32`, compiled by `gcc46-cxx` in the seed stdenv, with GMP, MPFR and MPC built in its tree and libgcc and libstdc++ compiled by the compiler the same make links, the compiler nixpkgs' `minimal-bootstrap` builds its current GCC with.** GCC 10 is the last GCC a C++98 compiler builds, and nixpkgs' `minimal-bootstrap` goes from GCC 4.6.4 to it with `gcc/10.nix`, which this follows: its release, 10.4.0, since 10.5.0 does not build with GCC 4.6; its GMP 6.2.1, MPFR 4.2.2 and MPC 1.4.1, unpacked into GCC's tree, where GCC's configure builds them; and its flags, `-O1` for the compiler, `-O0` for the C++ target libraries, and `install-strip`. The C target libraries are `-O2`, configure's default for them, where nixpkgs gives `-O0`: libgcc takes the top level's flags after its own, and at `-O0` its 64-bit division functions, compiled with `-fexceptions -fnon-call-exceptions`, call the SJLJ unwinder, which every C program then took in through MinGW-w64's printf after the libraries the unwinder needs, so none linked. libcpp carries GCC 11's change that has its configure look the archiver up, since GCC builds libcpp for the build machine too and its Makefile named `ar`, which here is busybox's applet. nixpkgs gives its native compiler musl's headers and libraries; here GCC is a cross compiler, as `gcc46-cxx` is, given MinGW-w64's v8.0.3 headers and the runtime `gcc-core` compiled with `--with-headers` and `--with-libs`, as nixpkgs' GCC 10 links the musl its GCC 4.6.4 compiled. The build runs `gcc46-cxx`'s `gcc` and `g++` and binutils' archiver, linker and strip under the target's names; `CXX` is new, since GCC 10 is written in C++ and configure looks a C++ compiler up under bare names, of which `PATH` has none. As in `gcc46-cxx`, `--disable-win32-registry` is not nixpkgs', `--disable-shared` keeps libgcc and libstdc++ static, exceptions are SJLJ, and no program the rung installs carries the time it was built. libgcc carries no debugging information either. GCC 10 compiles libgcc with `-g` from libgcc's own Makefile, which no variable the top level passes reaches, and the information names the build directory, which is named for the output's hash, in every program that links the objects it describes, so the install strips it from the three files libgcc compiles with it, as `install-strip` strips libstdc++'s archives. CI builds the rung on x64 and ARM64 Windows in a stage of its own, GCC 10 (Windows), which starts from the store GCC 4.6.4 C++ (Windows) hands it. Its `gcc` compiles and links a C program that prints the compiler's version and default standard and runs the three builtins GCC 4.6.4 lacks and newer MinGW-w64 runtimes call, and its `g++` a C++14 program that runs the C++ checks `gcc46-cxx`'s does with `std::unique_ptr`, lambdas, variadic templates, `constexpr`, `std::map` and `std::to_string`. Each check compares what its program prints and its exit status with what the C and C++ standards define, and pins the DLLs the program imports, the libgcc and libsupc++ functions it links and that it has no debugging section. A third check reads the time stamp in the header of every program the rung installs and compares the list with one in which each is zero. (#504)+- **`pkgs/windows` builds MinGW-w64 v14.0.0, the project's newest release and the one nixpkgs packages, with `gcc10`: `mingw-w64-headers-latest` installs its headers and `mingw-w64-crt-latest` compiles its runtime for `i686-w64-mingw32`, the runtime the compilers after `gcc10` are given.** The ladder's first runtime, v8.0.3, is the newest GCC 4.6.4 compiles, since later releases call `__atomic_load_n` (`misc/gettimeofday.c`), `__builtin_mul_overflow` (`misc/_recalloc.c`) and `__builtin_bswap16` (`misc/winbs_ushort.c`), which that compiler lacks and GCC 10 has. Both packages follow nixpkgs' `mingw_w64_headers` and `mingw_w64` and the ladder's v8.0.3 rungs: the headers install from the archive's own directory with no compiler, and the runtime configures its own directory from a build directory beside it with `--host=i686-w64-mingw32`, the stdenv's `CC`, `AR` and `C_INCLUDE_PATH` unset, the headers' output as its sysroot, `--enable-lib32 --disable-lib64` and `CFLAGS=-O2`. `--with-default-msvcrt=msvcrt` is nixpkgs' flag for this target and the runtime the ladder links; at this release it names msvcrt.dll's version 0x600 in `_mingw.h`, where v8.0.3 names 0x700, and makes `libmsvcrt.a` a copy of `libmsvcrt-os.a`, msvcrt.dll's import library with the functions it lacks compiled in. `_WIN32_WINNT` is the release's default, 0xa00, Windows 10, as in nixpkgs. Each file of this release's runtime has one install rule, so it installs with `$NIX_BUILD_CORES` jobs, where v8.0.3's installs with one. `gcc10` keeps v8.0.3's runtime in its own prefix: the new runtime's compiles read the new headers first, and the runtime links no program. CI builds both in the GCC 10 (Windows) stage on x64 and ARM64 Windows. One check pins every file the runtime installs, which is what the release's Makefile installs for this configuration, each a file Homebrew's mingw-w64 14.0.0 installs for i686 too, and the global symbols of `crt2.o`, which are those of the `crt2.o` GCC 16.2.0 compiled for that package, so that configure's test of whether `ld` defines `__ImageBase`, which changes the objects and not the build's exit status, shows if it fails on Windows. The other has `gcc10` link a program against the new runtime, given its directories with `-B` and `-isystem` as GCC's build gives a compiler its target's runtime: it prints the release and msvcrt.dll version the headers name, and calls `gettimeofday`, `_recalloc`, including a size whose product overflows, and `_byteswap_ushort`, each linked from the runtime's libraries. (#535)+- **`pkgs/windows` builds `gcc-latest`, GCC 16.2.0 with C and C++ for `i686-w64-mingw32`, compiled by `gcc10` in the seed stdenv against MinGW-w64 v14.0.0, with GMP, MPFR and MPC built in its tree and libgcc and libstdc++ compiled by the compiler the same make links: the GCC nixpkgs' `minimal-bootstrap` builds after GCC 10.** It takes nixpkgs' release, 16.2.0, which needs a C++14 compiler to build, and nixpkgs' GMP 6.3.0, MPFR 4.2.2 and MPC 1.3.1, the releases GCC's own `contrib/download_prerequisites` fetches for an in-tree build of 16.2.0. nixpkgs builds this GCC in pieces, GMP, MPFR, MPC, libiberty, libbacktrace, the compiler, libgcc and libstdc++ each a derivation of its own, and joins them with a wrapper that points the compiler at musl, libgcc and libstdc++. Here, as in `gcc10`, the compiler is one build, a cross compiler given the current MinGW-w64's headers and runtime with `--with-headers` and `--with-libs`, which GCC copies into its own prefix and hands the compiler it links when it builds libgcc and libstdc++, so the driver finds the runtime and both libraries with no flag and no wrapper, and neither of nixpkgs' two patches, which serve its separate builds, applies. nixpkgs' choices carry over where they mean the same here: `-O1` for the compiler and `-O0` for libstdc++, `--disable-gcov`, `--enable-linker-build-id`, which has every link this compiler makes write a CodeView build ID, the deletion of the configure arguments from the top-level Makefile, which keeps the store paths they name out of `gcc -v`, and the removal after the install of the `install-tools` directories, libstdc++'s Python pretty-printers and the manual and info pages. The install removes libstdc++'s gdb script too, which loads those printers, and the `share` directories the removals leave empty. `--enable-default-pie` is left out: GCC compiles 32-bit Windows code without PIC whatever it is told, so the flag would only pass `-pie` to every link, for which binutils' `ld` writes an empty export table into a program that is relocatable without it. The build names binutils' `windres` by the target's name, as it names the compilers: GCC 16 built for Windows embeds a manifest that runs its driver and compilers with the UTF-8 code page, compiled by `windres`, which configure looks up under its bare name, and `PATH` has none. libgcc is `-O2`, for the reason `gcc10`'s is, and its debugging information is stripped after the install, as nixpkgs strips it. The thread model is win32, this target's default, under which libstdc++ has `std::thread` because MinGW-w64 v14.0.0's headers name Windows 10. As in `gcc10`, `--disable-win32-registry` is not nixpkgs', `--disable-shared` keeps libgcc and libstdc++ static, exceptions are SJLJ, and no program the rung installs carries the time it was built. CI builds the rung on x64 and ARM64 Windows in a stage of its own, GCC 16 (Windows), which starts from the store GCC 10 (Windows) hands it. Its `gcc` compiles and links a C23 program, its default, that uses `constexpr`, `typeof`, `nullptr`, `bool` and `_BitInt(128)`, and its `g++` a C++20 program, its default, that uses `std::format`, concepts, ranges, `std::span`, a three-way comparison and four `std::jthread` threads synchronized with a `std::mutex` and a `std::condition_variable`. Each program prints the compiler's version and default standard and the runtime's release, and each check compares what it prints and its exit status with what the C and C++ standards define, and pins the DLLs it imports, the libgcc, libsupc++ and libstdc++ functions it links, that it carries one build ID and that it has no debugging section. A third check reads the time stamp in the header of every program the rung installs and compares the list with one in which each is zero. (#548)+- **`pkgs/windows` builds `binutils-x86_64`, GNU binutils 2.46 for `x86_64-w64-mingw32`, compiled by `gcc-latest` in the seed stdenv: the first rung of the ladder's x86_64 toolchain, which the package set's 64-bit packages need.** The ladder reaches x86_64 the way MinGW-w64's own build guide and nixpkgs' `pkgsCross.mingwW64` do, through a cross toolchain: these tools, then a GCC core that compiles the runtime, the runtime, and GCC with its libraries, each running on i686 Windows. binutils is a rung of its own rather than the i686 rung rebuilt with `--enable-targets`: GCC for `x86_64-w64-mingw32` and MinGW-w64's runtime look their tools up under the target's name, which only a binutils configured for that target installs, and the i686 rung is compiled by tcc with patches and flags for tcc and msvcrt.dll. The x86_64 target's own formats include i386 PE, so these tools read and write both. The release is nixpkgs' 2.46, from the archive nixpkgs fetches; GCC 16.2.0 does not need it, since its configure tests the assembler for each feature it would use and does without what 2.41 lacks, such as `.base64`. nixpkgs' flags carry over where they mean the same here; those for ELF, Linux or MIPS are left out, the zlib of binutils' tree is linked in place of a system one, the libraries are static, so the programs import no DLL of binutils', and NLS is off, since the ladder has no gettext. None of nixpkgs' patches applies: `deterministic.patch` sets a flag the PE writer does not read, and the others serve ELF, nixpkgs' split outputs, configure scripts it regenerates on Darwin alone, AVR, or a `windres` run by a path. Every link is told to write no time stamp, which `ld` otherwise writes into a PE image. CI builds the rung on x64 and ARM64 Windows in a new stage, x86_64, which starts from the store GCC 16 now hands on. One check has `as` assemble a function, `ar` archive it and `ld` link it into an x86_64 program and an i386 one that run and exit with its value, and compares what `nm`, `ar` and `objdump` read back, and the machine and optional header magic read from each program's PE header, PE32+ for x86_64, with what the formats define; the other reads the time stamp in the header of every program the rung installs and compares the list with one in which each is zero. (#550)+- **`pkgs/windows` builds `gcc-core-x86_64`, GCC 16.2.0's C compiler and libgcc for `x86_64-w64-mingw32`, compiled by `gcc-latest` in the seed stdenv: the GCC core that compiles the x86_64 runtime.** It is MinGW-w64's build guide's GCC core and nixpkgs' `gccWithoutTargetLibc`, the compiler a cross toolchain builds before its target's C library exists, and the second rung of the ladder's x86_64 toolchain. Its sources and configuration are `gcc-latest`'s, GCC 16.2.0 with GMP, MPFR and MPC built in its tree, for the other target: the compiler runs on i686 Windows, writes x86_64 code through `binutils-x86_64`'s assembler and linker, and reads the current MinGW-w64's headers, the same files for either target. make builds and installs the compiler and libgcc alone, as the 4.6.4 `gcc-core` does, which is what compiling the runtime needs; libgcc is static and single-threaded, as nixpkgs has it for this compiler, and links nothing, so it needs only the headers. nixpkgs' flags carry over where they mean the same; those naming target libraries the build never configures, and three read by no configure of 16.2.0's tree, have nothing to do. The compiler and libgcc are `-O2`, configure's own optimization, without the `-g` nixpkgs strips after its install, libgcc's own `-g` is stripped here too, and no installed program carries the time it was built. CI builds the rung in the x86_64 stage on x64 and ARM64 Windows. One check has the compiler read `windows.h` and compile a function that divides two 128-bit integers, which `ld` links with libgcc and no runtime into a program that runs and exits with the quotient, and compares the target, version and thread model the driver reports, the object's symbols, and the machine and optional header magic read from the program's PE header with what the configuration and the formats define; the other compares the time stamps of the installed programs with a list in which each is zero. (#550)+- **`pkgs/windows` builds `mingw-w64-crt-x86_64`, MinGW-w64 v14.0.0's runtime for `x86_64-w64-mingw32`, compiled by `gcc-core-x86_64` in the seed stdenv: the runtime the x86_64 GCC is given.** It is `mingw-w64-crt-latest`'s build for the other target, as nixpkgs' `mingw_w64` builds it for an x86_64 host: `--host=x86_64-w64-mingw32`, `--disable-lib32 --enable-lib64`, nixpkgs' flags for that host, and msvcrt.dll, the runtime the ladder links, compiled against `mingw-w64-headers-latest`, whose files serve either target. The 64-bit libraries install in `lib`, the directory the runtime's configure names for an x86_64 host. `gcc-core-x86_64` has no runtime yet, so configure's link to learn the suffix of executables fails, as the runtime's configure lets it, and its link with `-nostdlib`, which asks whether `ld` defines `__ImageBase`, is one that needs none. CI builds the rung in the x86_64 stage on x64 and ARM64 Windows. One check pins every file the runtime installs, each one Homebrew's mingw-w64 14.0.0 installs for x86_64 too, and the global symbols of `crt2.o`, which are those of the `crt2.o` in that package, so that the `__ImageBase` test, which changes the objects and not the build's exit status, shows if it fails on Windows. The other has `gcc-core-x86_64` link a program against the runtime, given its directories with `-B` and `-isystem` as GCC's build gives a compiler its target's runtime, that prints the release and msvcrt.dll version the headers name and calls `gettimeofday`, `_recalloc` and `_byteswap_ushort`, each linked from the runtime's libraries, and reads the program's PE header, which names an x86_64 PE32+ image. (#550)+- **`pkgs/windows` builds `gcc-x86_64`, GCC 16.2.0 with C and C++ for `x86_64-w64-mingw32`, compiled by `gcc-latest` in the seed stdenv against MinGW-w64 v14.0.0's headers and the x86_64 runtime: the ladder's first compiler that writes 64-bit programs.** It finishes the cross toolchain MinGW-w64's build guide builds, as nixpkgs' `pkgsCross.mingwW64` builds its GCC. The build is `gcc-latest`'s, one cross compiler build given its target's headers and runtime with `--with-headers` and `--with-libs`, so libgcc and libstdc++ are built against them by the same make and the installed driver finds all of them with no flag. The flags are those of nixpkgs' cross compiler, where `gcc-latest`'s are `minimal-bootstrap`'s: the compiler and its target libraries are `-O2`, configure's own optimization, without the `-g` nixpkgs strips after its install, and the build ID, gcov, the analyzer and libstdc++'s visibility and ABI are configure's defaults. nixpkgs gives libstdc++ the mcf thread model from mcfgthreads, which the ladder does not build; the model here is win32, the target's own on the Windows API alone and nixpkgs' choice for a MinGW target with no thread library, under which libstdc++ has `std::thread` because the headers name Windows 10. Exceptions are SEH, the x86_64 target's. Where nixpkgs' choices need what the ladder does not have, `gcc-latest`'s are kept: GMP, MPFR and MPC in the tree and no ISL, the tree's zlib, no NLS, static libgcc and libstdc++, so a program imports no DLL of GCC's, no LTO or plugins, and the target libraries other than libgcc and libstdc++ off. nixpkgs' patch for a Windows target serves a libstdc++ built without its C library, and this one is hosted. CI builds the rung on x64 and ARM64 Windows in a stage of its own, GCC 16 x86_64, which starts from the store x86_64 now hands on. Its `gcc` compiles and links a C23 program that prints the x86_64 Windows sizes of a pointer, a long, a long long and a long double, divides 128-bit integers through libgcc and multiplies `_BitInt(256)` values through it, and its `g++` the C++20 program `gcc-latest`'s check links, threads and exceptions included, which here unwind through SEH. Each check compares what its program prints and its exit status with what the standards and the ABI define, and pins the DLLs it imports, the libgcc, libsupc++ and libstdc++ functions it links, that it has no build ID and no debugging section, and the machine and optional header magic of its PE header, an x86_64 PE32+ image. A third check reads the time stamp in the header of every program the rung installs and compares the list with one in which each is zero. (#550)+- **`pkgs/windows` builds `binutils-native-x86_64` and `gcc-native-x86_64`, binutils 2.46 and GCC 16.2.0 with C and C++ that run on x86_64 Windows and write `x86_64-w64-mingw32`, compiled by `gcc-x86_64` in the seed stdenv: the ladder's first tools that run as `gcc`, `g++`, `as` and `ld`, as the MSYS2 stdenv's toolchain did.** Every rung before them runs on i686, and the x86_64 cross toolchain is named for its target. Each is a Canadian cross, as nixpkgs builds a toolchain whose host is its target: the stdenv's i686 triple is the build and `x86_64-w64-mingw32` the host and the target, so the programs take no prefix, the host's programs and GCC's target libraries are compiled by `gcc-x86_64`, a cross compiler of the same release as nixpkgs requires, and the programs the build runs itself by `gcc-latest`. The binutils flags are `binutils-x86_64`'s, and the GCC flags `gcc-x86_64`'s, but for what a compiler whose host is its target needs: GCC refuses `--with-headers` and `--with-libs` for it, so the build reads MinGW-w64's headers through `--with-build-sysroot` and `--with-native-system-header-dir`, as nixpkgs does, which also lets GCC's `limits.h` include MinGW-w64's, and the install copies the headers and the x86_64 runtime into the compiler's tool directory, where the installed driver finds them with no flag; `--with-as` and `--with-ld` name the native binutils. As nixpkgs' compilers do, it leaves `/usr/local/include` out of its search for headers, which a GCC whose host is its target otherwise searches ahead of the target's own, so a directory of that name on the build's drive cannot shadow MinGW-w64's. The thread model is win32 and libgcc and libstdc++ are static. MSYS2's GCC has the posix model and shared runtime DLLs that import winpthreads, which the MSYS2 stdenv carried by putting its toolchain on `PATH` and copying DLLs beside each output, but its packages used neither: they are C, and GNU Hello built with it imports no DLL of GCC's or winpthreads. nixpkgs gives a thread model only to a GCC whose host is not its target, so its native MinGW-w64 GCC takes win32, the target's default, which needs no thread library the ladder does not build and under which libstdc++ has `std::thread`; static libraries leave a program importing no DLL of GCC's, which the seed stdenv, having no fixup phase, could not carry. CI builds both rungs on x64 and ARM64 Windows in a new stage, Native x86_64, which starts from the store GCC 16 x86_64 now hands on. One check has the tools assemble, archive and link an x86_64 program and an i386 one that run; two have `gcc` and `g++` link the C23 and C++20 programs `gcc-x86_64`'s checks link, threads and SEH exceptions included, and compare their output, imports and symbols with what the standards and the ABI define. Each also reads the PE headers of the rung's own `as.exe` and `ld.exe`, or `gcc.exe`, `g++.exe`, `cc1.exe` and `cc1plus.exe`, which are x86_64 PE32+ images, and finds that none imports a DLL of GCC's runtime, winpthreads or mcfgthreads; and a check per rung reads the time stamp in the header of every program it installs and compares the list with one in which each is zero. (#618)+- **`pkgs/windows` has a stdenv on the seed ladder's native toolchain, to replace the MSYS2 one: the seed stdenv's builder and tools, busybox-w32's sh and applets and `gnumake`, with the ladder's `binutils-native-x86_64` and `gcc-native-x86_64`, as `x86_64-windows`, and `pkgs/windows`' GNU Hello package builds with it unchanged.** Its builds reach the compilers and the linker through its `cc`, as nixpkgs' reach theirs through `stdenv.cc`: `gcc`, `cc`, `g++`, `c++` and `ld`, scripts that give every build what the MSYS2 stdenv's wrapper gave its builds. The C drivers compile at `-std=gnu17` ahead of a package's own options, since GCC 16 defaults to C23, under which an empty parameter list declares a function that takes no arguments and the K&R declarations older gnulib copies carry conflict with the C library's; the C++ drivers keep the compiler's default. Every link a driver makes gets `--no-insert-timestamp` from a specs file appended to GCC's link spec, which the driver applies only when it links: the MSYS2 wrapper's `-Wl,--no-insert-timestamp`, added to each command with no compile-only option, was an input file to the driver, so with it `gcc -v` went on to link. `ld` gets the flag directly. Each driver runs with none of the variables GCC 16 searches directories from: `CPATH`, `C_INCLUDE_PATH`, `CPLUS_INCLUDE_PATH`, `COMPILER_PATH`, `LIBRARY_PATH`, `LPATH` and `GCC_EXEC_PREFIX`, the last three of which the MSYS2 wrapper left set; the Objective-C variables it also unsets serve a language `gcc-native-x86_64` does not compile. The wrappers are scripts with no extension, which busybox's sh and GNU make run through the `sh` their first line names, and neither toolchain's `bin` directory is on `PATH`, since GNU make looks for a command with `.exe` in every directory of `PATH` before it looks for one without, and would run `gcc.exe` past the wrapper. `AR` names binutils' archiver by its path, since busybox's sh runs its own `ar` applet for the name. configure is told `--build=x86_64-w64-mingw32`, since `config.guess` cannot read busybox's `uname`, and the stdenv's `config.site` makes `-O2` the default `CFLAGS` and `CXXFLAGS` in place of configure's `-g -O2`, whose debugging information would name the build directory, which nova-nix makes in the store directory. CI's ladder gains a Stdenv stage after Native x86_64 on x64 and ARM64 Windows, which builds Hello with the stdenv, runs it and checks that it names neither the store directory nor its build directory, and builds a check whose programs, compiled and linked by each wrapper by name, by `gcc` with a package's own `-std` and from a make recipe, and by `ld`, report the standard they were compiled at and carry a zero time stamp, and in which none of those variables reaches the compiler, though each reaches `gcc-native-x86_64`'s own drivers. A test reads the closures: the leaves the stdenv and the packages built with it add to the native toolchain's are the archives of Hello, sed and zlib, and its builds have the applets, `gnumake` and the wrappers alone on `PATH`. (#654)+- **The stdenv on the seed ladder's native toolchain bundles each DLL an output's programs and libraries import from a build input beside them, as the MSYS2 stdenv did, and builds the six packages the MSYS2 stdenv built: GNU Hello, GNU sed, zlib as a DLL, libgreet, and zdemo and greeter, which link zlib and libgreet.** Windows has no RPATH, so a program finds a DLL in its own directory before the system's and PATH's, and a program that links a DLL from another package runs only with that DLL beside it. It now runs its own setup script, which runs the seed stdenv's unchanged for every phase from unpack to install and then that fixup phase, reading each PE file's imports with binutils' `objdump` to a fixpoint and failing the build on a DLL that is neither a system one nor in a declared input; the seed ladder's rungs are untouched. `OBJDUMP` and `STRIP` name binutils' programs by their paths, as nixpkgs' bintools wrapper names them, since the stdenv keeps its toolchain off `PATH`, and `WINDRES` names a `windres` wrapper beside the compiler wrappers: windres preprocesses through `cmd.exe`, which cannot run the stdenv's `gcc`, a script, so the wrapper gives windres the native `gcc.exe` as its preprocessor, under the environment the `gcc` wrapper gives it. zlib's build passes `WINDRES` and `STRIP` to its makefile, which names them otherwise, and GNU sed's configure takes `WINDRES` from the environment for its tests' resource files. (#714)+- **`pkgs/windows`' `stdenv` is the stdenv on the seed ladder's native toolchain, so GNU Hello and the set's other packages build with the toolchain the seed ladder builds from its hex seed, and with no prebuilt compiler or shell.** It builds every package the MSYS2-based stage-1 one built, its DLLs bundled beside them. A first build substitutes the toolchain from the public cache, where the seed ladder's runs on main publish it; built from the seed, it takes hours. (#723)+- **Nothing in `pkgs/windows` downloads a prebuilt compiler or shell: `stage1Stdenv`, the stdenv on MSYS2's bash and MinGW-w64's GCC, is removed with the 39 MSYS2 and MinGW-w64 binary packages it was made of, and the set's `stdenv` takes its shell, tools and toolchain from the seed ladder, which builds them from stage0-pe32's seed.** The set's `stdenv` builds every package the stage-1 one built, so nothing in the set used the stage-1 one. The packages were pinned by SHA-256 to repo.msys2.org, which drops old versions, and `pkgs/windows/sources.nix`, from which CI publishes every source the set fetches to the public cache, no longer lists them. `builtin:unpack` no longer extracts `.tar.zst` archives or skips the files at an archive's root whose names begin with a dot, pacman's `.PKGINFO` and `.MTREE` among them, which only those packages needed: a `.tar.zst` source fails with `unsupported archive format`, and a dot file at an archive's root is extracted like any other. It still extracts `.tar.gz` and plain `.tar` archives, and stage0-pe32's chain reads GitHub's `.tar.gz` archives through it. (#726)+- **The Windows stdenv's `windres`, and the GCC 16 rungs' builds, run windres' preprocessor without `cmd.exe`.** windres reads the output of the preprocessor it runs on a resource script through `popen`, which starts the command through `cmd.exe`, a program from outside the store; `--use-temp-file` has windres start the preprocessor itself and read its output from a file. The stdenv's `windres` wrapper passes it, as do `gcc-latest`, `gcc-core-x86_64`, `gcc-x86_64` and `gcc-native-x86_64`, which compile GCC's UTF-8 manifest with windres. Their `WINDRES` is in the derivation's environment rather than in `configureFlags`, which the seed stdenv splits at spaces, and configure takes a tool that is already set. (#753)+- **`gcc-core` and `gcc46-cxx` build gmp's table of digits per bit from fixed digits, so `gcc46-cxx` builds to the same bytes on x64 and ARM64 Windows.** gmp writes the table at build time with a program it compiles and runs on the build machine, which computed each base's value with that machine's `log` and `printf`. Under ARM64 Windows' x86 emulator, which carries out x87 arithmetic in double precision, `gcc46-cxx`'s program wrote other last digits for 13 of the 255 bases, so the rung's `cc1` and `cc1plus` differed between the two legs of the ladder. A patch to gmp's generator has it write fixed digits instead, those an x86 processor gives, which are the table both rungs wrote on x64 before: each base's value is 0.69314718055994530942 divided by `log(base)` in double precision, the log and the quotient each rounded to the nearest double, written to sixteen places from its first seventeen significant digits. The later gmp that GCC 10 and GCC 16 build computes its table in integers, and needs no patch. (#752)+- **`pkgs/windows/unused-prebuilt.json` lists each prebuilt file in a source archive the stdenv's closure unpacks, with why no build uses it, and every build that unpacks one of those archives removes its listed files first.** GNU's GCC and binutils releases carry zlib's MASM objects, libgo's test data and binutils' test-suite inputs, and stage0-pe32's tree carries the original hex0, whose DOS header its development generators copy. GNU publishes no release archive without them and stage0-pe32's tree stays as it is, so what can hold is that no build reaches them. The seed stdenv's unpack phase, which the package set's stdenv runs too, removes the files a derivation's `unusedPrebuilt` names, and both stdenvs' `mkDerivation` set it from the list for `src`. A listed file the archive does not hold fails the build, so the list cannot go stale unnoticed. The Stdenv ladder job runs `nova-nix trust --json` over GNU Hello and fails on any input a build runs that is not the seed or a reproduction of it, any prebuilt file the list does not name, and any file the list names that the report does not find. Every rung's store path changes. (#762)+- **`pkgs/windows` builds GNU Bash 5.3 with GNU's twenty official patches, as `bash`, with the package set's stdenv, for x86_64 Windows on msvcrt alone, with no Cygwin or MSYS2 runtime, and CI's new Bash stage, after Stdenv on its handoff, checks it on x64 and ARM64.** nixpkgs' generic stdenv runs `setup.sh` under bash and setup.sh needs bash 5, so a from-source Windows stdenv for nixpkgs needs a bash built on the ladder. Windows has no fork, and bash forks for every child, so the port, in `pkgs/windows/by-name/ba/bash`, starts a program as a new process where bash would fork and exec one: the shell makes the program's redirections its own while it starts it, with CreateProcess, giving it exactly the descriptors a forked child would keep, close-on-exec and append mode included, through the table msvcrt passes a child and a list of the handles it inherits, then undoes them. A `#!` script runs its interpreter, which bash starts itself, as Windows reads no `#!` line (configure's check passes only because busybox-w32's `sh` reads it, so bash is told the system does not), a script with no `#!` line runs in a new bash, and `exec` and `bash -c` stand in for the program they would exec by waiting for it and exiting with its status. Subshells, command substitution, pipelines and background jobs, which need a copy of the shell, fail with `fork: Function not implemented` for now. A script's `PATH` keeps what it writes; the command search and a program's environment split it at `;` and at a `:` that does not end a drive letter, as busybox-w32 does, so a `PATH` of `C:\...` directories joined with `:` works, and a program finds it joined with `;`; in each directory the search takes `NAME.exe` where `NAME` is no program. `/dev/null`, `/dev/tty` and `/dev/fd/N` open as Windows names them, and a program's exit status reads back as POSIX's, an access violation as SIGSEGV. bash's malloc casts pointers to `long`, which is 32 bits on Windows, and now casts them to `intptr_t`; `builtins/psize.c` stops counting at a failed write where no SIGPIPE comes; and four of bash's files that assumed `st_blocks`, `TIOCGWINSZ`, networking or a header another one includes now build without them. GNU publishes the patches as context diffs, which busybox's `patch` does not read, so each is rewritten as the unified diff it is before it applies; the result is the tree GNU's `patch -p0` makes of them. The checks have bash run, as a build's builder, a script of functions, indexed and associative arrays, `local -n` and `shopt -s inherit_errexit`, and a program and two `#!` scripts, one whose interpreter is bash and one whose interpreter is another program, found on such a `PATH`, with their arguments, redirections and exit statuses. (#769)++### Dependencies++- **A tree on disk that cannot be read is still reported as `error: ` and the failure, now that nova-cache raises a walk's failure as `NarWalkError`.** nova-cache from 0.13 raises a walk's failure to read an entry as `NarWalkError`, which names the access and the entry, where 0.12 raised the bare `IOException`, so the command line's report of an I/O failure no command handled, and the checks that read an unreadable tree as a mismatch or as nothing there, would have let it through to GHC's uncaught-exception report. The command line reports it as it reports an I/O failure, naming the access that failed (`/d/tree/sub: listing directory: permission denied (Permission denied)`), a failed push names it the same way, and both checks catch it. `NarWalkError` arrived in nova-cache 0.13; the floor is 0.14, for the change below. (#561)+- **nova-nix builds against nova-cache 0.14, and a NAR it reads, a cache's included, is refused as upstream refuses it when it holds a keyword over 32 bytes, an entry name over 255, a symlink target over 4095, a symlink target that is empty or holds NUL, or a node 64 directories deep, and a tree it archives is refused with `path '<path>' exceeds maximum NAR directory depth of 64` when it holds an entry that deep.** nova-cache 0.14 holds its parser to the limits upstream's `parseDump` applies at 2.36.0, refusing a string past its limit from its length prefix, before the bytes it declares are read, and holds its walk to the depth at which upstream's `dumpPath` refuses an entry, before the entry's status is read. The parser accepted structural strings of up to 64 KiB in a streamed NAR, of any length in one held whole, and checked neither targets nor depth, so a substitution could unpack an archive upstream's restore refuses, and a source path, a build output or a pushed path nested that deep was archived where upstream refuses to dump it. A walk still archives a name or a target past its limit, as upstream's dump does, which a Windows name of up to 255 UTF-16 units can reach, and that archive does not parse, as upstream's does not. The floor on nova-cache rises to 0.14, whose `NarStep` carries the result `NarDone` finishes with. (#759)+ ## 0.10.0.0 - 2026-11-04  On Windows, CI builds the start of a toolchain from source as derivations on x64 and ARM64: stage0-pe32's chain from a 1,623-byte seed up to kaem, mescc-tools-extra's programs, and GNU Mes 0.27.1. A build tries a derivation's outputs before its inputs, as upstream does, so a package a cache holds no longer pulls in what it was built from, and a cache that fails stops the build unless `--fallback` is given.@@ -334,9 +689,9 @@  ## 0.4.0.0 - 2026-06-10 -### Milestone: The First Native Windows Build+### Native Windows builds -`nova-nix build pkgs/windows/hello.nix` compiles and runs a C program through a Nix derivation, natively on Windows: evaluation records the derivation closure, the builder realizes 17 fixed-output fetches and a toolchain unpack in dependency order, and a compiler that is itself a store path produces `C:\nix\store\...-hello\hello.exe`. The first package built natively on Windows by a Nix implementation.+`nova-nix build pkgs/windows/hello.nix` compiles and runs a C program through a Nix derivation, natively on Windows: evaluation records the derivation closure, the builder realizes 17 fixed-output fetches and a toolchain unpack in dependency order, and a compiler that is itself a store path produces `C:\nix\store\...-hello\hello.exe`: nova-nix's first package built natively on Windows.  - **New: `builtin:unpack`** - an in-process archive extractor, the counterpart to `builtin:fetchurl`: the unpacker is the thing being bootstrapped, so it cannot be a store tool, and ambient `tar` is unpinned. Extracts `.tar.zst`/`.tar` archives listed in `srcs` into the single `out` output, in order. MSYS2 packages share the `mingw64/` prefix, so a package set merges into one working toolchain root. Symlink and hardlink entries are materialized as copies (store outputs must not require Developer Mode), pacman per-package metadata is skipped, and cross-archive file collisions and path traversal fail the build loudly. MSYS2's zstd frames carry no pledged content size, so decompression is streaming. New dependencies: `tar >= 0.7.1`, `zstd`. - **New: `pkgs/windows/seed.nix`** - stage 0 of the native Windows stdenv: the 17-package runtime closure of `mingw-w64-x86_64-gcc`, sha256-pinned against `repo.msys2.org`, fetched and merged into a single toolchain root. `pkgs/windows/hello.nix` is the proof build; its recipe also documents the Windows DLL rule (a subprocess resolves DLLs via `PATH`, not RPATH, so dependencies' `bin` dirs go on the build `PATH`).@@ -369,11 +724,11 @@  - **Fix: `import <nixpkgs> {}` infinite recursion - lazy `derivation` over `derivationStrict`** - `builtins.derivation` was eager: forcing a derivation to WHNF forced its entire env/input closure. This turned nixpkgs' lazy `perl` and `libxcrypt` dependency cycle into a blackhole - `perl`'s `assert (libxcrypt != null)` forced `libxcrypt`'s build, which forced `perl` mid-construction. Restored Nix's two-tier model: the eager `builtins.derivationStrict` primop (identical content-hashing, renamed from the old `builtins.derivation` body) plus a lazy `derivation` wrapper over it (mirroring `corepkgs/derivation.nix`). Forcing a derivation to WHNF now yields its attribute spine without computing `drvPath`/`outPath` or forcing its inputs, so referencing a package no longer builds its closure. No C changes; `drvPath`/`outPath` hashes unchanged. The stdenv bootstrap now progresses through derivation construction instead of looping (next blocker: a variable-slot bug while evaluating perl's `@`-pattern). -### Technical Audit + C Data Layer Polish+### Correctness and the C Data Layer  - **Fix: Nix integer division semantics** - `builtins.div` and `builtins.mod` now use floored division (`div`/`mod`) instead of truncated (`quot`/`rem`). `-7 / 3` correctly returns `-3` (was `-2`). Affects `builtinDiv`, `builtinMod`, and `evalDiv`. - **Fix: `inherit (from)` in positional let/rec blocks** - The resolution pass treated `inherit (expr) x y;` as positional, but the bytecode evaluator did not handle `BcInheritFrom` in `allBcPositional`, `bcBindingSlotCount`, `buildBcSlotThunks`, or `buildBcAttrMapFromSlots`. This caused env slot count mismatches and `idx out of bounds` assertions on any nixpkgs expression using `inherit (from)` in a positional let block.-- **C memory safety audit** - `nn_bytecode.c`: `ensure_op_space`/`ensure_data_space` now return error codes instead of failing silently; overflow guard on capacity doubling. `nn_lambda.c`: `NN_ASSERT` bounds checks on entry accessors prevent null dereference when `formal_count == 0`. `nn_attrset.c`: documented partial-realloc-failure behavior.+- **C memory safety** - `nn_bytecode.c`: `ensure_op_space`/`ensure_data_space` now return error codes instead of failing silently; overflow guard on capacity doubling. `nn_lambda.c`: `NN_ASSERT` bounds checks on entry accessors prevent null dereference when `formal_count == 0`. `nn_attrset.c`: documented partial-realloc-failure behavior. - **Dead code removal** - Removed unused `cattrsetIntersect` Haskell wrapper, `nn_attrset_intersect`, and `nn_attrset_values_ptr` C functions. - **New: `nn_assert.h`** - Debug-mode bounds checking macro. Compiles to nothing under `NDEBUG`. - **Performance** - Stress test: 6.25 MB max residency, 56.3% GC productivity (down from 69.7 MB / 1.6% pre-C-data-layer).
NOTICE view
@@ -61,3 +61,51 @@   LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION   OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION   WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.++pkgs/windows/by-name/bi/binutils/fix-tinycc-attribute.patch+  Copied from pkgs/os-specific/linux/minimal-bootstrap/binutils in nixpkgs+  (https://github.com/NixOS/nixpkgs) at commit+  3cd60b6a1b2be2e4ce51b1ae3e58e0946be42368. Licensed under the MIT+  License:++  Copyright (c) 2003-2026 Eelco Dolstra and the Nixpkgs/NixOS contributors++  Permission is hereby granted, free of charge, to any person obtaining+  a copy of this software and associated documentation files (the+  "Software"), to deal in the Software without restriction, including+  without limitation the rights to use, copy, modify, merge, publish,+  distribute, sublicense, and/or sell copies of the Software, and to+  permit persons to whom the Software is furnished to do so, subject to+  the following conditions:++  The above copyright notice and this permission notice shall be+  included in all copies or substantial portions of the Software.++  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND+  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE+  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION+  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION+  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.++pkgs/windows/by-name/bi/binutils/compat,+pkgs/windows/by-name/bu/busybox-w32/compat and+pkgs/windows/seed-stdenv/include+  Declarations transcribed from the headers of mingw-w64+  (https://www.mingw-w64.org) v14.0.0, mingw-w64-headers, which their+  authors place in the public domain.++data/develop/get-env.sh+  Copied unchanged from src/nix/get-env.sh in Nix+  (https://github.com/NixOS/nix) at tag 2.35.4. Licensed under the GNU+  Lesser General Public License, version 2.1, whose text is+  data/develop/COPYING, copied from that tag's COPYING.++This product builds on other work:++pkgs/windows: the seed chain, from stage0-pe32 to the seed stdenv+  Builds on Gavin John's Windows port of the full-source bootstrap+  (https://github.com/Pandapip1/stage0-pe32): stage0-pe32 and its seed,+  the M2libc x86/windows target, the kaem changes, and the GNU Mes Windows+  port.
README.md view
@@ -4,154 +4,393 @@ [![Hackage](https://img.shields.io/hackage/v/nova-nix.svg)](https://hackage.haskell.org/package/nova-nix) [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](https://github.com/Novavero-AI/nova-nix/blob/main/LICENSE) -nova-nix is an implementation of [Nix](https://nixos.org) that runs natively on-Windows, without WSL or an existing Nix installation: the same language, the-same `/nix/store` paths as upstream Nix on Linux and macOS, and the same binary-caches. It is written in Haskell with a C99 data layer, has its own parser,-evaluator, store, builder and binary-cache substituter, and also runs on macOS-and Linux.+nova-nix is an implementation of [Nix](https://nixos.org) for Windows, macOS+and Linux. It evaluates Nix expressions, builds derivations into a Nix store+and downloads from binary caches. Its commands are its own: `nova-nix eval`+and `nova-nix build` take the place of `nix-instantiate --eval` and+`nix-build`, and `nova-nix profile` that of `nix profile`. -nova-nix is experimental. Read [Limitations](#limitations) before relying on-it.+- **Upstream's derivations.** On each nixpkgs tree [the scoreboard][scoreboard]+  walks, every package `nix-env -qa` lists for x86_64-linux that upstream Nix+  evaluates gets the same drvPath from nova-nix. Its store paths are+  upstream's, so on Linux and macOS it downloads what cache.nixos.org has+  built, checked against the cache's signature.+- **Native on Windows.** It runs with no WSL or existing Nix installation, and+  [`pkgs/windows`] builds a toolchain from source: from [stage0-pe32]'s seed,+  through GNU Mes, TinyCC and GCC 4.6.4, 10 and 16, to the native x86_64 GCC+  its stdenv wraps, on x64 Windows and, under emulation, on ARM64 Windows.+- **Rebuild checks.** `build --check` builds a derivation again and compares+  the result with the store's, as `nix-build --check` does.+- **Closure reports.** `trust` lists the fixed-output derivations a closure+  bottoms out in, and which of them run as builders or hold prebuilt code.+- **Cache uploads.** `push` uploads store paths and their closures to a+  [nova-cache] server, or writes them to a directory as a signed binary cache,+  which nova-nix and upstream Nix substitute from through a `file://` URL and+  a static web server can serve. -## Status+nova-nix is experimental; [Status](#status) says what it does not do. -- **Evaluation matches upstream Nix on the cases CI checks.** On every change,-  CI evaluates the nixpkgs derivations in [`drvpath-cases.txt`] and the-  expressions in [`eval-cases.sh`] with nova-nix and with upstream Nix, on each-  pairing of Nix and nixpkgs that [`parity.yml`] pins, and requires the same-  results. A matching `drvPath` means the whole build-time closure behind it-  matches too. It also probes `derivation` against upstream's over a corpus of-  calls, apart from the differences [`derivation-divergences.txt`] lists. How-  much of the rest of nixpkgs evaluates is not measured ([#29]).-- **Windows builds run natively.** CI builds GNU Hello on Windows through a-  stage-1 stdenv whose toolchain is prebuilt MinGW-w64 and MSYS2 packages,-  each pinned by SHA-256 ([`pkgs/windows/bootstrap`]). Replacing them with a-  toolchain built from source is tracked in [#26]. CI builds the start of it-  on x64 and ARM64 Windows from the 1,623-byte seed of [stage0-pe32]: the-  chain up to kaem, mescc-tools-extra, and [a Windows port] of GNU Mes 0.27.1.-- **Binary caches work in both directions.** `nova-nix push` uploads a closure-  to a [nova-cache] server, which signs it, and a build given a substituter-  downloads signed NARs from an HTTP binary cache instead of building. CI-  substitutes from a local nova-cache server on Linux. On every push to main-  it publishes the Windows Hello closure to the public cache at-  [cache.novavero.ai](https://cache.novavero.ai), then builds that closure into-  an empty store with the cache as its only substituter and fails if any path-  is built locally.+## Install -### Limitations+Windows, in PowerShell: -- No flakes, no `nix-shell` or `nix develop`, and no daemon or multi-user mode.-- Evaluation is slower than upstream's, most of all on large evaluations such-  as a NixOS system. The Parity job logs both evaluators' times for each-  derivation case.-- Garbage collection has no runtime roots: `nova-nix store gc` keeps what-  `build --out-link` registered and what the operator roots under the store's-  `.nova-nix/gcroots`, not what a running program has open. `keep-derivations`-  and `keep-outputs` are not implemented, so a rooted output does not keep the-  `.drv` that built it. `build` creates no result link unless `--out-link` is-  given, where `nix-build` defaults to `./result`.-- `--restrict-eval` and `--pure-eval`, and `restrict-eval`, `pure-eval` and-  `allowed-uris` in nix.conf, gate reads, the environment and fetches as-  upstream's modes do, with three differences: the closure of a search path-  root that is a store path is not allowed along with it,-  `builtins.findFile` treats a path the policy refuses as absent, and under-  `--pure-eval` `builtins.nixPath` lists the bundled `<nix/*>` directory,-  where upstream's is empty.-- `builtins.fetchurl` runs `curl`, `builtins.fetchTarball` runs `sh`, `curl` and-  `tar`, and `builtins.fetchGit` runs `git`, each from `PATH`.-- A store path's hash covers the spelling of the store directory. On Windows-  nova-nix hashes over `/nix/store`, as Linux and macOS do. Upstream's local-  store on Windows hashes over its native directory, `%ProgramData%\nix\store`-  by default since Nix 2.35, so the same derivation has a different store path-  in each.-- On Windows a build's process tree runs in a job object, so stopping a build-  stops everything it started. No platform isolates a build's filesystem or-  network; a Windows filesystem sandbox is tracked in [#194].-- nova-nix itself needs neither WSL nor Cygwin, but the Windows stdenv runs its-  build scripts with MSYS2's bash.-- Store paths that contain symlinks need Windows Developer Mode or an elevated-  shell. nova-nix creates native symlinks and fails rather than falling back-  to a copy.+```powershell+irm https://raw.githubusercontent.com/Novavero-AI/install-nova-nix/v1/install.ps1 | iex+``` -## Install+macOS and Linux: +```sh+curl --proto '=https' --tlsv1.2 -fsSL https://raw.githubusercontent.com/Novavero-AI/install-nova-nix/v1/install.sh | sh+```++The [installer](https://github.com/Novavero-AI/install-nova-nix) checks the+latest release against its published checksums, puts `nova-nix` on `PATH` and+sets up [the store](#the-store), so no command needs `--store`. Its README says+what it changes on each platform and how to uninstall. Then, in a new shell:++```console+$ nova-nix eval --expr '1 + 2'+3+```++The Windows executable is x64, and runs under emulation on Windows 11 on+Arm. The macOS executable needs macOS 26 or newer on Apple silicon. The Linux+executable needs glibc 2.38 or newer, and the GMP and zlib libraries+(`libgmp.so.10` and `libz.so.1`).++### By hand+ Each [release](https://github.com/Novavero-AI/nova-nix/releases/latest) has an archive per platform:  | Platform | Archive | | --- | --- |-| Linux x86_64 | [`nova-nix-linux-x64.tar.gz`](https://github.com/Novavero-AI/nova-nix/releases/latest/download/nova-nix-linux-x64.tar.gz) |-| macOS arm64 | [`nova-nix-macos-arm64.tar.gz`](https://github.com/Novavero-AI/nova-nix/releases/latest/download/nova-nix-macos-arm64.tar.gz) | | Windows x86_64 | [`nova-nix-windows-x64.zip`](https://github.com/Novavero-AI/nova-nix/releases/latest/download/nova-nix-windows-x64.zip) |+| macOS arm64 | [`nova-nix-macos-arm64.tar.gz`](https://github.com/Novavero-AI/nova-nix/releases/latest/download/nova-nix-macos-arm64.tar.gz) |+| Linux x86_64 | [`nova-nix-linux-x64.tar.gz`](https://github.com/Novavero-AI/nova-nix/releases/latest/download/nova-nix-linux-x64.tar.gz) | -Each archive unpacks to a single directory holding `bin/`, `share/nova-nix/`,-`pkgs/` and the license files. `share/nova-nix/` provides the `<nix/*>` search-path, so the binary works wherever the directory is unpacked, and `pkgs/` holds-the package recipes. Check the download against the `SHA256SUMS` file attached-to the same release, with `sha256sum --ignore-missing -c SHA256SUMS`.+An archive unpacks to one directory named after it, holding `bin/`,+`share/nova-nix/`, `pkgs/`, this README and the license files, and on Linux+`libexec/nova-nix/`, which holds the shell a sandboxed build runs as+`/bin/sh`. The executable finds the Nix expressions it bundles in+`share/nova-nix/` from its own location, so keep the directory together and+put its `bin/` on `PATH`. `pkgs/`+holds the Windows package recipes. `SHA256SUMS`, attached to the same release,+lists each archive's checksum. -In a GitHub Actions workflow:+#### Windows +In PowerShell:++```powershell+curl.exe -fsSLO https://github.com/Novavero-AI/nova-nix/releases/latest/download/nova-nix-windows-x64.zip+curl.exe -fsSLO https://github.com/Novavero-AI/nova-nix/releases/latest/download/SHA256SUMS+(Get-FileHash nova-nix-windows-x64.zip).Hash+Select-String nova-nix-windows-x64.zip SHA256SUMS+Expand-Archive nova-nix-windows-x64.zip -DestinationPath "$env:LOCALAPPDATA\Programs" -Force+$env:Path += ";$env:LOCALAPPDATA\Programs\nova-nix-windows-x64\bin"+```++The two hashes printed should match, apart from case. The last line puts+`nova-nix` on `Path` in this shell; for new shells, add+`%LOCALAPPDATA%\Programs\nova-nix-windows-x64\bin` to your user `Path` in+Settings (search for "environment variables").++```console+> nova-nix eval --expr '1 + 2'+3+```++#### macOS and Linux++```sh+curl -fsSLO https://github.com/Novavero-AI/nova-nix/releases/latest/download/nova-nix-macos-arm64.tar.gz+curl -fsSLO https://github.com/Novavero-AI/nova-nix/releases/latest/download/SHA256SUMS+shasum -a 256 --ignore-missing -c SHA256SUMS+tar -xzf nova-nix-macos-arm64.tar.gz -C "$HOME"+export PATH="$HOME/nova-nix-macos-arm64/bin:$PATH"+```++On Linux, the archive is `nova-nix-linux-x64.tar.gz`, its `bin/` is+`$HOME/nova-nix-linux-x64/bin`, and `sha256sum` checks it in place of+`shasum -a 256`. Add the `export` line to your shell's startup file+(`~/.zshrc` or `~/.bashrc`) so that new shells find `nova-nix`.++```console+$ nova-nix eval --expr '1 + 2'+3+```++### In GitHub Actions+ ```yaml - uses: Novavero-AI/install-nova-nix@v1 - run: nova-nix eval --expr '1 + 2' ``` -## Usage+The [action](https://github.com/Novavero-AI/install-nova-nix) installs the+latest release, or the one its `version` input names, on x64 Windows, arm64+macOS and x64 Linux runners, puts `nova-nix` on `PATH` and sets up+[the store](#the-store) as the installer does, so no command needs `--store`.+A macOS or Linux runner has to meet the requirements above, as `macos-latest`+and `ubuntu-latest` do. +## Set up++### The store++nova-nix keeps what it builds and downloads in a store directory, with its own+database inside it under `.nova-nix/`. Every command takes `--store DIR` to use+another directory, and nix.conf's `store` setting and `NIX_REMOTE` choose one+too.++Give nova-nix a store of its own. It does not read upstream Nix's database or+roots, so in a store upstream Nix also manages, `nova-nix store gc` would+delete upstream's paths, and a build would replace the upstream paths it builds+or downloads. A command that opens such a store itself refuses it before+writing to it, and the [command-line reference](https://novavero.ai/docs/nova-nix/cli)+says when each command does. Where upstream Nix is installed, give nova-nix+another directory with `--store`. A build in a store other than+`/nix/store` or `C:\nix\store` writes that store's directory into its output,+so the output differs from upstream's at the same store path.++A `nova-nix` command opens the store itself where its process can write it, and+otherwise goes through a daemon, nova-nix's or upstream's, when one is there;+`--store` chooses, and `nova-nix --help` says how. `nova-nix daemon` serves the+store to other users' clients in upstream Nix's protocol, over a Unix socket as+`nix daemon` does, or on Windows over the named pipe `\\.\pipe\nova-nix-daemon`.+The [command-line reference](https://novavero.ai/docs/nova-nix/cli) says which+clients it admits and trusts, and what it adds, builds and substitutes for them.+`trusted-public-keys` is empty unless nix.conf sets it, where upstream's default+holds the key of cache.nixos.org.++**Windows.** The store is `C:\nix\store`. The installer creates `C:\nix` so+that only you, SYSTEM and Administrators can change it, and nova-nix creates a+store directory with the same permissions. A `C:\nix` that nova-nix creates+itself grants other users nothing; the installer accepts it and gives it its+own permissions. nova-nix refuses a store when the store directory, or a+directory on the way to it below the drive root, is owned by another account or+lets one change it, and the error names the directory to move aside.+Turn on Developer Mode (Settings, For developers): nova-nix makes native+symlinks, inside store paths and for the `result` link a build makes, and+Windows allows them only in Developer Mode or an elevated shell. Without+either, building or downloading a path that holds a symlink fails, and so does+a build's `result` link, unless `--no-out-link` is given.++Expressions see store paths as `/nix/store/...` on Windows too, so a+derivation has the same store path whichever platform evaluates it; a build+prints the path under `C:\nix\store`. A path with a root but no drive, such as+`/src/default.nix`, names that path on the store's drive: `C:` for the default+store, or the drive of the directory `--store` names.++**Linux.** The store is `/nix/store`, which nova-nix creates when `/nix` is+yours. The installer gives you `/nix`; by hand:++```sh+sudo mkdir -p /nix+sudo chown "$USER" /nix+```++**macOS.** The store is `/nix/store` too. The root volume is read-only, so+`/nix` exists only if `/etc/synthetic.conf` creates it. The installer does, on+an APFS volume of its own, and+[upstream Nix's installer](https://nix.dev/manual/nix/latest/installation/installing-binary.html#macos-installation)+sets one up too. Without either, a command that writes to the store, such as a+build or an evaluation that computes a nixpkgs package's store path, fails:++```text+error: /nix: createDirectory: permission denied (Read-only file system)+```++In that case, give those commands a store in your home directory,+`--store ~/nix/store`, as the examples below do.++### Configuration++nova-nix reads `nix.conf` from a system file, a user file and the+`NIX_CONFIG` environment variable, as upstream Nix does. On Windows the files+are `%ProgramData%\nix\nix.conf` and `%APPDATA%\nix\nix.conf`; on macOS and+Linux they are `/etc/nix/nix.conf` and `~/.config/nix/nix.conf`. `nova-nix --help`+lists the order they apply in, the settings it reads and the variables that+move these files.++nova-nix has no default binary cache (upstream Nix defaults to+cache.nixos.org), so unless `substituters` or `--substituter` names one, every+derivation is built locally.++On Windows, for [cache.novavero.ai](https://cache.novavero.ai), which holds the+Windows packages CI builds (this replaces an existing user file):++```powershell+New-Item -ItemType Directory -Force "$env:APPDATA\nix" | Out-Null+Set-Content "$env:APPDATA\nix\nix.conf" 'substituters = https://cache.novavero.ai', 'trusted-public-keys = cache.novavero.ai-1:9gQ7tLWMM+2tdC9H5sKMJltDIPfD7X2GWlZe8Aa8hHQ='+```++Write the file as UTF-8 without a byte-order mark, as `Set-Content` does for+these lines. After a byte-order mark nova-nix ignores the first setting, or+refuses the file when its first line is a comment. Windows PowerShell 5.1's+`>` writes UTF-16, which nova-nix refuses as a syntax error.++To use cache.nixos.org on macOS or Linux (this also replaces an existing+file):++```sh+mkdir -p ~/.config/nix+printf '%s\n' 'substituters = https://cache.nixos.org' 'trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=' > ~/.config/nix/nix.conf+```++`NIX_CONFIG` holds the same lines and applies over the files, here for one+shell:++```sh+export NIX_CONFIG='substituters = https://cache.nixos.org+trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY='+```++`--substituter URL` and `--trusted-key KEY` add a cache and a key for one+command, on top of what is configured. The examples below pass them, so they+work with or without a `nix.conf`.++## First steps++### Evaluate an expression+ ```console-$ nova-nix eval --expr '1 + 2'-3-$ nova-nix build FILE.nix -A ATTR --out-link result-$ nova-nix build FILE.nix --substituter URL --trusted-key KEY --fallback-$ nova-nix store gc+$ nova-nix eval --expr '{ a = 1 + 1; }'+{ a = <CODE>; }+$ nova-nix eval --strict --expr '{ a = 1 + 1; }'+{ a = 2; } ``` -`nova-nix --help` lists every command and flag.+`eval` prints a value as `nix-instantiate --eval` does. A part of it that+evaluation never needed prints as `<CODE>`, and `--strict` evaluates the whole+value first. A file evaluates the same way: -Building GNU Hello on Windows, from the unpacked release directory, with the-[public cache](https://cache.novavero.ai) as its substituter:+```console+$ cat greet.nix+let name = "world"; in "Hello, ${name}!"+$ nova-nix eval greet.nix+"Hello, world!"+``` +### Build GNU Hello on Windows++From the directory the release unpacked to, with cache.novavero.ai as the+substituter:++```powershell+Set-Location "$env:LOCALAPPDATA\Programs\nova-nix-windows-x64"+```+ ```console-> bin\nova-nix build pkgs\windows\hello.nix --substituter https://cache.novavero.ai --trusted-key cache.novavero.ai-1:9gQ7tLWMM+2tdC9H5sKMJltDIPfD7X2GWlZe8Aa8hHQ=-...-C:\nix\store\<hash>-hello-> C:\nix\store\<hash>-hello\bin\hello.exe+> nova-nix build pkgs\windows\hello.nix --substituter https://cache.novavero.ai --trusted-key cache.novavero.ai-1:9gQ7tLWMM+2tdC9H5sKMJltDIPfD7X2GWlZe8Aa8hHQ=+  [subst]  hello+C:\nix\store\3w227dnigkhxgi8rsp30mszp927s35fr-hello+> .\result\bin\hello.exe Hello, world! ``` -The cache holds this closure as CI last built it from main, so the build-downloads what the cache holds and builds only what it lacks. Without a-substituter it fetches the pinned toolchain packages and builds the toolchain-before Hello.+The build downloads what the cache holds and builds only what it lacks.+Without a substituter it first builds Hello's toolchain from the seed+ladder's 1,623-byte seed, which takes hours, and then Hello with it. -## On Windows+Build scripts run in busybox-w32's sh, which the ladder builds too, so+nothing else needs installing. `pkgs\windows\default.nix` is the whole+Windows package set, and `-A` selects one of its packages. -The store is `C:\nix\store` by default. Derivations keep the `/nix/store`-spelling that hashes are computed over, and it is mapped to the real directory-only when a builder starts. A file's executable bit is kept in an NTFS-alternate data stream. A store path therefore serializes to the same NAR, with-the same hash, as it does on other platforms.+### Build a derivation on macOS or Linux -A path with a root but no drive, such as `/src/default.nix`, names that path on-the store's drive, whichever drive is current: `C:` for the default store, or-the drive of the directory `--store` names.+```console+$ nova-nix build --store ~/nix/store --expr 'derivation { name = "greeting"; system = builtins.currentSystem; builder = "/bin/sh"; args = [ "-c" "echo hello > $out" ]; }'+  [build]  greeting+/Users/me/nix/store/gs1rwhzwrg6p0vf3pk8lxv35d7z2dfiz-greeting+$ cat result+hello+``` -## Library+`build` prints the output's path on stdout and its progress on stderr, and+links the output from `./result`, a root that `nova-nix store gc` keeps, unless+`--no-out-link` is given. The collector does not keep the `.drv` behind a+rooted output, or a path a running program has open.+On Linux with `/nix` set up, leave out `--store`. -nova-nix is also a Haskell library, documented on-[Hackage](https://hackage.haskell.org/package/nova-nix). `Nix.Parser` parses,-`Nix.Eval` evaluates, and `Nix.Store`, `Nix.Builder`, `Nix.Realise` and-`Nix.Substituter` keep the store, build and substitute. Evaluation needs the C-data layer, so it runs between `arenaInit` and `arenaDestroy`, as-`Nix.Eval.Arena` describes.+### Get a package from cache.nixos.org on macOS or Linux +Unpack a nixpkgs revision in the working directory, then evaluate an+expression that imports it, or build one of its packages with `-A`:++```sh+curl -fsSL https://github.com/NixOS/nixpkgs/archive/6f06d204d8f2d8761d9da78778745974a3216381.tar.gz | tar -xz+mv nixpkgs-6f06d204d8f2d8761d9da78778745974a3216381 nixpkgs+```++```console+$ nova-nix eval --expr '(import ./nixpkgs { }).hello.version'+"2.12.3"+$ nova-nix build --store ~/nix/store ./nixpkgs -A hello --substituter https://cache.nixos.org --trusted-key cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=+  [subst]  hello-2.12.3+/Users/me/nix/store/0blwcqcg0swwz9x748rhyzbfyaybmql8-hello-2.12.3+```++A program from cache.nixos.org loads its libraries from `/nix/store`, so it+runs only from a store at `/nix/store`. From `~/nix/store`, macOS stops it with+`Library not loaded: /nix/store/...`. On Linux with `/nix` set up:++```console+$ nova-nix build ./nixpkgs -A hello --substituter https://cache.nixos.org --trusted-key cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=+  [subst]  hello-2.12.3+/nix/store/fkv51s1m2gsy6pz71nnyqyprbvfg7sd7-hello-2.12.3+$ ./result/bin/hello+Hello, world!+```++## Status++Not implemented yet, and on the [roadmap]: flakes, `nix-shell`, `nix develop`+on Windows, a multi-user install that starts `nova-nix daemon` at boot, and the+daemon as a Windows service. On Linux a build runs in a+sandbox, as upstream's does, where it sees only its inputs and, unless it is+fixed-output, no network; a builder that is a host program such as `/bin/sh`+needs `sandbox-paths` to bind it, as a release archive binds its own shell.+Ubuntu lets the sandbox in only under an AppArmor profile for+`nova-nix-sandbox`, and without one a build runs unsandboxed after a warning.+On macOS `sandbox = true` runs a build under a profile of macOS's sandbox, off+by default as upstream's is, where it reads only its inputs and the paths+`sandbox-paths` names and, unless it is fixed-output, reaches no network. As+root a build runs as a member of `build-users-group`, `nixbld` by default, as+upstream's does.+Builds on Windows, and on macOS by default, are not sandboxed: a builder there+can read and write outside its build directory and reach the network.++A target is a file, a directory or a `<NAME>` the search path finds, not a+URL, and `build` builds one derivation, where `nix-build` builds each one in a+list or set.+`builtins.fetchGit` runs `git` from `PATH`.++## Where to read more++- `nova-nix --help`, also [on the web](https://novavero.ai/docs/nova-nix/cli):+  every command, flag and `nix.conf` setting.+- [Hackage](https://hackage.haskell.org/package/nova-nix): nova-nix as a+  Haskell library.+- [Architecture](https://novavero.ai/docs/nova-nix/architecture/): how the+  evaluator, the store, the builder and the Windows port work together.+- [CHANGELOG.md]: what each release changed, and where nova-nix's behavior+  differs from upstream's.+- [`drvpath-cases.txt`], [`eval-cases.sh`] and [`parity.yml`]: what CI checks+  against upstream Nix, and on which pairings of Nix and nixpkgs.+- [The scoreboard's runs][scoreboard]: how nova-nix's evaluation of nixpkgs+  compares with upstream Nix's, in each run's summary.+- [`pkgs/windows`]: the Windows package set, and the toolchain built from+  [stage0-pe32]'s seed.+ ## Building from source  You need this only to work on nova-nix itself, not to use a release. It needs-GHC and cabal-install; `tested-with` in `nova-nix.cabal` names the GHC version-CI uses.+GHC and cabal-install, and on Linux zlib's development files (`zlib1g-dev` on+Debian and Ubuntu); `tested-with` in `nova-nix.cabal` names the GHC version CI+uses.  ```bash git clone https://github.com/Novavero-AI/nova-nix.git@@ -163,9 +402,8 @@  ## Contributing -See [CONTRIBUTING.md]. Planned work is on the-[Nova roadmap](https://github.com/orgs/Novavero-AI/projects/1) project. Please-report security issues privately through+See [CONTRIBUTING.md]. Planned work is on the [Nova roadmap][roadmap]+project. Please report security issues privately through [GitHub's vulnerability reporting](https://github.com/Novavero-AI/nova-nix/security/advisories/new) rather than in a public issue. @@ -176,14 +414,12 @@ [`drvpath-cases.txt`]: https://github.com/Novavero-AI/nova-nix/blob/main/.github/parity/drvpath-cases.txt [`eval-cases.sh`]: https://github.com/Novavero-AI/nova-nix/blob/main/.github/parity/eval-cases.sh [`parity.yml`]: https://github.com/Novavero-AI/nova-nix/blob/main/.github/workflows/parity.yml-[`derivation-divergences.txt`]: https://github.com/Novavero-AI/nova-nix/blob/main/test/data/derivation-divergences.txt-[`pkgs/windows/bootstrap`]: https://github.com/Novavero-AI/nova-nix/tree/main/pkgs/windows/bootstrap+[scoreboard]: https://github.com/Novavero-AI/nova-nix/actions/workflows/scoreboard.yml+[`pkgs/windows`]: https://github.com/Novavero-AI/nova-nix/tree/main/pkgs/windows [stage0-pe32]: https://github.com/Novavero-AI/stage0-pe32-[a Windows port]: https://github.com/Novavero-AI/mes [nova-cache]: https://github.com/Novavero-AI/nova-cache+[CHANGELOG.md]: https://github.com/Novavero-AI/nova-nix/blob/main/CHANGELOG.md [CONTRIBUTING.md]: https://github.com/Novavero-AI/nova-nix/blob/main/CONTRIBUTING.md [LICENSE]: https://github.com/Novavero-AI/nova-nix/blob/main/LICENSE [NOTICE]: https://github.com/Novavero-AI/nova-nix/blob/main/NOTICE-[#26]: https://github.com/Novavero-AI/nova-nix/issues/26-[#29]: https://github.com/Novavero-AI/nova-nix/issues/29-[#194]: https://github.com/Novavero-AI/nova-nix/issues/194+[roadmap]: https://github.com/orgs/Novavero-AI/projects/1
app/Main.hs view
@@ -1,1197 +1,2156 @@-{-# LANGUAGE ScopedTypeVariables #-}---- | nova-nix CLI entry point: parse the argument vector, dispatch one--- command, map its outcome to an exit code.------ The command and flag tables are deliberately not repeated here.--- 'usageLines' is the one place they live, and both @--help@ and the--- usage-error path print it, so the flag that adds itself to the parser--- documents itself in the same edit.  A copy here would go stale--- unnoticed: Haddock builds library targets by default, and this module--- is in the executable stanza, so nothing renders it.-module Main (main) where--import Control.Exception (AsyncException (UserInterrupt), IOException, displayException, handle, handleJust, try)-import Control.Monad (join, mfilter, void, (>=>))-import qualified Data.ByteString as BS-import qualified Data.ByteString.Builder as BB-import qualified Data.ByteString.Char8 as BC-import Data.IORef (readIORef)-import Data.List (find)-import qualified Data.Map.Strict as Map-import Data.Maybe (catMaybes, mapMaybe)-import qualified Data.Text as T-import qualified Data.Text.Encoding as TE-import qualified Data.Text.IO as TIO-import Data.Version (showVersion)-import Nix.Builder (BuildConfig (..), BuildResult (..), buildWithDeps, defaultBuildConfig, execWrapperConfig)-import Nix.Builtins (builtinEnv, isNixPathPseudoUrl, parseNixPath, rootScopeNames, searchPathRoots)-import Nix.Config (NixConfig (..))-import qualified Nix.Config as Config-import Nix.Derivation (Derivation (..), DerivationOutput (..), fromATerm)-import Nix.Environment (EnvLookup (..), lookupEnvBytes)-import Nix.Eval (Env, EvalPolicy (..), MonadEval, NixValue (..), Thunk (..), attrSetFromMap, attrSetLookup, attrSetToMap, eval, evaluated, force, readThunkValue)-import Nix.Eval.Arena (arenaInit)-import Nix.Eval.AttrPath (selectAttrPath)-import Nix.Eval.CallDepth (topLevelCallDepth)-import Nix.Eval.CanonPath (canonPathValue)-import Nix.Eval.IO (EvalState (..), allowEvalPath, newEvalState, renderEvalFailure, runEvalIOTraced)-import Nix.Eval.Print (printAmbiguous)-import Nix.Eval.Types (clistFromThunks, clistThunks, thunkToCPtr)-import Nix.Expr.Resolve (undefinedVariableMessage)-import Nix.Expr.Types (Expr)-import Nix.HostPath (hostPathFromBytes, hostPathText)-import Nix.Parser (SourceError (..), SourceOrigin (..), parseNixWithScope)-import Nix.Push (PushCompression (..), PushConfig (..), PushSummary (..), isDerivationPath, loadApiKeyFile, outputPathsOnly, parsePushCompression, pushCompressionValues, pushPaths, storePathBasename)-import Nix.Realise (Fallback (..))-import Nix.Store (DeleteOutcome (..), GcRoot (..), LiveSet, Store (..), addOutLinkRoot, canonicalStoreDir, closeStore, collectGarbage, deleteStorePathChecked, findRoots, gcSummaryLine, materializeEvalSources, materializeEvalStoreWrites, openStore, queryAllValidPaths, resolveDeleteTarget, withLiveSet, writeDrv, writeDrvClosure)-import Nix.Store.Path (StoreDir (..), StorePath, defaultStoreDir, parseStorePath, parseStorePathBaseName, platformStoreDir, qualifyPathText, storePathToFilePath, storePathToText)-import Nix.Substituter (CacheConfig (..))-import Paths_nova_nix (getDataDir, version)-import System.Directory (Permissions (executable), canonicalizePath, doesFileExist, findExecutable, getCurrentDirectory, getPermissions, getTemporaryDirectory, makeAbsolute)-import qualified System.Directory.OsPath as OsDir-import System.Environment (getArgs, getExecutablePath, lookupEnv)-import System.Exit (ExitCode (..), exitFailure, exitWith)-import qualified System.File.OsPath as OsFile-import System.FilePath (takeDirectory, takeFileName, (</>))-import System.IO (BufferMode (..), hPutStrLn, hSetBinaryMode, hSetBuffering, hSetEncoding, stderr, stdout, utf8)-import System.IO.Error (ioeGetErrorString, isDoesNotExistError, isUserError)-import qualified System.Info as SI-import System.OsPath (OsPath)-import qualified System.OsPath as OP---- ------------------------------------------------------------------------------ Argument parsing--- ------------------------------------------------------------------------------- | Parsed CLI options.-data CliOpts = CliOpts-  { optNixPaths :: ![T.Text],-    optStrict :: !Bool,-    optAterm :: !Bool,-    -- | Store directory override (default: the platform store).-    optStore :: !(Maybe FilePath),-    -- | Binary cache URL to substitute from before building.-    optSubstituter :: !(Maybe String),-    -- | Trusted public key (@name:base64@) for the substituter.-    optTrustedKey :: !(Maybe String),-    -- | @SYSTEM=PATH@ launchers for derivations this machine cannot execute-    -- directly, e.g. @x86_64-windows=/path/to/wine@.-    optExecWrappers :: ![String],-    -- | @--restrict-eval@: upstream's restrict-eval, turned on for this run.-    optRestrictEval :: !Bool,-    -- | @--pure-eval@: upstream's pure-eval, turned on for this run.-    optPureEval :: !Bool,-    -- | @--trace-verbose@: upstream's trace-verbose, turned on for this run.-    optTraceVerbose :: !Bool,-    -- | @--fallback@: upstream's fallback, turned on for this run.-    optFallback :: !Bool,-    optCommand :: !Command-  }--data Command-  = CmdEvalFile !FilePath-  | CmdEvalExpr !T.Text-  | CmdBuild !BuildTarget !(Maybe T.Text) !(Maybe FilePath)-  | CmdPush !PushArgs-  | CmdStoreDelete ![String]-  | -- | @store gc@: collect, or with the flag only list the roots.-    CmdStoreGc !Bool-  | -- | No command given.  Usage on stderr, non-zero: a bare invocation is-    -- a usage error, and a caller testing the exit status must see one.-    CmdUsage-  | -- | @--help@.  The same text on stdout, zero: it is a request that-    -- succeeded, and pipeable without redirecting stderr.-    CmdHelp-  | CmdVersion---- | Where a build's expression comes from.-data BuildTarget-  = -- | A @.nix@ file.  Relative paths inside it resolve beside the file.-    TargetFile !FilePath-  | -- | An inline expression.  Relative paths inside it resolve against the-    -- working directory, since there is no file to sit beside.-    TargetExpr !T.Text---- | Arguments to the build command, while the target is still unknown.-data BuildArgs = BuildArgs-  { baTarget :: !(Maybe BuildTarget),-    baAttrPath :: !(Maybe T.Text),-    -- | Where to create the result symlink, registered as a GC root.-    baOutLink :: !(Maybe FilePath)-  }---- | Build arguments before any flag is parsed.-emptyBuildArgs :: BuildArgs-emptyBuildArgs = BuildArgs Nothing Nothing Nothing---- | Arguments to the push command.-data PushArgs = PushArgs-  { paCacheUrl :: !(Maybe String),-    paKeyFile :: !(Maybe FilePath),-    paCompressionArg :: !(Maybe String),-    paAll :: !Bool,-    paPaths :: ![String]-  }---- | Push arguments before any flag is parsed.-emptyPushArgs :: PushArgs-emptyPushArgs = PushArgs Nothing Nothing Nothing False []---- | Parse the command line.  A malformed invocation is an error, never a--- silent drop: an unknown or typo'd flag once ended parsing and quietly--- discarded everything after it (e.g. a requested @--substituter@).-parseArgs :: [String] -> Either String CliOpts-parseArgs = go (CliOpts [] False False Nothing Nothing Nothing [] False False False False CmdUsage)-  where-    go opts [] = Right opts-    -- Answered before anything else is looked at, and the rest of the line-    -- is not parsed: --version must report the build even when the command-    -- after it is one this build does not have.-    go opts ("--version" : _) = Right opts {optCommand = CmdVersion}-    go opts ("--help" : _) = Right opts {optCommand = CmdHelp}-    go opts ("--nix-path" : val : rest) =-      go (opts {optNixPaths = optNixPaths opts ++ [T.pack val]}) rest-    go opts ("--strict" : rest) =-      go (opts {optStrict = True}) rest-    go opts ("--aterm" : rest) =-      go (opts {optAterm = True}) rest-    go opts ("--store" : dir : rest) =-      go (opts {optStore = Just dir}) rest-    go opts ("--substituter" : url : rest) =-      go (opts {optSubstituter = Just url}) rest-    go opts ("--trusted-key" : key : rest) =-      go (opts {optTrustedKey = Just key}) rest-    go opts ("--exec-wrapper" : spec : rest) =-      go (opts {optExecWrappers = optExecWrappers opts ++ [spec]}) rest-    go opts ("--restrict-eval" : rest) =-      go (opts {optRestrictEval = True}) rest-    go opts ("--pure-eval" : rest) =-      go (opts {optPureEval = True}) rest-    go opts ("--trace-verbose" : rest) =-      go (opts {optTraceVerbose = True}) rest-    go opts ("--fallback" : rest) =-      go (opts {optFallback = True}) rest-    go opts ("eval" : rest) = goEval opts rest-    go opts ("build" : rest) = goBuild opts emptyBuildArgs rest-    go opts ("push" : rest) = goPush opts emptyPushArgs rest-    go opts ("store" : rest) = goStore opts rest-    go _ [flag]-      | flag `elem` valueFlags = Left (flag ++ " requires a value")-    go _ (arg : _) = Left ("unknown argument: " ++ arg ++ " (run nova-nix --help for usage)")-    -- Sub-parser for eval: handles --strict and --expr interleaved with the file arg.-    goEval opts [] = Right opts-    goEval opts ("--strict" : rest) = goEval (opts {optStrict = True}) rest-    goEval opts ("--aterm" : rest) = goEval (opts {optAterm = True}) rest-    goEval opts ("--nix-path" : val : rest) =-      goEval (opts {optNixPaths = optNixPaths opts ++ [T.pack val]}) rest-    -- Accepted here as well as at the top level, like build and push:-    -- eval-side reads follow the selected store, so the flag means as-    -- much after the subcommand as before it.-    goEval opts ("--store" : dir : rest) =-      goEval (opts {optStore = Just dir}) rest-    goEval opts ("--restrict-eval" : rest) =-      goEval (opts {optRestrictEval = True}) rest-    goEval opts ("--pure-eval" : rest) =-      goEval (opts {optPureEval = True}) rest-    goEval opts ("--trace-verbose" : rest) =-      goEval (opts {optTraceVerbose = True}) rest-    goEval opts ("--fallback" : rest) =-      goEval (opts {optFallback = True}) rest-    goEval opts ("--expr" : expr : rest) =-      go (opts {optCommand = CmdEvalExpr (T.pack expr)}) rest-    goEval _ [flag]-      | flag `elem` valueFlags = Left (flag ++ " requires a value")-    goEval _ (arg@('-' : _) : _) = Left ("unknown eval flag: " ++ arg)-    goEval opts (path : rest) =-      go (opts {optCommand = CmdEvalFile path}) rest-    -- Sub-parser for build: the target, -A, and the shared flags in any-    -- order.  The shared flags are handled here rather than deferred back to-    -- 'go' so that one can follow the file argument, which is where a caller-    -- reaches for it, and so that -A is still recognised after it.-    goBuild opts buildArgs [] = finishBuild opts buildArgs-    -- Answered here as well as at the top level: a sub-parser that rejected-    -- them would make 'build --help' a usage error rather than a request.-    goBuild opts _ ("--help" : _) = Right opts {optCommand = CmdHelp}-    goBuild opts _ ("--version" : _) = Right opts {optCommand = CmdVersion}-    goBuild opts buildArgs ("--store" : dir : rest) =-      goBuild (opts {optStore = Just dir}) buildArgs rest-    goBuild opts buildArgs ("--substituter" : url : rest) =-      goBuild (opts {optSubstituter = Just url}) buildArgs rest-    goBuild opts buildArgs ("--trusted-key" : key : rest) =-      goBuild (opts {optTrustedKey = Just key}) buildArgs rest-    goBuild opts buildArgs ("--nix-path" : val : rest) =-      goBuild (opts {optNixPaths = optNixPaths opts ++ [T.pack val]}) buildArgs rest-    goBuild opts buildArgs ("--exec-wrapper" : spec : rest) =-      goBuild (opts {optExecWrappers = optExecWrappers opts ++ [spec]}) buildArgs rest-    goBuild opts buildArgs ("--restrict-eval" : rest) =-      goBuild (opts {optRestrictEval = True}) buildArgs rest-    goBuild opts buildArgs ("--pure-eval" : rest) =-      goBuild (opts {optPureEval = True}) buildArgs rest-    goBuild opts buildArgs ("--trace-verbose" : rest) =-      goBuild (opts {optTraceVerbose = True}) buildArgs rest-    goBuild opts buildArgs ("--fallback" : rest) =-      goBuild (opts {optFallback = True}) buildArgs rest-    goBuild opts buildArgs ("--expr" : expr : rest) =-      withTarget opts buildArgs (TargetExpr (T.pack expr)) rest-    goBuild opts buildArgs (flag : path : rest)-      | flag `elem` attrFlags = case baAttrPath buildArgs of-          Just _ -> Left "build accepts one attribute path"-          Nothing -> goBuild opts (buildArgs {baAttrPath = Just (T.pack path)}) rest-      | flag `elem` outLinkFlags = case baOutLink buildArgs of-          Just _ -> Left "build accepts one --out-link"-          Nothing -> goBuild opts (buildArgs {baOutLink = Just path}) rest-    goBuild _ _ [flag]-      | flag `elem` valueFlags = Left (flag ++ " requires a value")-    goBuild _ _ (arg@('-' : _) : _) = Left ("unknown build flag: " ++ arg)-    goBuild opts buildArgs (path : rest) =-      withTarget opts buildArgs (TargetFile path) rest-    -- A build evaluates one expression, so a second target is a mistake-    -- worth naming rather than a silent last-one-wins.-    withTarget opts buildArgs target rest = case baTarget buildArgs of-      Just _ -> Left "build takes one FILE.nix or one --expr, not both"-      Nothing -> goBuild opts (buildArgs {baTarget = Just target}) rest-    finishBuild opts buildArgs = case baTarget buildArgs of-      Nothing -> Left "build requires a FILE.nix argument or --expr EXPR"-      Just target -> Right opts {optCommand = CmdBuild target (baAttrPath buildArgs) (baOutLink buildArgs)}-    -- Sub-parser for push: flags and explicit store paths in any order.-    goPush opts pushArgs [] = Right opts {optCommand = CmdPush pushArgs}-    goPush opts pushArgs ("--store" : dir : rest) =-      goPush (opts {optStore = Just dir}) pushArgs rest-    goPush opts pushArgs ("--cache" : url : rest) =-      goPush opts (pushArgs {paCacheUrl = Just url}) rest-    goPush opts pushArgs ("--key-file" : path : rest) =-      goPush opts (pushArgs {paKeyFile = Just path}) rest-    goPush opts pushArgs ("--compression" : value : rest) =-      goPush opts (pushArgs {paCompressionArg = Just value}) rest-    goPush opts pushArgs ("--all" : rest) =-      goPush opts (pushArgs {paAll = True}) rest-    goPush _ _ [flag]-      | flag `elem` valueFlags = Left (flag ++ " requires a value")-    goPush _ _ (arg@('-' : _) : _) = Left ("unknown push flag: " ++ arg)-    goPush opts pushArgs (path : rest) =-      goPush opts (pushArgs {paPaths = paPaths pushArgs ++ [path]}) rest-    -- Sub-parser for store maintenance verbs.-    goStore _ [] = Left "store: expected a subcommand (delete, gc)"-    goStore opts ("delete" : rest) = goStoreDelete opts [] rest-    goStore opts ("gc" : rest) = goStoreGc opts False rest-    goStore _ (sub : _) = Left ("unknown store subcommand: " ++ sub ++ " (expected: delete, gc)")-    goStoreDelete opts paths []-      | null paths = Left "store delete: name at least one store path"-      | otherwise = Right opts {optCommand = CmdStoreDelete paths}-    goStoreDelete opts paths ("--store" : dir : rest) =-      goStoreDelete (opts {optStore = Just dir}) paths rest-    goStoreDelete _ _ [flag]-      | flag `elem` valueFlags = Left (flag ++ " requires a value")-    goStoreDelete _ _ (arg@('-' : _) : _) = Left ("unknown store delete flag: " ++ arg)-    goStoreDelete opts paths (path : rest) =-      goStoreDelete opts (paths ++ [path]) rest-    goStoreGc opts printRoots [] = Right opts {optCommand = CmdStoreGc printRoots}-    goStoreGc opts printRoots ("--store" : dir : rest) =-      goStoreGc (opts {optStore = Just dir}) printRoots rest-    goStoreGc opts _ ("--print-roots" : rest) = goStoreGc opts True rest-    goStoreGc _ _ [flag]-      | flag `elem` valueFlags = Left (flag ++ " requires a value")-    goStoreGc _ _ (arg : _) = Left ("unknown store gc argument: " ++ arg)-    -- Flags that consume the following argument as their value.-    valueFlags =-      ["--nix-path", "--store", "--substituter", "--trusted-key", "--exec-wrapper", "--expr", "--cache", "--key-file", "--compression"]-        ++ attrFlags-        ++ outLinkFlags-    -- Attribute selection, under both of upstream's spellings.-    attrFlags = ["-A", "--attr"]-    -- The result link, under both of nix-build's spellings.-    outLinkFlags = ["-o", "--out-link"]---- | Upstream C++ Nix's name for this directory, so an operator who knows--- one knows the other.-nixDataDirVar :: String-nixDataDirVar = "NIX_DATA_DIR"---- | The environment variable carrying inline nix.conf settings, above the--- config files and below the command line in precedence.-nixConfigVar :: BS.ByteString-nixConfigVar = "NIX_CONFIG"---- | The directory holding the system nix.conf, in place of @/etc/nix@.-nixConfDirVar :: BS.ByteString-nixConfDirVar = "NIX_CONF_DIR"---- | The user config files, first strongest, in place of the XDG cascade.-nixUserConfFilesVar :: BS.ByteString-nixUserConfFilesVar = "NIX_USER_CONF_FILES"---- | The XDG config dirs, searched for @nix\/nix.conf@ after the config home.-xdgConfigDirsVar :: BS.ByteString-xdgConfigDirsVar = "XDG_CONFIG_DIRS"---- | Windows' all-users application data directory, the machine-wide--- config directory there.-programDataVar :: BS.ByteString-programDataVar = "ProgramData"---- | Upstream's @sysconfdir@ on Unix, which libstore's meson.build forces--- absolute, so @\/etc\/nix@ is the compiled-in system directory.-posixSysconfDir :: FilePath-posixSysconfDir = "/etc"---- | The XDG base directory spec's default for @XDG_CONFIG_DIRS@, the--- literal upstream's @getConfigDirs@ falls back to.-posixXdgConfigDirs :: [FilePath]-posixXdgConfigDirs = ["/etc/xdg"]---- | Where a release archive keeps the bundled expressions, relative to the--- directory holding @bin@.-bundledDataSubdir :: FilePath-bundledDataSubdir = "share" </> "nova-nix"---- | The one file a data dir must contain, used to tell a real one from a--- directory that merely exists.-dataDirMarker :: FilePath-dataDirMarker = "nix" </> "fetchurl.nix"---- | Locate the bundled @\<nix/*\>@ expressions.------ Cabal bakes an absolute @datadir@ into the binary at configure time.  That--- is right for a @cabal install@ on this machine and wrong for every copied--- or downloaded one, because the path names the machine that did the build:--- a released binary would resolve @\<nix/fetchurl.nix\>@ to a directory that--- does not exist on the host running it.------ @NIX_DATA_DIR@ wins when set, since an operator setting upstream's own--- variable means it.  Otherwise a release layout (@bin/@ beside @share/@)--- answers from the executable's own location, which needs no configuration--- at all.  The Cabal path remains the fallback, so a local install is--- unaffected.-resolveDataDir :: IO FilePath-resolveDataDir = do-  fromEnv <- lookupEnv nixDataDirVar-  case fromEnv of-    Just dir | not (null dir) -> pure dir-    _ -> do-      exeDir <- takeDirectory <$> getExecutablePath-      let bundled = takeDirectory exeDir </> bundledDataSubdir-      bundledUsable <- doesFileExist (bundled </> dataDirMarker)-      if bundledUsable then pure bundled else getDataDir---- | Merge --nix-path entries, bundled data dir, and NIX_PATH search paths.--- The data dir is appended last so user paths take priority.-mergeSearchPaths :: [T.Text] -> FilePath -> [Thunk] -> [Thunk]-mergeSearchPaths extraPaths dataDir envPaths =-  concatMap (parseNixPath . TE.encodeUtf8) extraPaths ++ envPaths ++ parseNixPath (TE.encodeUtf8 (T.pack dataDir))---- ------------------------------------------------------------------------------ Main--- -----------------------------------------------------------------------------main :: IO ()-main = do-  hSetBuffering stdout LineBuffering-  -- UTF-8 on both output handles regardless of the console code page:-  -- locale encodings THROW on any character they cannot represent, so a-  -- store path or message containing one would otherwise abort the whole-  -- invocation mid-print on legacy Windows consoles.  An eval result does-  -- not pass through this: 'printResult' writes it as bytes.-  hSetEncoding stdout utf8-  hSetEncoding stderr utf8-  -- Initialize C data layer (symbol interning, thunk arena, env allocator)-  arenaInit-  args <- getArgs-  dataDir <- resolveDataDir-  opts <- either (failWith . T.pack) pure (parseArgs args)-  config <- loadNixConfig-  storeDir <- chosenStoreDir opts-  -- SIGINT reaches the main thread as UserInterrupt, which uncaught ends-  -- the process by the signal with nothing said, and an I/O failure no-  -- command handles reaches GHC's default handler, which prints an-  -- "Uncaught exception" report with a backtrace.  Upstream's-  -- handleExceptions logs either as one error line and exits 1-  -- (libmain/shared.cc at 2.24.9): checkInterrupt throws Interrupted, a-  -- BaseError like any other failure.-  handleJust userInterrupt (const reportInterrupt) . handle reportIOFailure $ case optCommand opts of-    CmdEvalFile filePath -> evalFile config opts storeDir dataDir filePath-    CmdEvalExpr expr-      | optAterm opts -> evalExprAterm config opts storeDir dataDir expr-      | otherwise -> evalExpr config opts storeDir dataDir expr-    CmdBuild target attrPath outLink -> buildCommand config opts storeDir dataDir target attrPath outLink-    CmdPush pushArgs -> pushCommand storeDir pushArgs-    CmdStoreDelete paths -> storeDeleteCommand storeDir paths-    CmdStoreGc printRoots -> storeGcCommand storeDir printRoots-    CmdUsage -> mapM_ (hPutStrLn stderr) usageLines >> exitFailure-    CmdHelp -> mapM_ putStrLn usageLines-    CmdVersion -> putStrLn versionLine---- | 'UserInterrupt' alone: every other asynchronous exception keeps--- propagating.-userInterrupt :: AsyncException -> Maybe ()-userInterrupt UserInterrupt = Just ()-userInterrupt _ = Nothing--reportInterrupt :: IO a-reportInterrupt = do-  hPutStrLn stderr "error: interrupted by the user"-  exitWith (ExitFailure 1)---- | An I/O failure no command handled, reported as upstream reports an--- error: @error: @ and the message, then exit status 1.-reportIOFailure :: IOException -> IO a-reportIOFailure failure = do-  hPutStrLn stderr ("error: " <> ioFailureMessage failure)-  exitWith (ExitFailure 1)---- | A 'userError' is its message alone, which 'show' would wrap in--- @user error (...)@; any other 'IOException' also names the operation--- and the file that failed.-ioFailureMessage :: IOException -> String-ioFailureMessage failure-  | isUserError failure = ioeGetErrorString failure-  | otherwise = displayException failure---- | What @--version@ reports.  Cabal's version, which is the one the publish--- workflow's tag guard checks a tag against, so a downloaded binary names--- exactly the release it came from and a bug report can say which build.-versionLine :: String-versionLine = "nova-nix " <> showVersion version---- | The usage text, returned rather than printed: a bare invocation is a--- usage error (stderr, non-zero) while @--help@ is a request that succeeded--- (stdout, zero), and the words are the same either way.-usageLines :: [String]-usageLines =-  [ "Usage: nova-nix [--nix-path NAME=PATH] <command>",-    "",-    "Commands:",-    "  eval FILE.nix          Evaluate a .nix file, print result",-    "  eval --expr 'EXPR'     Evaluate an inline expression",-    "  build FILE.nix         Build a derivation from a .nix file",-    "  build --expr 'EXPR'    Build a derivation from an inline expression",-    "  push --cache URL       Push store paths (and their closures) to a binary cache",-    "  store delete PATH...   Remove store paths, refused while a root or another valid path keeps them",-    "  store gc               Remove every store path not reachable from a root",-    "",-    "Flags:",-    "  --strict               Deep-force all thunks before printing (warning: OOM on large results)",-    "  --aterm                With eval --expr, print the derivation's .drv ATerm",-    "  -A, --attr ATTRPATH    With build: select a dotted attribute path (a.b.c)",-    "  -o, --out-link PATH    With build: create PATH as a symlink to the result and register it as a GC root",-    "  --print-roots          With store gc: list the roots as LINK -> PATH and delete nothing",-    "  --nix-path NAME=PATH   Add search path (repeatable, merged with NIX_PATH)",-    "  --all                  With push: select every valid path except derivations",-    "  --key-file PATH        With push: file holding the cache API key",-    "  --compression KIND     With push: artifact packaging (" <> T.unpack pushCompressionValues <> "; default none)",-    "  --exec-wrapper S=PATH  Run system S's derivations through PATH (repeatable),",-    "                         e.g. --exec-wrapper x86_64-windows=/usr/bin/wine",-    "  --store DIR            Use DIR as the store (default: the platform store)",-    "  --substituter URL      Try this binary cache before building",-    "  --trusted-key K        Public key (name:base64) for the substituter",-    "  --fallback             Build from source if substitution fails",-    "  --restrict-eval        Confine reads to the search path roots and what the",-    "                         evaluation itself writes; fetch only allowed-uris",-    "  --pure-eval            Confine reads as --restrict-eval does, with no search",-    "                         path, no currentTime, currentSystem or storePath, and",-    "                         pinned fetches only (allowed-uris applies only under",-    "                         --restrict-eval)",-    "  --trace-verbose        Make builtins.traceVerbose behave as builtins.trace;",-    "                         without it, the first argument is never forced",-    "",-    "  substituters, trusted-public-keys, fallback, max-call-depth,",-    "  restrict-eval, pure-eval, allowed-uris and trace-verbose also read from",-    "  nix.conf, in upstream's order: $NIX_CONF_DIR (default " <> systemConfDirName <> "),",-    "  the XDG nix/nix.conf files or $NIX_USER_CONF_FILES, then $NIX_CONFIG;",-    "  the flags above add to whatever those configure.",-    "",-    "  --help                 Print this text and exit",-    "  --version              Print the version and exit"-  ]---- | Canonicalize and read a source file.  The canonicalization matters:--- relative path literals inside the file resolve against the file's--- directory ('esBaseDir'), and a relative base dir would be re-prefixed on--- every resolution (doubling it).  An unreadable argument (missing file,--- a directory, no permission) is a clean CLI error, never an uncaught--- exception.  Only 'IOException' is caught: an interrupt or any other--- async exception must abort the run, not print as a read failure.-readSourceFile :: FilePath -> IO (FilePath, BS.ByteString)-readSourceFile rawPath = do-  attempt <- try $ do-    path <- canonicalizePath rawPath-    source <- BS.readFile path-    pure (path, source)-  case attempt of-    Left (e :: IOException) ->-      failWith ("cannot read " <> T.pack rawPath <> ": " <> T.pack (displayException e))-    Right ok -> pure ok---- | Where @--expr@ source comes from: text with no file to point at, which--- its parse errors name @<expr>@ and its positions name no file.-exprOrigin :: SourceOrigin-exprOrigin = SourceText "<expr>"---- | The evaluation policy for this run: the config cascade's settings,--- with each flag turning its setting on.  A flag only turns a setting on,--- so a machine configured for pure evaluation stays that way whatever the--- command line says, which is the direction a confinement should fail in.-evalPolicyFor :: CliOpts -> NixConfig -> EvalPolicy-evalPolicyFor opts config =-  EvalPolicy-    { epRestrictEval = optRestrictEval opts || ncRestrictEval config,-      epPureEval = optPureEval opts || ncPureEval config,-      epAllowedUris = ncAllowedUris config,-      epTraceVerbose = optTraceVerbose opts || ncTraceVerbose config-    }---- | The evaluation state and root environment for one command.  Upstream's--- constructor decides the same things in the same order (eval.cc at--- 2.24.9): under pure-eval the lookup path is empty, so neither--- @--nix-path@ nor @NIX_PATH@ contributes, and only the bundled @<nix/*>@--- directory remains, which upstream serves from an in-memory corepkgs--- filesystem and this binary serves from its data directory (so it stays--- visible in @builtins.nixPath@, where upstream shows nothing); under--- either mode every search path root is allowed, as @resolveLookupPathPath@--- allows the lookup path, so @-I nixpkgs=...@ is what makes a nixpkgs--- tree readable.------ Each root is allowed under its given spelling and under its resolved--- one.  The access walk follows symlinks, so a root reached through a--- symlinked directory (macOS's @/tmp@ is @/private/tmp@) is checked under--- the resolved spelling; upstream allows only the given one and refuses--- the read, which is a mismatch between its own allow list and walk, not--- a rule worth keeping.-setUpEval :: CliOpts -> NixConfig -> StoreDir -> FilePath -> FilePath -> IO (EvalState, Env)-setUpEval opts config storeDir dataDir baseDir = do-  let policy = evalPolicyFor opts config-  st0 <- newEvalState storeDir baseDir-  let searchPaths-        | epPureEval policy = parseNixPath (TE.encodeUtf8 (T.pack dataDir))-        | otherwise = mergeSearchPaths (optNixPaths opts) dataDir (esSearchPaths st0)-      st =-        st0-          { esSearchPaths = searchPaths,-            esPolicy = policy,-            esCallDepth = topLevelCallDepth (ncMaxCallDepth config)-          }-  -- A relative root resolves against the working directory, as upstream's-  -- absPath does, and a rooted one with no drive lands on the store's-  -- drive, where its lookups read ('qualifyPathText').  A pseudo-URL-  -- entry (channel:, flake:, a listed scheme) names a download this-  -- evaluator never performs and allows nothing:-  -- upstream allows such an entry's working-directory spelling only by-  -- falling through after a failed download (resolveLookupPathPath), and-  -- a run that cannot fetch should not widen what it may read.  A root-  -- with no UTF-8 reading allows nothing: allowed paths are text, so no-  -- read can name it, and a lossy spelling would allow a different path.-  roots <- mapM rootSpellings (mapMaybe textRoot (filter (not . isNixPathPseudoUrl) (searchPathRoots searchPaths)))-  mapM_ (allowEvalPath st) (concat roots)-  pure (st, builtinEnv policy (esTimestamp st) searchPaths)-  where-    textRoot = either (const Nothing) Just . TE.decodeUtf8'-    rootSpellings root = do-      given <- makeAbsolute (T.unpack (qualifyPathText storeDir root))-      resolved <- canonicalizePath given-      pure (map (canonPathValue . T.pack) [given, resolved])---- | Parse and bind source against the names the root environment--- 'setUpEval' builds will bind, which depend on the policy.-parseForEval :: CliOpts -> NixConfig -> FilePath -> SourceOrigin -> BS.ByteString -> Either SourceError Expr-parseForEval opts config = parseNixWithScope (rootScopeNames (evalPolicyFor opts config))---- | Evaluate a .nix file and print the result.-evalFile :: NixConfig -> CliOpts -> StoreDir -> FilePath -> FilePath -> IO ()-evalFile config opts storeDir dataDir rawFilePath = do-  (filePath, source) <- readSourceFile rawFilePath-  case parseForEval opts config (takeDirectory filePath) (SourceFile (T.pack filePath)) source of-    Left err -> failSource err-    Right expr -> do-      (st, env) <- setUpEval opts config storeDir dataDir (takeDirectory filePath)-      result <- runEvalIOTraced st (eval env expr >>= finalize (optStrict opts))-      case result of-        Left failure -> do-          TIO.hPutStrLn stderr (renderEvalFailure failure)-          exitFailure-        Right forced -> printResult forced---- | Evaluate an inline expression and print the result.-evalExpr :: NixConfig -> CliOpts -> StoreDir -> FilePath -> T.Text -> IO ()-evalExpr config opts storeDir dataDir source = do-  cwd <- getCurrentDirectory-  case parseForEval opts config cwd exprOrigin (TE.encodeUtf8 source) of-    Left err -> failSource err-    Right expr -> do-      (st, env) <- setUpEval opts config storeDir dataDir cwd-      result <- runEvalIOTraced st (eval env expr >>= finalize (optStrict opts))-      case result of-        Left failure -> do-          TIO.hPutStrLn stderr (renderEvalFailure failure)-          exitFailure-        Right forced -> printResult forced---- | Evaluate an inline expression to a derivation and print its ATerm (.drv--- contents), for diffing nova-nix's serialization against upstream Nix.-evalExprAterm :: NixConfig -> CliOpts -> StoreDir -> FilePath -> T.Text -> IO ()-evalExprAterm config opts storeDir dataDir source = do-  cwd <- getCurrentDirectory-  case parseForEval opts config cwd exprOrigin (TE.encodeUtf8 source) of-    Left err -> failSource err-    Right expr -> do-      (st, env) <- setUpEval opts config storeDir dataDir cwd-      result <- runEvalIOTraced st $ do-        val <- eval env expr-        forceDerivationAttrs val-        pure val-      case result of-        Left failure -> do-          TIO.hPutStrLn stderr (renderEvalFailure failure)-          exitFailure-        Right val -> do-          drvSP <- derivationPath val-          drvClosure <- readIORef (esDrvClosure st)-          aterm <- recordedAterm drvClosure drvSP-          -- The recorded bytes, not a re-serialization: these are what the-          -- path hashes.  BC.putStrLn bypasses the handle encoding, so the-          -- printed .drv diffs byte-exactly against upstream's.-          BC.putStrLn aterm---- | Parse, evaluate, extract derivation, build, and print result.--- The file argument is canonicalized for the same reason as in 'evalFile'.--- | Where a build reads its expression, and the directory relative paths--- inside it resolve against.-loadBuildSource :: BuildTarget -> IO (FilePath, SourceOrigin, BS.ByteString)-loadBuildSource (TargetFile rawFilePath) = do-  (filePath, source) <- readSourceFile rawFilePath-  pure (takeDirectory filePath, SourceFile (T.pack filePath), source)-loadBuildSource (TargetExpr source) = do-  cwd <- getCurrentDirectory-  pure (cwd, exprOrigin, TE.encodeUtf8 source)---- | Force the attributes 'derivationPath' goes on to read.  @derivation@--- is a lazy wrapper, and 'readThunkValue' answers 'Nothing' for a thunk that--- was never forced, so skipping this reports a real derivation as not one.--- Forcing @drvPath@ is also what computes the derivation and records its--- @.drv@ in the session closure ('recordedAterm').-forceDerivationAttrs :: (MonadEval m) => NixValue -> m ()-forceDerivationAttrs val = case val of-  VAttrs attrs ->-    mapM_-      (\k -> maybe (pure ()) (void . force) (attrSetLookup k attrs))-      derivationAttrKeys-  _ -> pure ()---- | What a build needs forced: the marker, the path whose closure the--- build driver writes, and the output it realizes.-derivationAttrKeys :: [T.Text]-derivationAttrKeys = ["type", "drvPath", "outputName"]--buildCommand :: NixConfig -> CliOpts -> StoreDir -> FilePath -> BuildTarget -> Maybe T.Text -> Maybe FilePath -> IO ()-buildCommand config opts storeDir dataDir target attrPath outLink = do-  let caches = resolveCaches config (optSubstituter opts) (optTrustedKey opts)-  wrappers <- either failWith pure (execWrapperConfig (optExecWrappers opts)) >>= checkExecWrappers-  (baseDir, origin, source) <- loadBuildSource target-  case parseForEval opts config baseDir origin source of-    Left err -> failSource err-    Right expr -> do-      (st, env) <- setUpEval opts config storeDir dataDir baseDir-      result <- runEvalIOTraced st $ do-        root <- eval env expr-        selected <- case attrPath of-          Nothing -> pure (Right root)-          Just path -> selectAttrPath path root-        -- Forced after selection, not before: forcing the root leaves the-        -- selected value's own attributes unforced, and derivationPath-        -- then reports a real derivation as not being one.-        either (pure . Left) (\val -> Right val <$ forceDerivationAttrs val) selected-      case result of-        Left failure -> do-          TIO.hPutStrLn stderr (renderEvalFailure failure)-          exitFailure-        Right (Left selectionErr) -> do-          TIO.hPutStrLn stderr ("error: " <> selectionErr)-          exitFailure-        Right (Right val) -> do-          drvSP <- derivationPath val-          outputName <- defaultOutputName drvSP val-          -- The full .drv closure (root + every transitive input) recorded-          -- during evaluation; written to the store before building.  The-          -- root's own recipe is read from the same map, so what is built-          -- is what its path hashes.-          drvClosure <- readIORef (esDrvClosure st)-          drv <- recordedDerivation drvClosure drvSP-          -- Resolved before the build, as nix-build resolves the output it-          -- realizes before building anything.-          outputPath <- namedOutputPath drv outputName-          sourceCache <- readIORef (esSourcePathCache st)-          storeWrites <- readIORef (esStoreWriteCache st)-          store <- openStore storeDir-          -- Materialize eval-coerced source paths (src = ./file, path-          -- interpolation): evaluation computes their store paths as text-          -- only - the parity runner's store is not writable - so the build-          -- driver performs the copy and registration.-          materializeEvalSources store sourceCache-          -- builtins.toFile wrote these during evaluation but could not-          -- register them; a derivation naming one needs them valid first.-          materializeEvalStoreWrites store storeWrites-          buildResult <- buildAndRegister store caches (fallbackFor opts config) wrappers drvClosure drv drvSP-          -- The root is registered before the handle closes: the handle's-          -- lease is what keeps a concurrent collection from running-          -- between the build's end and the link's creation.  The path-          -- prints after the link exists, as nix-build prints it, so a-          -- failed link prints nothing a script would take for success.-          rooted <- case buildResult of-            BuildSuccess _ -> traverse (\link -> addOutLinkRoot store link outputPath) outLink-            BuildFailure _ _ -> pure Nothing-          closeStore store-          case (buildResult, rooted) of-            (BuildFailure msg code, _) -> do-              TIO.hPutStrLn stderr ("build failed (exit " <> T.pack (show code) <> "): " <> msg)-              exitFailure-            (BuildSuccess _, Just (Left err)) -> failWith ("build: " <> err)-            (BuildSuccess _, _) ->-              TIO.putStrLn (T.pack (storePathToFilePath (stDir store) outputPath))---- | The @.drv@ store path of an evaluated derivation value: a set with--- @type = "derivation"@ whose @drvPath@ has been forced--- ('forceDerivationAttrs').  Store paths are ASCII, so the byte payload--- decodes strictly.-derivationPath :: NixValue -> IO StorePath-derivationPath (VAttrs attrs) = do-  case attrSetLookup "type" attrs of-    Just thunk | Just (VStr "derivation" _) <- readThunkValue thunk -> pure ()-    _ -> failWith "error: result is not a derivation (no type = \"derivation\")"-  case attrSetLookup "drvPath" attrs of-    Just thunk-      | Just (VStr pathBytes _) <- readThunkValue thunk,-        Right path <- TE.decodeUtf8' pathBytes ->-          maybe (failWith ("error: invalid drvPath: " <> path)) pure (parseStorePath defaultStoreDir path)-    _ -> failWith "error: derivation result missing drvPath"-derivationPath _ = failWith "error: result is not a derivation"---- | The output a build realizes and prints: the value's @outputName@, the--- first of its @outputs@, which is what upstream's nix-build builds and--- prints for a derivation (nix-build.cc, @queryOutputName@), with its--- message for a set that lacks the attribute.-defaultOutputName :: StorePath -> NixValue -> IO T.Text-defaultOutputName drvSP val = case val of-  VAttrs attrs-    | Just thunk <- attrSetLookup "outputName" attrs,-      Just (VStr nameBytes _) <- readThunkValue thunk,-      Right name <- TE.decodeUtf8' nameBytes ->-        pure name-  _ -> failWith ("error: derivation '" <> storePathToText defaultStoreDir drvSP <> "' lacks an 'outputName' attribute")---- | The path of a named output.  A @.drv@ lists its outputs by name, so--- the default output is found here by name, never by position.-namedOutputPath :: Derivation -> T.Text -> IO StorePath-namedOutputPath drv outputName =-  case find ((== outputName) . doName) (drvOutputs drv) of-    Just out -> pure (doPath out)-    Nothing -> failWith ("error: derivation has no output named '" <> outputName <> "'")---- | The @.drv@ ATerm evaluation recorded under a derivation path: the exact--- bytes whose hash is the path.  Every derivation computed in a session is--- recorded when its @drvPath@ is forced ('esDrvClosure'), so an absent entry--- means the path was never computed by this evaluation.-recordedAterm :: Map.Map T.Text BS.ByteString -> StorePath -> IO BS.ByteString-recordedAterm drvClosure drvSP =-  case Map.lookup (storePathToText defaultStoreDir drvSP) drvClosure of-    Just aterm -> pure aterm-    Nothing -> failWith ("error: no .drv was recorded for " <> storePathToText defaultStoreDir drvSP)---- | The 'Derivation' a recorded ATerm describes ('recordedAterm').-recordedDerivation :: Map.Map T.Text BS.ByteString -> StorePath -> IO Derivation-recordedDerivation drvClosure drvSP = do-  aterm <- recordedAterm drvClosure drvSP-  either (failWith . (("error: the recorded .drv for " <> storePathToText defaultStoreDir drvSP <> " does not parse: ") <>)) pure (fromATerm aterm)---- | The store directory selected by @--store@, or the platform default,--- under the canonical spelling 'openStore' keys the store by, so what--- evaluation and every command print is the spelling the database--- holds.-chosenStoreDir :: CliOpts -> IO StoreDir-chosenStoreDir opts = canonicalStoreDir (maybe platformStoreDir StoreDir (optStore opts))---- | Default priority for a config- or CLI-configured substituter--- (cache.nixos.org is 40).-substituterPriority :: Int-substituterPriority = 50---- | Turn resolved settings into the cache list.  One 'CacheConfig' per--- substituter, each carrying the whole trusted-key set: upstream's keys--- are not bound to a substituter, so a narinfo from any cache is accepted--- by any trusted key.  A substituter with no trusted key anywhere is not--- refused here (it simply accepts nothing at the signature gate), matching--- upstream, where @substituters@ and @trusted-public-keys@ are independent.-configToCaches :: NixConfig -> [CacheConfig]-configToCaches config =-  [ CacheConfig-      { ccUrl = T.dropWhileEnd (== '/') url,-        ccPublicKeys = ncTrustedPublicKeys config,-        ccPriority = substituterPriority-      }-  | url <- ncSubstituters config-  ]---- | What a failed substitute leads to on this run.  The flag only turns--- fallback on, as upstream's does, so it adds to the config's setting.-fallbackFor :: CliOpts -> NixConfig -> Fallback-fallbackFor opts config-  | optFallback opts || ncFallback config = BuildFromSource-  | otherwise = NoFallback---- | The caches from the resolved config plus the CLI flags.  The CLI--- @--substituter@ and @--trusted-key@ append on top, the highest--- precedence, so a flag adds to the configured set rather than being--- overridden by it.-resolveCaches :: NixConfig -> Maybe String -> Maybe String -> [CacheConfig]-resolveCaches base mUrl mKey =-  configToCaches-    base-      { ncSubstituters = ncSubstituters base ++ maybe [] (\url -> [T.pack url]) mUrl,-        ncTrustedPublicKeys = ncTrustedPublicKeys base ++ maybe [] (\key -> [T.pack key]) mKey-      }---- | Resolve nix.conf from the system file, the user-file cascade and--- @NIX_CONFIG@, the file locations coming from the environment and the--- platform's XDG defaults.  A file that cannot be read is absent, but one--- that is read and does not parse is a hard error, so a malformed--- security-relevant setting cannot pass for no setting.-loadNixConfig :: IO NixConfig-loadNixConfig = do-  locations <- configLocations-  nixConfigBytes <- configVariable nixConfigVar-  paths <- either configError pure (Config.configFilePaths locations)-  Config.loadConfig readConfigFile paths nixConfigBytes-    >>= either configError pure-  where-    configError = failWith . ("error: " <>)---- | A variable the configuration reads, as its bytes, the way upstream's--- @getEnv@ reads it.  A Windows value holding an unpaired UTF-16--- surrogate has no bytes nova-nix can carry, so it is refused, as--- @NIX_PATH@ holding one is.-configVariable :: BS.ByteString -> IO (Maybe BS.ByteString)-configVariable name = do-  found <- lookupEnvBytes name-  case found of-    EnvUnset -> pure Nothing-    EnvValue value -> pure (Just value)-    EnvUnpairedSurrogate ->-      failWith ("error: " <> TE.decodeLatin1 name <> " holds an unpaired UTF-16 surrogate, which has no UTF-8 form")---- | A variable naming a directory or a list of them, as a host path.-configVariablePath :: BS.ByteString -> IO (Maybe OsPath)-configVariablePath name = configVariable name >>= traverse (variableHostPath name)---- | A variable's bytes as a host path.  Every value 'configVariable'--- answers has one, since a Windows value arrives as UTF-8, so the--- refusal is for completeness.-variableHostPath :: BS.ByteString -> BS.ByteString -> IO OsPath-variableHostPath name value =-  maybe (failWith ("error: " <> TE.decodeLatin1 name <> " is not valid UTF-8, so it names no Windows path")) pure (hostPathFromBytes value)---- | Where the config files are on this machine.  @NIX_CONF_DIR@ and--- @XDG_CONFIG_DIRS@ are honoured on every platform; the defaults behind--- them are the platform's.  Upstream compiles @\/etc\/nix@ in as the--- system directory and falls back to @\/etc\/xdg@ for the dirs on every--- platform, Windows included, where neither names anything (a path with--- no drive resolves against the current drive).  The Windows analogues--- are chosen here the way the user file's was (@%APPDATA%@ for the XDG--- config home, the @directory@ package's own mapping): the system file is--- @%ProgramData%\\nix\\nix.conf@, the all-users application data directory--- being where Windows keeps machine-wide application configuration (it is--- also where @directory@ maps the system-wide XDG dirs), and there is no--- system file when @%ProgramData%@ is unset; the dirs default to none,--- because the one Windows directory that answers to them is already the--- system file, and a file read twice applies its @extra-@ settings twice.--- The config home comes from @directory@ (@~\/.config@ on Unix,--- @%APPDATA%@ on Windows, @XDG_CONFIG_HOME@ only when it is absolute); the--- dirs list is filtered the same way, since 'splitSearchPath' turns an--- empty POSIX entry into @.@, where upstream's tokenizer drops it, and the--- XDG spec says a relative entry is ignored.-configLocations :: IO Config.ConfigLocations-configLocations = do-  confDir <- configVariable nixConfDirVar-  systemConfDir <- platformSystemConfDir-  userFiles <- configVariable nixUserConfFilesVar-  home <- OsDir.getXdgDirectory OsDir.XdgConfig mempty-  configDirs <- configVariablePath xdgConfigDirsVar-  defaultConfigDirs <- traverse OP.encodeFS platformConfigDirs-  pure-    Config.ConfigLocations-      { Config.clConfDir = confDir,-        Config.clSystemConfDir = systemConfDir,-        Config.clUserConfFiles = userFiles,-        Config.clConfigHome = home,-        Config.clConfigDirs = maybe defaultConfigDirs (filter OP.isAbsolute . OP.splitSearchPath) configDirs-      }---- | Where the platform's machine-wide config directory comes from, with--- @nix@ beneath it either way: a fixed path (upstream's @sysconfdir@ on--- Unix) or an environment variable naming it (@%ProgramData%@ on--- Windows).  One value serves both the lookup and the help text, so the--- two cannot disagree.-data SystemConfDirSource = FixedConfDir !FilePath | EnvConfDir !BS.ByteString--platformSystemConfDirSource :: SystemConfDirSource-platformSystemConfDirSource = case SI.os of-  "mingw32" -> EnvConfDir programDataVar-  _ -> FixedConfDir posixSysconfDir---- | The machine-wide config directory the system file is read from unless--- @NIX_CONF_DIR@ moves it: upstream's @sysconfdir\/nix@ on Unix;--- @%ProgramData%\\nix@ on Windows, or none when that variable is unset or--- empty.-platformSystemConfDir :: IO (Maybe OsPath)-platformSystemConfDir = case platformSystemConfDirSource of-  FixedConfDir dir -> Just . (OP.</> Config.nixConfDirName) <$> OP.encodeFS dir-  EnvConfDir var -> do-    value <- mfilter (not . BS.null) <$> configVariable var-    traverse (fmap (OP.</> Config.nixConfDirName) . variableHostPath var) value---- | 'platformSystemConfDir' as the help text names it: the path on Unix,--- the variable on Windows.-systemConfDirName :: String-systemConfDirName = case platformSystemConfDirSource of-  FixedConfDir dir -> dir </> nixDirName-  EnvConfDir var -> "%" <> BC.unpack var <> "%" </> nixDirName-  where-    nixDirName = T.unpack (hostPathText Config.nixConfDirName)---- | What @XDG_CONFIG_DIRS@ names when it is unset: the spec's default on--- Unix, nothing on Windows (see 'configLocations').-platformConfigDirs :: [FilePath]-platformConfigDirs = case SI.os of-  "mingw32" -> []-  _ -> posixXdgConfigDirs---- | A config file's bytes, or why it could not be read: nothing at the--- path, or something that will not open (a directory, a permission--- refusal).  The open takes the 'OsPath' itself, so a POSIX name reaches--- it as the bytes it was spelled from rather than through the locale's--- codec.  Only 'IOException' is caught: an interrupt must abort the run,--- not read as an absent file.-readConfigFile :: OsPath -> IO (Either Config.ConfigReadFailure BS.ByteString)-readConfigFile path = do-  result <- try (OsFile.readFile' path) :: IO (Either IOException BS.ByteString)-  pure (either (Left . classify) Right result)-  where-    classify err-      | isDoesNotExistError err = Config.ConfigFileMissing-      | otherwise = Config.ConfigFileUnreadable---- | Resolve every launcher before any building starts, so a typo'd path is--- a configuration error now rather than a build failure after the whole--- closure has been realized.  A bare name resolves through @PATH@, the way--- a shell would; anything else has to be an executable file where it says.-checkExecWrappers :: Map.Map T.Text FilePath -> IO (Map.Map T.Text FilePath)-checkExecWrappers = Map.traverseWithKey check-  where-    check system path-      | path == takeFileName path =-          findExecutable path-            >>= maybe (failWith ("--exec-wrapper " <> system <> ": " <> T.pack path <> " is not on PATH")) pure-      | otherwise = do-          there <- doesFileExist path-          if not there-            then failWith ("--exec-wrapper " <> system <> ": " <> T.pack path <> " does not exist")-            else do-              perms <- getPermissions path-              if executable perms-                then pure path-                else failWith ("--exec-wrapper " <> system <> ": " <> T.pack path <> " is not executable")---- | Write the .drv file to the store and build with dependency resolution.--- The drvPath is the store path of the .drv file itself, extracted from--- the evaluation result alongside the Derivation struct.-buildAndRegister :: Store -> [CacheConfig] -> Fallback -> Map.Map T.Text FilePath -> Map.Map T.Text BS.ByteString -> Derivation -> StorePath -> IO BuildResult-buildAndRegister store caches fallback wrappers drvClosure drv drvSP = do-  -- Materialize the full input-.drv closure (every transitive dependency's-  -- recipe) to the store.  buildWithDeps reads these back to construct the-  -- dependency graph; without them it cannot realize any non-leaf derivation.-  writeDrvClosure store drvClosure-  -- Write the root .drv too (idempotent - it is also in the closure) so a build-  -- still works if the closure was not captured (e.g. a pre-built store drv).-  writeDrv store drv drvSP-  -- Build with dependency resolution-  tmpDir <- getTemporaryDirectory-  let config =-        (defaultBuildConfig (stDir store))-          { bcTmpDir = tmpDir,-            bcCaches = caches,-            bcFallback = fallback,-            bcExecWrappers = wrappers-          }-  buildWithDeps config store drv drvSP---- ------------------------------------------------------------------------------ Push command--- ------------------------------------------------------------------------------- | Push the closure of the selected store paths to a binary cache.-pushCommand :: StoreDir -> PushArgs -> IO ()-pushCommand storeDir pushArgs = do-  cacheUrl <- case paCacheUrl pushArgs of-    Just url -> pure (T.dropWhileEnd (== '/') (T.pack url))-    Nothing -> failWith "push: --cache URL is required"-  case (paAll pushArgs, paPaths pushArgs) of-    (True, _ : _) -> failWith "push: --all and explicit paths are mutually exclusive"-    (False, []) -> failWith "push: name store paths to push, or pass --all"-    _ -> pure ()-  apiKey <- case paKeyFile pushArgs of-    Nothing -> pure Nothing-    Just path -> do-      loaded <- loadApiKeyFile path-      either failWith (pure . Just) loaded-  compression <- case paCompressionArg pushArgs of-    Nothing -> pure PushNone-    Just value -> either (failWith . ("push: " <>)) pure (parsePushCompression (T.pack value))-  store <- openStore storeDir-  rootsResult <- resolvePushRoots store pushArgs-  case rootsResult of-    Left err -> do-      closeStore store-      failWith err-    Right roots -> do-      result <- pushPaths (PushConfig cacheUrl apiKey compression) store roots-      closeStore store-      case result of-        Left err -> failWith ("push failed: " <> err)-        Right summary ->-          TIO.putStrLn-            ( "pushed "-                <> T.pack (show (psPushed summary))-                <> " path(s), "-                <> T.pack (show (psSkipped summary))-                <> " already cached"-            )---- | Delete store paths: registration rows and on-disk trees.  Every--- argument is resolved before anything is touched; the paths are then--- deleted in argument order under one collector lock and one live set,--- with upstream's roots line printed once per invocation as its--- @--delete@ prints it, and the first failure stops the run, so a--- reference chain deletes leaf-first in one invocation.-storeDeleteCommand :: StoreDir -> [String] -> IO ()-storeDeleteCommand storeDir rawPaths = do-  targets <- either (failWith . prefixed) pure (traverse (resolveDeleteTarget storeDir . T.pack) rawPaths)-  store <- openStore storeDir-  result <- withLiveSet store (\live -> deleteEach store live targets)-  closeStore store-  either (failWith . prefixed) pure (join result)-  where-    prefixed err = "store delete: " <> err-    deleteEach :: Store -> LiveSet -> [T.Text] -> IO (Either T.Text ())-    deleteEach _ _ [] = pure (Right ())-    deleteEach store live (basename : rest) = do-      outcome <- deleteStorePathChecked store live basename-      case outcome of-        Left err -> pure (Left err)-        Right removed -> do-          TIO.putStrLn ("deleted " <> basename <> describeOutcome removed)-          deleteEach store live rest-    describeOutcome removed-      | doRowRemoved removed && doTreeRemoved removed = ""-      | doRowRemoved removed = " (no tree on disk)"-      | otherwise = " (unregistered tree)"---- | Collect garbage, or list the roots.  The summary line is upstream's--- (@PrintFreed@), on stdout; the progress lines come from the library on--- stderr.  @--print-roots@ lists @LINK -> PATH@ sorted, each once, as--- @nix-store --gc --print-roots@ does, and deletes nothing; it runs--- under the handle's own lease, as upstream's listing takes no--- collector lock, so it does not wait behind a running build.-storeGcCommand :: StoreDir -> Bool -> IO ()-storeGcCommand storeDir printRoots = do-  store <- openStore storeDir-  if printRoots-    then do-      roots <- findRoots store-      closeStore store-      mapM_ (\root -> TIO.putStrLn (T.pack (grLink root) <> " -> " <> grPath root)) roots-    else do-      results <- collectGarbage store-      closeStore store-      either (failWith . ("store gc: " <>)) (TIO.putStrLn . gcSummaryLine) results---- | Resolve push roots: every valid non-derivation path with @--all@, otherwise--- each named path.  Named paths may be full store paths in either store-dir--- form, or a bare @hash-name@ basename.  A named derivation is refused--- here, with the rule, rather than by the cache's 400 after its NAR has--- already been uploaded.-resolvePushRoots :: Store -> PushArgs -> IO (Either T.Text [StorePath])-resolvePushRoots store pushArgs-  | paAll pushArgs = do-      pathTexts <- queryAllValidPaths (stDB store)-      pure (outputPathsOnly <$> traverse parseDbPath pathTexts)-  | otherwise = pure (traverse parseArgPath (paPaths pushArgs) >>= refuseDerivations)-  where-    refuseDerivations roots = case filter isDerivationPath roots of-      [] -> Right roots-      drv : _ -> Left ("push: " <> storePathBasename drv <> " is a derivation; a binary cache serves build outputs, not recipes")-    -- DB rows are rendered with the OPENED store's dir - parsing against-    -- platformStoreDir made 'push --all --store DIR' fail on every row of-    -- a non-default store.-    parseDbPath txt =-      maybe (Left ("unparseable store DB path: " <> txt)) Right (parseStorePath (stDir store) txt)-    parseArgPath raw =-      let txt = T.pack raw-          attempts =-            [ parseStorePath (stDir store) txt,-              parseStorePath platformStoreDir txt,-              parseStorePath defaultStoreDir txt,-              -- A bare basename passes the same charset gate as every-              -- other spelling: push targets are real store paths.-              parseStorePathBaseName txt-            ]-       in case catMaybes attempts of-            (sp : _) -> Right sp-            [] -> Left ("not a store path: " <> txt)---- | Print an error to stderr and exit.-failWith :: T.Text -> IO a-failWith msg = do-  TIO.hPutStrLn stderr msg-  exitFailure---- | Fail on source that does not parse or bind.  An unbound variable is an--- evaluation error upstream, raised before evaluation starts, and reads as--- one here.-failSource :: SourceError -> IO a-failSource (SyntaxError err) = failWith ("parse error: " <> T.pack (show err))-failSource (UndefinedVariable name) = failWith ("error: " <> undefinedVariableMessage name)---- ------------------------------------------------------------------------------ Output formatting--- ------------------------------------------------------------------------------- | Optionally deep-force a value before printing.--- With @--strict@, all thunks are recursively materialized.--- Without it, thunks display as @"thunk"@ - safe for large results.-finalize :: (MonadEval m) => Bool -> NixValue -> m NixValue-finalize True = deepForceValue-finalize False = pure---- ------------------------------------------------------------------------------ Deep-force and pretty-print--- ------------------------------------------------------------------------------- | Recursively force all thunks in a value, returning the fully--- materialized tree.  Unlike 'deepForce' (which returns @()@), this--- rebuilds the value with all thunks replaced by computed C thunks.-deepForceValue :: (MonadEval m) => NixValue -> m NixValue-deepForceValue (VList cl) = do-  let thunks = map Thunk (clistThunks cl)-  forced <- mapM (force >=> deepForceValue) thunks-  pure (VList (clistFromThunks (map (thunkToCPtr . evaluated) forced)))-deepForceValue (VAttrs attrs) = do-  let m = attrSetToMap attrs-  forced <- mapM (force >=> deepForceValue) m-  pure (VAttrs (attrSetFromMap (Map.map evaluated forced)))-deepForceValue val = pure val---- | Write an eval result and its newline to stdout as bytes.  A string's--- payload need not be UTF-8, so nothing on this path decodes or re-encodes--- it: the handle is put in binary mode, as hPutBuilder asks, and no--- encoding or newline translation applies.-printResult :: NixValue -> IO ()-printResult val = do-  hSetBinaryMode stdout True-  BB.hPutBuilder stdout (printAmbiguous val <> BB.char7 '\n')+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | nova-nix CLI entry point: parse the argument vector, dispatch one+-- command, map its outcome to an exit code.+--+-- The commands and flags are documented in "Nix.Cli.Reference" and+-- parsed by "Nix.Cli.Args", both in the package's @cli@ library, where+-- the test suite reaches them; @--help@ and the usage-error path print the+-- reference's 'helpLines'.+module Main (main) where++import Control.Applicative ((<|>))+import Control.Exception (AsyncException (UserInterrupt), bracket, bracketOnError, displayException, finally, handle, handleJust, try)+import Control.Monad (foldM_, mfilter, unless, void, when, (>=>))+import Control.Monad.Except (ExceptT (..), runExceptT)+import Data.Bifunctor (first)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Builder as BB+import qualified Data.ByteString.Char8 as BC+import Data.Char (isDigit)+import Data.Functor.Identity (Identity (..))+import Data.IORef (readIORef)+import Data.Int (Int32)+import Data.List (find, intercalate, sort)+import qualified Data.Map.Strict as Map+import Data.Maybe (catMaybes, fromMaybe, isJust, listToMaybe, mapMaybe)+import qualified Data.Set as Set+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import qualified Data.Text.IO as TIO+import Data.Version (showVersion)+import Data.Void (absurd)+import Data.Word (Word64)+import Foreign.C.Error (Errno (..), ePIPE)+import GHC.IO.Exception (IOException (..))+import GHC.Profiling (requestHeapCensus)+import Nix.Builder (BuildConfig (..), BuildResult (..), BuildStop, SubstitutionAccess (..), buildWithDeps, defaultBuildConfig, execWrapperConfig, stopReported, substituteFromCaches)+import Nix.Builder.Buildenv (Activity (..))+import Nix.Builder.Sandbox (renderSandboxMode)+import Nix.Builder.Sandbox.Spawn (filePathBytes)+import Nix.Builder.Settings (configToCaches, machineDefaults, settingsBuildConfig, settingsFallback, settingsFetchRetry, settingsSubstitutes)+import Nix.Builtins (isNixPathPseudoUrl, parseNixPath, rootScopeNames, searchPathRoots)+import Nix.Cli.Args (AutoArg (..), CliOpts (..), Command (..), DevEnvFormat (..), DevelopArgs (..), JsonLayout (..), ListFormat (..), OutLink, ProfileSelection (..), PushArgs (..), RemoveMatcher (..), RemoveSelection (..), Target (..), TrustFormat (..), outLinkFor, parseArgs, storeFlagOf)+import Nix.Cli.Reference (Host (..), SystemConfDirSource (..), currentHost, helpLines, renderIndentedJson, systemConfDirSource)+import Nix.Config (NixConfig (..))+import qualified Nix.Config as Config+import Nix.Daemon.ClientStore (DaemonAddress, DaemonStoreConfig (..), clientSettings, dialDaemon, withDaemonFixedOutputs, withDaemonPushSource, withDaemonStore)+import Nix.Daemon.Connection (ServerConfig (..))+import Nix.Daemon.Dial (addressPresence)+import Nix.Daemon.Listen (DaemonOptions (..), TrustOverride, authSettingsFor, closeListener, daemonSocketPath, openListener, serveListener)+import Nix.Daemon.LocalStore (newServedStore, serveLocal)+import Nix.Daemon.Ops (ClientSettings (..))+import Nix.Daemon.Protocol (Verbosity (..), Version (..), featureRealisationWithPath, latestVersionNumber)+import Nix.Daemon.StoreChoice (StoreChoice (..), StoreProbe (..), StoreTarget (..), chooseStore, parseStoreTarget, storeOverride, storeReference)+import Nix.DependencyGraph (DepNode (..), buildDepGraph)+import Nix.Derivation (Derivation (..), DerivationOutput (..), DrvFile, drvFileATerm, drvFileDerivation, drvFilePath, fromATerm)+import Nix.Develop.Capture (CaptureFailure, OutputObject (..), captureDerivation, captureFailureMessage, environmentOutput, getEnvScriptContents, getEnvScriptName, getEnvScriptPath, noEnvironmentMessage)+import Nix.Develop.Environment (BuildEnvironment, EnvironmentScript (..), Prompt (..), ScriptDirectories (..), ScriptFile (..), Shell (..), buildEnvironmentJson, environmentScript, parseBuildEnvironment, renderRcfile)+import Nix.Develop.Shell (DevelopHost (..), EnvironmentChanges (..), bashProgram, developHost, shellArguments, shellEnvironment, shellModeFor)+import Nix.Environment (EnvLookup (..), argumentBytes, lookupEnvBytes)+import Nix.Eval (AttrSet, Env, EvalPolicy (..), MonadEval (..), NixValue (..), Thunk (..), attrSetElems, attrSetLookup, compileSource, deepForce, evalBytecode, evalParsed, evaluated, findInSearchPath, force, inputModuloHashes, readThunkValue, typeName)+import Nix.Eval.AttrPath (selectAttrPath)+import Nix.Eval.AutoCall (AutoArgs, autoCallFunction)+import Nix.Eval.CRegion (Regions (..), regionFigures, renderRegionFigures)+import Nix.Eval.CRoots (crootsAddThunk)+import Nix.Eval.CStats (CRoot (..), countSites, renderCensus, takeCensus, valueRoots)+import Nix.Eval.CallDepth (topLevelCallDepth)+import Nix.Eval.CanonPath (canonPathValue)+import Nix.Eval.IO (EvalFailure (..), EvalIO, EvalState (..), SessionSettings (..), SessionStore (..), allowEvalPath, evalBaseEnv, evalSearchPath, nixPathValue, readImportTarget, renderEvalFailure, resolveImportTarget, runEvalIOTraced, sourceCopies, withEvalSession)+import Nix.Eval.Policy (ImportFromDerivation (..), hostPathRules)+import Nix.Eval.Print (printAmbiguous)+import Nix.Eval.Symbol (symbolIntern)+import Nix.Eval.Types (clistThunks, mkStrBytes, mkThunkBc)+import Nix.ExperimentalFeature (addFeatures, featureSetWarnings, parseFeatures)+import Nix.Expr.Resolve (undefinedVariableMessage)+import Nix.HostPath (hostPathFromBytes, hostPathText)+import Nix.Json (Json, renderJson)+import Nix.Key (generateSecretKey, keyRefusalMessage, parseSecretKey, renderPublicKey, renderSecretKey)+import Nix.Logger (Logger, escapeFilterFor, handleLogger, logWarning)+import Nix.Parser (ParsedSource, SourceError (..), SourceOrigin (..), parseNixWithScope)+import Nix.Profile.Generation (Change (..), Changes (..), DatedGeneration (..), Generation (..), GenerationNumber (..), ProfileFailure (..), ProfileLinkPlace (..), RollbackTarget (..), WipeScope (..), absolutePath, checkProfileStore, currentEpochSeconds, cutoffBefore, findGenerations, generationDate, parseOlderThan, readGenerationNumber, readManifest, readProfileEnvironment, resolveDefaultProfile, switchGeneration, updateProfile, wipeHistory)+import Nix.Profile.Manifest (Conflict (..), ConflictSide (..), Element (..), FlakeSource (..), Manifest (..), Matcher (..), Selection (..), Selector (..), addElement, changeLine, defaultPriority, elementIdentifier, emptyManifest, flakeAttribute, manifestChanges, manifestErrorText, manifestJson, regexMatcher, selectElements)+import Nix.Profile.Tree (buildEnvFailureText)+import Nix.Push (PushCompression (..), PushConfig (..), PushSummary (..), defaultPartSize, isDerivationPath, loadKeyFile, outputPathsOnly, parsePushCompression, pushPaths, storePathBasename)+import Nix.Push.Directory (DirectoryPush (..), PushTarget (..), loadSecretKeyFile, pushTarget, pushToDirectory)+import Nix.Push.Source (PushSource (..), localPushSource)+import Nix.Realise (BuildMode (..))+import Nix.Signals (interruptOnTermination)+import Nix.Store (DeleteOutcome (..), GcRoot (..), Store (..), UpstreamHazard (..), canonicalStoreDir, closeStore, collectGarbage, deleteStorePaths, findRoots, gcSummaryLine, isValid, openStore, resolveDeleteTarget, storeEntryNameText, upstreamManagedRefusal, useStoreFileMask)+import Nix.Store.Access (probeStoreWriting)+import Nix.Store.DB (metaDirName)+import Nix.Store.Ops (EvalObjects (..), StoreOps (..), StoreQueries (..), localQueries, withLocalStore)+import Nix.Store.Path (StoreDir (..), StorePath (spName), badStorePathText, defaultStoreDir, parseStorePath, parseStorePathBaseName, parseStorePathPrefix, platformStoreDir, qualifyPathText, storePathToFilePath, storePathToText)+import Nix.Trust (fixedOutputInputs, renderTrustReport, trustReport, trustReportJson)+import Nix.Trust.Fetch (FixedOutputStore (..), fetchAndScan)+import Nix.Trust.Scan (scanFetched)+import qualified NovaCache.NAR as NAR+import Paths_nova_nix (getDataDir, version)+import System.Directory (Permissions (executable), canonicalizePath, doesDirectoryExist, doesFileExist, findExecutable, getCurrentDirectory, getFileSize, getPermissions, makeAbsolute, pathIsSymbolicLink)+import qualified System.Directory.OsPath as OsDir+import System.Environment (getArgs, getExecutablePath, lookupEnv)+import System.Exit (ExitCode (..), exitFailure, exitWith)+import qualified System.File.OsPath as OsFile+import System.FilePath (takeDirectory, takeFileName, (</>))+import System.IO (BufferMode (..), hFlush, hIsTerminalDevice, hPutStrLn, hSetBinaryMode, hSetBuffering, hSetEncoding, stderr, stdin, stdout, utf8)+import System.IO.Error (ioeGetErrorString, isDoesNotExistError, isUserError)+import System.Mem (performMajorGC)+import System.OsPath (OsPath)+import qualified System.OsPath as OP+import Text.Read (readMaybe)++-- ---------------------------------------------------------------------------+-- Where the data and the configuration are+-- ---------------------------------------------------------------------------++-- | Upstream C++ Nix's name for this directory, so an operator who knows+-- one knows the other.+nixDataDirVar :: String+nixDataDirVar = "NIX_DATA_DIR"++-- | The environment variable carrying inline nix.conf settings, above the+-- config files and below the command line in precedence.+nixConfigVar :: BS.ByteString+nixConfigVar = "NIX_CONFIG"++-- | The environment variable naming the store a command uses, the+-- default of nix.conf's @store@ setting.+nixRemoteVar :: BS.ByteString+nixRemoteVar = "NIX_REMOTE"++-- | The directory holding the system nix.conf, in place of+-- 'platformSystemConfDir'.+nixConfDirVar :: BS.ByteString+nixConfDirVar = "NIX_CONF_DIR"++-- | The user config files, first strongest, in place of the XDG cascade.+nixUserConfFilesVar :: BS.ByteString+nixUserConfFilesVar = "NIX_USER_CONF_FILES"++-- | The directory holding the user's own @nix.conf@, in place of @nix@+-- under the XDG config home.+nixConfigHomeVar :: BS.ByteString+nixConfigHomeVar = "NIX_CONFIG_HOME"++-- | The XDG config dirs, searched for @nix\/nix.conf@ after the config home.+xdgConfigDirsVar :: BS.ByteString+xdgConfigDirsVar = "XDG_CONFIG_DIRS"++-- | The XDG base directory spec's default for @XDG_CONFIG_DIRS@, the+-- literal upstream's @getConfigDirs@ falls back to.+posixXdgConfigDirs :: [FilePath]+posixXdgConfigDirs = ["/etc/xdg"]++-- | Where a release archive keeps the bundled expressions, relative to the+-- directory holding @bin@.+bundledDataSubdir :: FilePath+bundledDataSubdir = "share" </> "nova-nix"++-- | The one file a data dir must contain, used to tell a real one from a+-- directory that merely exists.+dataDirMarker :: FilePath+dataDirMarker = "nix" </> "fetchurl.nix"++-- | Locate the bundled @\<nix/*\>@ expressions.+--+-- Cabal bakes an absolute @datadir@ into the binary at configure time.  That+-- is right for a @cabal install@ on this machine and wrong for every copied+-- or downloaded one, because the path names the machine that did the build:+-- a released binary would resolve @\<nix/fetchurl.nix\>@ to a directory that+-- does not exist on the host running it.+--+-- @NIX_DATA_DIR@ wins when set and not empty, since an operator setting+-- upstream's own variable means it.  Otherwise a release layout (@bin/@ beside+-- @share/@) answers from the executable's own location, which needs no+-- configuration at all.  The Cabal path remains the fallback, so a local+-- install is unaffected.+resolveDataDir :: IO FilePath+resolveDataDir = do+  fromEnv <- lookupEnv nixDataDirVar+  case fromEnv of+    Just dir | not (null dir) -> pure dir+    _ -> do+      exeDir <- takeDirectory <$> getExecutablePath+      let bundled = takeDirectory exeDir </> bundledDataSubdir+      bundledUsable <- doesFileExist (bundled </> dataDirMarker)+      if bundledUsable then pure bundled else getDataDir++-- | Merge --nix-path entries, NIX_PATH's (its bytes) and the bundled data+-- dir, parsed in that order.  The data dir is appended last so user paths+-- take priority.+mergeSearchPaths :: [T.Text] -> FilePath -> BS.ByteString -> IO [Thunk]+mergeSearchPaths extraPaths dataDir nixPath = do+  extra <- concat <$> mapM (parseNixPath . TE.encodeUtf8) extraPaths+  envPaths <- parseNixPath nixPath+  bundled <- parseNixPath (TE.encodeUtf8 (T.pack dataDir))+  pure (extra ++ envPaths ++ bundled)++-- ---------------------------------------------------------------------------+-- Main+-- ---------------------------------------------------------------------------++main :: IO ()+main = do+  useStoreFileMask+  interruptOnTermination+  hSetBuffering stdout LineBuffering+  -- UTF-8 on both output handles regardless of the console code page:+  -- locale encodings THROW on any character they cannot represent, so a+  -- store path or message containing one would otherwise abort the whole+  -- invocation mid-print on legacy Windows consoles.  An eval result does+  -- not pass through this: 'printResult' writes it as bytes.+  hSetEncoding stdout utf8+  hSetEncoding stderr utf8+  -- Counting by site begins before anything is allocated, so the census+  -- 'writeCensus' takes covers every environment and attribute set.+  wantsCensus <- isJust <$> censusTarget+  when wantsCensus countSites+  args <- getArgs+  dataDir <- resolveDataDir+  opts <- either (failWith . T.pack) pure (parseArgs args)+  (configured, assignedBySources) <- loadNixConfig+  config <- withCommandLineFeatures opts configured+  let assigned = assignedBySources <> Config.assignedSettings (cliAssignments opts)+      chosenStore = resolveCommandStore config assigned opts+  -- SIGINT reaches the main thread as UserInterrupt, as SIGTERM and SIGHUP+  -- do on POSIX ('interruptOnTermination'), which uncaught ends+  -- the process by the signal with nothing said, and an I/O failure no+  -- command handles, or a walk of a tree on disk that failed to read an+  -- entry, reaches GHC's default handler, which prints an "Uncaught+  -- exception" report with a backtrace.  Upstream's handleExceptions logs+  -- each as one error line and exits 1 (libmain/shared.cc at 2.24.9):+  -- checkInterrupt throws Interrupted, a BaseError like any other failure.+  handleJust userInterrupt (const reportInterrupt) . handle reportIOFailure . handle reportWalkFailure $ case optCommand opts of+    CmdEval target+      | optAterm opts -> chosenStore >>= \store -> evalAterm config opts store dataDir target+      | otherwise -> chosenStore >>= \store -> evalCommand config opts store dataDir target+    CmdBuild target attrPath outLink -> chosenStore >>= \store -> buildCommand config opts store dataDir target attrPath outLink+    CmdDevelop target attrPath developArgs -> chosenStore >>= \store -> developCommand config opts store dataDir target attrPath developArgs+    CmdPrintDevEnv target attrPath format layout -> chosenStore >>= \store -> printDevEnvCommand config opts store dataDir target attrPath format layout+    CmdTrust target attrPath format layout -> chosenStore >>= \store -> trustCommand config opts store dataDir target attrPath format layout+    CmdPush pushArgs -> chosenStore >>= \store -> pushCommand config opts store pushArgs+    CmdStoreDelete paths -> chosenStore >>= openedDirectly "store delete" "delete paths" >>= \storeDir -> storeDeleteCommand storeDir paths+    CmdStoreGc printRoots -> chosenStore >>= openedDirectly "store gc" "collect garbage" >>= \storeDir -> storeGcCommand storeDir printRoots+    CmdProfileAdd target attrPath selection priority -> chosenStore >>= \store -> profileAddCommand config opts store dataDir target attrPath selection priority+    CmdProfileRemove selection removals -> chosenStore >>= \store -> profileRemoveCommand config opts store selection removals+    CmdProfileList selection format -> chosenStore >>= \store -> profileListCommand config (commandStoreDir store) selection format+    CmdProfileHistory selection -> chosenStore >>= \store -> profileHistoryCommand config (commandStoreDir store) selection+    CmdProfileRollback selection to changes -> chosenStore >>= \store -> profileRollbackCommand config (commandStoreDir store) selection to changes+    CmdProfileWipeHistory selection olderThan changes -> chosenStore >>= \store -> profileWipeHistoryCommand config (commandStoreDir store) selection olderThan changes+    CmdKeyGenerateSecret keyName -> keyGenerateSecretCommand keyName+    CmdKeyConvertSecretToPublic -> keyConvertSecretToPublicCommand+    CmdDaemon trust socketPath -> daemonStoreDir opts >>= \storeDir -> daemonCommand config storeDir trust socketPath+    CmdUsage -> mapM_ (TIO.hPutStrLn stderr) helpLines >> exitFailure+    CmdHelp -> toStdout (mapM_ TIO.putStrLn helpLines)+    CmdVersion -> toStdout (putStrLn versionLine)++-- | 'UserInterrupt' alone: every other asynchronous exception keeps+-- propagating.+userInterrupt :: AsyncException -> Maybe ()+userInterrupt UserInterrupt = Just ()+userInterrupt _ = Nothing++reportInterrupt :: IO a+reportInterrupt = do+  hPutStrLn stderr "error: interrupted by the user"+  exitWith (ExitFailure 1)++-- | An I/O failure no command handled, reported as upstream reports an+-- error: @error: @ and the message, then exit status 1.+reportIOFailure :: IOException -> IO a+reportIOFailure failure = do+  hPutStrLn stderr ("error: " <> ioFailureMessage failure)+  exitWith (ExitFailure 1)++-- | A walk of a tree on disk that no command handled, reported as+-- 'reportIOFailure' reports an I/O failure: the entry, the access that+-- failed on it, and the 'IOException' it raised.+reportWalkFailure :: NAR.NarWalkError -> IO a+reportWalkFailure failure = do+  hPutStrLn stderr ("error: " <> displayException failure)+  exitWith (ExitFailure 1)++-- | Run a write to stdout, dropping what is left of it once stdout's+-- reader has gone ('readerGone'), as a write through upstream's+-- @std::cout@ is dropped: upstream's main thread blocks SIGPIPE+-- (@unix::startSignalHandlerThread@ in libutil\/unix\/signals.cc), so the+-- write fails with EPIPE, which only sets the stream's error state, and the+-- command goes on to its own exit status (@processExpr@ in+-- nix-instantiate.cc).  A command that writes as it works, as @store delete@+-- does, still does all of its work.  GHC's flush of stdout at exit meets the+-- same failure when the write left bytes in the buffer, and passes it to the+-- finalizer exception handler; this program sets none, and the default+-- ignores it (@flushStdHandles@ in ghc-internal at 9.14.1).+toStdout :: IO () -> IO ()+toStdout = handleJust readerGone pure++-- | A write to stdout that failed because no process holds the read end+-- of the pipe it writes to: EPIPE on stdout, the one failure GHC's own+-- top-level handler also ends quietly.  GHC on Windows reports a write to+-- a pipe being closed as EPIPE too (@blockingWriteRawBufferPtr@ in+-- ghc-internal at 9.14.1).+readerGone :: IOException -> Maybe ()+readerGone failure+  | fmap Errno (ioe_errno failure) == Just ePIPE && ioe_handle failure == Just stdout = Just ()+  | otherwise = Nothing++-- | The logger the library reports to: each message and each line a+-- builder writes on stderr, a builder's line filtered for what stderr is+-- ('escapeFilterFor').+cliLogger :: IO Logger+cliLogger = (`handleLogger` stderr) <$> escapeFilterFor stderr++-- | A 'userError' is its message alone, which 'show' would wrap in+-- @user error (...)@; any other 'IOException' also names the operation+-- and the file that failed.+ioFailureMessage :: IOException -> String+ioFailureMessage failure+  | isUserError failure = ioeGetErrorString failure+  | otherwise = displayException failure++-- | What @--version@ reports.  Cabal's version, which is the one the publish+-- workflow's tag guard checks a tag against, so a downloaded binary names+-- exactly the release it came from and a bug report can say which build.+versionLine :: String+versionLine = "nova-nix " <> showVersion version++-- | Canonicalize and read a source file, or the @default.nix@ of a+-- directory, which upstream's @resolveExprPath@ appends to a path that is+-- one and resolves no further (eval.cc), so relative paths in it resolve+-- against the directory.  The canonicalization matters: relative path+-- literals inside the file resolve against the file's directory+-- ('esBaseDir'), and a relative base dir would be re-prefixed on every+-- resolution (doubling it).  An unreadable argument (a missing file, a+-- directory with no @default.nix@, no permission) is a clean CLI error, never+-- an uncaught exception.  Only 'IOException' is caught: an interrupt or any+-- other async exception must abort the run, not print as a read failure.+readSourceFile :: FilePath -> IO (FilePath, BS.ByteString)+readSourceFile rawPath = do+  attempt <- try $ do+    canonical <- canonicalizePath rawPath+    isDirectory <- doesDirectoryExist canonical+    let path = if isDirectory then canonical </> directoryExprFile else canonical+    source <- BS.readFile path+    pure (path, source)+  case attempt of+    Left (e :: IOException) ->+      failWith ("cannot read " <> T.pack rawPath <> ": " <> T.pack (displayException e))+    Right ok -> pure ok++-- | The file a directory target stands for.+directoryExprFile :: FilePath+directoryExprFile = "default.nix"++-- | Where @--expr@ and @--arg@ source comes from: text with no file to+-- point at, which its parse errors name @<expr>@ and its positions name+-- no file.+exprOrigin :: SourceOrigin+exprOrigin = SourceText "<expr>"++-- | The evaluation policy for this run: the config cascade's settings,+-- with each flag moving its setting from the default.  A flag only moves+-- a setting that way, so a machine configured for pure evaluation, or+-- with import from derivation off, stays that way whatever the command+-- line says, which is the direction a confinement should fail in.+evalPolicyFor :: CliOpts -> NixConfig -> EvalPolicy+evalPolicyFor opts config =+  EvalPolicy+    { epRestrictEval = optRestrictEval opts || ncRestrictEval config,+      epPureEval = optPureEval opts || ncPureEval config,+      epAllowedUris = ncAllowedUris config,+      epTraceVerbose = optTraceVerbose opts || ncTraceVerbose config,+      epImportFromDerivation = importFromDerivationFor opts config,+      epExperimentalFeatures = ncExperimentalFeatures config+    }++-- | What @allow-import-from-derivation@ and @trace-import-from-derivation@+-- say for this run.  Off, by the flag or the configuration, the trace is+-- moot, as upstream's has no effect then (@traceImportFromDerivation@ in+-- eval-settings.hh, from 2.34.9).+importFromDerivationFor :: CliOpts -> NixConfig -> ImportFromDerivation+importFromDerivationFor opts config+  | optNoAllowImportFromDerivation opts || not (ncAllowImportFromDerivation config) = RefuseImportFromDerivation+  | ncTraceImportFromDerivation config = TraceImportFromDerivation+  | otherwise = AllowImportFromDerivation++-- | Run an action in the evaluation session of one command+-- ('withEvalSession'), its state's roots allowed.  Every value the+-- action evaluates is used inside it: the session's end frees them.+-- Upstream Nix decides the same things in the same order: under pure-eval+-- the lookup path is empty, so neither @--nix-path@ nor @NIX_PATH@+-- contributes, and only the bundled @<nix/*>@ directory remains, which+-- upstream serves from an in-memory corepkgs filesystem and this binary+-- serves from its data directory (so it stays visible in+-- @builtins.nixPath@, where upstream shows nothing); under either mode+-- every search path root is allowed but a pseudo-URL entry and one with no+-- UTF-8 reading, as upstream allows the lookup path, so+-- @--nix-path nixpkgs=...@ is what makes a nixpkgs tree readable.+--+-- Each root is allowed under its given spelling and under its resolved+-- one.  The access walk follows symlinks, so a root reached through a+-- symlinked directory (macOS's @/tmp@ is @/private/tmp@) is checked under+-- the resolved spelling; upstream allows only the given one and refuses+-- the read, which is a mismatch between its own allow list and walk, not+-- a rule worth keeping.+withCliSession :: CliOpts -> NixConfig -> StoreDir -> SessionStore -> FilePath -> FilePath -> Regions -> (EvalState -> IO a) -> IO a+withCliSession opts config storeDir store dataDir baseDir regions action = do+  let policy = evalPolicyFor opts config+  -- Read whatever the policy, so a NIX_PATH with no UTF-8 form is refused+  -- under pure-eval too, but parsed only where it is used.+  nixPath <- nixPathValue+  let searchPath+        | epPureEval policy = parseNixPath (TE.encodeUtf8 (T.pack dataDir))+        | otherwise = mergeSearchPaths (optNixPaths opts) dataDir nixPath+  logger <- cliLogger+  withEvalSession (SessionSettings policy searchPath storeDir baseDir regions store logger) $ \st0 -> do+    let st = st0 {esCallDepth = topLevelCallDepth (ncMaxCallDepth config), esFetchRetry = settingsFetchRetry config}+    allowSearchPathRoots st+    action st+  where+    -- A relative root resolves against the working directory, as+    -- upstream's absPath does, and a rooted one with no drive lands on+    -- the store's drive, where its lookups read ('qualifyPathText').  A+    -- pseudo-URL entry (channel:, flake:, a listed scheme) names a+    -- download this evaluator never performs and allows nothing:+    -- upstream allows such an entry's working-directory spelling only by+    -- falling through after a failed download (resolveLookupPathPath),+    -- and a run that cannot fetch should not widen what it may read.  A+    -- root with no UTF-8 reading allows nothing: allowed paths are text,+    -- so no read can name it, and a lossy spelling would allow a+    -- different path.+    allowSearchPathRoots st = do+      rootBytes <- searchPathRoots (evalSearchPath st)+      roots <- mapM rootSpellings (mapMaybe textRoot (filter (not . isNixPathPseudoUrl) rootBytes))+      mapM_ (allowEvalPath st) (concat roots)+    textRoot = either (const Nothing) Just . TE.decodeUtf8'+    rootSpellings root = do+      given <- makeAbsolute (T.unpack (qualifyPathText storeDir root))+      resolved <- canonicalizePath given+      pure (map (canonPathValue . T.pack) [given, resolved])++-- | Parse and bind source against the names the root environment+-- 'withCliSession' builds will bind, which depend on the policy.+parseForEval :: CliOpts -> NixConfig -> FilePath -> SourceOrigin -> BS.ByteString -> Either SourceError ParsedSource+parseForEval opts config = parseNixWithScope (rootScopeNames (evalPolicyFor opts config))++-- | Run an action on a target in the evaluation session of one command,+-- in the order upstream's commands take them (@main_nix_instantiate@ in+-- nix-instantiate.cc and @main_nix_build@ in nix-build.cc): the session, then+-- the cells @--arg@ and @--argstr@ give ('sessionAutoArgs'), then the target,+-- found, read and parsed.  The action runs with the target's directory as the+-- session's base, and gets the cells and the parsed target.  A failure to+-- find, read or parse is reported and exits.+withTarget :: NixConfig -> CliOpts -> StoreDir -> SessionStore -> FilePath -> Regions -> Target -> (EvalState -> AutoArgs -> ParsedSource -> IO a) -> IO a+withTarget config opts storeDir store dataDir regions target action = do+  cwd <- getCurrentDirectory+  withCliSession opts config storeDir store dataDir cwd regions $ \st -> do+    autoArgs <- sessionAutoArgs opts config cwd st+    (baseDir, origin, source) <- targetSource cwd st target+    case parseForEval opts config baseDir origin source of+      Left err -> failSource err+      Right parsed -> action (st {esBaseDir = baseDir}) autoArgs parsed++-- | The cells a target's function is called with, made in name order,+-- each name interned after its expression, as upstream's @getAutoArgs@+-- makes them (common-eval-args.cc).  An @--arg@ expression is parsed from the+-- argument's bytes, relative paths against the working directory, before+-- anything else is read, and evaluated in the root environment only when the+-- function uses it; an @--argstr@ value is a string of the argument's bytes.+-- A name is an attribute name, which is text here, so one whose bytes have no+-- UTF-8 reading is refused where upstream keeps the bytes.  Each cell+-- outlives the step that makes it, so it is registered as a root+-- ("Nix.Eval.CRoots").+sessionAutoArgs :: CliOpts -> NixConfig -> FilePath -> EvalState -> IO AutoArgs+sessionAutoArgs opts config cwd st = do+  prepared <- traverse prepare (Map.toAscList (optAutoArgs opts))+  Map.fromList <$> evalOrExit st (traverse cell prepared)+  where+    prepare (rawName, arg) = do+      let flag = autoArgFlag arg+      nameBytes <- commandLineBytes flag rawName+      name <- either (const (failWith ("error: " <> flag <> ": invalid UTF-8 in argument name"))) pure (TE.decodeUtf8' nameBytes)+      made <- case arg of+        AutoArgExpr source ->+          commandLineBytes flag source >>= either failSource (pure . Left) . parseForEval opts config cwd exprOrigin+        AutoArgString value -> Right <$> commandLineBytes flag value+      pure (name, made)+    cell (name, made) = do+      thunk <- either (compileSource >=> mkThunkBc (evalBaseEnv st)) (evaluated . mkStrBytes) made+      crootsAddThunk (unThunk thunk)+      (name, thunk) <$ symbolIntern name+    autoArgFlag (AutoArgExpr _) = "--arg"+    autoArgFlag (AutoArgString _) = "--argstr"++-- | The bytes of a command-line argument ('argumentBytes'), the command+-- failing for a Windows argument with no UTF-8 form.+commandLineBytes :: T.Text -> String -> IO BS.ByteString+commandLineBytes what arg =+  argumentBytes arg+    >>= maybe (failWith ("error: " <> what <> " holds an unpaired UTF-16 surrogate, which has no UTF-8 form")) pure++-- | Where a target's expression is read from: the directory relative+-- paths in it resolve against, its origin and its bytes.  A @\<NAME\>@+-- is found and read as @import \<NAME\>@ finds and reads its file+-- ('findInSearchPath', 'resolveImportTarget'), failing as that does, so+-- a file in the store keeps its store path's spelling and a path literal+-- in it names a place in that store path.+targetSource :: FilePath -> EvalState -> Target -> IO (FilePath, SourceOrigin, BS.ByteString)+targetSource _ _ (TargetFile path) = fileSource path+targetSource cwd st (TargetSearchPath name) = do+  nameBytes <- commandLineBytes "<NAME>" name+  (target, source) <- evalOrExit st $ do+    located@(target, _) <- findInSearchPath (evalSearchPath st) nameBytes >>= resolveImportTarget cwd+    (,) target <$> readImportTarget located+  pure (takeDirectory target, SourceFile (T.pack target), source)+targetSource cwd _ (TargetExpr source) = (,,) cwd exprOrigin <$> commandLineBytes "--expr" source++-- | A target file's directory, origin and bytes ('readSourceFile').+fileSource :: FilePath -> IO (FilePath, SourceOrigin, BS.ByteString)+fileSource rawPath = do+  (filePath, source) <- readSourceFile rawPath+  pure (takeDirectory filePath, SourceFile (T.pack filePath), source)++-- | Run an evaluation, reporting a failure and exiting.+evalOrExit :: EvalState -> EvalIO a -> IO a+evalOrExit st action =+  runEvalIOTraced st action >>= \case+    Left failure -> do+      TIO.hPutStrLn stderr (renderEvalFailure failure)+      exitFailure+    Right value -> pure value++-- | Evaluate a target and print its value.  A function is called first+-- when an argument is given, as @nix-instantiate --eval@ calls it only+-- then.  The session is read-only, as @nix-instantiate --eval@'s is+-- ('withReadOnlySession'), unless @--read-write-mode@ asks for a read-write+-- one, as it asks @nix-instantiate@'s: then what evaluation made is added+-- to the store before a context's realisation that needs it and once+-- evaluation succeeds, where upstream adds each object as it makes it.  An+-- evaluation that made nothing adds nothing, so it asks nothing of a store+-- upstream Nix manages.+evalCommand :: NixConfig -> CliOpts -> CommandStore -> FilePath -> Target -> IO ()+evalCommand config opts store dataDir target = do+  regions <- regionsWanted+  withEvalSessionStore config opts store $ \session -> withTarget config opts (commandStoreDir store) session dataDir regions target $ \st autoArgs parsed -> do+    let call+          | Map.null autoArgs = pure+          | otherwise = autoCallFunction autoArgs+    (env, forced) <- evalOrExit st (evalRooted (optStrict opts) (evalBaseEnv st) call parsed)+    case session of+      ReadOnlySession _ _ -> pure ()+      ReadWriteSession ops -> sessionObjects st >>= soAddEvalObjects ops >>= either (failWith . ("error: " <>)) pure+    printResult forced >> writeCensus env forced >> writeRegionCensus++-- | The store an @eval@ session realises contexts against: read-only by+-- default ('withReadOnlySession'), and under @--read-write-mode@ the+-- store a build uses, under the build's configuration, so the cache,+-- key, fallback and launcher flags reach what it builds.+withEvalSessionStore :: NixConfig -> CliOpts -> CommandStore -> (SessionStore -> IO a) -> IO a+withEvalSessionStore config opts store action+  | optReadWriteMode opts = withCommandStore store config opts (buildConfigFor config opts) (action . ReadWriteSession)+  | otherwise = withReadOnlySession config opts store action++-- | What a session's evaluation made: the copies of the paths it coerced,+-- the trees it wrote and the derivations it recorded, as the store adds+-- them ('soAddEvalObjects').+sessionObjects :: EvalState -> IO EvalObjects+sessionObjects st =+  EvalObjects+    . sourceCopies+    <$> readIORef (esSourcePathCache st)+    <*> readIORef (esStoreWriteCache st)+    <*> readIORef (esDrvClosure st)++-- | Evaluate the source in the root environment, pass the value through+-- @call@, and give the result 'finalize' gives, with that environment,+-- which 'writeCensus' counts as held.+evalRooted :: Bool -> Env -> (NixValue -> EvalIO NixValue) -> ParsedSource -> EvalIO (Env, NixValue)+evalRooted strict env call parsed = do+  code <- compileSource parsed+  forced <- evalBytecode env code >>= call >>= finalize strict+  pure (env, forced)++-- | The variable naming the file 'writeCensus' writes.+censusVar :: BS.ByteString+censusVar = "NOVA_NIX_C_STATS"++-- | The file 'censusVar' names, when it names one: set and not empty.+censusTarget :: IO (Maybe BS.ByteString)+censusTarget = mfilter (not . BS.null) <$> configVariable censusVar++-- | With 'censusVar' set to a path, write a census of the C data layer+-- ("Nix.Eval.CStats") to it once an evaluation has succeeded.  Its roots+-- are what the process still holds once the evaluation has returned: the+-- result and the root environment, and every root the session registered+-- ("Nix.Eval.CRoots"), the import cache's values among them.  A census of GHC's heap+-- follows, which a run under a heap profile (@+RTS -hT@) records as its+-- last sample: taken after the C census, so that no periodic sample falls+-- between it and the end however long the mark runs, in the major+-- collection that leaves nothing in GHC's heap the evaluation has dropped.+writeCensus :: Env -> NixValue -> IO ()+writeCensus env result = do+  target <- censusTarget+  case target of+    Nothing -> pure ()+    Just bytes -> do+      path <- variableHostPath censusVar bytes+      census <- takeCensus (RootRegistered : RootEnv env : valueRoots result)+      requestHeapCensus+      performMajorGC+      case census of+        Left failure -> failWith ("error: " <> T.pack (displayException failure))+        Right taken -> OsFile.writeFile' path (renderCensus taken)++-- | The variable naming the file 'writeRegionCensus' writes.+regionCensusVar :: BS.ByteString+regionCensusVar = "NOVA_NIX_REGION_STATS"++-- | The file 'regionCensusVar' names, when it names one: set and not+-- empty.+regionCensusTarget :: IO (Maybe BS.ByteString)+regionCensusTarget = mfilter (not . BS.null) <$> configVariable regionCensusVar++-- | What an evaluation runs regions for: a census of them when+-- 'regionCensusVar' names a file; nothing when 'censusVar' does, since the+-- census of the C data layer counts everything the evaluation allocated,+-- which the collector would have freed some of; and the collector+-- otherwise.+regionsWanted :: IO Regions+regionsWanted = wanted <$> regionCensusTarget <*> censusTarget+  where+    wanted (Just _) _ = RegionsCensus+    wanted Nothing (Just _) = RegionsOff+    wanted Nothing Nothing = RegionsCollect++-- | With 'regionCensusVar' set to a path, write what the session's census+-- of regions found ("Nix.Eval.CRegion") once an evaluation has+-- succeeded: for each force, what it allocated and what still reached it+-- as it returned, and what collectors freeing at those points would have+-- held.+writeRegionCensus :: IO ()+writeRegionCensus = do+  target <- regionCensusTarget+  case target of+    Nothing -> pure ()+    Just bytes -> do+      path <- variableHostPath regionCensusVar bytes+      figures <- regionFigures+      case figures of+        Left failure -> failWith ("error: " <> T.pack (displayException failure))+        Right found -> OsFile.writeFile' path (renderRegionFigures found)++-- | Evaluate a target to a derivation and print its ATerm (.drv+-- contents), for diffing nova-nix's serialization against upstream Nix.+-- A function is called first, whether or not an argument is given, as+-- @nix-instantiate@ calls one before it writes a derivation+-- (@getDerivations@ in get-drvs.cc).  The session is read-write, as plain+-- @nix-instantiate@'s is, which runs read-only only under @--eval@+-- (@main_nix_instantiate@ in nix-instantiate.cc): what an import from+-- derivation names is added and built.+evalAterm :: NixConfig -> CliOpts -> CommandStore -> FilePath -> Target -> IO ()+evalAterm config opts store dataDir target =+  withCommandStore store config opts (buildConfigFor config opts) $ \ops -> withTarget config opts (commandStoreDir store) (ReadWriteSession ops) dataDir RegionsCollect target $ \st autoArgs parsed -> do+    val <- evalOrExit st $ do+      val <- evalParsed (pure (evalBaseEnv st)) parsed >>= autoCallFunction autoArgs+      val <$ forceDerivationAttrs val+    drvSP <- derivationPath val+    drvClosure <- readIORef (esDrvClosure st)+    aterm <- recordedAterm drvClosure drvSP+    -- The recorded bytes, not a re-serialization: these are what the+    -- path hashes.  BC.putStrLn bypasses the handle encoding, so the+    -- printed .drv diffs byte-exactly against upstream's.+    toStdout (BC.putStrLn aterm)++-- | Force the attributes 'derivationPath' goes on to read.  @derivation@+-- is a lazy wrapper, and 'readThunkValue' answers 'Nothing' for a thunk that+-- was never forced, so skipping this reports a real derivation as not one.+-- Forcing @drvPath@ is also what computes the derivation and records its+-- @.drv@ in the session closure ('recordedAterm').+forceDerivationAttrs :: (MonadEval m) => NixValue -> m ()+forceDerivationAttrs val = case val of+  VAttrs attrs ->+    mapM_+      (\k -> attrSetLookup k attrs >>= maybe (pure ()) (void . force))+      derivationAttrKeys+  _ -> pure ()++-- | What a build needs forced: the marker, the path whose closure the+-- build driver writes, and the output it prints and links.+derivationAttrKeys :: [T.Text]+derivationAttrKeys = ["type", "drvPath", "outputName"]++-- | Evaluate a target command's target and select the attribute path, when+-- one is given, with the attributes 'derivationPath' reads forced, and+-- run an action in the session with the state the evaluation recorded+-- and the selected value.  A function is called with the command line's+-- arguments before each component of the path is selected from it, and+-- once the path has selected it, as @nix-build@ calls one.+-- The action reads what the command needs out of them: the session's end+-- frees the value.  A failure is reported and exits.+evalTarget :: NixConfig -> CliOpts -> StoreDir -> SessionStore -> FilePath -> Target -> Maybe T.Text -> (EvalState -> NixValue -> IO a) -> IO a+evalTarget config opts storeDir store dataDir target attrPath action =+  withTarget config opts storeDir store dataDir RegionsCollect target $ \st autoArgs parsed -> do+    let call = autoCallFunction autoArgs+    selected <- evalOrExit st $ do+      root <- evalParsed (pure (evalBaseEnv st)) parsed+      chosen <- case attrPath of+        Nothing -> pure (Right root)+        Just path -> selectAttrPath call path root+      -- Forced after selection, not before: forcing the root leaves the+      -- selected value's own attributes unforced, and derivationPath+      -- then reports a real derivation as not being one.+      traverse (call >=> \val -> val <$ forceDerivationAttrs val) chosen+    case selected of+      Left selectionErr -> do+        TIO.hPutStrLn stderr ("error: " <> selectionErr)+        exitFailure+      Right val -> action st val++-- | Parse, evaluate, extract the derivation, build it, and print its+-- output path.  A store directory upstream Nix's database also manages+-- is refused before evaluation, which can write to the store too+-- ("Nix.Store.Upstream"), when the store is opened directly.+buildCommand :: NixConfig -> CliOpts -> CommandStore -> FilePath -> Target -> Maybe T.Text -> OutLink -> IO ()+buildCommand config opts store dataDir target attrPath outLink = do+  refuseUpstreamManaged "build" store+  -- One handle serves the evaluation, which adds and builds what an+  -- import from derivation names, and the build after it, and opens with+  -- whichever first asks for the store.  The root is registered before+  -- the store closes: its lease is what keeps a concurrent collection+  -- from running between the build's end and the link's creation.  The+  -- path prints after the store has closed and the link exists, as+  -- nix-build prints it, so a failed link prints nothing a script would+  -- take for success.+  (outcome, outputPath) <- withCommandStore store config opts (buildConfigFor config opts) $ \ops -> do+    -- The session ends before the build starts, freeing the evaluation's+    -- memory: the build needs only what is read out of it here.  The+    -- full .drv closure (root + every transitive input) recorded during+    -- evaluation is written to the store before building, and the root's+    -- own recipe is read from the same map, so what is built is what its+    -- path hashes.+    (drvSP, outputName, evalObjects) <-+      evalTarget config opts storeDir (ReadWriteSession ops) dataDir target attrPath $ \st val -> do+        drvSP <- derivationPath val+        outputName <- defaultOutputName drvSP val+        (,,) drvSP outputName <$> sessionObjects st+    drv <- recordedDerivation (eoDerivations evalObjects) drvSP+    -- Resolved before the build, as nix-build resolves the output it+    -- realizes before building anything.+    outputPath <- namedOutputPath drv outputName+    let -- Evaluation computes the paths of the sources it coerced and of+        -- the .drv files it recorded, and writes trees such as+        -- builtins.toFile's.  An import from derivation adds all of it+        -- made by then, so a build adds the rest first; the add passes+        -- over what is valid.  The whole recorded .drv closure goes in,+        -- the root's own recipe among it, since the build reads each one+        -- back.+        -- With --check the derivation is checked, every output of it,+        -- and otherwise the output outputName names is realised, the+        -- only one nix-build realises.+        build = case buildModeFor opts of+          BuildNormal -> soBuild ops [(drvSP, Set.singleton outputName)]+          BuildCheck -> soCheck ops drvSP+    outcome <- runExceptT $ do+      ExceptT (first AddRefused <$> soAddEvalObjects ops evalObjects)+      ExceptT (first BuildStopped <$> build)+      traverse (\link -> ExceptT (first LinkRefused <$> soAddOutLinkRoot ops link outputPath)) (outLinkFor outLink outputName)+    pure (outcome, outputPath)+  case outcome of+    Left stop -> reportStop stop+    Right _ -> toStdout (TIO.putStrLn (T.pack (storePathToFilePath storeDir outputPath)))+  where+    storeDir = commandStoreDir store++-- | Report why a build command stopped once evaluation was done, and exit.+reportStop :: BuildCommandStop -> IO a+reportStop stop = case stop of+  -- Reported as a refusal an add throws is ('reportIOFailure').+  AddRefused reason -> do+    TIO.hPutStrLn stderr ("error: " <> reason)+    exitWith (ExitFailure 1)+  -- The status printed is the status exited with: 1, or upstream's 104+  -- for a check that found an output different.+  BuildStopped stopped -> do+    let (msg, code) = stopReported stopped+    TIO.hPutStrLn stderr ("build failed (exit " <> T.pack (show code) <> "): " <> msg)+    exitWith (ExitFailure code)+  LinkRefused err -> failWith ("build: " <> err)++-- | The configuration a command's builds run under: what its settings+-- give ('cliSettings'), on this machine, with the launchers its options+-- name.+buildConfigFor :: NixConfig -> CliOpts -> StoreDir -> IO BuildConfig+buildConfigFor config opts storeDir = do+  wrappers <- either failWith pure (execWrapperConfig (optExecWrappers opts)) >>= checkExecWrappers+  defaults <- machineDefaults readKernelFile+  pure (settingsBuildConfig defaults (cliSettings opts config) storeDir) {bcExecWrappers = wrappers}++-- | Run an action with a read-only session's store for a command's store,+-- as @nix-instantiate --eval@ runs read-only (@main_nix_instantiate@ in+-- nix-instantiate.cc).  In a store opened directly its queries make no+-- store and write no row ('localQueries', beside whose database SQLite+-- can make its wal-index files).  The store's operations open it only to+-- add what a fetcher fetched, as upstream's fetchers add theirs in any+-- mode, or to build: an output a context names is realised by a build that+-- refuses every substitution ('RefuseSubstitution'), which in a store+-- upstream Nix manages opens nothing.  Through a daemon the queries and+-- the operations are the daemon's, which connect when first asked, and+-- the daemon realises an output a context names as it chooses.+withReadOnlySession :: NixConfig -> CliOpts -> CommandStore -> (SessionStore -> IO a) -> IO a+withReadOnlySession config opts store action =+  withCommandStore store config opts readOnlyConfig $ \ops -> action (ReadOnlySession (queriesOf store ops) ops)+  where+    readOnlyConfig dir = (\buildConfig -> buildConfig {bcSubstitution = RefuseSubstitution}) <$> buildConfigFor config opts dir+    queriesOf (LocalCommandStore dir) _ = localQueries dir+    queriesOf (DaemonCommandStore {}) ops = soQueries ops++-- | Why a build command stopped once evaluation was done.+data BuildCommandStop+  = -- | The store refused evaluation's objects.+    AddRefused !T.Text+  | -- | The build stopped.+    BuildStopped !BuildStop+  | -- | The out-link could not be made or rooted.+    LinkRefused !T.Text++-- | Evaluate the target, find the fixed-output derivations of its+-- derivation's closure, fetch each one nova-nix's builtins fetch alone,+-- substitute the others from the configured caches, scan the outputs the+-- store holds, and print what the closure relies on ("Nix.Trust"), as+-- lines or, with @--json@, as one JSON document.  The+-- graph is read from the recipes evaluation recorded.  The evaluation is+-- read-only ('withReadOnlySession'), so it writes only what a fetcher+-- fetches and what a context's realisation builds, and otherwise only the+-- fetches and substitutions of fixed-output inputs write to the store: a+-- closure with no fixed-output input does not open it after evaluation.+-- A store directory upstream Nix's database+-- also manages is refused before those are made, as a build refuses one+-- ("Nix.Store.Upstream").  A store reached through a daemon has the+-- daemon fetch and substitute them, and the files of what it holds are+-- read from the store's directory ('withDaemonFixedOutputs').+trustCommand :: NixConfig -> CliOpts -> CommandStore -> FilePath -> Target -> Maybe T.Text -> TrustFormat -> JsonLayout -> IO ()+trustCommand config opts store dataDir target attrPath format layout = do+  (drvSP, drvClosure) <- withReadOnlySession config opts store $ \session -> evalTarget config opts (commandStoreDir store) session dataDir target attrPath $ \st val ->+    (,) <$> derivationPath val <*> readIORef (esDrvClosure st)+  drv <- recordedDerivation drvClosure drvSP+  graph <- either (failWith . ("error: " <>)) pure (runIdentity (buildDepGraph (Identity . recordedRecipe drvClosure) drv drvSP))+  facts <- case fixedOutputInputs graph drvSP of+    [] -> pure Map.empty+    inputs -> do+      refuseUpstreamManaged "trust" store+      logger <- cliLogger+      scanned <- case store of+        LocalCommandStore dir -> bracket (openStore logger dir) closeStore (\opened -> fetchAndScan (localFixedOutputs config opts opened) inputs)+        DaemonCommandStore address dir assigned storeSetting ->+          withDaemonFixedOutputs (daemonStoreConfig address dir assigned storeSetting config opts logger) (dialDaemon address) (recordedAtermBytes drvClosure) (`fetchAndScan` inputs)+      either (failWith . ("trust: " <>)) pure scanned+  let report = trustReport facts graph drvSP+  case format of+    TrustLines -> toStdout (mapM_ TIO.putStrLn (renderTrustReport report))+    TrustJson -> printJson layout (trustReportJson report)++-- | What trust asks of a store opened directly: an input a builtin fetches+-- is built, which fetches or substitutes it, under the configuration's+-- caches, and any other is substituted from them.+localFixedOutputs :: NixConfig -> CliOpts -> Store -> FixedOutputStore IO+localFixedOutputs config opts store =+  FixedOutputStore+    { fosFetch = \node -> built <$> buildWithDeps buildConfig store (dnDerivation node) (dnDrvPath node),+      fosSubstitute = \output -> Right <$> substituteFromCaches buildConfig store [output],+      fosHeld = fmap Right . isValid store,+      fosScan = scanFetched . storePathToFilePath (stDir store)+    }+  where+    settings = cliSettings opts config+    buildConfig =+      (defaultBuildConfig (stDir store))+        { bcCaches = configToCaches settings,+          bcFallback = settingsFallback settings,+          bcSubstitutes = settingsSubstitutes settings,+          bcFetchRetry = settingsFetchRetry settings+        }+    built = \case+      BuildSuccess _ -> Right ()+      BuildFailure msg _ -> Left msg++-- | The @.drv@ store path of an evaluated derivation value: a set with+-- @type = "derivation"@ whose @drvPath@ has been forced+-- ('forceDerivationAttrs').  Store paths are ASCII, so the byte payload+-- decodes strictly.+derivationPath :: NixValue -> IO StorePath+derivationPath (VAttrs attrs) = do+  computedAttr "type" attrs >>= \case+    Just (VStr "derivation" _) -> pure ()+    _ -> failWith "error: result is not a derivation (no type = \"derivation\")"+  computedAttr "drvPath" attrs >>= \case+    Just (VStr pathBytes _)+      | Right path <- TE.decodeUtf8' pathBytes ->+          maybe (failWith ("error: invalid drvPath: " <> path)) pure (parseStorePath defaultStoreDir path)+    _ -> failWith "error: derivation result missing drvPath"+derivationPath _ = failWith "error: result is not a derivation"++-- | The output a build realises, prints and links (@--check@ checks every+-- output): the value's @outputName@, the first of its @outputs@, which+-- is what upstream's nix-build builds and prints for a derivation, with+-- its message for a set that lacks the attribute.+defaultOutputName :: StorePath -> NixValue -> IO T.Text+defaultOutputName drvSP val = do+  outputName <- case val of+    VAttrs attrs -> computedAttr "outputName" attrs+    _ -> pure Nothing+  case outputName of+    Just (VStr nameBytes _)+      | Right name <- TE.decodeUtf8' nameBytes -> pure name+    _ -> failWith ("error: derivation '" <> storePathToText defaultStoreDir drvSP <> "' lacks an 'outputName' attribute")++-- | An attribute's value if it has been computed, without forcing it.+computedAttr :: T.Text -> AttrSet -> IO (Maybe NixValue)+computedAttr key attrs = attrSetLookup key attrs >>= maybe (pure Nothing) readThunkValue++-- | The path of a named output.  A @.drv@ lists its outputs by name, so+-- the default output is found here by name, never by position.+namedOutputPath :: Derivation -> T.Text -> IO StorePath+namedOutputPath drv outputName =+  case find ((== outputName) . doName) (drvOutputs drv) of+    Just out -> pure (doPath out)+    Nothing -> failWith ("error: derivation has no output named '" <> outputName <> "'")++-- | The @.drv@ ATerm evaluation recorded under a derivation path: the exact+-- bytes whose hash is the path.  Every derivation computed in a session is+-- recorded when its @drvPath@ is forced ('esDrvClosure'), so an absent entry+-- means the path was never computed by this evaluation.+recordedAtermBytes :: Map.Map T.Text BS.ByteString -> StorePath -> Either T.Text BS.ByteString+recordedAtermBytes drvClosure drvSP =+  maybe (Left ("no .drv was recorded for " <> storePathToText defaultStoreDir drvSP)) Right (Map.lookup (storePathToText defaultStoreDir drvSP) drvClosure)++-- | The 'Derivation' a recorded ATerm describes ('recordedAtermBytes').+recordedRecipe :: Map.Map T.Text BS.ByteString -> StorePath -> Either T.Text Derivation+recordedRecipe drvClosure drvSP =+  recordedAtermBytes drvClosure drvSP+    >>= first (("the recorded .drv for " <> storePathToText defaultStoreDir drvSP <> " does not parse: ") <>) . fromATerm++-- | 'recordedAtermBytes', failing the command when there is none.+recordedAterm :: Map.Map T.Text BS.ByteString -> StorePath -> IO BS.ByteString+recordedAterm drvClosure = either (failWith . ("error: " <>)) pure . recordedAtermBytes drvClosure++-- | 'recordedRecipe', failing the command when there is none or it does+-- not parse.+recordedDerivation :: Map.Map T.Text BS.ByteString -> StorePath -> IO Derivation+recordedDerivation drvClosure = either (failWith . ("error: " <>)) pure . recordedRecipe drvClosure++-- ---------------------------------------------------------------------------+-- The store a command uses+-- ---------------------------------------------------------------------------++-- | The store a command uses, and where its files are.  A store opened+-- directly is a directory.  A store reached through a daemon is the+-- daemon's, its files read from the platform store, the directory every+-- store path is computed under, with what the sources of settings set,+-- which the daemon is told ('clientSettings'), and the @store@ setting's+-- override it is told besides ('storeOverride'), none when the setting+-- was not set.  Each directory is under the canonical spelling+-- 'openStore' keys a store by, so what evaluation and every command print+-- is the spelling the database holds.+data CommandStore+  = LocalCommandStore !StoreDir+  | DaemonCommandStore !DaemonAddress !StoreDir !Config.AssignedSettings !(Map.Map BS.ByteString BS.ByteString)++-- | Where the store's files are.+commandStoreDir :: CommandStore -> StoreDir+commandStoreDir = \case+  LocalCommandStore dir -> dir+  DaemonCommandStore _ dir _ _ -> dir++-- | The store a command uses ('storeReference', 'chooseStore'): what+-- @--store@ names, else nix.conf's @store@, else @NIX_REMOTE@, else+-- @auto@, the daemon's default address being where this machine's daemon+-- listens ('daemonSocketPath').+resolveCommandStore :: NixConfig -> Config.AssignedSettings -> CliOpts -> IO CommandStore+resolveCommandStore config assigned opts = do+  flag <- traverse (commandLineBytes "--store") (optStore opts)+  environment <- configVariable nixRemoteVar+  let setting = ncStore config+  target <- either (failWith . ("error: " <>)) pure (parseStoreTarget (storeReference flag setting environment))+  platform <- canonicalStoreDir platformStoreDir+  socket <- daemonSocketPath+  let probe = StoreProbe (probeStoreWriting (unStoreDir platform </> metaDirName)) addressPresence+  choice <- chooseStore probe socket target+  case choice of+    DirectStore Nothing -> pure (LocalCommandStore platform)+    DirectStore (Just directory) -> LocalCommandStore <$> directoryStore directory+    ThroughDaemon address -> DaemonCommandStore address platform assigned <$> either (failWith . ("error: " <>)) pure (storeOverride hostPathRules (storeFlagOf (optCommand opts)) flag setting environment)++-- | The store directory a spelling names, under its canonical spelling.+directoryStore :: BS.ByteString -> IO StoreDir+directoryStore spelling = do+  path <- bytesHostPath spelling >>= OP.decodeFS+  canonicalStoreDir (StoreDir path)++-- | The store the daemon command serves, from @--store@ alone: it serves+-- a store it opens itself, so neither the @store@ setting nor+-- @NIX_REMOTE@ is read, and a store reached through a daemon is refused.+daemonStoreDir :: CliOpts -> IO StoreDir+daemonStoreDir opts = do+  flag <- traverse (commandLineBytes "--store") (optStore opts)+  target <- either (failWith . ("error: " <>)) pure (parseStoreTarget (storeReference flag Nothing Nothing))+  case target of+    DaemonSocket _ -> failWith "daemon: --store names a store reached through a daemon; the daemon serves a store it opens itself"+    LocalStore (Just directory) -> directoryStore directory+    AutoStore -> canonicalStoreDir platformStoreDir+    LocalStore Nothing -> canonicalStoreDir platformStoreDir++-- | Run an action over a command's store, with the build configuration+-- the command's settings give for the store's directory.  A store opened+-- directly is opened when the action first asks for it ('withLocalStore').+-- A store reached through a daemon connects then, and builds where the+-- daemon does, so a launcher the command names, which only a build here+-- can run, is refused before anything is built.+withCommandStore :: CommandStore -> NixConfig -> CliOpts -> (StoreDir -> IO BuildConfig) -> (StoreOps IO -> IO a) -> IO a+withCommandStore store config opts buildConfigAt action = case store of+  LocalCommandStore dir -> do+    buildConfig <- buildConfigAt dir+    logger <- cliLogger+    withLocalStore logger buildConfig action+  DaemonCommandStore address dir assigned storeSetting -> do+    unless (null (optExecWrappers opts)) (failWith "error: --exec-wrapper needs a store nova-nix builds in itself; give --store local, or a store directory")+    logger <- cliLogger+    withDaemonStore (daemonStoreConfig address dir assigned storeSetting config opts logger) (dialDaemon address) action++-- | How a command's session with a daemon is set up: where the daemon is+-- and the store's files are, and the settings the daemon is told, which+-- are the command's ('clientSettings') with the @store@ setting's override+-- over what the settings give.+daemonStoreConfig :: DaemonAddress -> StoreDir -> Config.AssignedSettings -> Map.Map BS.ByteString BS.ByteString -> NixConfig -> CliOpts -> Logger -> DaemonStoreConfig+daemonStoreConfig address dir assigned storeSetting config opts =+  DaemonStoreConfig address dir settings {csOverrides = storeSetting <> csOverrides settings}+  where+    settings = clientSettings assigned (cliSettings opts config)++-- | Refuse, as a command that would write the store does, a store+-- directory upstream Nix's database also manages ('upstreamManagedRefusal').+-- A store reached through a daemon is the daemon's to protect.+refuseUpstreamManaged :: T.Text -> CommandStore -> IO ()+refuseUpstreamManaged commandName = \case+  LocalCommandStore dir -> upstreamManagedRefusal ReplacesUpstreamPaths dir >>= mapM_ (failWith . ((commandName <> ": ") <>))+  DaemonCommandStore {} -> pure ()++-- | The directory of a store a command opens directly: the command, named+-- and with what it does, failing for a store reached through a daemon,+-- which the commands that need the store's database and files cannot yet+-- use.+openedDirectly :: T.Text -> T.Text -> CommandStore -> IO StoreDir+openedDirectly commandName doing = \case+  LocalCommandStore dir -> pure dir+  DaemonCommandStore {} -> failWith (commandName <> ": nova-nix does not " <> doing <> " through the daemon yet; give --store local where the store can be written")++-- | The settings a command's builds run under: nix.conf's, with the+-- flags that set one applied over them, as upstream's flags set+-- settings.  @--substituter@ and @--trusted-key@ append to theirs, so a+-- flag adds to the configured set rather than being overridden by it;+-- @--fallback@ and @--keep-failed@ only turn theirs on; and a sandbox+-- flag replaces @sandbox@.+cliSettings :: CliOpts -> NixConfig -> NixConfig+cliSettings opts config =+  config+    { ncSubstituters = ncSubstituters config ++ maybe [] (\url -> [T.pack url]) (optSubstituter opts),+      ncTrustedPublicKeys = ncTrustedPublicKeys config ++ maybe [] (\key -> [T.pack key]) (optTrustedKey opts),+      ncFallback = optFallback opts || ncFallback config,+      ncKeepFailed = optKeepFailed opts || ncKeepFailed config,+      ncSandbox = optSandbox opts <|> ncSandbox config+    }++-- | The assignments the flags that set a setting stand for, spelled as+-- nix.conf spells them, so that 'Config.assignedSettings' records how+-- each flag set its setting as it records how a file does: the flags that+-- append are @extra-@ assignments, and a sandbox flag replaces.  This+-- mirrors 'cliSettings', which applies the same flags to the+-- configuration, and is what tells a daemon which settings the command+-- line set.  @--fallback@ and @--keep-failed@ are sent as the options+-- they are, and @--store@ is not recorded here: the @store@ setting is+-- sent by 'storeOverride', which knows how the command's flag sets it.+cliAssignments :: CliOpts -> [Config.ConfigAssignment]+cliAssignments opts =+  [Config.ConfigAssignment extraSubstitutersSetting (spelled url) | Just url <- [optSubstituter opts]]+    ++ [Config.ConfigAssignment extraTrustedKeysSetting (spelled key) | Just key <- [optTrustedKey opts]]+    ++ [Config.ConfigAssignment sandboxSetting (renderSandboxMode mode) | Just mode <- [optSandbox opts]]+  where+    spelled = TE.encodeUtf8 . T.pack++-- | The names nix.conf gives the settings a flag sets.+extraSubstitutersSetting, extraTrustedKeysSetting, sandboxSetting :: BS.ByteString+extraSubstitutersSetting = "extra-substituters"+extraTrustedKeysSetting = "extra-trusted-public-keys"+sandboxSetting = "sandbox"++-- | What this run does with the derivation it is asked for: with+-- @--check@ it checks it, as @nix-build --check@ selects upstream's+-- @bmCheck@.  Upstream has no setting for it, so the flag alone decides.+buildModeFor :: CliOpts -> BuildMode+buildModeFor opts+  | optCheck opts = BuildCheck+  | otherwise = BuildNormal++-- | Resolve nix.conf from the system file, the user-file cascade and+-- @NIX_CONFIG@, the file locations coming from the environment and the+-- platform's XDG defaults, and which settings those sources set.  A file+-- that cannot be read is absent, but one that is read and does not parse+-- is a hard error, so a malformed security-relevant setting cannot pass+-- for no setting.+loadNixConfig :: IO (NixConfig, Config.AssignedSettings)+loadNixConfig = do+  locations <- configLocations+  nixConfigBytes <- configVariable nixConfigVar+  paths <- either configError pure (Config.configFilePaths locations)+  Config.loadConfigAssigned readConfigFile paths nixConfigBytes+    >>= either configError pure+  where+    configError = failWith . ("error: " <>)++-- | The configuration with each @--extra-experimental-features@ value's+-- features added, as upstream applies a setting flag over the files, and+-- the warnings parsing the setting's values gave reported, the+-- configuration's first, as upstream gives them while it reads them.+withCommandLineFeatures :: CliOpts -> NixConfig -> IO NixConfig+withCommandLineFeatures opts config = do+  values <- traverse (commandLineBytes "--extra-experimental-features") (optExtraExperimentalFeatures opts)+  let features = foldl addFeatures (ncExperimentalFeatures config) (map parseFeatures values)+  logger <- cliLogger+  mapM_ (logWarning logger) (featureSetWarnings features)+  pure config {ncExperimentalFeatures = features}++-- | A variable the CLI reads, as its bytes, the way upstream's+-- @getEnv@ reads it.  A Windows value holding an unpaired UTF-16+-- surrogate has no bytes nova-nix can carry, so it is refused, as+-- @NIX_PATH@ holding one is.+configVariable :: BS.ByteString -> IO (Maybe BS.ByteString)+configVariable name = do+  found <- lookupEnvBytes name+  case found of+    EnvUnset -> pure Nothing+    EnvValue value -> pure (Just value)+    EnvUnpairedSurrogate ->+      failWith ("error: " <> TE.decodeLatin1 name <> " holds an unpaired UTF-16 surrogate, which has no UTF-8 form")++-- | A variable naming a directory or a list of them, as a host path.+configVariablePath :: BS.ByteString -> IO (Maybe OsPath)+configVariablePath name = configVariable name >>= traverse (variableHostPath name)++-- | A variable's bytes as a host path.  Every value 'configVariable'+-- answers has one, since a Windows value arrives as UTF-8, so the+-- refusal is for completeness.+variableHostPath :: BS.ByteString -> BS.ByteString -> IO OsPath+variableHostPath name value =+  maybe (failWith ("error: " <> TE.decodeLatin1 name <> " is not valid UTF-8, so it names no Windows path")) pure (hostPathFromBytes value)++-- | Where the config files are on this machine.  @NIX_CONF_DIR@ and+-- @XDG_CONFIG_DIRS@ are honoured on every platform; the defaults behind+-- them are the platform's.  Upstream compiles @\/etc\/nix@ in as the+-- system directory and falls back to @\/etc\/xdg@ for the dirs on every+-- platform, Windows included, where neither names anything (a path with+-- no drive resolves against the current drive).  The Windows analogues+-- are chosen here the way the user file's was (@%APPDATA%@ for the XDG+-- config home, the @directory@ package's own mapping): the system file is+-- @%ProgramData%\\nix\\nix.conf@, the all-users application data directory+-- being where Windows keeps machine-wide application configuration (it is+-- also where @directory@ maps the system-wide XDG dirs), and there is no+-- system file when @%ProgramData%@ is unset; the dirs default to none,+-- because the one Windows directory that answers to them is already the+-- system file, and a file read twice applies its @extra-@ settings twice.+-- The config home comes from @directory@ (@~\/.config@ on Unix,+-- @%APPDATA%@ on Windows, @XDG_CONFIG_HOME@ only when it is absolute); the+-- dirs list is filtered the same way, since 'splitSearchPath' turns an+-- empty POSIX entry into @.@, where upstream's tokenizer drops it, and the+-- XDG spec says a relative entry is ignored.  @NIX_CONFIG_HOME@, which+-- takes the config home's place, is carried as its bytes.+configLocations :: IO Config.ConfigLocations+configLocations = do+  confDir <- configVariable nixConfDirVar+  systemConfDir <- platformSystemConfDir+  userFiles <- configVariable nixUserConfFilesVar+  nixConfigHome <- configVariable nixConfigHomeVar+  home <- OsDir.getXdgDirectory OsDir.XdgConfig mempty+  configDirs <- configVariablePath xdgConfigDirsVar+  defaultConfigDirs <- traverse OP.encodeFS platformConfigDirs+  pure+    Config.ConfigLocations+      { Config.clConfDir = confDir,+        Config.clSystemConfDir = systemConfDir,+        Config.clUserConfFiles = userFiles,+        Config.clNixConfigHome = nixConfigHome,+        Config.clConfigHome = home,+        Config.clConfigDirs = maybe defaultConfigDirs (filter OP.isAbsolute . OP.splitSearchPath) configDirs+      }++-- | The machine-wide config directory the system file is read from unless+-- @NIX_CONF_DIR@ moves it: upstream's @sysconfdir\/nix@ on Unix;+-- @%ProgramData%\\nix@ on Windows, or none when that variable is unset or+-- empty.+platformSystemConfDir :: IO (Maybe OsPath)+platformSystemConfDir = case systemConfDirSource currentHost of+  FixedConfDir dir -> Just . (OP.</> Config.nixConfDirName) <$> OP.encodeFS dir+  EnvConfDir var -> do+    value <- mfilter (not . BS.null) <$> configVariable var+    traverse (fmap (OP.</> Config.nixConfDirName) . variableHostPath var) value++-- | What @XDG_CONFIG_DIRS@ names when it is unset: the spec's default on+-- Unix, nothing on Windows (see 'configLocations').+platformConfigDirs :: [FilePath]+platformConfigDirs = case currentHost of+  WindowsHost -> []+  PosixHost -> posixXdgConfigDirs++-- | A config file's bytes, or why it could not be read: nothing at the+-- path, or something that will not open (a directory, a permission+-- refusal).  The open takes the 'OsPath' itself, so a POSIX name reaches+-- it as the bytes it was spelled from rather than through the locale's+-- codec.  Only 'IOException' is caught: an interrupt must abort the run,+-- not read as an absent file.+readConfigFile :: OsPath -> IO (Either Config.ConfigReadFailure BS.ByteString)+readConfigFile path = do+  result <- try (OsFile.readFile' path) :: IO (Either IOException BS.ByteString)+  pure (either (Left . classify) Right result)+  where+    classify err+      | isDoesNotExistError err = Config.ConfigFileMissing+      | otherwise = Config.ConfigFileUnreadable++-- | A kernel file's bytes, or 'Nothing' when it cannot be read, which+-- upstream's @getMaxCPU@ takes as no limit.  As in 'readConfigFile', the+-- open takes the path's own bytes, and only 'IOException' is caught.+readKernelFile :: OsPath -> IO (Maybe BS.ByteString)+readKernelFile path = do+  result <- try (OsFile.readFile' path) :: IO (Either IOException BS.ByteString)+  pure (either (const Nothing) Just result)++-- | Resolve every launcher before any building starts, so a typo'd path is+-- a configuration error now rather than a build failure after the whole+-- closure has been realized.  A bare name resolves through @PATH@, the way+-- a shell would; anything else has to be an executable file where it says.+checkExecWrappers :: Map.Map T.Text FilePath -> IO (Map.Map T.Text FilePath)+checkExecWrappers = Map.traverseWithKey check+  where+    check system path+      | path == takeFileName path =+          findExecutable path+            >>= maybe (failWith ("--exec-wrapper " <> system <> ": " <> T.pack path <> " is not on PATH")) pure+      | otherwise = do+          there <- doesFileExist path+          if not there+            then failWith ("--exec-wrapper " <> system <> ": " <> T.pack path <> " does not exist")+            else do+              perms <- getPermissions path+              if executable perms+                then pure path+                else failWith ("--exec-wrapper " <> system <> ": " <> T.pack path <> " is not executable")++-- ---------------------------------------------------------------------------+-- Develop commands+-- ---------------------------------------------------------------------------++-- | Start @bash@ with the build environment of the target's derivation,+-- as @nix develop@ does (@CmdDevelop::run@ in develop.cc): capture the+-- environment ('captureEnvironment'), make the script that sets it, refuse+-- what upstream refuses only once it has, in its words and order, write the+-- structured attributes' files and the rcfile, and replace this process with+-- the shell ("Nix.Develop.Shell").  Upstream makes the rcfile, the files'+-- directory and the files before its three refusals (@CmdDevelop::run@, the+-- last two in @MixEnvironment::setEnviron@ in command.cc), and when one is+-- made leaves the rcfile behind, empty; here the directory is removed then,+-- and the rcfile and the files are written only once all three have passed.+-- The directory is removed too when there are no files to write, where+-- upstream leaves it empty.  The files it holds under structured attributes+-- outlive the shell, as upstream's do, since nothing is left after the exec+-- to remove them.+developCommand :: NixConfig -> CliOpts -> CommandStore -> FilePath -> Target -> Maybe T.Text -> DevelopArgs -> IO ()+developCommand config opts store dataDir target attrPath args = do+  host <- hostOrRefuse+  command <- traverse (traverse (commandLineBytes "--command")) (daCommand args)+  phase <- traverse (commandLineBytes "--phase") (daPhase args)+  changes <- environmentChanges args+  (gcroot, environment) <- captureEnvironment "develop" config opts store dataDir target attrPath+  cwd <- getCurrentDirectory >>= filePathBytes+  bracketOnError (makeTemporaryDirectory host developDirectoryPrefix) removeHostPath $ \attrsDir -> do+    script <- either failError pure (environmentScript (ScriptDirectories cwd attrsDir) environment)+    mode <- either failError pure (shellModeFor command phase (promptFor config))+    caller <- processEnvironment host+    shellEnv <- either failError pure (shellEnvironment changes (TE.encodeUtf8 (storePathToText (commandStoreDir store) gcroot)) caller)+    writeScriptFiles script+    when (null (scriptFiles script)) (removeHostPath attrsDir)+    bracketOnError (createRcfile host (\path -> renderRcfile (Shell path mode bashProgram) script)) removeHostPath $ \rcfile -> do+      started <- try (replaceProcess host (shellArguments mode rcfile) shellEnv)+      either (failWith . execFailure) absurd started+  where+    execFailure :: IOException -> T.Text+    execFailure failure = "error: unable to execute '" <> TE.decodeLatin1 bashProgram <> "': " <> T.pack (ioe_description failure)++-- | Print the script that sets the build environment of the target's+-- derivation, or with @--json@ the environment, as @nix print-dev-env@+-- does (@CmdPrintDevEnv@ in develop.cc).  The script names the structured+-- attributes' files in a temporary directory that is removed once it is+-- printed, as upstream removes it.  The script is followed by a newline, as+-- upstream's @writeToStdout@ writes it, and the JSON is printed as+-- 'printJson' prints it.+printDevEnvCommand :: NixConfig -> CliOpts -> CommandStore -> FilePath -> Target -> Maybe T.Text -> DevEnvFormat -> JsonLayout -> IO ()+printDevEnvCommand config opts store dataDir target attrPath format layout = do+  host <- hostOrRefuse+  (_, environment) <- captureEnvironment "print-dev-env" config opts store dataDir target attrPath+  case format of+    DevEnvJson -> printJson layout (buildEnvironmentJson environment)+    DevEnvScript -> do+      cwd <- getCurrentDirectory >>= filePathBytes+      bracket (makeTemporaryDirectory host printDirectoryPrefix) removeHostPath $ \attrsDir -> do+        script <- either failError pure (environmentScript (ScriptDirectories cwd attrsDir) environment)+        writeScriptFiles script+        toStdout (BS.putStr (scriptText script <> "\n"))++-- | What upstream names the directories of the structured attributes'+-- files, for @develop@ and for @print-dev-env@ (@CmdDevelop::run@ and+-- @CmdPrintDevEnv::run@ in develop.cc).+developDirectoryPrefix, printDirectoryPrefix :: BS.ByteString+developDirectoryPrefix = "nix-develop"+printDirectoryPrefix = "nix-dev-env"++-- | The t'DevelopHost' for this host, the command failing where it has none.+hostOrRefuse :: IO DevelopHost+hostOrRefuse = either failError pure developHost++promptFor :: NixConfig -> Prompt+promptFor config = Prompt (ncBashPrompt config) (ncBashPromptPrefix config) (ncBashPromptSuffix config)++-- | The environment flags' names and values as their bytes.+environmentChanges :: DevelopArgs -> IO EnvironmentChanges+environmentChanges args =+  EnvironmentChanges (daEnvironmentBase args)+    <$> names "--keep-env-var" (daKeep args)+    <*> names "--unset-env-var" (daUnset args)+    <*> (Map.fromList <$> traverse assignment (Map.toList (daSet args)))+  where+    names flagName = fmap Set.fromList . traverse (commandLineBytes flagName) . Set.toList+    assignment (name, value) = (,) <$> commandLineBytes "--set-env-var" name <*> commandLineBytes "--set-env-var" value++writeScriptFiles :: EnvironmentScript -> IO ()+writeScriptFiles = mapM_ (\file -> bytesHostPath (scriptFilePath file) >>= (`OsFile.writeFile'` scriptFileContents file)) . scriptFiles++-- | Remove a temporary file, or a directory with what it holds, passing+-- over one already gone.+removeHostPath :: BS.ByteString -> IO ()+removeHostPath path = bytesHostPath path >>= OsDir.removePathForcibly++-- | The host path a path's bytes name ('hostPathFromBytes').+bytesHostPath :: BS.ByteString -> IO OsPath+bytesHostPath path = maybe (failWith ("error: '" <> TE.decodeUtf8Lenient path <> "' is not valid UTF-8, so it names no Windows path")) pure (hostPathFromBytes path)++-- | The build environment of the target's derivation, captured as+-- upstream's @nix develop@ captures it (@getDerivationEnvironment@ in+-- develop.cc), and the store path of the output it was read from.  The target+-- is evaluated in a read-write session as @build@ evaluates it; the capture+-- of its derivation is made in that session ('recordCapture'), and what the+-- session made is added and every output of the capture realised, as @build@+-- adds and realises, so its inputs are built or substituted, and a capture+-- already valid is not built again.  A failure stops the command as it stops+-- @build@.  The store has closed by the time this returns.+captureEnvironment :: T.Text -> NixConfig -> CliOpts -> CommandStore -> FilePath -> Target -> Maybe T.Text -> IO (StorePath, BuildEnvironment)+captureEnvironment commandName config opts store dataDir target attrPath = do+  refuseUpstreamManaged commandName store+  script <- readGetEnvScript dataDir+  scriptPath <- either (failWith . ("error: " <>) . badStorePathText) pure (getEnvScriptPath script)+  withCommandStore store config opts (buildConfigFor config opts) $ \ops -> do+    (capture, evalObjects) <-+      evalTarget config opts storeDir (ReadWriteSession ops) dataDir target attrPath $ \st val -> do+        drvSP <- derivationPath val+        drv <- readIORef (esDrvClosure st) >>= (`recordedDerivation` drvSP)+        name <- maybe (failWith ("error: '" <> storePathToText defaultStoreDir drvSP <> "' is not a derivation's path")) pure (T.stripSuffix drvSuffix (spName drvSP))+        capture <- evalOrExit st (recordCapture script scriptPath name drv) >>= either (failWith . ("error: " <>) . captureFailureMessage) pure+        (,) capture <$> sessionObjects st+    let captured = drvFileDerivation capture+    outcome <- runExceptT $ do+      ExceptT (first AddRefused <$> soAddEvalObjects ops evalObjects)+      ExceptT (first BuildStopped <$> soBuild ops [(drvFilePath capture, Set.fromList (map doName (drvOutputs captured)))])+    either reportStop pure outcome+    readEnvironment storeDir captured+  where+    storeDir = commandStoreDir store+    drvSuffix = ".drv"++-- | The capture of a derivation whose @.drv@ is named @name.drv@+-- ('captureDerivation'), with @get-env.sh@ written to the store and the+-- capture's @.drv@ recorded, so that adding what the session made adds+-- both, as upstream adds the script and writes the capture+-- (@getDerivationEnvironment@ in develop.cc).  A derivation the capture+-- refuses writes nothing, as upstream refuses its builder before adding the+-- script.  The input derivations' modulo hashes are the session's, which+-- evaluating the target computed.+recordCapture :: BS.ByteString -> StorePath -> T.Text -> Derivation -> EvalIO (Either CaptureFailure DrvFile)+recordCapture script scriptPath name drv = do+  inputHashes <- inputModuloHashes (drvInputDrvs drv)+  case captureDerivation scriptPath name inputHashes drv of+    Left failure -> pure (Left failure)+    Right capture -> do+      void (writeToStore getEnvScriptName (getEnvScriptContents script) [])+      recordDrvAterm (storePathToText defaultStoreDir (drvFilePath capture)) (drvFileATerm capture)+      pure (Right capture)++-- | Upstream's @get-env.sh@, from the data directory, where the package+-- installs it and a release archive ships it.+readGetEnvScript :: FilePath -> IO BS.ByteString+readGetEnvScript dataDir = do+  attempt <- try (BS.readFile (dataDir </> getEnvScriptFile))+  case attempt of+    Left (failure :: IOException) -> failWith ("error: cannot read get-env.sh: " <> T.pack (displayException failure))+    Right script -> pure script++-- | Where @get-env.sh@ is, relative to the data directory.+getEnvScriptFile :: FilePath+getEnvScriptFile = "develop" </> "get-env.sh"++-- | The environment a built capture holds, and the store path of the+-- output it is read from: the one 'environmentOutput' picks, read and+-- parsed as upstream's @getBuildEnvironment@ reads it (develop.cc).+readEnvironment :: StoreDir -> Derivation -> IO (StorePath, BuildEnvironment)+readEnvironment storeDir capture = do+  objects <- traverse (\output -> (,) (doName output) <$> outputObject (storePathToFilePath storeDir (doPath output))) (drvOutputs capture)+  output <-+    maybe (failWith ("error: " <> noEnvironmentMessage)) pure $+      environmentOutput (Map.fromList objects) >>= \name -> find ((== name) . doName) (drvOutputs capture)+  bytes <- BS.readFile (storePathToFilePath storeDir (doPath output))+  either (failWith . ("error: " <>)) (pure . (,) (doPath output)) (parseBuildEnvironment bytes)++-- | What an output's root is, as upstream's @maybeLstat@ answers: a link+-- is not followed.+outputObject :: FilePath -> IO OutputObject+outputObject path = do+  link <- pathIsSymbolicLink path+  regular <- if link then pure False else doesFileExist path+  if regular then RegularFile . fromIntegral <$> getFileSize path else pure NotRegularFile++-- ---------------------------------------------------------------------------+-- Push command+-- ---------------------------------------------------------------------------++-- | Push the closure of the selected store paths to a binary cache: a+-- nova-cache server, or a directory.  A store opened directly is read+-- from its database; one reached through a daemon is asked for each+-- path's record, and its files are read from the store's directory+-- ('withDaemonPushSource').+pushCommand :: NixConfig -> CliOpts -> CommandStore -> PushArgs -> IO ()+pushCommand config opts store pushArgs = do+  url <- maybe (failWith "push: --cache URL is required") pure (paCacheUrl pushArgs)+  target <- either (failWith . ("push: " <>)) pure (pushTarget url (paKeyFile pushArgs) (paSecretKeyFile pushArgs))+  case (paAll pushArgs, paPaths pushArgs) of+    (True, _ : _) -> failWith "push: --all and explicit paths are mutually exclusive"+    (False, []) -> failWith "push: name store paths to push, or pass --all"+    _ -> pure ()+  compression <- case paCompressionArg pushArgs of+    Nothing -> pure PushNone+    Just value -> either (failWith . ("push: " <>)) pure (parsePushCompression (T.pack value))+  push <- case target of+    ServerTarget cacheUrl apiKeyFile -> do+      apiKey <- traverse (loadKeyFile >=> either failWith pure) apiKeyFile+      pure $+        pushPaths+          PushConfig+            { pcCacheUrl = cacheUrl,+              pcApiKey = apiKey,+              pcCompression = compression,+              pcPartSize = defaultPartSize,+              pcRetry = settingsFetchRetry config+            }+    DirectoryTarget dir secretKeyFile -> do+      secretKey <- loadSecretKeyFile secretKeyFile >>= either failWith pure+      pure (pushToDirectory (DirectoryPush dir secretKey compression))+  logger <- cliLogger+  case store of+    LocalCommandStore dir -> bracket (openStore logger dir) closeStore (pushFromSource push pushArgs . localPushSource)+    DaemonCommandStore address dir assigned storeSetting ->+      withDaemonPushSource (daemonStoreConfig address dir assigned storeSetting config opts logger) (dialDaemon address) (pushFromSource push pushArgs)++-- | Resolve the paths a push is for in a source and push them, reporting+-- the outcome.+pushFromSource :: (PushSource -> [StorePath] -> IO (Either T.Text PushSummary)) -> PushArgs -> PushSource -> IO ()+pushFromSource push pushArgs source =+  resolvePushRoots source pushArgs >>= \case+    Left err -> failWith err+    Right roots ->+      push source roots >>= \case+        Left err -> failWith (pushFailed err)+        Right summary ->+          toStdout . TIO.putStrLn $+            "pushed "+              <> T.pack (show (psPushed summary))+              <> " path(s), "+              <> T.pack (show (psSkipped summary))+              <> " already cached"++-- | Delete store paths: registration rows and on-disk trees.  Every+-- argument is resolved before anything is touched; one+-- 'deleteStorePaths' call then deletes the paths in argument order+-- under one collector lock and one live set, printing a line for each+-- as it goes, with upstream's roots line printed once per invocation as+-- its @--delete@ prints it, and the first failure stops the run, so a+-- reference chain deletes leaf-first in one invocation.+storeDeleteCommand :: StoreDir -> [String] -> IO ()+storeDeleteCommand storeDir rawPaths = do+  targets <- either (failWith . prefixed) pure (traverse (resolveDeleteTarget storeDir . T.pack) rawPaths)+  logger <- cliLogger+  store <- openStore logger storeDir+  result <- deleteStorePaths store targets reportDeleted+  closeStore store+  either (failWith . prefixed) pure result+  where+    prefixed err = "store delete: " <> err+    reportDeleted name removed = toStdout (TIO.putStrLn ("deleted " <> storeEntryNameText name <> describeOutcome removed))+    describeOutcome removed+      | doRowRemoved removed && doTreeRemoved removed = ""+      | doRowRemoved removed = " (no tree on disk)"+      | otherwise = " (unregistered tree)"++-- | Collect garbage, or list the roots.  The summary line is upstream's+-- (@PrintFreed@), on stdout; the progress lines come from the library on+-- stderr.  @--print-roots@ lists @LINK -> PATH@ sorted, each once, as+-- @nix-store --gc --print-roots@ does, and deletes nothing; it runs+-- under the handle's own lease, as upstream's listing takes no+-- collector lock, so it does not wait behind a running build.+storeGcCommand :: StoreDir -> Bool -> IO ()+storeGcCommand storeDir printRoots = do+  logger <- cliLogger+  store <- openStore logger storeDir+  if printRoots+    then do+      roots <- findRoots store+      closeStore store+      toStdout (mapM_ (\root -> TIO.putStrLn (T.pack (grLink root) <> " -> " <> grPath root)) roots)+    else do+      results <- collectGarbage store Set.empty+      closeStore store+      either (failWith . ("store gc: " <>)) (toStdout . TIO.putStrLn . gcSummaryLine) results++-- ---------------------------------------------------------------------------+-- The daemon+-- ---------------------------------------------------------------------------++-- | Serve the store over the daemon's socket, or on Windows its named+-- pipe, until the process is stopped, holding it open all the while.  A+-- store upstream Nix's database also manages is refused first, since the+-- daemon serves the store in upstream's daemon's place.  Paths go over+-- the wire under @\/nix\/store@, the directory every store path is+-- computed under, wherever the store's files are, as upstream's daemon+-- names the paths of a store whose files are elsewhere by its logical+-- directory.+daemonCommand :: NixConfig -> StoreDir -> TrustOverride -> Maybe String -> IO ()+daemonCommand config storeDir trust socketPathArg = do+  upstreamManagedRefusal ReplacesUpstreamPaths storeDir >>= mapM_ (failWith . ("daemon: " <>))+  socketPath <- maybe daemonSocketPath socketPathBytes socketPathArg+  auth <- authSettingsFor config+  logger <- cliLogger+  bracket (openStore logger storeDir) closeStore $ \store -> do+    defaults <- machineDefaults readKernelFile+    served <- newServedStore defaults store+    let server =+          ServerConfig+            { scStoreDir = defaultStoreDir,+              scVersion = Version latestVersionNumber (Set.singleton featureRealisationWithPath),+              scNixVersion = BC.pack versionLine,+              scVerbosity = daemonVerbosity,+              scConfig = config+            }+    listener <- openListener socketPath >>= either (failWith . ("daemon: " <>)) pure+    serveListener logger (DaemonOptions trust auth (serveLocal served server)) listener `finally` closeListener listener+  where+    socketPathBytes arg = argumentBytes arg >>= maybe (failWith ("daemon: the socket path '" <> T.pack arg <> "' has no spelling as bytes")) pure++-- | How much the daemon tells a client that has not set its own+-- verbosity: upstream's default, the info level.+daemonVerbosity :: Verbosity+daemonVerbosity = Verbosity 3++-- ---------------------------------------------------------------------------+-- Profile commands+-- ---------------------------------------------------------------------------++-- | Where the link to the default profile is, as nix.conf's+-- @use-xdg-base-directories@ says.+profileLinkPlace :: NixConfig -> ProfileLinkPlace+profileLinkPlace config+  | ncUseXdgBaseDirectories config = StateProfileLink+  | otherwise = HomeProfileLink++-- | The profile a profile command works on.  The default profile is+-- resolved first, its directory and its link made when they are missing,+-- whether or not @--profile@ names another, as upstream's+-- @MixDefaultProfile@ resolves it (command.cc); a profile @--profile@ names+-- is made absolute without reading a link (@MixProfile::updateProfile@ in+-- command.cc).+chosenProfile :: NixConfig -> ProfileSelection -> IO OsPath+chosenProfile config selection = do+  env <- cliLogger >>= readProfileEnvironment >>= either failError pure+  defaulted <- resolveDefaultProfile (profileLinkPlace config) env >>= either failError pure+  case selection of+    DefaultProfile -> pure defaulted+    ProfileAt raw -> do+      bytes <- commandLineBytes "--profile" raw+      path <- maybe (failError "--profile is not valid UTF-8, so it names no Windows path") pure (hostPathFromBytes bytes)+      cwd <- OsDir.getCurrentDirectory+      pure (absolutePath cwd path)++-- | Add a package to a profile: the store path a file argument leads to,+-- or the target's derivation, built for the outputs it installs, named+-- after its paths and at the priority @--priority@ gives.  A store+-- directory upstream Nix's database also manages is refused before+-- anything is evaluated, as a build refuses one, when the store is opened+-- directly.+profileAddCommand :: NixConfig -> CliOpts -> CommandStore -> FilePath -> Target -> Maybe T.Text -> ProfileSelection -> Maybe String -> IO ()+profileAddCommand config opts store dataDir target attrPath selection priorityArg = do+  refuseUpstreamManaged "profile add" store+  priority <- maybe (pure defaultPriority) priorityValue priorityArg+  profile <- chosenProfile config selection+  -- The profile's store and its manifest are checked before anything is+  -- evaluated, as upstream reads the manifest before it builds+  -- (CmdProfileAdd::run in profile.cc), so another store's profile,+  -- nix-env's, or a manifest that cannot be read is refused before a build.+  -- Each attempt at the change checks them again.+  checkProfileStore storeDir profile >>= either (failError . profileFailureText storeDir) pure+  readManifest profile >>= either (failError . profileFailureText storeDir) (const (pure ()))+  logger <- cliLogger+  outcome <- withCommandStore store config opts (buildConfigFor config opts) $ \ops -> do+    paths <- addedPaths config opts storeDir dataDir ops target attrPath+    let element = Element paths Active priority Nothing+    updateProfile logger ops storeDir profile (pure . Changed . addElement (elementIdentifier element) element)+  either (failError . profileFailureText storeDir) (const (pure ())) outcome+  where+    storeDir = commandStoreDir store++-- | A @--priority@ value: an int, with an optional sign, as upstream reads+-- one (@string2IntWithUnitPrefix@ in util.hh), refused in its words+-- otherwise.  Upstream also takes a binary unit suffix and narrows a 64-bit+-- value into an int; neither is taken here.+priorityValue :: String -> IO Int+priorityValue raw = maybe (failError ("'" <> T.pack raw <> "' is not an integer")) pure parsed+  where+    parsed = do+      value <- case raw of+        '-' : digits -> negate <$> decimal digits+        '+' : digits -> decimal digits+        digits -> decimal digits+      if value >= toInteger (minBound :: Int32) && value <= toInteger (maxBound :: Int32) then Just (fromInteger value) else Nothing+    decimal digits+      | not (null digits), all isDigit digits = readMaybe digits+      | otherwise = Nothing++-- | The store paths @profile add@ adds: the store path a file argument+-- leads to, in itself or through its links, when no attribute is selected+-- (upstream's @followLinksToStorePath@ in store-api.cc), which must be valid;+-- otherwise the outputs the target's derivation installs+-- ('installedOutputs'), built.+addedPaths :: NixConfig -> CliOpts -> StoreDir -> FilePath -> StoreOps IO -> Target -> Maybe T.Text -> IO (Set.Set StorePath)+addedPaths config opts storeDir dataDir ops target attrPath = do+  inStore <- case (target, attrPath) of+    (TargetFile raw, Nothing) -> storePathLedTo storeDir raw+    _ -> pure Nothing+  case inStore of+    Just path -> do+      held <- sqValidPaths (soQueries ops) (Set.singleton path)+      if Set.member path held+        then pure (Set.singleton path)+        else failError ("path '" <> T.pack (storePathToFilePath storeDir path) <> "' is not valid")+    Nothing -> builtOutputs config opts storeDir dataDir ops target attrPath++-- | How many links 'storePathLedTo' follows before it gives up, as+-- upstream's @followLinksToStore@ does (store-api.cc, from 2.34.9).+maxLinkFollows :: Int+maxLinkFollows = 1024++-- | The store path a path argument is in, made absolute against the+-- working directory without reading a link and then followed through+-- links until it is in the store, by the store's own spelling; 'Nothing'+-- when it reaches something in no store.+storePathLedTo :: StoreDir -> FilePath -> IO (Maybe StorePath)+storePathLedTo storeDir raw = do+  bytes <- commandLineBytes "PATH" raw+  start <- maybe (failError "PATH is not valid UTF-8, so it names no Windows path") pure (hostPathFromBytes bytes)+  cwd <- OsDir.getCurrentDirectory+  follow maxLinkFollows (absolutePath cwd start)+  where+    follow remaining path = do+      spelled <- OP.decodeFS path+      case parseStorePathPrefix storeDir (T.pack spelled) of+        Just sp -> pure (Just sp)+        Nothing -> do+          probed <- try (OsDir.pathIsSymbolicLink path)+          case probed of+            Right True+              | remaining <= 0 -> failError ("too many symbolic links encountered while resolving '" <> T.pack raw <> "'")+              | otherwise -> OsDir.getSymbolicLinkTarget path >>= follow (remaining - 1) . absolutePath (OP.takeDirectory path)+            Right False -> pure Nothing+            Left (_ :: IOException) -> pure Nothing++-- | Evaluate the target to a derivation and build it for the outputs it+-- installs, as @build@ evaluates and builds one, and give their paths.+builtOutputs :: NixConfig -> CliOpts -> StoreDir -> FilePath -> StoreOps IO -> Target -> Maybe T.Text -> IO (Set.Set StorePath)+builtOutputs config opts storeDir dataDir ops target attrPath = do+  (drvSP, outputs, evalObjects) <-+    evalTarget config opts storeDir (ReadWriteSession ops) dataDir target attrPath $ \st val -> do+      drvSP <- derivationPath val+      outputs <- evalOrExit st (installedOutputs val)+      (,,) drvSP outputs <$> sessionObjects st+  drv <- recordedDerivation (eoDerivations evalObjects) drvSP+  paths <- traverse (namedOutputPath drv) (Set.toList outputs)+  outcome <- runExceptT $ do+    ExceptT (first AddRefused <$> soAddEvalObjects ops evalObjects)+    ExceptT (first BuildStopped <$> soBuild ops [(drvSP, outputs)])+  either reportStop (const (pure (Set.fromList paths))) outcome++-- | The outputs @profile add@ installs of a derivation, as upstream's+-- @queryOutputs(false, true)@ chooses them (get-drvs.cc), and @out@ when that+-- chooses none (@InstallableAttrPath::toDerivedPaths@ in+-- installable-attr-path.cc): the output @outputName@ names when+-- @outputSpecified@ is true; else those @meta.outputsToInstall@ names, when+-- it passes upstream's @checkMeta@ (through @queryMeta@ in get-drvs.cc); else+-- every output @outputs@ lists, or @out@ when there is no @outputs@.+installedOutputs :: NixValue -> EvalIO (Set.Set T.Text)+installedOutputs val = case val of+  VAttrs attrs -> do+    outputs <- attrSetLookup "outputs" attrs >>= maybe (pure (Set.singleton outName)) (force >=> outputNames)+    specified <- attrSetLookup "outputSpecified" attrs >>= maybe (pure False) (force >=> boolean "the 'outputSpecified' attribute of a derivation")+    chosen <-+      if specified+        then do+          selected <- attrSetLookup "outputName" attrs >>= maybe (pure "") (force >=> text "the output name of a derivation")+          if Set.member selected outputs+            then pure (Set.singleton selected)+            else throwEvalError ("derivation does not have output '" <> selected <> "'")+        else toInstall attrs outputs+    pure (if Set.null chosen then Set.singleton outName else chosen)+  _ -> pure (Set.singleton outName)+  where+    outName = "out"+    outputNames value = case value of+      VList items -> clistThunks items >>= fmap Set.fromList . traverse (force . Thunk >=> text "the name of an output of a derivation")+      other -> throwEvalError ("expected a list but found " <> typeName other <> " while evaluating the 'outputs' attribute of a derivation")+    toInstall attrs outputs =+      attrSetLookup "meta" attrs >>= \case+        Nothing -> pure outputs+        Just metaThunk ->+          force metaThunk >>= \case+            VAttrs meta ->+              attrSetLookup "outputsToInstall" meta >>= \case+                Nothing -> pure outputs+                Just listed -> do+                  value <- force listed+                  usable <- checkMeta value+                  if not usable then pure outputs else namedIn outputs value+            other -> throwEvalError ("expected a set but found " <> typeName other <> " while evaluating the 'meta' attribute of a derivation")+    namedIn outputs value = case value of+      VList items -> clistThunks items >>= fmap Set.fromList . traverse (force . Thunk >=> installed outputs)+      _ -> badOutputsToInstall+    installed outputs value = case value of+      VStr bytes _+        | Right name <- TE.decodeUtf8' bytes, Set.member name outputs -> pure name+      _ -> badOutputsToInstall+    badOutputsToInstall = throwEvalError "this derivation has bad 'meta.outputsToInstall'"+    boolean what value = case value of+      VBool b -> pure b+      other -> throwEvalError ("expected a Boolean but found " <> typeName other <> " while evaluating " <> what)+    text what value = case value of+      VStr bytes _ | Right decoded <- TE.decodeUtf8' bytes -> pure decoded+      other -> throwEvalError ("expected a string but found " <> typeName other <> " while evaluating " <> what)++-- | Whether a @meta@ value is one upstream reads (@checkMeta@ in+-- get-drvs.cc): an int, a Boolean, a string or a float, or a list of such+-- values, or a set of them that is not a derivation, which has an @outPath@.+checkMeta :: NixValue -> EvalIO Bool+checkMeta value = case value of+  VList items -> clistThunks items >>= allChecked . map Thunk+  VAttrs attrs ->+    attrSetLookup "outPath" attrs >>= \case+      Just _ -> pure False+      Nothing -> attrSetElems attrs >>= allChecked+  VInt _ -> pure True+  VBool _ -> pure True+  VStr _ _ -> pure True+  VFloat _ -> pure True+  _ -> pure False+  where+    allChecked thunks = case thunks of+      [] -> pure True+      thunk : rest -> force thunk >>= checkMeta >>= \ok -> if ok then allChecked rest else pure False++-- | Take packages off a profile, as the matchers select them.  A store+-- directory upstream Nix's database also manages is refused first, when+-- the store is opened directly.+profileRemoveCommand :: NixConfig -> CliOpts -> CommandStore -> ProfileSelection -> RemoveSelection -> IO ()+profileRemoveCommand config opts store selection removals = do+  refuseUpstreamManaged "profile remove" store+  selector <- case removals of+    RemoveAll -> pure SelectAll+    RemoveSome matchers -> SelectSome <$> traverse (removalMatcher storeDir) matchers+  profile <- chosenProfile config selection+  logger <- cliLogger+  outcome <- withCommandStore store config opts (pure . defaultBuildConfig) $ \ops -> updateProfile logger ops storeDir profile (removing selector)+  either (failError . profileFailureText storeDir) (const (pure ())) outcome+  where+    storeDir = commandStoreDir store+    warn = TIO.hPutStrLn stderr . ("warning: " <>)+    -- Upstream's lines (CmdProfileRemove::run in profile.cc): each element+    -- taken off, then the counts.+    removing selector manifest@(Manifest elements) = do+      let Selection names warnings = selectElements selector manifest+      mapM_ warn warnings+      if Set.null names+        then Unchanged <$ warn "No packages to remove. Use 'nova-nix profile list' to see the current profile."+        else do+          let kept = Map.withoutKeys elements names+          mapM_ (\element -> TIO.hPutStrLn stderr ("removing '" <> elementIdentifier element <> "'")) (Map.restrictKeys elements names)+          TIO.hPutStrLn stderr ("removed " <> T.pack (show (Map.size elements - Map.size kept)) <> " packages, kept " <> T.pack (show (Map.size kept)) <> " packages")+          pure (Changed (Manifest kept))++-- | What a @profile remove@ selector matches (the @MixProfileElementMatchers@+-- constructor in profile.cc): a number is refused, as upstream refuses an+-- index, in words of nova-nix's own, since upstream's say it no longer takes+-- one, which describes upstream's history and not nova-nix's; a store path,+-- in the canonical spelling or the store's own, selects the elements holding+-- it; any other word, the element of that name.  A pattern that does not+-- compile is refused before the profile is read.+removalMatcher :: StoreDir -> RemoveMatcher -> IO Matcher+removalMatcher storeDir removal = case removal of+  RemoveRegex raw -> do+    regex <- argumentText "--regex" raw+    maybe (failError ("invalid regular expression '" <> regex <> "'")) pure (regexMatcher regex)+  RemoveNamed raw -> do+    named <- argumentText "NAME" raw+    case indexNumber raw of+      Just index -> failError ("'nova-nix profile' does not support indices ('" <> T.pack (show index) <> "')")+      Nothing -> pure (maybe (MatchName named) MatchStorePath (parseStorePath storeDir named <|> parseStorePath defaultStoreDir named))+  where+    -- Upstream's string2Int<size_t>: digits after an optional '+', within+    -- 64 bits (util.cc).+    indexNumber arg = do+      value <- case arg of+        '+' : digits -> decimal digits+        digits -> decimal digits+      if value <= toInteger (maxBound :: Word64) then Just value else Nothing+    decimal :: String -> Maybe Integer+    decimal digits+      | not (null digits), all isDigit digits = readMaybe digits+      | otherwise = Nothing++-- | A command-line argument's text, refused when it is not UTF-8.+argumentText :: T.Text -> String -> IO T.Text+argumentText what arg = commandLineBytes what arg >>= either (const (failError (what <> " is not valid UTF-8"))) pure . TE.decodeUtf8'++-- | Print a new secret key with the given name, and no line feed after it,+-- as @nix key generate-secret@ prints one ("Nix.Key").+keyGenerateSecretCommand :: String -> IO ()+keyGenerateSecretCommand keyName = do+  name <- commandLineBytes "--key-name" keyName+  secretKey <- generateSecretKey name+  printBytes (renderSecretKey secretKey)++-- | Read a secret key from stdin, every byte as it arrives, and print its+-- public key with no line feed after it, as @nix key+-- convert-secret-to-public@ does.  A key that does not read is refused in+-- upstream's words, with status 1.+keyConvertSecretToPublicCommand :: IO ()+keyConvertSecretToPublicCommand = do+  hSetBinaryMode stdin True+  spelled <- BS.hGetContents stdin+  case parseSecretKey spelled of+    Left refusal -> do+      BS.hPut stderr (keyRefusalMessage refusal <> "\n")+      exitWith (ExitFailure 1)+    Right secretKey -> printBytes (renderPublicKey secretKey)++-- | Write bytes to stdout as they are, flushed here, so a reader that went+-- away ends the command quietly ('toStdout') rather than at exit.+printBytes :: BS.ByteString -> IO ()+printBytes bytes = toStdout (BS.hPut stdout bytes >> hFlush stdout)++-- | Print what a profile holds: upstream's lines, or with @--json@ its+-- manifest, as 'printJson' prints it.+profileListCommand :: NixConfig -> StoreDir -> ProfileSelection -> ListFormat -> IO ()+profileListCommand config storeDir selection format = do+  profile <- chosenProfile config selection+  -- Upstream lists a profile of any store; here its paths would be+  -- printed under this store's spelling, naming paths it does not hold.+  checkProfileStore storeDir profile >>= either (failError . profileFailureText storeDir) pure+  manifest <- readManifest profile >>= either (failError . profileFailureText storeDir) pure+  case format of+    ListJson layout -> printJson layout (manifestJson manifest)+    ListText -> do+      styling <- stdoutStyling+      toStdout (mapM_ TIO.putStrLn (listLines styling storeDir manifest))++-- | Print each generation of a profile and what changed in it from the+-- one listed before it, as upstream's @profile history@ does.  A+-- generation's lines are printed once its manifest is read, so one that+-- cannot be read stops the command after the lines of those before it.+profileHistoryCommand :: NixConfig -> StoreDir -> ProfileSelection -> IO ()+profileHistoryCommand config storeDir selection = do+  profile <- chosenProfile config selection+  -- Upstream reads the generations of a profile of any store; here they+  -- would be read against a store that does not hold them, as for list.+  checkProfileStore storeDir profile >>= either (failError . profileFailureText storeDir) pure+  (dated, current) <- findGenerations profile >>= either (failError . profileFailureText storeDir) pure+  styling <- stdoutStyling+  let printGeneration previous entry = do+        let generation = datedGeneration entry+        manifest <- readManifest (generationPath generation) >>= either (failError . profileFailureText storeDir) pure+        toStdout (mapM_ TIO.putStrLn (historyLines styling current previous entry manifest))+        pure (Just (generationNumber generation, manifest))+  foldM_ printGeneration Nothing dated++-- | One generation's lines in a profile's history, as upstream prints+-- them: a blank line when a generation was listed before it,+-- @Version N (DATE)@, the date in UTC, then @ <- M@ for that earlier+-- generation and a colon, the number in green for the current generation+-- and in bold for the others, then what changed from the earlier+-- generation's manifest, or from none, each line indented by two spaces.+historyLines :: Styling -> Maybe GenerationNumber -> Maybe (GenerationNumber, Manifest) -> DatedGeneration -> Manifest -> [T.Text]+historyLines styling current previous (DatedGeneration (Generation number _) made) manifest =+  [T.empty | isJust previous]+    ++ ["Version " <> style styling numberStyle <> generationText number <> style styling ansiNormal <> " (" <> generationDate made <> ")" <> maybe T.empty ((" <- " <>) . generationText . fst) previous <> ":"]+    ++ map (indent <>) (if null changes then ["No changes."] else map changeLine changes)+  where+    changes = manifestChanges (maybe emptyManifest snd previous) manifest+    numberStyle+      | Just number == current = ansiGreen+      | otherwise = ansiBold+    indent = "  "++-- | A generation's number, as a message shows it.+generationText :: GenerationNumber -> T.Text+generationText (GenerationNumber n) = T.pack (show n)++-- | Switch a profile to the generation before its current one, or to the+-- one the last @--to@ names, as upstream's @profile rollback@ does.  Every+-- @--to@ is read, in order, and the first that does not read is refused, as+-- upstream reads each as it parses its flags; the default profile is+-- resolved first, as upstream resolves it before it parses them.+profileRollbackCommand :: NixConfig -> StoreDir -> ProfileSelection -> [String] -> Changes -> IO ()+profileRollbackCommand config storeDir selection toArgs changes = do+  profile <- chosenProfile config selection+  numbers <- either failError pure (traverse readGenerationNumber toArgs)+  let target = maybe PreviousGeneration GenerationAt (listToMaybe (reverse numbers))+  checkProfileStore storeDir profile >>= either (failError . profileFailureText storeDir) pure+  logger <- cliLogger+  switchGeneration logger profile target changes >>= either (failError . profileFailureText storeDir) pure++-- | Delete a profile's generations but the current one, or with+-- @--older-than@ those made before its cutoff but the newest of them, as+-- upstream's @profile wipe-history@ does.  The cutoff is taken from the+-- clock as the age is read, before the profile's lock is waited for, as+-- upstream takes it.+profileWipeHistoryCommand :: NixConfig -> StoreDir -> ProfileSelection -> Maybe String -> Changes -> IO ()+profileWipeHistoryCommand config storeDir selection olderThan changes = do+  profile <- chosenProfile config selection+  scope <- case olderThan of+    Nothing -> pure WipeEveryOld+    Just age -> do+      days <- either failError pure (parseOlderThan age)+      now <- currentEpochSeconds+      pure (WipeOlderThan (cutoffBefore now days))+  checkProfileStore storeDir profile >>= either (failError . profileFailureText storeDir) pure+  logger <- cliLogger+  wipeHistory logger profile scope changes >>= either (failError . profileFailureText storeDir) pure++-- | Whether a line printed on stdout keeps the escapes that style it.+data Styling = Styled | Plain++-- | Whether this run's stdout takes the escapes that style a line, as+-- upstream decides for its stdout: never while @NO_COLOR@ or @NOCOLOR@ is+-- set, always while @CLICOLOR_FORCE@ or @FORCE_COLOR@ is, and otherwise+-- when stdout is a terminal and @TERM@ is set to something other than+-- @dumb@.  A variable counts as set whatever its value, an empty one+-- included.+stdoutStyling :: IO Styling+stdoutStyling = do+  uncoloured <- anySet ["NO_COLOR", "NOCOLOR"]+  forced <- anySet ["CLICOLOR_FORCE", "FORCE_COLOR"]+  terminal <- hIsTerminalDevice stdout+  term <- lookupEnvBytes "TERM"+  pure (if not uncoloured && (forced || terminal && rendersColour term) then Styled else Plain)+  where+    anySet = fmap (any (/= EnvUnset)) . traverse lookupEnvBytes+    rendersColour term = case term of+      EnvUnset -> False+      EnvValue value -> value /= "dumb"+      EnvUnpairedSurrogate -> True++-- | An escape as a styled line holds it: itself when stdout takes them,+-- and nothing otherwise, where upstream writes the line with every escape+-- taken out.+style :: Styling -> T.Text -> T.Text+style styling escape = case styling of+  Styled -> escape+  Plain -> T.empty++-- | Print JSON as upstream's @printJSON@ prints it+-- (common-args.cc, from 2.34.9): indented or on one line as the layout says,+-- by default indented when stdout is a terminal, and followed by a newline,+-- as @writeToStdout@ ends what it writes.+printJson :: JsonLayout -> Json -> IO ()+printJson layout json = do+  indented <- case layout of+    IndentedOnTerminal -> hIsTerminalDevice stdout+    Indented -> pure True+    Compact -> pure False+  toStdout (BS.putStr (if indented then renderIndentedJson json else renderJson json <> "\n"))++-- | The escapes upstream sets text in bold, red or green, and back with.+ansiBold, ansiRed, ansiGreen, ansiNormal :: T.Text+ansiBold = "\ESC[1m"+ansiRed = "\ESC[31;1m"+ansiGreen = "\ESC[32;1m"+ansiNormal = "\ESC[0m"++-- | What @profile list@ prints, as upstream prints it: for each element+-- its name, in bold, with @(inactive)@, in red, after an inactive one's,+-- its flake's lines for one a flake made, and its paths as the store spells+-- them, with a blank line between elements.  The escapes are written only+-- where stdout takes them ('stdoutStyling'); a name holding an escape of its+-- own keeps it, where upstream takes every escape out of the line.+listLines :: Styling -> StoreDir -> Manifest -> [T.Text]+listLines styling storeDir (Manifest elements) = intercalate [""] (map elementLines (Map.toAscList elements))+  where+    elementLines (name, element) =+      ("Name:               " <> style styling ansiBold <> name <> style styling ansiNormal <> activity (elementActivity element))+        : maybe [] sourceLines (elementSource element)+        ++ ["Store paths:        " <> T.unwords (sort [T.pack (storePathToFilePath storeDir path) | path <- Set.toList (elementPaths element)])]+    activity Active = ""+    activity Inactive = " " <> style styling ansiRed <> "(inactive)" <> style styling ansiNormal+    sourceLines source =+      [ "Flake attribute:    " <> flakeAttribute source,+        "Original flake URL: " <> sourceOriginalUrl source,+        "Locked flake URL:   " <> sourceUrl source+      ]++-- | A profile's failure in words.  A conflict is upstream's, with+-- nova-nix's commands in its hints (the @BuildEnvFileConflictError@ handler+-- of @CmdProfileAdd::run@ in profile.cc).+profileFailureText :: StoreDir -> ProfileFailure -> T.Text+profileFailureText storeDir failure = case failure of+  ProfileIOFailed reason -> reason+  ManifestFailed path manifestError -> manifestErrorText path manifestError+  NixEnvProfile profile -> "profile " <> quotedPath profile <> " was made by nix-env, whose manifest.nix nova-nix does not read"+  ForeignGeneration profile current ->+    "profile "+      <> quotedPath profile+      <> " is in another store: its current generation, "+      <> quotedPath current+      <> ", is not in the store \""+      <> T.pack (unStoreDir storeDir)+      <> "\"; name that store with --store, or another profile with --profile"+  TreeFailed treeFailure -> buildEnvFailureText treeFailure+  TreeConflict (Conflict (ConflictSide existingFile existingName _) (ConflictSide newFile _ newPaths) priority) ->+    T.concat+      [ "An existing package already provides the following file:\n\n  ",+        quotedPath existingFile,+        "\n\nThis is the conflicting file from the new package:\n\n  ",+        quotedPath newFile,+        "\n\nTo remove the existing package:\n\n  nova-nix profile remove ",+        existingName,+        "\n\nThe new package can also be added next to the existing one by assigning a different priority.\nThe conflicting packages have a priority of ",+        T.pack (show priority),+        ".\nTo prioritise the new package:\n\n  nova-nix profile add ",+        T.unwords (Set.toAscList newPaths),+        " --priority ",+        T.pack (show (priority - 1)),+        "\n\nTo prioritise the existing package:\n\n  nova-nix profile add ",+        T.unwords (Set.toAscList newPaths),+        " --priority ",+        T.pack (show (priority + 1)),+        "\n"+      ]+  StoreRefused reason -> reason+  NoSuchGeneration number -> "profile version " <> generationText number <> " does not exist"+  NoOlderGeneration current -> "no profile version older than the current (" <> generationText (fromMaybe (GenerationNumber 0) current) <> ") exists"+  where+    quotedPath path = "\"" <> hostPathText path <> "\""++-- | Fail with an error as upstream prints one: @error: @ and the message,+-- its later lines indented under the first.+failError :: T.Text -> IO a+failError = failWith . renderEvalFailure . EvalFailure []++-- | Resolve push roots: every valid non-derivation path with @--all@, otherwise+-- each named path.  Named paths may be full store paths in either store-dir+-- form, or a bare @hash-name@ basename.  A named derivation is refused+-- here, with the rule, rather than by the cache's 400 after its NAR has+-- already been uploaded.  A source that cannot list its valid paths fails+-- the push with its reason ('pushFailed').+resolvePushRoots :: PushSource -> PushArgs -> IO (Either T.Text [StorePath])+resolvePushRoots source pushArgs+  | paAll pushArgs = first pushFailed . fmap outputPathsOnly <$> psAllValid source+  | otherwise = pure (traverse parseArgPath (paPaths pushArgs) >>= refuseDerivations)+  where+    refuseDerivations roots = case filter isDerivationPath roots of+      [] -> Right roots+      drv : _ -> Left ("push: " <> storePathBasename drv <> " is a derivation; a binary cache serves build outputs, not recipes")+    -- A path may be spelled with the store's directory, which under+    -- --store is not platformStoreDir, so it parses against it first.+    parseArgPath raw =+      let txt = T.pack raw+          attempts =+            [ parseStorePath (psStoreDir source) txt,+              parseStorePath platformStoreDir txt,+              parseStorePath defaultStoreDir txt,+              -- A bare basename passes the same charset gate as every+              -- other spelling: push targets are real store paths.+              parseStorePathBaseName txt+            ]+       in case catMaybes attempts of+            (sp : _) -> Right sp+            [] -> Left ("not a store path: " <> txt)++-- | A push's failure as the command reports it: the reason, led by+-- @push failed:@.+pushFailed :: T.Text -> T.Text+pushFailed = ("push failed: " <>)++-- | Print an error to stderr and exit.+failWith :: T.Text -> IO a+failWith msg = do+  TIO.hPutStrLn stderr msg+  exitFailure++-- | Fail on source that does not parse or bind.  An unbound variable is an+-- evaluation error upstream, raised before evaluation starts, and reads as+-- one here.+failSource :: SourceError -> IO a+failSource (SyntaxError err) = failWith ("parse error: " <> T.pack (show err))+failSource (UndefinedVariable name) = failWith ("error: " <> undefinedVariableMessage name)++-- ---------------------------------------------------------------------------+-- Output formatting+-- ---------------------------------------------------------------------------++-- | With @--strict@, force everything inside the result before it prints,+-- as nix-instantiate does (@processExpr@ in nix-instantiate.cc).  The value+-- itself is what prints: the IO evaluator keeps each forced value in its+-- cell, where the printer reads it, so a set or list the result holds twice+-- is still one set or list, and prints as repeated the second time.  Without+-- @--strict@, an element or attribute never forced prints as upstream's thunk+-- marker.+finalize :: Bool -> NixValue -> EvalIO NixValue+finalize True val = val <$ deepForce val+finalize False val = pure val++-- | Write an eval result and its newline to stdout as bytes.  A string's+-- payload need not be UTF-8, so nothing on this path decodes or re-encodes+-- it: the handle is put in binary mode, as hPutBuilder asks, and no+-- encoding or newline translation applies.+printResult :: NixValue -> IO ()+printResult val = toStdout $ do+  hSetBinaryMode stdout True+  printed <- printAmbiguous val+  BB.hPutBuilder stdout (printed <> BB.char7 '\n')
cbits/nn_arena.c view
@@ -1,39 +1,17 @@ /*- * nn_arena.c - Batch StablePtr collection from the thunk arena.- *- * The Haskell teardown (Nix.Eval.Arena) needs every Haskell StablePtr the C- * arena holds so it can free them.  These two entry points delegate to the- * single-pass block-list walk in nn_thunk.c (nn_thunk_{count,collect}_- * stableptrs), which is O(total) - index-based iteration via nn_thunk_get- * would be O(total * blocks), since each get re-walks the block list.- *- * StablePtr sources (see nn_thunk.c):- *   1. PENDING/BLACKHOLE: payload = StablePtr Env (knot-tying laziness)- *   2. COMPUTED with val_tag == NN_VALUE_PTR: StablePtr NixValue- * All other COMPUTED payloads (inline scalars, C pointers) are NOT freed.+ * nn_arena.c - Whether every sub-arena of the C data layer is live.  */  #include "nn_arena.h" #include "nn_bytecode.h" #include "nn_env.h"+#include "nn_str.h" #include "nn_symbol.h" #include "nn_thunk.h"  int nn_arena_live(void) {-    return nn_symbol_live() && nn_thunk_live() && nn_env_live()-        && nn_bytecode_live();-}--uint32_t-nn_arena_stableptr_count(void)-{-    return nn_thunk_count_stableptrs();-}--uint32_t-nn_arena_collect_stableptrs(void **output, uint32_t max_count)-{-    return nn_thunk_collect_stableptrs(output, max_count);+    return nn_symbol_live() && nn_str_live() && nn_thunk_live()+        && nn_env_live() && nn_bytecode_live(); }
cbits/nn_arena.h view
@@ -1,44 +1,28 @@ /*- * nn_arena.h - Unified arena lifecycle and StablePtr cleanup.- *- * Provides batch collection of StablePtr payloads from the thunk arena- * for efficient cleanup.  After M6 bytecode integration, PENDING thunks- * hold (bc_idx, StablePtr Env) - the Expr is eliminated, replaced by- * a bytecode index.  COMPUTED/NN_VALUE_PTR thunks hold StablePtr NixValue.- *- * Inline scalar/C-pointer payloads (INT, FLOAT, BOOL, NULL, STR,- * PATH, LIST, ATTRS, CTXSTR) are skipped.- *- * Used by Haskell-side Arena.hs to free all StablePtrs before- * destroying the sub-arenas (thunk, env, symbol, bytecode).+ * nn_arena.h - Whether the C data layer's arenas are live.  *  * nn_arena_live answers whether every sub-arena is inside its init ..- * destroy window.  Outside it, each sub-arena's allocators report- * failure through their ordinary sentinel (NULL, UINT32_MAX,- * NN_SYMBOL_INVALID) instead of touching freed or never-allocated- * state; the Haskell boundary asks this on that failure path to tell a- * missing arenaInit from exhaustion.+ * destroy window, which an evaluation session opens.  Outside it, each+ * sub-arena's allocators report failure through their ordinary sentinel+ * (NULL, UINT32_MAX, NN_SYMBOL_INVALID) instead of touching freed or+ * never-allocated state, and so do the allocators of the objects the+ * arena's teardown frees one by one (nn_tracker.h), which ask it as they+ * add each object to its tracker.+ *+ * The Haskell boundary asks it in three places: after an allocator's+ * failure, to tell a call outside an evaluation session from+ * exhaustion (Nix.Eval.CStatus); as a session starts, to share the+ * arenas of a session already running rather than set up its own+ * (Nix.Eval.IO.withEvalSession); and for a symbol id the table does not+ * hold, to tell a call outside a session from a defect+ * (Nix.Eval.Symbol).  */  #ifndef NN_ARENA_H #define NN_ARENA_H -#include <stdint.h>--/* Bulk-free all tracked attribute sets (called during arena teardown). */-void nn_attrset_free_all(void);--/* Nonzero when the symbol table, thunk arena, env allocator and bytecode- * store are all initialized. */+/* Nonzero when the symbol table, string arena, thunk arena, env+ * allocator and bytecode store are all initialized. */ int nn_arena_live(void);--/* Count how many thunk payloads are StablePtrs (need freeing).- * Iterates all thunks, checks state + val_tag. */-uint32_t nn_arena_stableptr_count(void);--/* Collect StablePtr payloads into `output`.  Writes at most `max_count`- * pointers.  Returns the number actually written.- * Caller must allocate the output buffer. */-uint32_t nn_arena_collect_stableptrs(void **output, uint32_t max_count);  #endif /* NN_ARENA_H */
cbits/nn_assert.h view
@@ -5,12 +5,26 @@ #include <stdlib.h>  /*- * Debug-mode bounds checking.  Compiles to nothing under NDEBUG.- * Use for array accesses, index validation, and invariant checks.+ * An invariant check that holds in every build, NDEBUG or not: a breach+ * prints its message and site and aborts.+ *+ * Each invariant is guarded once, where its bound is known:+ *   - An allocator asserts.  Its NULL means only that it could not+ *     allocate (no live arena, exhaustion, or a size past its limit),+ *     which the Haskell boundary reports as a resource failure, so a+ *     breach must not share it.+ *   - A reader whose caller knows the bound asserts.  The caller checks+ *     a list's length, a set's size or an application's form before it+ *     reads, so a breach is a defect in the caller.+ *   - A reader whose bound only the C side knows answers NULL for a+ *     breach: an index into the bytecode string table, an env+ *     coordinate past its chain or slots, a builtin past the static+ *     cells.  Its Haskell binding raises that NULL as CInvariantViolated+ *     naming the C function, so the defect is reported with its site and+ *     a test can provoke it.+ *   - A function with no NULL to spare, a setter or a reader of a scalar+ *     such as an opcode or a data word, asserts.  */-#ifdef NDEBUG-#define NN_ASSERT(cond, msg) ((void)0)-#else #define NN_ASSERT(cond, msg) \     do { \         if (!(cond)) { \@@ -19,6 +33,5 @@             abort(); \         } \     } while (0)-#endif  #endif /* NN_ASSERT_H */
cbits/nn_attrset.c view
@@ -12,61 +12,38 @@  *   positions: [ 9, 0, 13, 17 ]    (parallel, in the same block)  *   values:    [ p0, p1, p2, p3 ]  (parallel opaque pointers)  *- * This replaces Haskell's Map.Bin tree:+ * A layer (nn_attrset_update) holds a right operand's entries in these+ * arrays and points at its base, the set it sits on; its size counts the+ * names of the whole chain, each once, and a walk over them merges the+ * chain's arrays, the topmost entry of a name winning (cursor_next).+ *+ * Against Haskell's Map.Bin tree:  *   Map.Bin: ~48 bytes/node (constructor + key + value + size + left + right)  *   nn_attrset: ~16 bytes/entry (4-byte key + 4-byte position + 8-byte pointer)- *   For 30k entries: 1.4 MB down to 480 KB (3x reduction, plus cache-friendly)+ *   For 30k entries: 480 KB against 1.4 MB, in one contiguous run  */  #include "nn_attrset.h" #include "nn_assert.h"+#include "nn_region.h"+#include "nn_stats.h"  #include <stdlib.h> #include <string.h> -/* --- Global tracking for bulk cleanup --- */--static nn_attrset_t **g_tracked = NULL;-static uint32_t g_tracked_count = 0;-static uint32_t g_tracked_cap   = 0;--/* Returns 0, or -1 when the tracking array cannot grow. */-static int nn_attrset_track(nn_attrset_t *set)-{-    if (g_tracked_count >= g_tracked_cap) {-        if (g_tracked_cap > UINT32_MAX / 2) return -1;-        uint32_t new_cap = g_tracked_cap ? g_tracked_cap * 2 : 256;-        nn_attrset_t **new_arr = (nn_attrset_t **)realloc(-            g_tracked, (size_t)new_cap * sizeof(nn_attrset_t *));-        if (!new_arr) return -1;-        g_tracked = new_arr;-        g_tracked_cap = new_cap;-    }-    g_tracked[g_tracked_count++] = set;-    return 0;-}--void nn_attrset_free_all(void)-{-    uint32_t i;-    for (i = 0; i < g_tracked_count; i++) {-        nn_attrset_free(g_tracked[i]);-    }-    free(g_tracked);-    g_tracked = NULL;-    g_tracked_count = 0;-    g_tracked_cap = 0;-}+/* Every set allocated, for bulk cleanup. */+static nn_tracker_t g_tracked;  /* --- Internal representation --- */  struct nn_attrset {     nn_symbol_t        *keys;      /* the shared block: capacity keys, then positions */-    uint32_t    *positions;  /* keys + capacity */     void              **values;-    uint32_t     count;     /* entries used */+    const nn_attrset_t *base;      /* the set this one is layered on, or NULL */+    uint32_t            count;     /* entries this set's own arrays hold */     uint32_t            capacity;  /* entries allocated */-    uint32_t     frozen;    /* 1 after freeze, 0 during construction */+    uint32_t            size;      /* entries the set binds, each name once */+    uint32_t            layers;    /* 0 while built, 1 flat, base's + 1 layered */ };  /* --- Internal types --- */@@ -90,6 +67,14 @@     return (size_t)capacity * (sizeof(nn_symbol_t) + sizeof(uint32_t)); } +/* The positions, after the `capacity` keys in the shared block.  The+ * shared empty set has no block, and no positions: an offset from its+ * NULL keys would be undefined. */+static uint32_t *positions_of(const nn_attrset_t *set)+{+    return set->keys ? set->keys + set->capacity : NULL;+}+ /* Double the capacity, stopping at NN_ATTRSET_MAX_ENTRIES; the doubling  * is computed in uint64_t so it cannot wrap.  Returns 0, or -1 with the  * capacity unchanged when the set is at the ceiling or an allocation@@ -114,9 +99,10 @@     memmove(new_keys + new_cap, new_keys + set->capacity,             (size_t)set->count * sizeof(uint32_t));     set->keys = new_keys;-    set->positions = new_keys + new_cap; +    uint64_t before = nn_attrset_bytes(set);     set->capacity = new_cap;+    if (nn_region_mode) nn_region_tracked_grew(nn_attrset_bytes(set) - before);     return 0; } @@ -141,7 +127,9 @@  /* --- Lifecycle --- */ -nn_attrset_t *nn_attrset_new(uint32_t capacity)+/* A tracked set with room for `capacity` entries (0 picks a small+ * default), not yet counted under any site. */+static nn_attrset_t *attrset_alloc(uint32_t capacity) {     nn_attrset_t *set = (nn_attrset_t *)malloc(sizeof(nn_attrset_t));     if (!set) return NULL;@@ -149,270 +137,466 @@     if (capacity == 0) capacity = 8;      set->keys = (nn_symbol_t *)malloc(names_block_bytes(capacity));-    set->positions = set->keys ? set->keys + capacity : NULL;     set->values = (void **)malloc((size_t)capacity * sizeof(void *));+    set->base = NULL;     set->count = 0;     set->capacity = capacity;-    set->frozen = 0;+    set->size = 0;+    set->layers = 0; -    if (!set->keys || !set->values || nn_attrset_track(set) != 0) {+    if (!set->keys || !set->values || nn_tracker_add(&g_tracked, set) != 0) {         free(set->keys);         free(set->values);         free(set);         return NULL;     }+    if (nn_region_mode)+        nn_region_tracked(NN_REGION_SET, set, g_tracked.count - 1, nn_attrset_bytes(set));     return set; } -void nn_attrset_free(nn_attrset_t *set)+/* Count a set just allocated at `site` while the census counts sites+ * (nn_stats.h).  The evaluator sizes every set for the entries it puts+ * in, so its bytes now are its bytes once built. */+static void count_at(uint32_t site, const nn_attrset_t *set, int shareable) {-    if (!set) return;+    if (nn_stats_counting) nn_stats_count_set(site, nn_attrset_bytes(set), shareable);+}++nn_attrset_t *nn_attrset_new(uint32_t capacity, uint32_t site)+{+    nn_attrset_t *set = attrset_alloc(capacity);+    if (set) count_at(site, set, capacity == 0);+    return set;+}++/* Free a set's arrays and the set, and not its values: they are cells+ * the thunk arena owns. */+static void attrset_free(void *object)+{+    nn_attrset_t *set = (nn_attrset_t *)object;     free(set->keys);     free(set->values);     free(set); } +void nn_attrset_free_all(void)+{+    nn_tracker_free_all(&g_tracked, attrset_free);+}++void nn_attrset_sweep(uint32_t from, nn_tracker_keep_t keep, void *ctx)+{+    nn_tracker_sweep(&g_tracked, from, keep, ctx, attrset_free);+}++static nn_attrset_t g_empty_set = { NULL, NULL, NULL, 0, 0, 0, 1 };++nn_attrset_t *nn_attrset_empty(void)+{+    return &g_empty_set;+}+ /* --- Construction --- */  int nn_attrset_insert(nn_attrset_t *set, nn_symbol_t key, void *value, uint32_t pos) {+    NN_ASSERT(set->layers == 0, "nn_attrset_insert: the set is frozen");     if (set->count >= set->capacity && grow(set) != 0) return -1;     set->keys[set->count] = key;-    set->positions[set->count] = pos;+    positions_of(set)[set->count] = pos;     set->values[set->count] = value;     set->count++;+    set->size = set->count;     return 0; } -void nn_attrset_freeze(nn_attrset_t *set)-{-    if (set->frozen) return;--    if (set->count <= 1) {-        set->frozen = 1;-        return;-    }+/* Sets of at most this many entries are sorted by insertion, which needs+ * no allocation; larger ones by qsort over tagged entries. */+#define NN_ATTRSET_INSERTION_SORT_MAX 64u -    /*-     * Sort by key.  We need last-writer-wins for duplicates, but qsort-     * isn't stable.  Strategy: tag each entry with its insertion index,-     * sort by (key, index), then dedup keeping the highest index per key.-     *-     * For small sets (<= 64), use a simple insertion sort that IS stable-     * (avoids the malloc overhead of tagging).-     */-    if (set->count <= 64) {-        /* Stable insertion sort. */-        uint32_t i, j;+/* Insertion-sort the entries by key.  The sort is stable: entries with+ * one key keep the order they were inserted in. */+static void insertion_sort(nn_attrset_t *set)+{+    uint32_t *positions = positions_of(set);+    uint32_t i;     for (i = 1; i < set->count; i++) {-            nn_symbol_t tmpk = set->keys[i];-            uint32_t tmpp = set->positions[i];-            void *tmpv = set->values[i];-            j = i;-            while (j > 0 && set->keys[j - 1] > tmpk) {-                set->keys[j] = set->keys[j - 1];-                set->positions[j] = set->positions[j - 1];-                set->values[j] = set->values[j - 1];-                j--;-            }-            set->keys[j] = tmpk;-            set->positions[j] = tmpp;-            set->values[j] = tmpv;-        }-    } else {-        /*-         * Large set: tag entries with insertion index, qsort by (key, index),-         * then strip tags.  This gives stable sort semantics.-         */-        nn_tagged_entry_t *tagged = (nn_tagged_entry_t *)malloc(-            (size_t)set->count * sizeof(nn_tagged_entry_t));-        if (!tagged) {-            /* Fallback: in-place insertion sort for large sets when malloc-             * fails.  Falls through to the dedup block below. */-            for (uint32_t i = 1; i < set->count; i++) {         nn_symbol_t key = set->keys[i];-                uint32_t pos = set->positions[i];-                void *val = set->values[i];+        uint32_t pos = positions[i];+        void *value = set->values[i];         uint32_t j = i;         while (j > 0 && set->keys[j - 1] > key) {             set->keys[j] = set->keys[j - 1];-                    set->positions[j] = set->positions[j-1];+            positions[j] = positions[j - 1];             set->values[j] = set->values[j - 1];             j--;         }         set->keys[j] = key;-                set->positions[j] = pos;-                set->values[j] = val;+        positions[j] = pos;+        set->values[j] = value;     }-        } else {+}++/* Sort the entries by key with qsort.  qsort is not stable, so each+ * entry is tagged with its insertion index, which orders the entries of+ * one key and makes the sort stable.  Returns 0, or -1 with the set+ * unchanged when the tags cannot be allocated. */+static int tagged_sort(nn_attrset_t *set)+{+    uint32_t *positions = positions_of(set);     uint32_t i;+    nn_tagged_entry_t *tagged = (nn_tagged_entry_t *)malloc(+        (size_t)set->count * sizeof(nn_tagged_entry_t));+    if (!tagged) return -1;     for (i = 0; i < set->count; i++) {         tagged[i].key = set->keys[i];         tagged[i].idx = i;-                tagged[i].pos = set->positions[i];+        tagged[i].pos = positions[i];         tagged[i].value = set->values[i];     }--            /* Sort by key, break ties by insertion index (ascending). */     qsort(tagged, set->count, sizeof(nn_tagged_entry_t), cmp_tagged);-     for (i = 0; i < set->count; i++) {         set->keys[i] = tagged[i].key;-                set->positions[i] = tagged[i].pos;+        positions[i] = tagged[i].pos;         set->values[i] = tagged[i].value;     }     free(tagged);-        }+    return 0; } -    /* Dedup: keep last occurrence of each key (last-writer-wins).-     * After stable sort, duplicates are adjacent with the last insert-     * at the highest index position. */+void nn_attrset_freeze(nn_attrset_t *set) {     uint32_t write = 0;     uint32_t read;+    uint32_t *positions;++    if (set->layers) return;++    /* Stable, so the last insert of a repeated key sorts last of its run.+     * A large set whose tags cannot be allocated is sorted by insertion,+     * slower and in place. */+    if (set->count <= NN_ATTRSET_INSERTION_SORT_MAX || tagged_sort(set) != 0) {+        insertion_sort(set);+    }+    positions = positions_of(set);++    /* Keep the last entry of each run of one key. */     for (read = 0; read < set->count; read++) {-            /* If next entry has the same key, skip this one (keep the later one). */         if (read + 1 < set->count && set->keys[read] == set->keys[read + 1]) {             continue;         }         if (write != read) {             set->keys[write] = set->keys[read];-                set->positions[write] = set->positions[read];+            positions[write] = positions[read];             set->values[write] = set->values[read];         }         write++;     }     set->count = write;-    }--    set->frozen = 1;+    set->size = write;+    set->layers = 1; }  /* --- Query --- */  void *nn_attrset_lookup(const nn_attrset_t *set, nn_symbol_t key) {-    uint32_t idx = bsearch_key(set->keys, set->count, key);-    if (idx == NN_ATTRSET_NOT_FOUND) return NULL;-    return set->values[idx];+    const nn_attrset_t *layer;+    for (layer = set; layer; layer = layer->base) {+        uint32_t idx = bsearch_key(layer->keys, layer->count, key);+        if (idx != NN_ATTRSET_NOT_FOUND) return layer->values[idx];     }+    return NULL;+} +int nn_attrset_find(const nn_attrset_t *set, nn_symbol_t key,+                    uint32_t *pos, void **value)+{+    const nn_attrset_t *layer;+    for (layer = set; layer; layer = layer->base) {+        uint32_t idx = bsearch_key(layer->keys, layer->count, key);+        if (idx == NN_ATTRSET_NOT_FOUND) continue;+        if (pos) *pos = positions_of(layer)[idx];+        if (value) *value = layer->values[idx];+        return 1;+    }+    return 0;+}+ uint32_t nn_attrset_index(const nn_attrset_t *set, nn_symbol_t key) {+    NN_ASSERT(set->base == NULL, "nn_attrset_index: the set is layered");     return bsearch_key(set->keys, set->count, key); }  void nn_attrset_set_value(nn_attrset_t *set, uint32_t idx, void *value) {+    NN_ASSERT(set->base == NULL, "nn_attrset_set_value: the set is layered");     NN_ASSERT(idx < set->count, "nn_attrset_set_value: idx out of bounds");     set->values[idx] = value; }  void *nn_attrset_get_value(const nn_attrset_t *set, uint32_t idx) {+    NN_ASSERT(set->base == NULL, "nn_attrset_get_value: the set is layered");     NN_ASSERT(idx < set->count, "nn_attrset_get_value: idx out of bounds");     return set->values[idx]; }  nn_symbol_t nn_attrset_get_key(const nn_attrset_t *set, uint32_t idx) {+    NN_ASSERT(set->base == NULL, "nn_attrset_get_key: the set is layered");     NN_ASSERT(idx < set->count, "nn_attrset_get_key: idx out of bounds");     return set->keys[idx]; }  uint32_t nn_attrset_get_pos(const nn_attrset_t *set, uint32_t idx) {+    NN_ASSERT(set->base == NULL, "nn_attrset_get_pos: the set is layered");     NN_ASSERT(idx < set->count, "nn_attrset_get_pos: idx out of bounds");-    return set->positions[idx];+    return positions_of(set)[idx]; }  uint32_t nn_attrset_size(const nn_attrset_t *set) {-    return set->count;+    return set->size; } -const nn_symbol_t *nn_attrset_keys_ptr(const nn_attrset_t *set)+const nn_attrset_t *nn_attrset_base(const nn_attrset_t *set) {-    return set->keys;+    return set->base; } +/* --- The entries a set binds, in symbol order --- */++/* A walk over the entries a set binds: one head for each set in its+ * chain, top first, at the next entry of that set's own arrays.  Each+ * step takes the least name at any head, from the topmost head that has+ * it, and moves every head at that name past it, as upstream's iterator+ * merges a set's layers (Bindings::iterator in attr-set.hh at 2.34.9). */+typedef struct {+    const nn_attrset_t *layer[NN_ATTRSET_MAX_LAYERS];+    uint32_t            next[NN_ATTRSET_MAX_LAYERS];+    uint32_t            heads;+} cursor_t;++static void cursor_start(cursor_t *cursor, const nn_attrset_t *set)+{+    const nn_attrset_t *layer;+    cursor->heads = 0;+    for (layer = set; layer; layer = layer->base) {+        NN_ASSERT(cursor->heads < NN_ATTRSET_MAX_LAYERS,+                  "cursor_start: a chain longer than NN_ATTRSET_MAX_LAYERS");+        cursor->layer[cursor->heads] = layer;+        cursor->next[cursor->heads] = 0;+        cursor->heads++;+    }+}++/* The next entry: 1 with the set that holds it and its index there, or+ * 0 past the last. */+static int cursor_next(cursor_t *cursor, const nn_attrset_t **from, uint32_t *idx)+{+    uint32_t head, best = cursor->heads;+    nn_symbol_t least = 0;+    for (head = 0; head < cursor->heads; head++) {+        const nn_attrset_t *layer = cursor->layer[head];+        if (cursor->next[head] >= layer->count) continue;+        if (best == cursor->heads || layer->keys[cursor->next[head]] < least) {+            best = head;+            least = layer->keys[cursor->next[head]];+        }+    }+    if (best == cursor->heads) return 0;+    *from = cursor->layer[best];+    *idx = cursor->next[best];+    for (head = 0; head < cursor->heads; head++) {+        const nn_attrset_t *layer = cursor->layer[head];+        if (cursor->next[head] < layer->count && layer->keys[cursor->next[head]] == least)+            cursor->next[head]++;+    }+    return 1;+}++/* Insert the entry at `idx` of `from` into `result`. */+static int insert_from(nn_attrset_t *result, const nn_attrset_t *from, uint32_t idx)+{+    return nn_attrset_insert(result, from->keys[idx], from->values[idx], positions_of(from)[idx]);+}++/* Freeze a set filled in symbol order, one entry for each name. */+static void finish_sorted(nn_attrset_t *set)+{+    set->size = set->count;+    set->layers = 1;+}++void nn_attrset_entries(const nn_attrset_t *set, nn_symbol_t *keys,+                        uint32_t *positions, void **values)+{+    cursor_t cursor;+    const nn_attrset_t *from;+    uint32_t idx, i = 0;+    cursor_start(&cursor, set);+    while (cursor_next(&cursor, &from, &idx)) {+        NN_ASSERT(i < set->size, "nn_attrset_entries: more entries than the set's size");+        keys[i] = from->keys[idx];+        positions[i] = positions_of(from)[idx];+        values[i] = from->values[idx];+        i++;+    }+}+ /* --- Set operations --- */ -nn_attrset_t *nn_attrset_union(const nn_attrset_t *a, const nn_attrset_t *b)+nn_attrset_t *nn_attrset_union(const nn_attrset_t *a, const nn_attrset_t *b,+                               uint32_t site) {-    /* The merge-join below assumes both inputs are sorted; every set this-     * module produces is frozen (hence sorted), so guard it in debug. */-    NN_ASSERT(a->frozen && b->frozen, "nn_attrset_union: inputs must be frozen");+    /* The merge-join below needs both inputs sorted, as a frozen set is. */+    NN_ASSERT(a->layers && b->layers, "nn_attrset_union: inputs must be frozen");     /* Merge-join: all keys from both, b wins on conflict.  The sum of two-     * uint32_t counts needs 33 bits; sized at the ceiling instead, the+     * uint32_t sizes needs 33 bits; sized at the ceiling instead, the      * result still holds any union with enough shared keys to fit, and      * an insert refuses the one that does not. */-    uint64_t total = (uint64_t)a->count + b->count;+    uint64_t total = (uint64_t)a->size + b->size;     uint32_t cap = total > NN_ATTRSET_MAX_ENTRIES                        ? NN_ATTRSET_MAX_ENTRIES : (uint32_t)total;-    nn_attrset_t *result = nn_attrset_new(cap);+    nn_attrset_t *result = attrset_alloc(cap);     if (!result) return NULL;-    uint32_t ia = 0, ib = 0;+    count_at(site, result, a->size == 0 || b->size == 0);+    cursor_t ca, cb;+    const nn_attrset_t *fa, *fb;+    uint32_t ia, ib;+    int more_a, more_b;+    cursor_start(&ca, a);+    cursor_start(&cb, b);+    more_a = cursor_next(&ca, &fa, &ia);+    more_b = cursor_next(&cb, &fb, &ib);      /* A refused result stays tracked, so teardown frees it. */-    while (ia < a->count && ib < b->count) {-        int status;-        if (a->keys[ia] < b->keys[ib]) {-            status = nn_attrset_insert(result, a->keys[ia], a->values[ia], a->positions[ia]);-            ia++;-        } else if (a->keys[ia] > b->keys[ib]) {-            status = nn_attrset_insert(result, b->keys[ib], b->values[ib], b->positions[ib]);-            ib++;+    while (more_a || more_b) {+        nn_symbol_t ka = more_a ? fa->keys[ia] : 0;+        nn_symbol_t kb = more_b ? fb->keys[ib] : 0;+        if (more_a && (!more_b || ka < kb)) {+            if (insert_from(result, fa, ia) != 0) return NULL;+            more_a = cursor_next(&ca, &fa, &ia);         } else {-            /* Same key - b wins (right-biased //), its position too. */-            status = nn_attrset_insert(result, b->keys[ib], b->values[ib], b->positions[ib]);-            ia++;-            ib++;+            /* b's entry, and over a's of the same key (right-biased //),+             * its position too. */+            if (insert_from(result, fb, ib) != 0) return NULL;+            if (more_a && ka == kb) more_a = cursor_next(&ca, &fa, &ia);+            more_b = cursor_next(&cb, &fb, &ib);         }-        if (status != 0) return NULL;     }-    while (ia < a->count) {-        if (nn_attrset_insert(result, a->keys[ia], a->values[ia], a->positions[ia]) != 0) return NULL;-        ia++;++    finish_sorted(result);+    return result; }-    while (ib < b->count) {-        if (nn_attrset_insert(result, b->keys[ib], b->values[ib], b->positions[ib]) != 0) return NULL;-        ib++;++/* `b` layered on `a`: a set at `site` holding b's entries alone, with a+ * as its base, as upstream's ExprOpUpdate::eval builds one+ * (eval.cc at 2.34.9).  Its size counts each name of b that a's chain+ * already binds once, as upstream's finishSizeIfNecessary does+ * (attr-set.hh), in 64 bits, and a layer past NN_ATTRSET_MAX_ENTRIES is+ * refused. */+static nn_attrset_t *layer_on(const nn_attrset_t *a, const nn_attrset_t *b, uint32_t site)+{+    cursor_t cursor;+    const nn_attrset_t *from;+    uint32_t idx;+    uint64_t size = a->size;+    nn_attrset_t *layer = attrset_alloc(b->size);+    if (!layer) return NULL;+    count_at(site, layer, 0);+    cursor_start(&cursor, b);+    while (cursor_next(&cursor, &from, &idx)) {+        if (insert_from(layer, from, idx) != 0) return NULL;+        if (!nn_attrset_find(a, from->keys[idx], NULL, NULL)) size++;     }+    if (size > NN_ATTRSET_MAX_ENTRIES) return NULL;+    layer->base = a;+    layer->size = (uint32_t)size;+    layer->layers = a->layers + 1;+    return layer;+} -    result->frozen = 1;  /* Merge preserves sorted order. */+nn_attrset_t *nn_attrset_update(const nn_attrset_t *a, const nn_attrset_t *b,+                                uint32_t site)+{+    nn_attrset_t *result;+    uint64_t copied;+    NN_ASSERT(a->layers && b->layers, "nn_attrset_update: inputs must be frozen");+    if (a->size != 0 && b->size != 0 && a->layers < NN_ATTRSET_MAX_LAYERS+        && b->size <= NN_ATTRSET_LAYER_RHS_MAX) {+        result = layer_on(a, b, site);+        copied = b->size;+    } else {+        result = nn_attrset_union(a, b, site);+        copied = result ? result->size : 0;+    }+    if (result && nn_stats_counting) nn_stats_count_update(copied);     return result; }  nn_attrset_t *nn_attrset_remove_keys(     const nn_attrset_t *set,     const nn_symbol_t *keys,-    uint32_t key_count)+    uint32_t key_count,+    uint32_t site) {-    NN_ASSERT(set->frozen, "nn_attrset_remove_keys: input must be frozen");-    nn_attrset_t *result = nn_attrset_new(set->count);+    NN_ASSERT(set->layers, "nn_attrset_remove_keys: input must be frozen");+    nn_attrset_t *result = attrset_alloc(set->size);     if (!result) return NULL;-    uint32_t i;+    count_at(site, result, set->size == 0);+    cursor_t cursor;+    const nn_attrset_t *from;+    uint32_t idx; -    for (i = 0; i < set->count; i++) {-        /* Linear scan of removal keys - fine for small removal lists.-         * For large removal lists, sort them and merge-scan instead. */+    cursor_start(&cursor, set);+    while (cursor_next(&cursor, &from, &idx)) {+        /* Each entry scans the removal keys: entries * keys comparisons. */         uint32_t j;         int skip = 0;         for (j = 0; j < key_count; j++) {-            if (set->keys[i] == keys[j]) {+            if (from->keys[idx] == keys[j]) {                 skip = 1;                 break;             }         }-        if (!skip && nn_attrset_insert(result, set->keys[i], set->values[i], set->positions[i]) != 0) {-            return NULL;-        }+        if (!skip && insert_from(result, from, idx) != 0) return NULL;     } -    result->frozen = 1;  /* Source was sorted, no removals change order. */+    finish_sorted(result);  /* The walk is in order, and removals keep it. */     return result;+}++/* --- Census --- */++const nn_tracker_t *nn_attrset_tracked(void)+{+    return &g_tracked;+}++uint64_t nn_attrset_bytes(const nn_attrset_t *set)+{+    return sizeof(*set) + (uint64_t)names_block_bytes(set->capacity)+         + (uint64_t)set->capacity * sizeof(void *);+}++uint32_t nn_attrset_layer_count(const nn_attrset_t *set)+{+    return set->count;+}++const nn_symbol_t *nn_attrset_layer_keys(const nn_attrset_t *set)+{+    return set->keys;+}++void *const *nn_attrset_layer_values(const nn_attrset_t *set)+{+    return set->values; }  /* --- Internal: tagged sort comparator --- */
cbits/nn_attrset.h view
@@ -1,10 +1,11 @@ /*  * nn_attrset.h - Sorted symbol-keyed attribute set for nova-nix.  *- * Replaces Haskell's Data.Map.Strict (48 bytes per Bin node, pointer-- * chasing balanced tree) with a contiguous sorted array of (symbol,- * position, slot) entries.  Binary search for O(log n) lookup; linear- * scan for iteration.+ * Parallel arrays of symbols, positions and values, sorted by symbol+ * (nn_attrset.c draws the layout), against the 48 bytes per node of the+ * pointer-chasing balanced tree Haskell's Data.Map.Strict would take.+ * A lookup is a binary search of each layer, top first, at most+ * NN_ATTRSET_MAX_LAYERS of them; iteration is a scan, merged across them.  *  * Construction is two-phase:  *   1. nn_attrset_new(cap) + nn_attrset_insert() - append unsorted@@ -14,21 +15,40 @@  * but keys cannot change).  This matches Nix semantics: attribute sets  * are constructed once and never gain/lose keys.  *- * Values are opaque void* - Haskell passes StablePtr Thunk.  The C- * side never dereferences them.+ * A set nn_attrset_update makes can be a layer: its own arrays hold the+ * right operand's entries, and it sits on the left operand, its base,+ * which it binds the rest of, as upstream 2.34's Bindings layer on one+ * another (attr-set.hh).  A lookup searches the layers top first, and+ * the set binds each name once, to its topmost entry, in symbol order.+ * A set's size counts every name it binds; the functions that take an+ * index read a flat set alone, one with no base, as a name table always+ * is.  *+ * Values are the nn_thunk_t * of each attribute, or NULL in a frame's+ * name table until the frame fills it.  The set never dereferences them;+ * a census (nn_stats.h) follows them.+ *  * Each entry also carries the position it was defined at, an opaque  * uint32_t the evaluator assigns and resolves, as each attribute of  * upstream's Bindings carries a PosIdx (attr-set.hh at 2.24.9).  * Positions travel with their entries through freeze, union and key  * removal.  *- * Lifecycle: arena-managed.  Every set is tracked at creation and bulk-freed- * by nn_attrset_free_all at evaluation teardown; nn_attrset_free is that- * teardown's per-set primitive and must not be called on a tracked set (it- * would then be double-freed by nn_attrset_free_all).- * Values (StablePtrs) are NOT freed by nn_attrset_free - Haskell owns them.+ * Lifecycle: arena-managed.  Every set is tracked at creation and+ * bulk-freed by nn_attrset_free_all at arena teardown, or freed earlier+ * by the region collector once nothing reaches it (nn_attrset_sweep,+ * nn_region.h).  Neither frees a value: the values are cells the thunk+ * arena owns.  *+ * Every constructor names its site, the construct or builtin that makes+ * the set (nn_stats.h), under which the census counts it.+ *+ * One set is not allocated: nn_attrset_empty, the set with no entries+ * the evaluator gives wherever upstream gives its one emptyBindings,+ * which its allocBindings hands out for a capacity of 0+ * (attr-set.cc).  The constructors here make a new set whenever they are+ * called.+ *  * Counts and indices are uint32_t.  A set holds at most  * NN_ATTRSET_MAX_ENTRIES entries, the ceiling upstream's Bindings has  * (its size_t is uint32_t), so every index is below NN_ATTRSET_NOT_FOUND.@@ -40,6 +60,7 @@ #define NN_ATTRSET_H  #include "nn_symbol.h"+#include "nn_tracker.h" #include <stddef.h> #include <stdint.h> @@ -54,43 +75,73 @@ /* nn_attrset_index's answer for an absent key: no index reaches it. */ #define NN_ATTRSET_NOT_FOUND UINT32_MAX +/* The most sets one chain of layers holds, the set and its bases,+ * upstream's Bindings::maxLayers (attr-set.hh at 2.34.9). */+#define NN_ATTRSET_MAX_LAYERS 8u++/* The most entries a right operand of nn_attrset_update has for the+ * result to be a layer on the left: upstream's default for+ * eval-attrset-update-layer-rhs-threshold (bindingsUpdateLayerRhsSizeThreshold+ * in eval-settings.hh at 2.34.9), which is larger where a pointer takes 4+ * bytes. */+#define NN_ATTRSET_LAYER_RHS_MAX (sizeof(void *) == 4 ? 8192u : 16u)+ /* --- Lifecycle --- */ -/* Allocate a new empty attribute set with space for `capacity` entries- * (0 picks a small default).  Returns NULL on allocation failure. */-nn_attrset_t *nn_attrset_new(uint32_t capacity);+/* Allocate a new empty attribute set at `site` with space for `capacity`+ * entries (0 picks a small default).  Returns NULL on allocation+ * failure. */+nn_attrset_t *nn_attrset_new(uint32_t capacity, uint32_t site); -/* Free the attribute set structure.  Does NOT free the value pointers- * (Haskell owns those via StablePtr). */-void nn_attrset_free(nn_attrset_t *set);+/* The shared empty set: frozen, no entries, and no arrays behind it.  A+ * file-scope static, not tracked and never freed, so it has one address+ * in every evaluation and outside all of them.  Nothing writes it: it is+ * frozen, so nn_attrset_insert never adds to it, and it has no index for+ * nn_attrset_set_value to write at. */+nn_attrset_t *nn_attrset_empty(void);  /* --- Construction (before freeze) --- */  /* Append a key-value pair defined at `pos`.  Keys need not be sorted or- * unique at this stage - duplicates are resolved at freeze time (last- * insert wins, position included, matching Nix // merge semantics).- * Grows the internal arrays if capacity is exceeded.  Returns 0, or -1- * with the set unchanged when it already holds NN_ATTRSET_MAX_ENTRIES- * entries or cannot grow. */+ * unique at this stage: freeze sorts them, and of a repeated key keeps+ * the last insert, position included.  The parser refuses a repeated+ * name, but an expression built through Nix.Expr can hold one in a+ * frame's names, and the resolver likewise keeps a repeated name's last+ * definition.  Grows the internal arrays if capacity is exceeded.+ * Returns 0, or -1 with the set unchanged when it already holds+ * NN_ATTRSET_MAX_ENTRIES entries or cannot grow.  A frozen set aborts+ * (NN_ASSERT). */ int nn_attrset_insert(nn_attrset_t *set, nn_symbol_t key, void *value, uint32_t pos); -/* Sort entries by symbol ID and deduplicate (last writer wins).- * Must be called exactly once before any lookup/keys/values access.- * After freeze, no more inserts are allowed. */+/* Sort the entries by symbol ID, keep the last insert of a repeated key,+ * and freeze the set: a lookup needs the order, and nn_attrset_insert+ * aborts on a frozen set.  Freezing a frozen set does nothing. */ void nn_attrset_freeze(nn_attrset_t *set);  /* --- Query (after freeze) --- */  /* Look up a key by symbol.  Returns the value pointer, or NULL if- * the key is not present.  O(log n) binary search. */+ * the key is not present.  A binary search of each layer, top first. */ void *nn_attrset_lookup(const nn_attrset_t *set, nn_symbol_t key); +/* Whether the set binds `key`, writing its entry's position through+ * `pos` and its value through `value`, each only when not NULL.  A value+ * that is NULL, as a name table's is until its frame fills it, is found+ * as well, where nn_attrset_lookup answers NULL as for a key not bound.+ * Returns 1 when the set binds the key, else 0 with nothing written.+ * A binary search of each layer, top first. */+int nn_attrset_find(const nn_attrset_t *set, nn_symbol_t key,+                    uint32_t *pos, void **value);+ /* Return the index of a key, or NN_ATTRSET_NOT_FOUND.- * Useful for updating value slots in place. */+ * Useful for updating value slots in place.  This and the functions+ * below that take an index read a flat set; a layered one aborts+ * (NN_ASSERT). */ uint32_t nn_attrset_index(const nn_attrset_t *set, nn_symbol_t key);  /* Update the value at a known index.  Index must be valid (0 <= idx < count).- * Used for lazy materialization: slot starts NULL, gets filled on first force. */+ * Fills a frame's name table, built with NULL values before its thunks+ * exist. */ void nn_attrset_set_value(nn_attrset_t *set, uint32_t idx, void *value);  /* Return the value at a known index. */@@ -104,38 +155,89 @@  /* --- Bulk access --- */ -/* Number of entries (after freeze: unique keys). */+/* Number of entries (after freeze: the names the set binds, in every+ * layer, each once). */ uint32_t nn_attrset_size(const nn_attrset_t *set); -/* Direct pointer to the sorted keys array (count elements).- * Valid until the set is freed. */-const nn_symbol_t *nn_attrset_keys_ptr(const nn_attrset_t *set);+/* The set a layer sits on, or NULL for a flat set. */+const nn_attrset_t *nn_attrset_base(const nn_attrset_t *set); +/* Write the entries a frozen set binds, nn_attrset_size of them, in+ * symbol order: each name's key, position and value, from the topmost+ * layer that holds the name, to the three arrays, each with room for+ * that many. */+void nn_attrset_entries(const nn_attrset_t *set, nn_symbol_t *keys,+                        uint32_t *positions, void **values);+ /* --- Lifecycle: bulk cleanup --- */  /* Free all tracked attribute sets at once (arena-style cleanup).- * Every set created via nn_attrset_new is automatically tracked.+ * Every set the constructors here make is tracked.  * Call this once at evaluation end, before destroying sub-arenas. */ void nn_attrset_free_all(void);  /* --- Set operations --- */ -/* Create a new set that is the right-biased union of `a` and `b`- * (keys in `b` override `a`, positions with them).  Both inputs must be- * frozen.+/* Create a new flat set at `site` that is the right-biased union of `a`+ * and `b` (keys in `b` override `a`, positions with them), sized for the+ * entries of both.  Both inputs must be frozen.  * The result is returned frozen and is arena-tracked (freed by- * nn_attrset_free_all) - do NOT pass it to nn_attrset_free.  Returns- * NULL when the union would pass NN_ATTRSET_MAX_ENTRIES or an- * allocation fails. */-nn_attrset_t *nn_attrset_union(const nn_attrset_t *a, const nn_attrset_t *b);+ * nn_attrset_free_all, or by nn_attrset_sweep).  Returns NULL when the union+ * would pass+ * NN_ATTRSET_MAX_ENTRIES or an allocation fails. */+nn_attrset_t *nn_attrset_union(const nn_attrset_t *a, const nn_attrset_t *b,+                               uint32_t site); -/* Create a new set with the given keys removed.  Input must be frozen.+/* `a // b` at `site`, as upstream's ExprOpUpdate::eval makes it+ * (eval.cc at 2.34.9): while a's chain holds fewer than+ * NN_ATTRSET_MAX_LAYERS sets and b at most NN_ATTRSET_LAYER_RHS_MAX+ * entries, a layer on `a` holding b's entries, else the set+ * nn_attrset_union makes.  While the census counts sites (nn_stats.h),+ * the entries copied count: b's for a layer, the result's for a union,+ * as upstream counts them in nrOpUpdateValuesCopied.  The evaluator+ * gives the other operand for an empty one, as upstream does before it+ * counts, so it calls this with two sets that hold entries; given one+ * with none, this makes the union.  Both inputs must be frozen.  Returns+ * NULL as nn_attrset_union does, and for a layer whose size would pass+ * NN_ATTRSET_MAX_ENTRIES. */+nn_attrset_t *nn_attrset_update(const nn_attrset_t *a, const nn_attrset_t *b,+                                uint32_t site);++/* Create a new flat set at `site` with the given keys removed, sized for+ * the entries of `set`.  Input must be frozen.  * The result is returned frozen and is arena-tracked (freed by- * nn_attrset_free_all) - do NOT pass it to nn_attrset_free.  Returns- * NULL when an allocation fails. */+ * nn_attrset_free_all, or by nn_attrset_sweep).  Returns NULL when an+ * allocation fails. */ nn_attrset_t *nn_attrset_remove_keys(     const nn_attrset_t *set,     const nn_symbol_t *keys,-    uint32_t key_count);+    uint32_t key_count,+    uint32_t site);++/* --- Census (nn_stats.h) --- */++/* Every set allocated and not yet freed: the module's own tracker, whose+ * array moves when the next set is created and is freed by+ * nn_attrset_free_all. */+const nn_tracker_t *nn_attrset_tracked(void);++/* Free the sets from place `from` of the tracker on that `keep` refuses,+ * and close up the rest (nn_tracker_sweep). */+void nn_attrset_sweep(uint32_t from, nn_tracker_keep_t keep, void *ctx);++/* Bytes a set holds from the allocator: its header, and its keys,+ * positions and values at its capacity. */+uint64_t nn_attrset_bytes(const nn_attrset_t *set);++/* The entries a frozen set's own arrays hold, in symbol order, a+ * layer's without its base's: their number, and the arrays of their+ * keys and their values, which hold that many and are valid until the+ * set is freed.  Before freeze the arrays hold the inserts in their+ * order, a name repeated among them, and move when the set grows.  The+ * object graph follows a set by them and its base (nn_graph.h), and the+ * census counts its size by them. */+uint32_t nn_attrset_layer_count(const nn_attrset_t *set);+const nn_symbol_t *nn_attrset_layer_keys(const nn_attrset_t *set);+void *const *nn_attrset_layer_values(const nn_attrset_t *set);  #endif /* NN_ATTRSET_H */
+ cbits/nn_buildusers.c view
@@ -0,0 +1,417 @@+/* glibc declares setgroups, syscall, pipe2 and strsignal only past strict+ * C99. */+#define _GNU_SOURCE++#include "nn_buildusers.h"++#ifndef _WIN32++#include <errno.h>+#include <fcntl.h>+#include <grp.h>+#include <limits.h>+#include <pthread.h>+#include <signal.h>+#include <stdlib.h>+#include <string.h>+#include <sys/resource.h>+#include <sys/types.h>+#include <sys/wait.h>+#include <unistd.h>++#if defined(__linux__) || defined(__APPLE__)+#include <sys/syscall.h>+#endif++/* Every call here forks nova-nix's own process, which the GHC runtime+ * runs threaded, so each child makes only async-signal-safe calls before+ * it executes or exits: whatever another thread held at the fork, a lock of+ * the allocator's or of the name service's among them, stays held in the+ * child.  The process library can start a program as another user only+ * by looking that user up in its child, with getpwuid_r and initgroups;+ * here the caller looks the groups up beforehand and the child only sets+ * them.  Every signal is blocked across the fork, so none runs a handler+ * of the runtime's in the child before the child has put each back to+ * its default. */++/* How far up descriptors are closed where the descriptor limit is not+ * finite. */+#define CLOSE_FALLBACK_TOP 1024++/* What a child that failed to start its program tells its parent. */+struct spawn_failure {+  int step;+  int error;+};++/* The ids a builder that runs as a build user drops to between the fork+ * and the exec, the groups already as setgroups takes them. */+struct build_ids {+  uid_t uid;+  gid_t gid;+  int group_count;+  const gid_t *groups;+};++/* The descriptor limit, read before the fork: the top of the range a+ * child closes. */+static int descriptor_top(void) {+  struct rlimit limit;+  if (getrlimit(RLIMIT_NOFILE, &limit) == 0 && limit.rlim_cur != RLIM_INFINITY &&+      limit.rlim_cur < (rlim_t)INT_MAX) {+    return (int)limit.rlim_cur;+  }+  return CLOSE_FALLBACK_TOP;+}++/* Close every descriptor from 3 up to TOP but KEEP, as upstream's child+ * closes them before it executes the builder: a build user is not to+ * hold a descriptor of the process that started it.  On Linux a range is+ * closed in one call where the kernel has it, whatever the limit. */+static void close_descriptors(int keep, int top) {+  int fd;+#if defined(__linux__) && defined(SYS_close_range)+  if ((keep <= 3 || syscall(SYS_close_range, 3U, (unsigned int)keep - 1U, 0U) == 0) &&+      syscall(SYS_close_range, (unsigned int)keep + 1U, ~0U, 0U) == 0) {+    return;+  }+#endif+  for (fd = 3; fd < top; fd++) {+    if (fd != keep) {+      close(fd);+    }+  }+}++/* Put every signal a handler catches back to its default, and SIGPIPE,+ * which the GHC runtime ignores and an exec would leave ignored, so the+ * program starts with the dispositions a program expects. */+static void default_signals(void) {+  struct sigaction found;+  struct sigaction default_action;+  int signal_number;+  default_action.sa_handler = SIG_DFL;+  default_action.sa_flags = 0;+  sigemptyset(&default_action.sa_mask);+  for (signal_number = 1; signal_number < NSIG; signal_number++) {+    if (signal_number == SIGKILL || signal_number == SIGSTOP) {+      continue;+    }+    if (sigaction(signal_number, NULL, &found) == 0 &&+        (signal_number == SIGPIPE || (found.sa_handler != SIG_DFL && found.sa_handler != SIG_IGN))) {+      sigaction(signal_number, &default_action, NULL);+    }+  }+}++/* Make FD the descriptor TARGET, open across the exec.  dup2 of a+ * descriptor onto itself changes nothing, so one that is already TARGET,+ * as it is when this process had TARGET closed, has its close-on-exec flag+ * cleared instead. */+static int move_descriptor(int fd, int target) {+  int flags;+  if (fd != target) {+    return dup2(fd, target);+  }+  flags = fcntl(fd, F_GETFD);+  return flags < 0 ? -1 : fcntl(fd, F_SETFD, flags & ~FD_CLOEXEC);+}++/* Tell the parent which step failed, then end. */+static void child_fail(int report, int step) {+  struct spawn_failure failure;+  ssize_t written;+  failure.step = step;+  failure.error = errno;+  do {+    written = write(report, &failure, sizeof failure);+  } while (written < 0 && errno == EINTR);+  _exit(127);+}++/* Start PROGRAM in the forked child as upstream's child starts a builder,+ * dropping to IDS first where there are any. */+static void child_run(const char *program, char *const argv[], char *const envp[], const char *cwd, int input_fd,+                      int output_fd, const struct build_ids *ids, int report, int top) {+  sigset_t none;+  /* No core dumps, with upstream's own call, whose failure it ignores: a+   * hard limit already finite, which only root may raise again, leaves+   * the call refused and the soft limit as it was. */+  struct rlimit core = {0, RLIM_INFINITY};++  /* No controlling terminal, and no terminal signals, as upstream's child+   * makes a session of its own. */+  if (setsid() < 0) {+    child_fail(report, NN_SPAWN_SESSION);+  }+  if (move_descriptor(input_fd, STDIN_FILENO) < 0) {+    child_fail(report, NN_SPAWN_INPUT);+  }+  if (move_descriptor(output_fd, STDOUT_FILENO) < 0 || move_descriptor(output_fd, STDERR_FILENO) < 0) {+    child_fail(report, NN_SPAWN_OUTPUT);+  }+  close_descriptors(report, top);++  setrlimit(RLIMIT_CORE, &core);++  if (chdir(cwd) < 0) {+    child_fail(report, NN_SPAWN_CHDIR);+  }++  /* The supplementary groups first, then the group, then the user, which+   * gives up the right to change the other two; setuid as root sets the+   * real, effective and saved ids, each checked as upstream checks them. */+  if (ids != NULL) {+    if (setgroups(ids->group_count, ids->groups) < 0) {+      child_fail(report, NN_SPAWN_GROUPS);+    }+    if (setgid(ids->gid) < 0 || getgid() != ids->gid || getegid() != ids->gid) {+      child_fail(report, NN_SPAWN_GID);+    }+    if (setuid(ids->uid) < 0 || getuid() != ids->uid || geteuid() != ids->uid) {+      child_fail(report, NN_SPAWN_UID);+    }+  }++  default_signals();+  sigemptyset(&none);+  sigprocmask(SIG_SETMASK, &none, NULL);+  execve(program, argv, envp);+  child_fail(report, NN_SPAWN_EXEC);+}++/* A pipe whose ends close at an exec, made so in one call where the+ * system has one, so a fork in another thread cannot inherit an end. */+static int report_pipe(int ends[2]) {+#if defined(__linux__)+  return pipe2(ends, O_CLOEXEC);+#else+  if (pipe(ends) < 0) {+    return -1;+  }+  if (fcntl(ends[0], F_SETFD, FD_CLOEXEC) < 0 || fcntl(ends[1], F_SETFD, FD_CLOEXEC) < 0) {+    int error = errno;+    close(ends[0]);+    close(ends[1]);+    errno = error;+    return -1;+  }+  return 0;+#endif+}++/* Fork a child that starts PROGRAM, as IDS where there are any, and wait+ * until it has executed the program or failed to. */+static int spawn_builder(const char *program, char *const argv[], char *const envp[], const char *cwd, int input_fd,+                         int output_fd, const struct build_ids *ids, int *pid, int *step) {+  int report[2];+  int top = descriptor_top();+  pid_t child;+  struct spawn_failure failure;+  ssize_t got;+  int wait_status;+  sigset_t all;+  sigset_t original;++  /* The report pipe closes at the exec, so a read that finds its end+   * means the program started. */+  if (report_pipe(report) < 0) {+    *step = NN_SPAWN_PIPE;+    return errno;+  }++  sigfillset(&all);+  pthread_sigmask(SIG_SETMASK, &all, &original);+  child = fork();+  if (child == 0) {+    close(report[0]);+    child_run(program, argv, envp, cwd, input_fd, output_fd, ids, report[1], top);+  }+  pthread_sigmask(SIG_SETMASK, &original, NULL);+  if (child < 0) {+    int error = errno;+    close(report[0]);+    close(report[1]);+    *step = NN_SPAWN_FORK;+    return error;+  }++  close(report[1]);+  do {+    got = read(report[0], &failure, sizeof failure);+  } while (got < 0 && errno == EINTR);+  close(report[0]);+  if (got == 0) {+    *pid = (int)child;+    return 0;+  }++  while (waitpid(child, &wait_status, 0) < 0 && errno == EINTR) {+  }+  if (got != (ssize_t)sizeof failure) {+    *step = NN_SPAWN_FORK;+    return EIO;+  }+  *step = failure.step;+  return failure.error;+}++int nn_spawn_as_user(const char *program, char *const argv[], char *const envp[], const char *cwd, int input_fd,+                     int output_fd, unsigned int uid, unsigned int gid, int group_count, const unsigned int *groups,+                     int *pid, int *step) {+  struct build_ids ids;+  gid_t *group_ids = NULL;+  int answer;+  int i;++  if (uid == 0) {+    *step = NN_SPAWN_UID;+    return EINVAL;+  }+  if (geteuid() != 0) {+    *step = NN_SPAWN_UID;+    return EPERM;+  }++  /* The groups as setgroups takes them, copied before the fork. */+  if (group_count > 0) {+    group_ids = malloc((size_t)group_count * sizeof *group_ids);+    if (group_ids == NULL) {+      *step = NN_SPAWN_FORK;+      return ENOMEM;+    }+    for (i = 0; i < group_count; i++) {+      group_ids[i] = (gid_t)groups[i];+    }+  }++  ids.uid = (uid_t)uid;+  ids.gid = (gid_t)gid;+  ids.group_count = group_count;+  ids.groups = group_ids;+  answer = spawn_builder(program, argv, envp, cwd, input_fd, output_fd, &ids, pid, step);+  free(group_ids);+  return answer;+}++int nn_spawn_as_invoker(const char *program, char *const argv[], char *const envp[], const char *cwd, int input_fd,+                        int output_fd, int *pid, int *step) {+  return spawn_builder(program, argv, envp, cwd, input_fd, output_fd, NULL, pid, step);+}++/* Send SIGKILL to every process the caller may signal but the caller+ * itself.  Linux's kill(-1) leaves the caller out; macOS's libc kill+ * takes it in, so there the call passes the argument that leaves it out,+ * as upstream's does, through the system call the SDK marks deprecated+ * and offers no other way to. */+static int kill_all_others(void) {+#if defined(__APPLE__)+#pragma clang diagnostic push+#pragma clang diagnostic ignored "-Wdeprecated-declarations"+  return syscall(SYS_kill, -1, SIGKILL, 0);+#pragma clang diagnostic pop+#else+  return kill(-1, SIGKILL);+#endif+}++int nn_kill_user(unsigned int uid, int *status) {+  pid_t child;+  int wait_status;+  pid_t waited;++  if (uid == 0) {+    return EINVAL;+  }+  /* Only root may become another user, so only root's child can be the+   * build user alone: a caller that is not root is refused before any+   * child exists, since a setuid to its own uid would succeed and the+   * kill would end the caller's every other process. */+  if (geteuid() != 0) {+    return EPERM;+  }+  child = fork();+  if (child < 0) {+    return errno;+  }+  if (child == 0) {+    if (setuid((uid_t)uid) < 0 || getuid() != (uid_t)uid || geteuid() != (uid_t)uid) {+      _exit(1);+    }+    /* A user with no other process is no failure. */+    while (kill_all_others() < 0) {+      if (errno == ESRCH || errno == EPERM) {+        _exit(0);+      }+      if (errno != EINTR) {+        _exit(1);+      }+    }+    _exit(0);+  }++  do {+    waited = waitpid(child, &wait_status, 0);+  } while (waited < 0 && errno == EINTR);+  if (waited < 0) {+    return errno;+  }+  if (WIFEXITED(wait_status)) {+    *status = WEXITSTATUS(wait_status);+  } else if (WIFSIGNALED(wait_status)) {+    *status = 256 + WTERMSIG(wait_status);+  } else {+    *status = 1;+  }+  return 0;+}++const char *nn_signal_text(int signal) { return strsignal(signal); }++#else /* _WIN32 */++#include <errno.h>++int nn_spawn_as_user(const char *program, char *const argv[], char *const envp[], const char *cwd, int input_fd,+                     int output_fd, unsigned int uid, unsigned int gid, int group_count, const unsigned int *groups,+                     int *pid, int *step) {+  (void)program;+  (void)argv;+  (void)envp;+  (void)cwd;+  (void)input_fd;+  (void)output_fd;+  (void)uid;+  (void)gid;+  (void)group_count;+  (void)groups;+  (void)pid;+  *step = NN_SPAWN_FORK;+  return ENOSYS;+}++int nn_spawn_as_invoker(const char *program, char *const argv[], char *const envp[], const char *cwd, int input_fd,+                        int output_fd, int *pid, int *step) {+  (void)program;+  (void)argv;+  (void)envp;+  (void)cwd;+  (void)input_fd;+  (void)output_fd;+  (void)pid;+  *step = NN_SPAWN_FORK;+  return ENOSYS;+}++int nn_kill_user(unsigned int uid, int *status) {+  (void)uid;+  *status = 1;+  return ENOSYS;+}++const char *nn_signal_text(int signal) {+  (void)signal;+  return "";+}++#endif
+ cbits/nn_buildusers.h view
@@ -0,0 +1,63 @@+/* The start of a builder outside the sandbox, as upstream's child starts+ * one, as the user nova-nix runs as or as a build user, which it drops to+ * between the fork and the exec, and the kill of every process a build+ * user has (Nix.Builder.BuildUser).  POSIX only; every other platform+ * compiles stubs that answer ENOSYS, because the cabal c-sources entry is+ * unconditional and the Haskell side calls them only on Linux and+ * macOS. */+#ifndef NN_BUILDUSERS_H+#define NN_BUILDUSERS_H++/* The step of a start that failed, which nn_spawn_as_user and+ * nn_spawn_as_invoker answer in *STEP with the errno it failed with. */+enum nn_spawn_step {+  NN_SPAWN_PIPE = 1,+  NN_SPAWN_FORK = 2,+  NN_SPAWN_SESSION = 3,+  NN_SPAWN_INPUT = 4,+  NN_SPAWN_OUTPUT = 5,+  NN_SPAWN_CHDIR = 6,+  NN_SPAWN_GROUPS = 7,+  NN_SPAWN_GID = 8,+  NN_SPAWN_UID = 9,+  NN_SPAWN_EXEC = 10+};++/* Start PROGRAM with the arguments ARGV and the environment ENVP, each+ * NULL-terminated, in the directory CWD, reading INPUT_FD and writing+ * OUTPUT_FD as both its standard output and its standard error, as the+ * user UID with the group GID and the GROUP_COUNT supplementary groups+ * GROUPS, leading a session of its own, with upstream's limit on core+ * dumps (a soft limit of 0 and no hard limit, which a caller that is not+ * root is refused where its hard limit is finite, keeping its soft limit,+ * as upstream's is), the default disposition for every signal and every+ * other descriptor closed.+ * Answers 0 with the child's process id in *PID once the program has+ * replaced the child, or the errno of the step that failed, named in+ * *STEP, with no child left behind; EINVAL for uid 0, which is no build+ * user, and EPERM, before any child exists, for a caller that is not+ * root, which no other user may become. */+int nn_spawn_as_user(const char *program, char *const argv[], char *const envp[], const char *cwd, int input_fd,+                     int output_fd, unsigned int uid, unsigned int gid, int group_count, const unsigned int *groups,+                     int *pid, int *step);++/* Start PROGRAM as nn_spawn_as_user does, but as the user and groups the+ * caller has, which it keeps. */+int nn_spawn_as_invoker(const char *program, char *const argv[], char *const envp[], const char *cwd, int input_fd,+                        int output_fd, int *pid, int *step);++/* Send SIGKILL to every process whose user is UID, from a child that is+ * that user, as kill(-1) reaches only the processes its caller may+ * signal.  Answers 0 with *STATUS 0 once the signal went out, or with+ * *STATUS the child's exit code, or 256 plus the signal that ended it,+ * when the child could not send it, the child having checked that its+ * real and effective uids are UID before any kill; or the errno of a fork+ * or a wait that failed, EINVAL for uid 0, whose kill would reach every+ * process, and EPERM, before any child exists, for a caller that is not+ * root, whose child could only become the caller itself. */+int nn_kill_user(unsigned int uid, int *status);++/* The system's description of the signal SIGNAL. */+const char *nn_signal_text(int signal);++#endif
cbits/nn_bytecode.c view
@@ -1,12 +1,14 @@ /*  * nn_bytecode.c -- Flat bytecode storage for Nix expressions.  *- * Two growable arrays:+ * Three growable arrays:  *   - g_ops:     nn_op_t instructions (16 bytes each), indexed by uint32  *   - g_data:    uint32_t values for variable-length operands+ *   - g_strings: the code's strings, indexed by uint32  *- * Both use realloc-doubling.  Write-once during compilation, random- * access during evaluation.  Indices remain stable across realloc.+ * All use realloc-doubling.  Write-once during compilation, random+ * access during evaluation.  Indices remain stable across realloc, and+ * the strings the table points at live in an arena, so they never move.  */  #include "nn_bytecode.h"@@ -18,22 +20,9 @@  /* --- Constants --- */ -#define NN_BC_DEFAULT_OP_CAPACITY    65536u-#define NN_BC_DEFAULT_DATA_CAPACITY 131072u--/* --- Reserved instructions (layout in nn_bytecode.h) --- */--static const nn_op_t g_reserved_ops[] = {-    { .opcode = NN_OP_RESOLVED_VAR, .arg1 = 0, .arg2 = 0 },-    { .opcode = NN_OP_RESOLVED_VAR, .arg1 = 0, .arg2 = 1 },-    { .opcode = NN_OP_APP, .flags = NN_APP_DEFERRED, .arg1 = 0, .arg2 = 1 },-    { .opcode = NN_OP_RESOLVED_VAR, .arg1 = 0, .arg2 = 2 },-    { .opcode = NN_OP_APP, .flags = NN_APP_DEFERRED,-      .arg1 = NN_BC_RESERVED_APPLY1, .arg2 = 3 },-};--typedef char nn_bc_reserved_count_check_[-    (sizeof g_reserved_ops / sizeof g_reserved_ops[0] == NN_BC_RESERVED_COUNT) ? 1 : -1];+#define NN_BC_OP_INITIAL_CAPACITY      65536u+#define NN_BC_DATA_INITIAL_CAPACITY   131072u+#define NN_BC_STRING_INITIAL_CAPACITY   4096u  /* --- Global state --- */ @@ -45,26 +34,29 @@ static uint32_t  g_data_count    = 0; static uint32_t  g_data_capacity = 0; +static nn_str_t      **g_strings          = NULL;+static uint32_t        g_string_count     = 0;+static uint32_t        g_string_capacity  = 0;+static nn_str_arena_t  g_string_arena;+ /* --- Lifecycle --- */ -void nn_bytecode_init(uint32_t op_capacity, uint32_t data_capacity)+void nn_bytecode_init(void) {-    if (g_ops) nn_bytecode_destroy();--    if (op_capacity == 0)   op_capacity   = NN_BC_DEFAULT_OP_CAPACITY;-    if (op_capacity < NN_BC_RESERVED_COUNT) op_capacity = NN_BC_RESERVED_COUNT;-    if (data_capacity == 0) data_capacity = NN_BC_DEFAULT_DATA_CAPACITY;--    g_ops         = (nn_op_t *)malloc((size_t)op_capacity * sizeof(nn_op_t));+    g_ops         = (nn_op_t *)malloc((size_t)NN_BC_OP_INITIAL_CAPACITY * sizeof(nn_op_t));     if (!g_ops) { fprintf(stderr, "nn_bytecode_init: ops alloc failed\n"); abort(); }-    memcpy(g_ops, g_reserved_ops, sizeof g_reserved_ops);-    g_op_count    = NN_BC_RESERVED_COUNT;-    g_op_capacity = op_capacity;+    g_op_count    = 0;+    g_op_capacity = NN_BC_OP_INITIAL_CAPACITY; -    g_data          = (uint32_t *)malloc((size_t)data_capacity * sizeof(uint32_t));+    g_data          = (uint32_t *)malloc((size_t)NN_BC_DATA_INITIAL_CAPACITY * sizeof(uint32_t));     if (!g_data) { fprintf(stderr, "nn_bytecode_init: data alloc failed\n"); abort(); }     g_data_count    = 0;-    g_data_capacity = data_capacity;+    g_data_capacity = NN_BC_DATA_INITIAL_CAPACITY;++    g_strings         = (nn_str_t **)malloc((size_t)NN_BC_STRING_INITIAL_CAPACITY * sizeof(nn_str_t *));+    if (!g_strings) { fprintf(stderr, "nn_bytecode_init: strings alloc failed\n"); abort(); }+    g_string_count    = 0;+    g_string_capacity = NN_BC_STRING_INITIAL_CAPACITY; }  int nn_bytecode_live(void)@@ -83,37 +75,32 @@     g_data          = NULL;     g_data_count    = 0;     g_data_capacity = 0;++    free(g_strings);+    g_strings         = NULL;+    g_string_count    = 0;+    g_string_capacity = 0;+    nn_str_arena_free(&g_string_arena); }  /* --- Internal: grow arrays --- */ -static int ensure_op_space(void)-{-    /* No store before nn_bytecode_init or after nn_bytecode_destroy.-     * Doubling a zero capacity would realloc to zero bytes and the-     * emit would then write past it. */-    if (!g_ops) return -1;-    if (g_op_count < g_op_capacity) return 0;-    uint32_t new_cap = g_op_capacity * 2;-    if (new_cap < g_op_capacity) return -1; /* overflow guard */-    nn_op_t *new_ops = (nn_op_t *)realloc(g_ops, (size_t)new_cap * sizeof(nn_op_t));-    if (!new_ops) return -1;-    g_ops = new_ops;-    g_op_capacity = new_cap;-    return 0;-}--static int ensure_data_space(void)+/* Room for one more element in an array of *cap elements of `size`+ * bytes, `count` of them used: the array, or the array moved to double+ * its capacity.  NULL, leaving the array and *cap as they were, for no+ * array (before nn_bytecode_init or after nn_bytecode_destroy), when+ * doubling would pass UINT32_MAX elements, or when the allocator+ * refuses.  A capacity stops at 2^31, so UINT32_MAX, the emitters'+ * failure answer, is never an index. */+static void *reserve(void *items, uint32_t count, uint32_t *cap, size_t size) {-    if (!g_data) return -1;-    if (g_data_count < g_data_capacity) return 0;-    uint32_t new_cap = g_data_capacity * 2;-    if (new_cap < g_data_capacity) return -1; /* overflow guard */-    uint32_t *new_data = (uint32_t *)realloc(g_data, (size_t)new_cap * sizeof(uint32_t));-    if (!new_data) return -1;-    g_data = new_data;-    g_data_capacity = new_cap;-    return 0;+    void *grown;+    if (!items) return NULL;+    if (count < *cap) return items;+    if (*cap > UINT32_MAX / 2) return NULL;+    grown = realloc(items, (size_t)*cap * 2 * size);+    if (grown) *cap *= 2;+    return grown; }  /* --- Emit --- */@@ -121,7 +108,9 @@ uint32_t nn_bc_emit(uint8_t opcode, uint8_t flags, uint16_t short_arg,                     uint32_t arg1, uint32_t arg2, uint32_t arg3) {-    if (ensure_op_space() != 0) return UINT32_MAX;+    nn_op_t *ops = (nn_op_t *)reserve(g_ops, g_op_count, &g_op_capacity, sizeof(nn_op_t));+    if (!ops) return UINT32_MAX;+    g_ops = ops;     uint32_t idx = g_op_count++;     nn_op_t *op  = &g_ops[idx];     op->opcode    = opcode;@@ -135,12 +124,26 @@  uint32_t nn_bc_emit_data(uint32_t value) {-    if (ensure_data_space() != 0) return UINT32_MAX;+    uint32_t *data = (uint32_t *)reserve(g_data, g_data_count, &g_data_capacity, sizeof(uint32_t));+    if (!data) return UINT32_MAX;+    g_data = data;     uint32_t offset = g_data_count++;     g_data[offset]  = value;     return offset; } +uint32_t nn_bc_emit_string(const char *bytes, size_t len)+{+    nn_str_t **strings = (nn_str_t **)reserve(g_strings, g_string_count, &g_string_capacity, sizeof(nn_str_t *));+    if (!strings) return UINT32_MAX;+    g_strings = strings;+    nn_str_t *s = nn_str_arena_new(&g_string_arena, bytes, len);+    if (!s) return UINT32_MAX;+    uint32_t index = g_string_count++;+    g_strings[index] = s;+    return index;+}+ /* --- Read instructions --- */  uint8_t  nn_bc_opcode(uint32_t idx)    { NN_ASSERT(idx < g_op_count, "nn_bc_opcode: idx out of bounds"); return g_ops[idx].opcode;    }@@ -154,7 +157,28 @@  uint32_t nn_bc_data(uint32_t offset)   { NN_ASSERT(offset < g_data_count, "nn_bc_data: offset out of bounds"); return g_data[offset]; } +/* The index comes from a data word or an argument the compiler wrote, so+ * only a corrupt store holds one out of range; it answers NULL, which the+ * Haskell boundary raises as CInvariantViolated. */+nn_str_t *nn_bc_string(uint32_t index)+{+    return index < g_string_count ? g_strings[index] : NULL;+}+ /* --- Diagnostics --- */  uint32_t nn_bc_op_count(void)   { return g_op_count;   } uint32_t nn_bc_data_count(void) { return g_data_count; }++uint64_t nn_bc_reserved_bytes(void)+{+    return (uint64_t)g_op_capacity * sizeof(nn_op_t)+         + (uint64_t)g_data_capacity * sizeof(uint32_t)+         + (uint64_t)g_string_capacity * sizeof(nn_str_t *)+         + nn_str_arena_reserved_bytes(&g_string_arena);+}++const nn_str_arena_t *nn_bc_strings(void)+{+    return &g_string_arena;+}
cbits/nn_bytecode.h view
@@ -1,8 +1,8 @@ /*  * nn_bytecode.h -- Flat bytecode representation for Nix expressions.  *- * Compiles the 19-constructor Expr AST into a contiguous instruction- * array (nn_op_t[]) plus a variable-length data buffer (uint32_t[]).+ * Compiles the Expr AST into a contiguous instruction array (nn_op_t[])+ * plus a variable-length data buffer (uint32_t[]).  * Each Expr node maps to exactly one instruction.  Children are  * referenced by their index in the instruction array (post-order  * traversal guarantees children < parent).  Variable-length data@@ -10,10 +10,16 @@  * stored in the data buffer, referenced by offset from instructions,  * and so are the source positions bindings refer to.  *- * Goal: eliminate StablePtr (Expr, Env) in pending thunks.  After- * compilation, pending thunks hold (bc_idx, nn_env_t*) -- both- * C-native, zero GHC heap pressure.+ * The bytes of the code's literals (a string's literal parts, a URI, a+ * path, a source file's path) are strings of the code's own (nn_str.h),+ * named by their index in a string table: an instruction or data word+ * holds the index, and nn_bc_string answers the string.  A value a+ * literal evaluates to can point at that string rather than copy it,+ * since the code's strings live as long as the code.  *+ * A pending thunk holds an instruction's index and the nn_env_t * it+ * runs in, both C, so pending code takes nothing on GHC's heap.+ *  * Lifecycle: nn_bytecode_init() before evaluation, nn_bytecode_destroy()  * after.  Not thread-safe -- single-threaded evaluation only.  */@@ -21,92 +27,14 @@ #ifndef NN_BYTECODE_H #define NN_BYTECODE_H +#include <stddef.h> #include <stdint.h> -/* --- Opcodes (one per Expr constructor) --- */--#define NN_OP_LIT_INT        0-#define NN_OP_LIT_FLOAT      1-#define NN_OP_LIT_BOOL       2-#define NN_OP_LIT_NULL       3-#define NN_OP_LIT_URI        4-#define NN_OP_LIT_PATH       5-#define NN_OP_STR            6-#define NN_OP_IND_STR        7-#define NN_OP_VAR            8-#define NN_OP_WITH_VAR       9-#define NN_OP_RESOLVED_VAR  10-#define NN_OP_ATTRS         11-#define NN_OP_LIST          12-#define NN_OP_SELECT        13-#define NN_OP_HAS_ATTR      14-#define NN_OP_APP           15-#define NN_OP_LAMBDA        16-#define NN_OP_LET           17-#define NN_OP_IF            18-#define NN_OP_WITH          19-#define NN_OP_ASSERT        20-#define NN_OP_UNARY         21-#define NN_OP_BINARY        22-#define NN_OP_SEARCH_PATH   23-#define NN_OP_PATH_STR      24--/* --- App flags (NN_OP_APP) --- */--#define NN_APP_DIRECT    0-#define NN_APP_DEFERRED  1--/* --- UnaryOp flags (NN_OP_UNARY) --- */--#define NN_UNARY_NOT     0-#define NN_UNARY_NEGATE  1--/* --- BinaryOp flags (NN_OP_BINARY) --- */--#define NN_BINARY_ADD     0-#define NN_BINARY_SUB     1-#define NN_BINARY_MUL     2-#define NN_BINARY_DIV     3-#define NN_BINARY_AND     4-#define NN_BINARY_OR      5-#define NN_BINARY_IMPL    6-#define NN_BINARY_EQ      7-#define NN_BINARY_NEQ     8-#define NN_BINARY_LT      9-#define NN_BINARY_LTE    10-#define NN_BINARY_GT     11-#define NN_BINARY_GTE    12-#define NN_BINARY_CONCAT 13-#define NN_BINARY_UPDATE 14--/* --- Formal type flags (NN_OP_LAMBDA) --- */--#define NN_FORMAL_NAME       0-#define NN_FORMAL_SET        1-#define NN_FORMAL_NAMED_SET  2--/* --- String part tags (data buffer) --- */--#define NN_STRPART_LIT    0-#define NN_STRPART_INTERP 1-#define NN_STRPART_ESC    2--/* --- Binding type tags (data buffer) --- */--#define NN_BIND_NAMED         0-#define NN_BIND_INHERIT       1-#define NN_BIND_INHERIT_FROM  2--/* --- CaptureInfo type tags (data buffer) --- */--#define NN_CAPTURE_NONE         0-#define NN_CAPTURE_SLOTS        1-#define NN_CAPTURE_WITH_SCOPES  2--/* --- Attr path element tags (data buffer) --- */+#include "nn_str.h" -#define NN_ATTRKEY_STATIC  0-#define NN_ATTRKEY_DYNAMIC 1+/* The opcodes, their flags and the data buffer's tags are the Haskell+ * side's (Nix.Eval.CBytecode), which writes every instruction and reads+ * it back; the store keeps the words without interpreting them. */  /* --- Instruction (16 bytes, naturally aligned) --- */ @@ -120,42 +48,19 @@                             region and the payload starts one word later                             (emit/decode live on the Haskell side:                             Nix.Eval.CBytecode.cbcCountedPayload). */-    uint32_t arg1;       /* Child index, symbol, data offset, lo32, etc. */+    uint32_t arg1;       /* Child index, symbol, string index, data offset, lo32, etc. */     uint32_t arg2;       /* Child index, symbol, hi32, etc. */     uint32_t arg3;       /* Child index, data offset, etc. */ } nn_op_t; -/* --- Reserved instructions ---- *- * nn_bytecode_init lays these down at the front of every store, so each- * index below names the same code for the store's whole life, and the- * next init lays them down again.  They are the code of the application- * thunks a builtin makes once per element (map, genList, mapAttrs and- * the like): each such thunk runs it against a minimal env of its own,- * whose slots hold the function and its arguments.  The store is freed- * only by nn_bytecode_destroy, so code compiled per element would grow- * it with the element count.- *- *   0  RESOLVED_VAR  level 0, slot 0- *   1  RESOLVED_VAR  level 0, slot 1- *   2  APP deferred  0 applied to 1     slot 0 applied to slot 1- *   3  RESOLVED_VAR  level 0, slot 2- *   4  APP deferred  2 applied to 3     that applied to slot 2- */--#define NN_BC_RESERVED_APPLY1  2u-#define NN_BC_RESERVED_APPLY2  4u-#define NN_BC_RESERVED_COUNT   5u- /* --- Lifecycle --- */ -/* Initialize the global bytecode store and lay down the reserved- * instructions.  op_capacity is initial instruction slots (0 = default- * 65536; never fewer than NN_BC_RESERVED_COUNT).  data_capacity is- * initial data buffer slots (0 = default 131072).  Both grow- * automatically.  Outside the init .. destroy window both emitters- * return UINT32_MAX. */-void nn_bytecode_init(uint32_t op_capacity, uint32_t data_capacity);+/* Initialize the global bytecode store: the instruction array, the data+ * buffer and the string table, each of which grows as it fills.  Called+ * only while the store is not live (nn_bytecode_live is 0), as a second+ * init would leak the live store.  Outside the init .. destroy window+ * every emitter returns UINT32_MAX. */+void nn_bytecode_init(void);  /* Nonzero between nn_bytecode_init and nn_bytecode_destroy. */ int nn_bytecode_live(void);@@ -176,6 +81,12 @@  * UINT32_MAX on failure (same contract as nn_bc_emit). */ uint32_t nn_bc_emit_data(uint32_t value); +/* Copy len bytes into a new string of the code's and add it to the string+ * table.  (NULL, 0) is the empty string.  Returns its index, or+ * UINT32_MAX on failure (same contract as nn_bc_emit; a length past+ * NN_STR_MAX_LEN is refused before a byte is read). */+uint32_t nn_bc_emit_string(const char *bytes, size_t len);+ /* --- Read instructions --- */  uint8_t  nn_bc_opcode(uint32_t idx);@@ -189,9 +100,22 @@  uint32_t nn_bc_data(uint32_t offset); +/* The string at an index nn_bc_emit_string returned, valid until+ * nn_bytecode_destroy(), or NULL for an index it did not return. */+nn_str_t *nn_bc_string(uint32_t index);+ /* --- Diagnostics --- */  uint32_t nn_bc_op_count(void); uint32_t nn_bc_data_count(void);++/* Bytes the store holds from the allocator: the instruction and data+ * arrays and the string table at their capacities, and the arena of the+ * code's strings (nn_stats.h). */+uint64_t nn_bc_reserved_bytes(void);++/* The arena of the code's strings, which the census places a string in+ * without counting it (nn_stats.h). */+const nn_str_arena_t *nn_bc_strings(void);  #endif /* NN_BYTECODE_H */
+ cbits/nn_cpus.c view
@@ -0,0 +1,14 @@+#include "nn_cpus.h"++#ifndef _WIN32++#include <unistd.h>++long nn_online_processors(void) { return sysconf(_SC_NPROCESSORS_ONLN); }++#else /* _WIN32 */++/* Windows has no sysconf. */+long nn_online_processors(void) { return -1; }++#endif
+ cbits/nn_cpus.h view
@@ -0,0 +1,15 @@+/* The processor count upstream Nix's C++ runtime reports for+ * std::thread::hardware_concurrency, which upstream's default for its+ * `cores` setting is built on.  Windows compiles a constant -1 stub+ * because the cabal c-sources entry is unconditional; the Haskell side+ * counts processors through GHC's RTS there and never calls it. */+#ifndef NN_CPUS_H+#define NN_CPUS_H++/* sysconf(_SC_NPROCESSORS_ONLN), the call libc++ makes for+ * hardware_concurrency.  libstdc++ calls glibc's get_nprocs instead, the+ * function glibc's sysconf answers that name with.  Returns the count, or+ * -1 when sysconf has no answer, and -1 on Windows. */+long nn_online_processors(void);++#endif
cbits/nn_ctxstr.c view
@@ -2,47 +2,24 @@  * nn_ctxstr.c - Context-bearing string allocation and tracking.  *  * Each nn_ctxstr_t is a single contiguous malloc (header + flexible- * array of nn_sce_t elements).  Pointers are tracked in a global- * dynamic array for bulk cleanup via nn_ctxstr_free_all().+ * array of nn_sce_t elements), tracked (nn_tracker.h) for bulk cleanup+ * via nn_ctxstr_free_all().  */  #include "nn_ctxstr.h" #include "nn_assert.h"+#include "nn_region.h"  #include <stdlib.h> #include <string.h> -/* --- Tracking array --- */--#define NN_CTXSTR_INITIAL_CAPACITY 256u--static nn_ctxstr_t **g_tracked = NULL;-static uint32_t      g_tracked_count = 0;-static uint32_t      g_tracked_capacity = 0;--/* Returns 0, or -1 when the tracking array cannot grow. */-static int-track(nn_ctxstr_t *s)-{-    if (g_tracked_count >= g_tracked_capacity) {-        if (g_tracked_capacity > UINT32_MAX / 2) return -1;-        uint32_t new_cap = g_tracked_capacity == 0-                               ? NN_CTXSTR_INITIAL_CAPACITY-                               : g_tracked_capacity * 2;-        nn_ctxstr_t **new_arr = (nn_ctxstr_t **)realloc(-            g_tracked, (size_t)new_cap * sizeof(nn_ctxstr_t *));-        if (!new_arr) return -1;-        g_tracked = new_arr;-        g_tracked_capacity = new_cap;-    }-    g_tracked[g_tracked_count++] = s;-    return 0;-}+/* Every string allocated, for bulk cleanup. */+static nn_tracker_t g_tracked;  /* --- Lifecycle --- */  nn_ctxstr_t *-nn_ctxstr_new(uint32_t text, uint32_t ctx_count)+nn_ctxstr_new(nn_str_t *text, uint32_t ctx_count) {     /* The count is input-reachable (it scales with the evaluated      * expression); computing the size in uint64_t and capping it at the@@ -56,51 +33,45 @@     s->text = text;     s->ctx_count = ctx_count;     memset(s->ctx, 0, (size_t)ctx_count * sizeof(nn_sce_t));-    if (track(s) != 0) {+    if (nn_tracker_add(&g_tracked, s) != 0) {         free(s);         return NULL;     }+    if (nn_region_mode) nn_region_tracked(NN_REGION_CTXSTR, s, g_tracked.count - 1, nn_ctxstr_bytes(s));     return s; }  void nn_ctxstr_free_all(void) {-    uint32_t i;-    for (i = 0; i < g_tracked_count; i++) {-        free(g_tracked[i]);+    nn_tracker_free_all(&g_tracked, free); }-    free(g_tracked);-    g_tracked = NULL;-    g_tracked_count = 0;-    g_tracked_capacity = 0;++void+nn_ctxstr_sweep(uint32_t from, nn_tracker_keep_t keep, void *ctx)+{+    nn_tracker_sweep(&g_tracked, from, keep, ctx, free); }  /* --- Element setters --- */ -/* Element bounds stay live under NDEBUG: the fill index derives from- * input-sized data crossing the FFI, so a violated bound must drop the- * write, not run past the sized array. */- void nn_ctxstr_set_plain(nn_ctxstr_t *s, uint32_t idx,-                    uint32_t sp_hash, uint32_t sp_name)+                    nn_str_t *sp_hash, nn_str_t *sp_name) {-    NN_ASSERT(s != NULL && idx < s->ctx_count, "nn_ctxstr_set_plain: idx out of bounds");-    if (s == NULL || idx >= s->ctx_count) return;+    NN_ASSERT(idx < s->ctx_count, "nn_ctxstr_set_plain: idx out of bounds");     s->ctx[idx].tag = NN_SCE_PLAIN;     s->ctx[idx].sp_hash = sp_hash;     s->ctx[idx].sp_name = sp_name;-    s->ctx[idx].output = 0;+    s->ctx[idx].output = NULL; }  void nn_ctxstr_set_drv_output(nn_ctxstr_t *s, uint32_t idx,-                         uint32_t sp_hash, uint32_t sp_name,-                         uint32_t output)+                         nn_str_t *sp_hash, nn_str_t *sp_name,+                         nn_str_t *output) {-    NN_ASSERT(s != NULL && idx < s->ctx_count, "nn_ctxstr_set_drv_output: idx out of bounds");-    if (s == NULL || idx >= s->ctx_count) return;+    NN_ASSERT(idx < s->ctx_count, "nn_ctxstr_set_drv_output: idx out of bounds");     s->ctx[idx].tag = NN_SCE_DRV_OUTPUT;     s->ctx[idx].sp_hash = sp_hash;     s->ctx[idx].sp_name = sp_name;@@ -109,19 +80,18 @@  void nn_ctxstr_set_all_outputs(nn_ctxstr_t *s, uint32_t idx,-                          uint32_t sp_hash, uint32_t sp_name)+                          nn_str_t *sp_hash, nn_str_t *sp_name) {-    NN_ASSERT(s != NULL && idx < s->ctx_count, "nn_ctxstr_set_all_outputs: idx out of bounds");-    if (s == NULL || idx >= s->ctx_count) return;+    NN_ASSERT(idx < s->ctx_count, "nn_ctxstr_set_all_outputs: idx out of bounds");     s->ctx[idx].tag = NN_SCE_ALL_OUTPUTS;     s->ctx[idx].sp_hash = sp_hash;     s->ctx[idx].sp_name = sp_name;-    s->ctx[idx].output = 0;+    s->ctx[idx].output = NULL; }  /* --- Accessors --- */ -uint32_t+nn_str_t * nn_ctxstr_text(const nn_ctxstr_t *s) {     return s->text;@@ -133,37 +103,44 @@     return s->ctx_count; } -/* Element reads keep their bound live under NDEBUG (see setters);- * a violated bound returns 0 rather than reading out of bounds. */- uint8_t nn_ctxstr_elem_tag(const nn_ctxstr_t *s, uint32_t idx) {-    NN_ASSERT(s != NULL && idx < s->ctx_count, "nn_ctxstr_elem_tag: idx out of bounds");-    if (s == NULL || idx >= s->ctx_count) return 0;+    NN_ASSERT(idx < s->ctx_count, "nn_ctxstr_elem_tag: idx out of bounds");     return s->ctx[idx].tag; } -uint32_t+nn_str_t * nn_ctxstr_elem_hash(const nn_ctxstr_t *s, uint32_t idx) {-    NN_ASSERT(s != NULL && idx < s->ctx_count, "nn_ctxstr_elem_hash: idx out of bounds");-    if (s == NULL || idx >= s->ctx_count) return 0;+    NN_ASSERT(idx < s->ctx_count, "nn_ctxstr_elem_hash: idx out of bounds");     return s->ctx[idx].sp_hash; } -uint32_t+nn_str_t * nn_ctxstr_elem_name(const nn_ctxstr_t *s, uint32_t idx) {-    NN_ASSERT(s != NULL && idx < s->ctx_count, "nn_ctxstr_elem_name: idx out of bounds");-    if (s == NULL || idx >= s->ctx_count) return 0;+    NN_ASSERT(idx < s->ctx_count, "nn_ctxstr_elem_name: idx out of bounds");     return s->ctx[idx].sp_name; } -uint32_t+nn_str_t * nn_ctxstr_elem_output(const nn_ctxstr_t *s, uint32_t idx) {-    NN_ASSERT(s != NULL && idx < s->ctx_count, "nn_ctxstr_elem_output: idx out of bounds");-    if (s == NULL || idx >= s->ctx_count) return 0;+    NN_ASSERT(idx < s->ctx_count, "nn_ctxstr_elem_output: idx out of bounds");     return s->ctx[idx].output;+}++/* --- Census --- */++const nn_tracker_t *+nn_ctxstr_tracked(void)+{+    return &g_tracked;+}++uint64_t+nn_ctxstr_bytes(const nn_ctxstr_t *s)+{+    return sizeof(*s) + (uint64_t)s->ctx_count * sizeof(nn_sce_t); }
cbits/nn_ctxstr.h view
@@ -3,7 +3,7 @@  *  * Nix strings carry a StringContext: a set of store path references  * that track derivation dependencies.  Context-free strings use- * nn_thunk tag 4 (bare nn_symbol_t).  Context-bearing strings use+ * nn_thunk tag 4 (an nn_str_t pointer).  Context-bearing strings use  * tag 8 (nn_ctxstr_t pointer).  *  * Each context element is one of:@@ -11,11 +11,17 @@  *   SCDrvOutput  - derivation output (.drv path + output name)  *   SCAllOutputs - all outputs of a derivation (drvPath itself)  *- * StorePaths are represented as two interned symbols (hash + name).+ * The text, a StorePath's hash and name, and an output name are each an+ * nn_str_t (nn_str.h), made in the value arena for the string they+ * belong to, as upstream copies each context element for each value+ * (encodeContext in eval.cc at 2.24.9, and+ * Value::StringWithContext::Context::fromBuilder at 2.36.0).  None is a+ * symbol: upstream interns no string value, and a symbol taken here would+ * move the place of every name interned after it.  *  * Memory: each nn_ctxstr_t is a single contiguous allocation via- * C99 flexible array member.  Headers are tracked globally for- * bulk cleanup via nn_ctxstr_free_all().+ * C99 flexible array member, tracked (nn_tracker.h) for bulk cleanup via+ * nn_ctxstr_free_all().  */  #ifndef NN_CTXSTR_H@@ -23,6 +29,9 @@  #include <stdint.h> +#include "nn_str.h"+#include "nn_tracker.h"+ /* --- Context element tags --- */  #define NN_SCE_PLAIN        0@@ -32,27 +41,24 @@ /* --- Types --- */  /* A single string context element: store path reference with kind tag.- * sp_hash and sp_name are interned nn_symbol_t values representing- * the StorePath's hash and name fields.  output is an interned symbol- * for the derivation output name (only valid when tag == DRV_OUTPUT,- * 0 otherwise). */+ * sp_hash and sp_name are the StorePath's hash and name.  output is the+ * derivation output name when tag == DRV_OUTPUT, and NULL otherwise. */ typedef struct nn_sce {     uint8_t     tag;-    uint32_t    sp_hash;-    uint32_t    sp_name;-    uint32_t    output;+    nn_str_t   *sp_hash;+    nn_str_t   *sp_name;+    nn_str_t   *output; } nn_sce_t; -/* A string with context.  text is an interned nn_symbol_t for the- * string content.  ctx_count is the number of context elements; it is- * a full uint32_t because context sets scale with the evaluated- * expression (a narrower count would wrap and undersize the array).- * ctx[] is a C99 flexible array of context elements, sorted by- * (tag, sp_hash, sp_name, output) for deterministic comparison.+/* A string with context.  text is the string's bytes.  ctx_count is the+ * number of context elements; it is a full uint32_t because context sets+ * scale with the evaluated expression (a narrower count would wrap and+ * undersize the array).  ctx[] is a C99 flexible array of context+ * elements, in the order they were set.  *  * Single contiguous allocation: header + elements. */ typedef struct nn_ctxstr {-    uint32_t    text;+    nn_str_t   *text;     uint32_t    ctx_count;     nn_sce_t    ctx[]; } nn_ctxstr_t;@@ -60,42 +66,55 @@ /* --- Lifecycle --- */  /* Allocate a new nn_ctxstr_t with space for ctx_count elements.- * Elements are uninitialized - caller must fill via nn_ctxstr_set_*.+ * Elements are zeroed until the caller fills them via nn_ctxstr_set_*.  * Tracked globally for bulk cleanup.  Returns NULL on allocation  * failure or if the element array size would overflow - the caller  * must check. */-nn_ctxstr_t *nn_ctxstr_new(uint32_t text, uint32_t ctx_count);+nn_ctxstr_t *nn_ctxstr_new(nn_str_t *text, uint32_t ctx_count); -/* Free all tracked nn_ctxstr_t allocations.  Called during arena- * teardown, after thunk iteration but before env/symbol cleanup. */+/* Free all tracked nn_ctxstr_t allocations.  Called once at arena+ * teardown. */ void nn_ctxstr_free_all(void);  /* --- Element setters --- */ -/* idx must be < ctx_count.  A NULL struct or out-of-range idx is- * dropped (asserts in debug builds) rather than writing out of- * bounds - the bound stays live under NDEBUG. */+/* idx must be < ctx_count: an index past it aborts (NN_ASSERT). */  void nn_ctxstr_set_plain(nn_ctxstr_t *s, uint32_t idx,-                         uint32_t sp_hash, uint32_t sp_name);+                         nn_str_t *sp_hash, nn_str_t *sp_name);  void nn_ctxstr_set_drv_output(nn_ctxstr_t *s, uint32_t idx,-                              uint32_t sp_hash, uint32_t sp_name,-                              uint32_t output);+                              nn_str_t *sp_hash, nn_str_t *sp_name,+                              nn_str_t *output);  void nn_ctxstr_set_all_outputs(nn_ctxstr_t *s, uint32_t idx,-                               uint32_t sp_hash, uint32_t sp_name);+                               nn_str_t *sp_hash, nn_str_t *sp_name);  /* --- Accessors --- */ -uint32_t nn_ctxstr_text(const nn_ctxstr_t *s);+nn_str_t *nn_ctxstr_text(const nn_ctxstr_t *s); uint32_t  nn_ctxstr_ctx_count(const nn_ctxstr_t *s); -/* Element reads with idx >= ctx_count return 0 (asserts in debug- * builds) rather than reading out of bounds. */+/* Element reads take idx < ctx_count: an index past it aborts+ * (NN_ASSERT). */ uint8_t   nn_ctxstr_elem_tag(const nn_ctxstr_t *s, uint32_t idx);-uint32_t nn_ctxstr_elem_hash(const nn_ctxstr_t *s, uint32_t idx);-uint32_t nn_ctxstr_elem_name(const nn_ctxstr_t *s, uint32_t idx);-uint32_t nn_ctxstr_elem_output(const nn_ctxstr_t *s, uint32_t idx);+nn_str_t *nn_ctxstr_elem_hash(const nn_ctxstr_t *s, uint32_t idx);+nn_str_t *nn_ctxstr_elem_name(const nn_ctxstr_t *s, uint32_t idx);+nn_str_t *nn_ctxstr_elem_output(const nn_ctxstr_t *s, uint32_t idx);++/* --- Census (nn_stats.h) --- */++/* Every string allocated and not yet freed: the module's own tracker,+ * whose array moves when the next string is created and is freed by+ * nn_ctxstr_free_all. */+const nn_tracker_t *nn_ctxstr_tracked(void);++/* Free the strings from place `from` of the tracker on that `keep`+ * refuses, and close up the rest (nn_tracker_sweep). */+void nn_ctxstr_sweep(uint32_t from, nn_tracker_keep_t keep, void *ctx);++/* Bytes a string holds from the allocator: its header and its context+ * elements. */+uint64_t nn_ctxstr_bytes(const nn_ctxstr_t *s);  #endif /* NN_CTXSTR_H */
cbits/nn_env.c view
@@ -1,42 +1,85 @@ /*  * nn_env.c - C-native evaluation environments.  *- * Arena-allocated nn_env_t structs and backing arrays.  Pages are- * 256 KB each, allocated on demand as a linked list.  Each allocation- * bumps a pointer within the current page.+ * Arena-allocated envs (nn_env.h), with-scope arrays, list items arrays+ * and deferred applications' cells.  Pages are NN_ENV_PAGE_SIZE bytes, or+ * a request's own size when it is larger, allocated on demand as a linked+ * list.  Each allocation bumps a pointer within the current room: a new+ * page, or, while the region collector runs, a run of a page's free lines+ * (nn_region_refill).  *- * All memory is freed in bulk via nn_env_destroy().+ * Pages are freed only in bulk, by nn_env_destroy().  */  #include "nn_env.h" #include "nn_assert.h"+#include "nn_region.h"+#include "nn_stats.h"  #include <stdio.h> #include <stdlib.h> #include <string.h> -/* --- Constants --- */--#define NN_ENV_PAGE_SIZE (256u * 1024u)  /* 256 KB per page */-#define NN_ENV_ALIGN     8u              /* 8-byte alignment */- /* --- Internal types --- */  struct nn_env_page {     struct nn_env_page *next;     /* NULL for newest page */-    uint32_t            used;     /* bytes used in this page */+    uint32_t            used;     /* one past the last byte ever handed out */     uint32_t            capacity; /* usable bytes in this page */     /* Flexible array member: page data follows */     char                data[]; }; +/* --- Alignment --- */++/* C99 has no alignof: a type's alignment is the offset it takes after a+ * char in a struct.  Every allocation starts at an NN_ENV_ALIGNMENT+ * boundary of a page's data, which malloc aligns for any type.  An env's+ * strictest member is a slot, a void *, so the env, its slots, and the+ * parent and scopes that follow the slots a whole number of pointers on+ * are aligned when the boundary is a multiple of a pointer's alignment+ * and the parent and scopes need no more than a pointer does. */+struct nn_env_align_pointer { char c; void *p; };+struct nn_env_align_env_pointer { char c; nn_env_t *p; };+struct nn_env_align_scopes { char c; nn_env_scopes_t s; };+struct nn_env_align_word { char c; uintptr_t w; };++typedef char nn_env_page_data_check_[+    (offsetof(struct nn_env_page, data) % NN_ENV_ALIGNMENT == 0) ? 1 : -1];+typedef char nn_env_pointer_align_check_[+    (NN_ENV_ALIGNMENT % offsetof(struct nn_env_align_pointer, p) == 0) ? 1 : -1];+typedef char nn_env_env_pointer_align_check_[+    (offsetof(struct nn_env_align_env_pointer, p) <= offsetof(struct nn_env_align_pointer, p)) ? 1 : -1];+typedef char nn_env_scopes_align_check_[+    (offsetof(struct nn_env_align_scopes, s) <= offsetof(struct nn_env_align_pointer, p)) ? 1 : -1];++/* A short env keeps its slot count in the low bits of its parent's+ * address, so every env's address has them clear: one from the pages,+ * at an NN_ENV_ALIGNMENT boundary, and the static empty env, aligned as+ * its word is. */+typedef char nn_env_short_page_check_[(NN_ENV_ALIGNMENT > NN_ENV_SHORT_MASK) ? 1 : -1];+typedef char nn_env_short_static_check_[+    (offsetof(struct nn_env_align_word, w) > NN_ENV_SHORT_MASK) ? 1 : -1];+typedef char nn_env_short_max_check_[(NN_ENV_SHORT_MAX == NN_ENV_SHORT_MASK) ? 1 : -1];+ /* --- Global state --- */ +/* The first page and the newest, for iteration and for linking a new+ * one, and the page envs are bumped from, with its room: from the cursor+ * to below the limit, in bytes.  A page is a room of its own when it is+ * new; while the region collector runs, a room can also be lines of a+ * page it freed (nn_region_refill). */ static struct nn_env_page *g_first_page = NULL;+static struct nn_env_page *g_last_page = NULL; static struct nn_env_page *g_current_page = NULL;-static uint64_t g_total_bytes = 0;+static uint32_t g_cursor = 0;+static uint32_t g_limit = 0;+static uint64_t g_app_count = 0;+static uint64_t g_app_bytes = 0;+static uint64_t g_bytes_allocated = 0; -/* Global empty env - initialized in nn_env_init, valid until destroy. */+/* The empty env: a zeroed static that nothing writes, valid in and+ * outside every init .. destroy window. */ static nn_env_t g_empty_env;  /* --- Internal helpers --- */@@ -50,6 +93,8 @@     page->next = NULL;     page->used = 0;     page->capacity = capacity;+    /* Every page made becomes the one allocation bumps from. */+    if (nn_region_mode) nn_region_block(NN_REGION_ENV_PAGE, page->data, capacity, 1);     return page; } @@ -59,6 +104,35 @@     return (n + alignment - 1) & ~(alignment - 1); } +/* Bump from the room the collector names next, with space for `bytes`,+ * or from a new page.  A request larger than a page gets a page of its+ * own. */+static int+refill(uint32_t bytes)+{+    const char *data;+    uint64_t start, limit;+    struct nn_env_page *page;+    if (nn_region_mode == NN_REGION_COLLECT && bytes <= NN_ENV_PAGE_SIZE) {+        /* The room ends here even if no page follows (nn_region_refill). */+        g_limit = g_cursor;+        if (nn_region_refill(NN_REGION_ENV_PAGE, g_cursor, bytes, &data, &start, &limit) == 0) {+            g_current_page = (struct nn_env_page *)(void *)(data - offsetof(struct nn_env_page, data));+            g_cursor = (uint32_t)start;+            g_limit = (uint32_t)limit;+            return 0;+        }+    }+    page = alloc_page(bytes > NN_ENV_PAGE_SIZE ? bytes : NN_ENV_PAGE_SIZE);+    if (!page) return -1;+    g_last_page->next = page;+    g_last_page = page;+    g_current_page = page;+    g_cursor = 0;+    g_limit = page->capacity;+    return 0;+}+ /* Allocate raw bytes from the page-based bump allocator.  * Returns aligned, zero-initialized memory, or NULL on overflow/OOM. */ static void *@@ -66,49 +140,149 @@ {     /* align_up would wrap for sizes near UINT32_MAX; such a request can      * only be corrupt input, so fail it instead of wrapping small. */-    if (bytes > UINT32_MAX - (NN_ENV_ALIGN - 1)) return NULL;-    bytes = align_up(bytes, NN_ENV_ALIGN);+    if (bytes > UINT32_MAX - (NN_ENV_ALIGNMENT - 1)) return NULL;+    bytes = align_up(bytes, NN_ENV_ALIGNMENT);      /* No pages before nn_env_init or after nn_env_destroy.  Opening a      * first page here instead would hand out memory the next      * nn_env_init frees, under every pointer built from it. */     if (!g_current_page) return NULL; -    /* used <= capacity always holds, so capacity - used cannot underflow;-     * the additive form (used + bytes > capacity) overflows uint32_t for+    /* cursor <= limit always holds, so limit - cursor cannot underflow;+     * the additive form (cursor + bytes > limit) overflows uint32_t for      * near-4GB requests and would pass the check, then memset past the      * end of a 256 KB page. */-    if (bytes > g_current_page->capacity - g_current_page->used) {-        uint32_t page_cap = bytes > NN_ENV_PAGE_SIZE ? bytes : NN_ENV_PAGE_SIZE;-        struct nn_env_page *page = alloc_page(page_cap);-        if (!page) return NULL;-        g_current_page->next = page;-        g_current_page = page;-    }+    if (bytes > g_limit - g_cursor && refill(bytes) != 0) return NULL; -    void *result = g_current_page->data + g_current_page->used;+    void *result = g_current_page->data + g_cursor;     memset(result, 0, bytes);-    g_current_page->used += bytes;-    g_total_bytes += bytes;+    g_cursor += bytes;+    if (g_cursor > g_current_page->used) g_current_page->used = g_cursor;+    g_bytes_allocated += bytes;     return result; } +/* An array of `count` pointers, or NULL for none or for one past the+ * allocator's uint32 byte limit. */+static void **+nn_env_alloc_pointers(uint32_t count)+{+    if (count == 0) return NULL;+    uint64_t bytes64 = (uint64_t)count * sizeof(void *);+    if (bytes64 > UINT32_MAX) return NULL;+    return (void **)nn_env_alloc_raw((uint32_t)bytes64);+}++/* --- The word (nn_env.h) --- */++/* Whether an env is short: its word is its parent and slot count. */+static int+is_short(const nn_env_t *env)+{+    return (env->word & NN_ENV_SHORT_MASK) != 0;+}++static uint32_t+slot_count_of(const nn_env_t *env)+{+    return is_short(env) ? (uint32_t)(env->word & NN_ENV_SHORT_MASK)+                         : (uint32_t)(env->word >> NN_ENV_COUNT_SHIFT);+}++/* The fields a header says follow the slots; none for a short env. */+static uintptr_t+fields_of(const nn_env_t *env)+{+    return is_short(env) ? 0 : env->word & (NN_ENV_PARENT | NN_ENV_SCOPES);+}++/* The bytes an env of this shape takes: its word, its slots and the+ * fields its header names (nn_env.h), none for a short env. */+static uint64_t+env_shape_bytes(uint32_t slot_count, uintptr_t fields)+{+    return (uint64_t)sizeof(nn_env_t)+         + (uint64_t)slot_count * sizeof(void *)+         + ((fields & NN_ENV_PARENT) ? sizeof(nn_env_t *) : 0)+         + ((fields & NN_ENV_SCOPES) ? sizeof(nn_env_scopes_t) : 0);+}++/* The first byte past an env's slots, where a header's parent and scopes+ * go. */+static char *+tail_of(nn_env_t *env)+{+    return (char *)(void *)(env->slots + slot_count_of(env));+}++static const char *+const_tail_of(const nn_env_t *env)+{+    return (const char *)(const void *)(env->slots + slot_count_of(env));+}++/* Where the scopes of a header with NN_ENV_SCOPES start: after its parent+ * when it has one. */+static size_t+scopes_offset(uintptr_t fields)+{+    return (fields & NN_ENV_PARENT) ? sizeof(nn_env_t *) : 0;+}++static nn_env_t *+parent_of(const nn_env_t *env)+{+    if (is_short(env)) return (nn_env_t *)(env->word & ~NN_ENV_SHORT_MASK);+    if (!(env->word & NN_ENV_PARENT)) return NULL;+    return *(nn_env_t *const *)(const void *)const_tail_of(env);+}++/* An env of `slot_count` NULL slots under `parent` (or none), with the+ * scopes when `scopes` is non-NULL: short when nn_env.h says it is, and+ * otherwise a header and the fields it names.  It counts once under+ * `site` while the census counts sites (nn_stats.h), with its slots and+ * its bytes, which are a whole number of NN_ENV_ALIGNMENT units. */+static nn_env_t *+env_alloc(uint32_t slot_count, nn_env_t *parent, const nn_env_scopes_t *scopes,+          uint32_t site)+{+    int short_env = slot_count >= 1 && slot_count <= NN_ENV_SHORT_MAX && !scopes;+    uintptr_t fields = short_env ? 0+                     : (parent ? NN_ENV_PARENT : 0) | (scopes ? NN_ENV_SCOPES : 0);+    uint64_t bytes = env_shape_bytes(slot_count, fields);+    /* A parent's low bits would read back as a slot count.  No env's+     * address has them set, so a parent that does is corrupt state. */+    NN_ASSERT(((uintptr_t)parent & NN_ENV_SHORT_MASK) == 0,+              "env_alloc: parent address with NN_ENV_SHORT_MASK bits set");+    if (bytes > UINT32_MAX) return NULL;+    nn_env_t *env = (nn_env_t *)nn_env_alloc_raw((uint32_t)bytes);+    if (!env) return NULL;+    if (nn_stats_counting) nn_stats_count_env(site, slot_count, bytes);+    if (short_env) {+        env->word = (uintptr_t)parent | (uintptr_t)slot_count;+        return env;+    }+    env->word = ((uintptr_t)slot_count << NN_ENV_COUNT_SHIFT) | fields;+    if (parent) *(nn_env_t **)(void *)tail_of(env) = parent;+    if (scopes)+        *(nn_env_scopes_t *)(void *)(tail_of(env) + scopes_offset(fields)) = *scopes;+    return env;+}+ /* --- Lifecycle --- */  void nn_env_init(void) {-    if (g_first_page) {-        nn_env_destroy();-    }-     g_first_page = alloc_page(NN_ENV_PAGE_SIZE);     if (!g_first_page) { fprintf(stderr, "nn_env_init: page alloc failed\n"); abort(); }+    g_last_page = g_first_page;     g_current_page = g_first_page;-    g_total_bytes = 0;--    /* Initialize global empty env */-    memset(&g_empty_env, 0, sizeof(g_empty_env));+    g_cursor = 0;+    g_limit = g_first_page->capacity;+    g_app_count = 0;+    g_app_bytes = 0;+    g_bytes_allocated = 0; }  int@@ -127,22 +301,65 @@         page = next;     }     g_first_page = NULL;+    g_last_page = NULL;     g_current_page = NULL;-    g_total_bytes = 0;+    g_cursor = 0;+    g_limit = 0;+    g_app_count = 0;+    g_app_bytes = 0;+    g_bytes_allocated = 0; } -/* --- Slot allocation --- */+/* --- List items --- */  void **-nn_env_alloc_slots(uint32_t count)+nn_env_alloc_items(uint32_t count) {-    if (count == 0) return NULL;-    uint64_t bytes64 = (uint64_t)count * sizeof(void *);-    if (bytes64 > UINT32_MAX) return NULL;-    uint32_t bytes = (uint32_t)bytes64;-    return (void **)nn_env_alloc_raw(bytes);+    return nn_env_alloc_pointers(count); } +/* --- Deferred applications' cells --- */++void **+nn_env_alloc_app_cells(uint32_t count)+{+    void **cells = nn_env_alloc_pointers(count);+    if (cells) {+        g_app_count++;+        g_app_bytes += (uint64_t)count * sizeof(void *);+    }+    return cells;+}++uint64_t+nn_env_app_count(void)+{+    return g_app_count;+}++uint64_t+nn_env_app_bytes(void)+{+    return g_app_bytes;+}++/* --- With-scopes arrays --- */++/* An array of `count` with-scope entries for an env at `site`, all NULL,+ * or NULL for none, for one past the allocator's uint32 byte limit or on+ * OOM. */+static void **+nn_env_alloc_with_scopes(uint32_t count, uint32_t site)+{+    void **withs = nn_env_alloc_pointers(count);+    /* nn_env_alloc_pointers refused every count whose bytes pass+     * UINT32_MAX, and a whole number of pointers is a whole number of+     * NN_ENV_ALIGNMENT units. */+    if (withs && nn_stats_counting)+        nn_stats_count_env_bytes(site, (uint64_t)count * sizeof(void *));+    return withs;+}+ /* --- Env constructors --- */  nn_env_t *@@ -152,81 +369,71 @@ }  nn_env_t *-nn_env_new(void **slots, uint32_t slot_count,-           void *lazy_scope, nn_env_t *parent,-           void **with_scopes, uint32_t with_count)+nn_env_new(uint32_t slot_count, nn_env_t *parent, uint32_t site) {-    nn_env_t *env = (nn_env_t *)nn_env_alloc_raw((uint32_t)sizeof(nn_env_t));-    if (!env) return NULL;-    env->slots = slots;-    env->slot_count = slot_count;-    env->lazy_scope = lazy_scope;-    env->parent = parent;-    env->with_scopes = with_scopes;-    env->with_count = with_count;-    return env;+    return env_alloc(slot_count, parent, NULL, site); }  nn_env_t *-nn_env_from_slots(void **slots, uint32_t slot_count,-                  nn_env_t *parent)+nn_env_new_scoped(uint32_t slot_count, nn_env_t *parent,+                  void *name_table,+                  void **with_scopes, uint32_t with_count,+                  uint32_t site) {-    nn_env_t *env = (nn_env_t *)nn_env_alloc_raw((uint32_t)sizeof(nn_env_t));-    if (!env) return NULL;-    env->slots = slots;-    env->slot_count = slot_count;-    env->lazy_scope = NULL;-    env->parent = parent;-    env->with_scopes = parent ? parent->with_scopes : NULL;-    env->with_count = parent ? parent->with_count : 0;-    return env;+    nn_env_scopes_t scopes;+    /* A count without its array would send nn_env_push_with's copy and+     * every with lookup through NULL. */+    NN_ASSERT(with_count == 0 || with_scopes != NULL,+              "nn_env_new_scoped: a with-scope count without an array");+    scopes.name_table = name_table;+    scopes.with_scopes = with_scopes;+    scopes.with_count = with_count;+    return env_alloc(slot_count, parent, &scopes, site); }  nn_env_t *-nn_env_push_with(nn_env_t *base, void *scope)+nn_env_push_with(nn_env_t *base, void *scope, uint32_t site) {-    /* The increment must not wrap.  Counts anywhere near this bound-     * cannot allocate anyway (the array alloc caps at UINT32_MAX-     * bytes), so this is the formal guard, not a reachable limit. */-    if (base->with_count == UINT32_MAX) return NULL;-    uint32_t new_count = base->with_count + 1;-    void **new_withs = nn_env_alloc_with_scopes(new_count);+    const nn_env_t *owner = nn_env_with_owner(base);+    uint32_t outer = owner ? nn_env_with_count(owner) : 0;++    /* Every with-scopes array is one nn_env_alloc_with_scopes made, of+     * fewer than UINT32_MAX entries, so the increment does not wrap. */+    NN_ASSERT(outer < UINT32_MAX,+              "nn_env_push_with: with-scope count at UINT32_MAX");+    uint32_t new_count = outer + 1;+    void **new_withs = nn_env_alloc_with_scopes(new_count, site);     if (!new_withs) return NULL; -    /* New scope at index 0 (innermost) */+    /* New scope at index 0 (innermost), then the ones base sees. */     new_withs[0] = scope;-    /* Copy existing with-scopes after it */-    if (base->with_count > 0 && base->with_scopes) {-        memcpy(new_withs + 1, base->with_scopes,-               (size_t)base->with_count * sizeof(void *));+    if (outer > 0) {+        memcpy(new_withs + 1, nn_env_with_scopes(owner),+               (size_t)outer * sizeof(void *));     } -    nn_env_t *env = (nn_env_t *)nn_env_alloc_raw((uint32_t)sizeof(nn_env_t));+    uint32_t slot_count = slot_count_of(base);+    nn_env_t *env = nn_env_new_scoped(slot_count, parent_of(base),+                                      nn_env_name_table(base),+                                      new_withs, new_count, site);     if (!env) return NULL;-    env->slots = base->slots;-    env->slot_count = base->slot_count;-    env->lazy_scope = base->lazy_scope;-    env->parent = base->parent;-    env->with_scopes = new_withs;-    env->with_count = new_count;+    if (slot_count > 0) {+        memcpy(env->slots, base->slots, (size_t)slot_count * sizeof(void *));+    }     return env; } -nn_env_t *-nn_env_new_minimal(void **slots, uint32_t slot_count)+void+nn_env_resolve_with(void **with_scopes, uint32_t idx, void *set) {-    nn_env_t *env = (nn_env_t *)nn_env_alloc_raw((uint32_t)sizeof(nn_env_t));-    if (!env) return NULL;-    env->slots = slots;-    env->slot_count = slot_count;-    /* lazy_scope, parent, with_scopes, with_count already zero from alloc_raw */-    return env;+    with_scopes[idx] = set;+    if (nn_region_mode) nn_region_record_with(&with_scopes[idx]); }  /* --- Accessors --- */  void **-nn_env_slots(const nn_env_t *env)+nn_env_slots(nn_env_t *env) {     return env->slots; }@@ -234,85 +441,121 @@ uint32_t nn_env_slot_count(const nn_env_t *env) {-    return env->slot_count;+    return slot_count_of(env); } -void *-nn_env_lazy_scope(const nn_env_t *env)+nn_env_t *+nn_env_parent(const nn_env_t *env) {-    return env->lazy_scope;+    return parent_of(env); } -nn_env_t *-nn_env_parent(const nn_env_t *env)+const nn_env_scopes_t *+nn_env_scopes(const nn_env_t *env) {-    return env->parent;+    uintptr_t fields = fields_of(env);+    if (!(fields & NN_ENV_SCOPES)) return NULL;+    return (const nn_env_scopes_t *)(const void *)+        (const_tail_of(env) + scopes_offset(fields)); } +void *+nn_env_name_table(const nn_env_t *env)+{+    const nn_env_scopes_t *scopes = nn_env_scopes(env);+    return scopes ? scopes->name_table : NULL;+}+ void ** nn_env_with_scopes(const nn_env_t *env) {-    return env->with_scopes;+    const nn_env_scopes_t *scopes = nn_env_scopes(env);+    return scopes ? scopes->with_scopes : NULL; }  uint32_t nn_env_with_count(const nn_env_t *env) {-    return env->with_count;+    const nn_env_scopes_t *scopes = nn_env_scopes(env);+    return scopes ? scopes->with_count : 0; } +uint32_t+nn_env_bytes(const nn_env_t *env)+{+    /* env_alloc refused every shape past UINT32_MAX bytes. */+    return (uint32_t)env_shape_bytes(slot_count_of(env), fields_of(env));+}+ /* --- Lookup --- */  void *-nn_env_lookup_resolved(const nn_env_t *env, int level, int idx)+nn_env_lookup_resolved(const nn_env_t *env, uint32_t level, uint32_t idx) {-    NN_ASSERT(env != NULL, "nn_env_lookup_resolved: NULL env");     if (env == NULL) {         return NULL;     }     while (level > 0) {-        NN_ASSERT(env->parent != NULL, "nn_env_lookup_resolved: parent chain too short for level");-        if (env->parent == NULL) {+        const nn_env_t *parent = parent_of(env);+        if (parent == NULL) {             return NULL;         }-        env = env->parent;+        env = parent;         level--;     }-    /* The resolver supplies these indices; guard the slot read in release-       builds too (NDEBUG strips the assert) so a resolver bug surfaces as a-       NULL rather than an out-of-bounds read past the slot array. */-    NN_ASSERT(idx >= 0 && (uint32_t)idx < env->slot_count, "nn_env_lookup_resolved: idx out of bounds");-    if (idx < 0 || (uint32_t)idx >= env->slot_count) {+    if (idx >= slot_count_of(env)) {         return NULL;     }     return env->slots[idx]; } -void *-nn_env_root_scope(const nn_env_t *env)+nn_env_t *+nn_env_with_owner(nn_env_t *env) {-    while (env->parent) {-        env = env->parent;+    while (env && nn_env_with_count(env) == 0) {+        env = parent_of(env);     }-    return env->lazy_scope;+    return env; } -/* --- With-scopes array allocation --- */+/* --- Diagnostics --- */ -void **-nn_env_alloc_with_scopes(uint32_t count)+uint64_t+nn_env_bytes_allocated(void) {-    if (count == 0) return NULL;-    uint64_t bytes64 = (uint64_t)count * sizeof(void *);-    if (bytes64 > UINT32_MAX) return NULL;-    uint32_t bytes = (uint32_t)bytes64;-    return (void **)nn_env_alloc_raw(bytes);+    return g_bytes_allocated; } -/* --- Diagnostics --- */+/* --- Census --- */ +uint32_t+nn_env_pages(char **data, uint32_t *used, uint32_t max)+{+    uint32_t n = 0;+    struct nn_env_page *page;+    for (page = g_first_page; page; page = page->next) {+        if (n < max) {+            data[n] = page->data;+            used[n] = page->used;+        }+        n++;+    }+    return n;+}+ uint64_t-nn_env_bytes_allocated(void)+nn_env_cursor(void) {-    return g_total_bytes;+    return g_cursor;+}++uint64_t+nn_env_reserved_bytes(void)+{+    uint64_t bytes = 0;+    struct nn_env_page *page;+    for (page = g_first_page; page; page = page->next) {+        bytes += sizeof(struct nn_env_page) + (uint64_t)page->capacity;+    }+    return bytes; }
cbits/nn_env.h view
@@ -1,14 +1,43 @@ /*  * nn_env.h - C-native evaluation environments.  *- * Nix evaluation creates millions of environments, each with a- * variable-size array of slot pointers, optional lazy scope (attr set),- * optional parent pointer, and a with-scopes chain.+ * Nix evaluation creates millions of environments.  An env is a word and+ * its slots, followed by the fields its word says it has:  *- * All nn_env_t structs and their backing arrays are arena-allocated- * from a page-based bump allocator.  Nothing is individually freed -- * nn_env_destroy() tears down everything at eval end.+ *   word                 the parent and slot count, or a header+ *   slots[slot_count]    one nn_thunk_t * each+ *   parent               an nn_env_t *, when a header has NN_ENV_PARENT+ *   scopes               an nn_env_scopes_t, when a header has NN_ENV_SCOPES  *+ * An env of 1 to NN_ENV_SHORT_MAX slots and no scopes is short: its word+ * is its parent's address, or 0 for none, with the slot count in the low+ * bits every env's alignment leaves clear, so it takes a word and a+ * pointer a slot, as upstream's Env is a parent and its values+ * (struct Env in eval.hh).  A call's env, the most common, is short,+ * and so is nearly every frame.  Any other env's word is a header: those+ * bits clear, which fields follow the slots, and the slot count.  Only a+ * root env (the builtins, or scopedImport's names over them), a frame+ * whose names are not all static, a with and a trimmed closure under a+ * with have scopes.  Everything an env points to is found from the env+ * alone: its word gives the slot count and which fields follow them.+ *+ * The slots follow the word as a C99 flexible array member, so the+ * compiler places them at a pointer-aligned offset, which nn_env_t's size+ * check below pins at NN_ENV_WORD_BYTES.  Every env starts at an+ * NN_ENV_ALIGNMENT boundary of its page, and every field after the slots+ * starts a whole number of pointers past them, so every slot, parent and+ * scopes field is pointer-aligned.+ *+ * Envs, the with-scope arrays, the list items arrays (nn_list.h) and the+ * cells of deferred applications (nn_thunk.h) are allocated from a+ * page-based bump allocator.  No object is freed on its own: while the+ * region collector runs, a page's lines that hold nothing reached are+ * freed and bumped from again (nn_region.h), and nn_env_destroy() frees+ * every page at eval end.+ *+ * Every allocation for an env names its site, the construct or builtin+ * that makes the env (nn_stats.h), under which the census counts it.+ *  * Lifecycle: nn_env_init() before evaluation, nn_env_destroy() after.  * Not thread-safe - single-threaded evaluation only.  */@@ -16,28 +45,66 @@ #ifndef NN_ENV_H #define NN_ENV_H +#include <stddef.h> #include <stdint.h>  /* --- Env struct --- */ -/* 48 bytes on 64-bit (with padding after slot_count and with_count).- * Could be reduced to 40 bytes by reordering fields, but the current- * layout groups related fields logically and matches access patterns. */ typedef struct nn_env {-    void         **slots;        /* nn_thunk_t* array (or NULL for 0 slots) */-    uint32_t       slot_count;   /* 4 bytes + 4 pad to align lazy_scope */-    void          *lazy_scope;   /* nn_attrset_t* or NULL */-    struct nn_env *parent;       /* nn_env_t* or NULL */-    void         **with_scopes;  /* array of nn_attrset_t* (or NULL) */-    uint32_t       with_count;   /* 4 bytes + 4 pad to struct alignment */+    uintptr_t word;        /* the parent and slot count, or a header */+    void     *slots[];     /* nn_thunk_t *, NULL until the frame is filled */ } nn_env_t; +/* The low bits of a word: a short env's slot count, and 0 in a header.+ * An env's address is a multiple of NN_ENV_ALIGNMENT, which nn_env.c+ * checks exceeds them, so a parent's address has them clear. */+#define NN_ENV_SHORT_MASK ((uintptr_t)7)+#define NN_ENV_SHORT_MAX  7u++/* A header: the fields that follow the slots, in this order, and the+ * slot count from NN_ENV_COUNT_SHIFT up. */+#define NN_ENV_PARENT ((uintptr_t)8)    /* the enclosing env */+#define NN_ENV_SCOPES ((uintptr_t)16)   /* an nn_env_scopes_t */+#define NN_ENV_COUNT_SHIFT 8++/* What an env with NN_ENV_SCOPES has: a name table, an attribute set+ * whose names it binds (the root env's builtins, scopedImport's names+ * over them, or the static names of a frame that also has dynamic ones),+ * and its own with-scopes, innermost first, which every env under it+ * that has none of its own sees (nn_env_with_owner).  Either may be+ * absent: NULL, and NULL with a count of 0. */+typedef struct nn_env_scopes {+    void     *name_table;   /* nn_attrset_t * or NULL */+    void    **with_scopes;  /* with-scope entries or NULL */+    uint32_t  with_count;+} nn_env_scopes_t;++#define NN_ENV_WORD_BYTES   8+#define NN_ENV_SCOPES_BYTES 24++/* C99-compatible compile-time checks of the sizes above, which the+ * bytes an env takes (nn_env_bytes) and the census's figures rest on,+ * and that a header holds any uint32_t slot count. */+typedef char nn_env_word_size_check_[(sizeof(nn_env_t) == NN_ENV_WORD_BYTES) ? 1 : -1];+typedef char nn_env_slots_offset_check_[(offsetof(nn_env_t, slots) == NN_ENV_WORD_BYTES) ? 1 : -1];+typedef char nn_env_scopes_size_check_[(sizeof(nn_env_scopes_t) == NN_ENV_SCOPES_BYTES) ? 1 : -1];+typedef char nn_env_count_width_check_[(UINTPTR_MAX >> NN_ENV_COUNT_SHIFT >= UINT32_MAX) ? 1 : -1];++/* A with-scope entry is an nn_attrset_t *, or a with-scope not yet forced:+ * the nn_thunk_t * of its expression with this bit set, which the+ * evaluator replaces by the set once it forces the thunk. */+#define NN_ENV_LAZY_WITH ((uintptr_t)1)++/* The bytes of each page, or of a request's own size when it is larger. */+#define NN_ENV_PAGE_SIZE (256u * 1024u)+ /* --- Lifecycle --- */  /* Initialize the global env allocator.  Must be called once before  * any nn_env_* calls (except nn_env_destroy, nn_env_live and- * nn_env_empty); outside the init .. destroy window every allocating- * call returns NULL. */+ * nn_env_empty), and only while none is live: nn_env_destroy ends one+ * window before the next nn_env_init opens another.  Outside the+ * init .. destroy window every allocating call returns NULL. */ void nn_env_init(void);  /* Nonzero between nn_env_init and nn_env_destroy. */@@ -47,67 +114,124 @@  * All pointers returned by any nn_env_* function become invalid. */ void nn_env_destroy(void); -/* --- Slot allocation (unchanged from original API) --- */+/* --- List items --- */ -/* Allocate an array of `count` void* pointers.  O(1) amortized.- * All slots initialized to NULL.  Returns NULL if count is 0. */-void **nn_env_alloc_slots(uint32_t count);+/* Allocate an array of `count` void* pointers for a list's items+ * (nn_list.h), which no env site counts.  O(1) amortized.  All entries+ * initialized to NULL.  Returns NULL if count is 0, past the allocator's+ * uint32 byte limit, or on OOM. */+void **nn_env_alloc_items(uint32_t count); +/* --- Deferred applications' cells --- */++/* Allocate an array of `count` void* pointers for the cells of a deferred+ * application (nn_thunk.h), which no env site counts.  All entries+ * initialized to NULL.  Returns NULL if count is 0, past the allocator's+ * uint32 byte limit, or on OOM. */+void **nn_env_alloc_app_cells(uint32_t count);++/* The cell arrays nn_env_alloc_app_cells has handed out since+ * nn_env_init, and their bytes. */+uint64_t nn_env_app_count(void);+uint64_t nn_env_app_bytes(void);+ /* --- Env constructors (all arena-allocated) --- */ -/* Return a pointer to the global empty env (all fields zero/NULL).- * Valid until nn_env_destroy().  Do not modify the returned struct. */+/* Return a pointer to the global empty env: no slots, no parent, no+ * scopes.  A static, valid in and outside every init .. destroy window.+ * Do not modify it. */ nn_env_t *nn_env_empty(void); -/* Full constructor: set all fields explicitly. */-nn_env_t *nn_env_new(void **slots, uint32_t slot_count,-                     void *lazy_scope, nn_env_t *parent,-                     void **with_scopes, uint32_t with_count);+/* An env of `slot_count` NULL slots under `parent`, or under none for a+ * NULL parent, made at `site`.  Its with-scopes are its parent's.+ * Returns NULL past the allocator's uint32 byte limit or on OOM.  A+ * parent with any of NN_ENV_SHORT_MASK set in its address, which no env+ * has, aborts (NN_ASSERT). */+nn_env_t *nn_env_new(uint32_t slot_count, nn_env_t *parent, uint32_t site); -/* Child env with positional slots, inheriting parent's with-scopes.- * lazy_scope = NULL. */-nn_env_t *nn_env_from_slots(void **slots, uint32_t slot_count,-                            nn_env_t *parent);+/* nn_env_new for an env with scopes: a name table (or NULL) and its own+ * with-scopes (or NULL and 0, to see its parent's).  The env holds the+ * array itself, not a copy, so envs may share one: once an env holds it,+ * the only write to an entry is the evaluator's replacing a lazy one by+ * the set its thunk evaluates to, the same set for every env sharing it.+ * A count above 0 without an array aborts (NN_ASSERT). */+nn_env_t *nn_env_new_scoped(uint32_t slot_count, nn_env_t *parent,+                            void *name_table,+                            void **with_scopes, uint32_t with_count,+                            uint32_t site); -/* Copy base env with a new with-scope prepended (innermost position).- * Allocates a new with-scopes array of size (base->with_count + 1). */-nn_env_t *nn_env_push_with(nn_env_t *base, void *scope);+/* The env a with's body runs in, made at `site`: base's slots, parent+ * and name table, with `scope` prepended (innermost) to the with-scopes+ * base sees.  The slots are copied, so base's must all be filled, as they+ * are: nothing is evaluated in a frame before tieFrame (Nix.Eval.Types)+ * fills it.  Allocates a with-scopes array one longer than the one base+ * sees, which is shorter than UINT32_MAX entries, as every array the+ * allocator makes is (NN_ASSERT). */+nn_env_t *nn_env_push_with(nn_env_t *base, void *scope, uint32_t site); -/* Minimal env: slots only, no parent, no with-scopes, no lazy scope. */-nn_env_t *nn_env_new_minimal(void **slots, uint32_t slot_count);+/* Resolve the with-scope entry at `idx` of a with-scopes array to the+ * set its thunk evaluated to (NN_ENV_LAZY_WITH).  The one write into an+ * array after its creation, which a census of regions records+ * (nn_region.h). */+void nn_env_resolve_with(void **with_scopes, uint32_t idx, void *set);  /* --- Accessors --- */ -void       **nn_env_slots(const nn_env_t *env);+/* The env's slots, which the caller fills after construction. */+void       **nn_env_slots(nn_env_t *env); uint32_t     nn_env_slot_count(const nn_env_t *env);-void        *nn_env_lazy_scope(const nn_env_t *env);+/* The parent, or NULL for an env without one. */ nn_env_t    *nn_env_parent(const nn_env_t *env);+/* The scopes, or NULL for an env without them. */+const nn_env_scopes_t *nn_env_scopes(const nn_env_t *env);+/* The name table, or NULL. */+void        *nn_env_name_table(const nn_env_t *env);+/* The env's own with-scopes and their count, NULL and 0 when it has+ * none of its own; nn_env_with_owner finds the ones it sees. */ void       **nn_env_with_scopes(const nn_env_t *env); uint32_t     nn_env_with_count(const nn_env_t *env); +/* The bytes the env takes from its page. */+uint32_t     nn_env_bytes(const nn_env_t *env);+ /* --- Lookup --- */  /* Resolved variable lookup: walk `level` parent hops, then read- * slots[idx].  Returns the nn_thunk_t* at that position.- * Caller must ensure level/idx are in bounds (guaranteed by- * the resolution pass). */-void *nn_env_lookup_resolved(const nn_env_t *env, int level, int idx);--/* Walk parent chain to the root env (parent == NULL), return its- * lazy_scope.  Returns NULL if the root has no lazy scope. */-void *nn_env_root_scope(const nn_env_t *env);--/* --- With-scopes array allocation --- */+ * slots[idx].  Returns the nn_thunk_t* there, or NULL for a NULL env, a+ * level past the parent chain, an index outside the slots, or a slot not+ * yet filled, which the Haskell boundary raises as CInvariantViolated. */+void *nn_env_lookup_resolved(const nn_env_t *env, uint32_t level, uint32_t idx); -/* Allocate an arena array of `count` void* pointers for with-scopes.- * All entries initialized to NULL.  Returns NULL if count is 0, if the- * array size would exceed the allocator's uint32 byte limit, or on- * OOM - the caller must check. */-void **nn_env_alloc_with_scopes(uint32_t count);+/* The env whose with-scopes `env` sees: the first on its parent chain,+ * itself included, with with-scopes of its own, or NULL for none.  An env+ * made under a parent sees what its parent sees until a with or a trimmed+ * closure gives it its own. */+nn_env_t *nn_env_with_owner(nn_env_t *env);  /* --- Diagnostics --- */ -/* Total bytes allocated across all pages (for memory tracking). */+/* The bytes the pages have handed out since nn_env_init. */ uint64_t nn_env_bytes_allocated(void);++/* --- Census (nn_stats.h) --- */++/* The pages, oldest first: for each of the first `max`, its first byte+ * and one past the last byte it has ever handed out go to `data` and+ * `used`.  Every+ * allocation starts at an NN_ENV_ALIGNMENT boundary from its page's first+ * byte.  Returns the number of pages, which may exceed `max`; 0 outside+ * the init .. destroy window. */+uint32_t nn_env_pages(char **data, uint32_t *used, uint32_t max);++/* The alignment nn_env_pages promises. */+#define NN_ENV_ALIGNMENT 8u++/* Bytes the pages hold from the allocator, headers and unused tails+ * included. */+uint64_t nn_env_reserved_bytes(void);++/* Where the next env comes from in the page envs are bumped from, in+ * bytes from its first byte (nn_region.h). */+uint64_t nn_env_cursor(void);  #endif /* NN_ENV_H */
+ cbits/nn_graph.c view
@@ -0,0 +1,186 @@+/*+ * nn_graph.c - The pointers each object of the C data layer holds+ * (nn_graph.h).+ */++#include "nn_graph.h"++#include "nn_ctxstr.h"+#include "nn_env.h"+#include "nn_lambda.h"+#include "nn_list.h"+#include "nn_primop.h"+#include "nn_attrset.h"+#include "nn_thunk.h"++static void object(const nn_graph_visitor_t *v, void *ctx, int kind, const void *p)+{+    if (p) v->object(ctx, kind, p);+}++static void string(const nn_graph_visitor_t *v, void *ctx, const nn_str_t *s)+{+    if (s) v->string(ctx, s);+}++static void array(const nn_graph_visitor_t *v, void *ctx, int kind, const void *owner,+                  void *const *base, uint32_t count)+{+    if (base && count > 0) v->array(ctx, kind, owner, base, count);+}++/* A pending or blackholed thunk holds what it will run: a blackhole keeps+ * its pending form and payload (nn_thunk_mark_pending puts it back to+ * work).  A computed one holds its value's object, if the value is one. */+static void thunk_children(const nn_thunk_t *t, const nn_graph_visitor_t *v, void *ctx)+{+    uint8_t state = nn_thunk_state(t);+    if (state == NN_THUNK_PENDING || state == NN_THUNK_BLACKHOLE) {+        uint8_t form = nn_thunk_pending_form(t);+        switch (form) {+        case NN_PENDING_CODE:+            object(v, ctx, NN_GRAPH_ENV, nn_thunk_payload(t));+            return;+        case NN_PENDING_APPLY1:+        case NN_PENDING_APPLY2:+            /* One more cell than the form's arguments: the function's. */+            array(v, ctx, NN_GRAPH_APP_CELLS, t, (void *const *)nn_thunk_payload(t), (uint32_t)form + 1);+            return;+        default:+            v->unknown(ctx);+            return;+        }+    }+    if (state != NN_THUNK_COMPUTED) {+        v->unknown(ctx);+        return;+    }+    switch (nn_thunk_value_tag(t)) {+    case NN_VALUE_INT:+    case NN_VALUE_FLOAT:+    case NN_VALUE_BOOL:+    case NN_VALUE_NULL:+    case NN_VALUE_PRIMOP:+        return;+    case NN_VALUE_STR:+    case NN_VALUE_PATH:+        string(v, ctx, (const nn_str_t *)nn_thunk_payload(t));+        return;+    case NN_VALUE_LIST:+        object(v, ctx, NN_GRAPH_LIST, nn_thunk_payload(t));+        return;+    case NN_VALUE_ATTRS:+        object(v, ctx, NN_GRAPH_ATTRSET, nn_thunk_payload(t));+        return;+    case NN_VALUE_CTXSTR:+        object(v, ctx, NN_GRAPH_CTXSTR, nn_thunk_payload(t));+        return;+    case NN_VALUE_LAMBDA:+        object(v, ctx, NN_GRAPH_LAMBDA, nn_thunk_payload(t));+        return;+    case NN_VALUE_PRIMOP_APP:+        object(v, ctx, NN_GRAPH_PRIMOP_APP, nn_thunk_payload(t));+        return;+    default:+        v->unknown(ctx);+        return;+    }+}++/* An env's slots and its parent, and its name table and with-scopes when+ * it has scopes. */+static void env_children(const nn_env_t *env, const nn_graph_visitor_t *v, void *ctx)+{+    uint32_t i;+    const nn_env_scopes_t *scopes = nn_env_scopes(env);+    uint32_t slot_count = nn_env_slot_count(env);+    for (i = 0; i < slot_count; i++) object(v, ctx, NN_GRAPH_THUNK, env->slots[i]);+    object(v, ctx, NN_GRAPH_ENV, nn_env_parent(env));+    if (!scopes) return;+    object(v, ctx, NN_GRAPH_ATTRSET, scopes->name_table);+    array(v, ctx, NN_GRAPH_WITH_SCOPES, env, (void *const *)scopes->with_scopes, scopes->with_count);+}++static void attrset_children(const nn_attrset_t *set, const nn_graph_visitor_t *v, void *ctx)+{+    uint32_t n = nn_attrset_layer_count(set), i;+    const nn_symbol_t *keys = nn_attrset_layer_keys(set);+    void *const *values = nn_attrset_layer_values(set);+    for (i = 0; i < n; i++) {+        v->symbol(ctx, keys[i]);+        object(v, ctx, NN_GRAPH_THUNK, values[i]);+    }+    object(v, ctx, NN_GRAPH_ATTRSET, nn_attrset_base(set));+}++static void lambda_children(const nn_lambda_t *lam, const nn_graph_visitor_t *v, void *ctx)+{+    uint32_t i;+    uint32_t formals = nn_lambda_formal_count(lam);+    object(v, ctx, NN_GRAPH_ENV, lam->env);+    v->symbol(ctx, lam->name_sym);+    v->symbol(ctx, lam->lambda_name_sym);+    for (i = 0; i < formals; i++) v->symbol(ctx, lam->entries[i].name_sym);+}++static void primop_app_children(const nn_primop_app_t *app, const nn_graph_visitor_t *v, void *ctx)+{+    uint16_t i;+    for (i = 0; i < app->taken; i++) object(v, ctx, NN_GRAPH_THUNK, app->args[i]);+}++static void ctxstr_children(const nn_ctxstr_t *s, const nn_graph_visitor_t *v, void *ctx)+{+    uint32_t i;+    string(v, ctx, s->text);+    for (i = 0; i < s->ctx_count; i++) {+        string(v, ctx, s->ctx[i].sp_hash);+        string(v, ctx, s->ctx[i].sp_name);+        string(v, ctx, s->ctx[i].output);+    }+}++void nn_graph_children(int kind, const void *p, const nn_graph_visitor_t *v, void *ctx)+{+    switch (kind) {+    case NN_GRAPH_THUNK:+        thunk_children((const nn_thunk_t *)p, v, ctx);+        return;+    case NN_GRAPH_ENV:+        env_children((const nn_env_t *)p, v, ctx);+        return;+    case NN_GRAPH_ATTRSET:+        attrset_children((const nn_attrset_t *)p, v, ctx);+        return;+    case NN_GRAPH_LIST: {+        const nn_list_t *list = (const nn_list_t *)p;+        array(v, ctx, NN_GRAPH_ITEMS, list, (void *const *)list->items, list->count);+        return;+    }+    case NN_GRAPH_LAMBDA:+        lambda_children((const nn_lambda_t *)p, v, ctx);+        return;+    case NN_GRAPH_PRIMOP_APP:+        primop_app_children((const nn_primop_app_t *)p, v, ctx);+        return;+    case NN_GRAPH_CTXSTR:+        ctxstr_children((const nn_ctxstr_t *)p, v, ctx);+        return;+    default:+        v->unknown(ctx);+        return;+    }+}++void nn_graph_entry(int kind, const void *entry, const nn_graph_visitor_t *v, void *ctx)+{+    if (kind == NN_GRAPH_WITH_SCOPES) {+        uintptr_t word = (uintptr_t)entry;+        if (word & NN_ENV_LAZY_WITH)+            object(v, ctx, NN_GRAPH_THUNK, (const void *)(word & ~NN_ENV_LAZY_WITH));+        else+            object(v, ctx, NN_GRAPH_ATTRSET, entry);+        return;+    }+    object(v, ctx, NN_GRAPH_THUNK, entry);+}
+ cbits/nn_graph.h view
@@ -0,0 +1,71 @@+/*+ * nn_graph.h - The pointers each object of the C data layer holds.+ *+ * A walk over the value graph (a census's mark, a region's) needs to know,+ * for every kind of object, which other objects it points at.  That+ * knowledge lives here alone: nn_graph_children hands each pointer an+ * object holds to a visitor, which decides what reaching it means.+ *+ * Objects are thunk cells, envs, attribute sets, list headers, lambdas,+ * builtins' partial applications and strings with context.  Three arrays+ * live in the env pages and are reached through an object, not on their+ * own: an env's with-scopes, a list's items, and a deferred application's+ * cells.  A visitor is handed each array with the object that holds it,+ * and follows the entries it chooses with nn_graph_entry, so a walk can+ * tell an array several owners share from one it has not seen.  Strings+ * and symbols hold no pointer and are handed over as leaves.+ *+ * A NULL pointer is never handed over: an empty slot, an absent parent, a+ * context element without an output.  Statics (the null, true, false and+ * empty list cells, the builtins' cells, the empty env, set and string)+ * are, and the visitor tells them apart.+ */++#ifndef NN_GRAPH_H+#define NN_GRAPH_H++#include <stdint.h>++#include "nn_str.h"++/* --- Kinds --- */++/* Objects. */+#define NN_GRAPH_THUNK      0+#define NN_GRAPH_ENV        1+#define NN_GRAPH_ATTRSET    2+#define NN_GRAPH_LIST       3+#define NN_GRAPH_LAMBDA     4+#define NN_GRAPH_PRIMOP_APP 5+#define NN_GRAPH_CTXSTR     6++/* Arrays of the env pages, each reached through the object that holds+ * it: entries tagged NN_ENV_LAZY_WITH or sets; cells; cells. */+#define NN_GRAPH_WITH_SCOPES 0+#define NN_GRAPH_ITEMS       1+#define NN_GRAPH_APP_CELLS   2++/* --- Visitor --- */++typedef struct nn_graph_visitor {+    /* An object of an NN_GRAPH_* object kind. */+    void (*object)(void *ctx, int kind, const void *object);+    /* An array of an NN_GRAPH_* array kind: `count` entries from `base`,+     * held by `owner` (the env, list header or thunk). */+    void (*array)(void *ctx, int kind, const void *owner, void *const *base, uint32_t count);+    void (*string)(void *ctx, const nn_str_t *s);+    void (*symbol)(void *ctx, uint32_t sym);+    /* A thunk state, pending form or value tag no object has. */+    void (*unknown)(void *ctx);+} nn_graph_visitor_t;++/* Hand every pointer the object holds to the visitor.  An object kind+ * nn_graph does not name goes to `unknown`. */+void nn_graph_children(int kind, const void *object, const nn_graph_visitor_t *visitor, void *ctx);++/* Hand the object an array entry holds to the visitor: a set or a lazy+ * with-scope's thunk for NN_GRAPH_WITH_SCOPES, a cell otherwise.  A NULL+ * entry hands over nothing. */+void nn_graph_entry(int kind, const void *entry, const nn_graph_visitor_t *visitor, void *ctx);++#endif /* NN_GRAPH_H */
+ cbits/nn_hangup.c view
@@ -0,0 +1,112 @@+#if defined(__APPLE__)+#define _DARWIN_C_SOURCE+#elif !defined(_WIN32)+#define _POSIX_C_SOURCE 200809L+#endif++#include "nn_hangup.h"++#include <errno.h>++#if defined(__APPLE__)++#include <stdint.h>+#include <sys/event.h>+#include <sys/types.h>+#include <unistd.h>++/* Wait on a queue watching both descriptors until one reports the end+ * of its file: 1 for the watched socket, 0 for the pipe, -1 on failure. */+static int wait_for_eof(int queue, int watch_fd) {+  struct kevent event;+  int count;++  for (;;) {+    count = kevent(queue, NULL, 0, &event, 1, NULL);+    if (count < 0) {+      if (errno == EINTR) {+        continue;+      }+      return -1;+    }+    if (count > 0 && (event.flags & EV_ERROR) != 0) {+      errno = (int)event.data;+      return -1;+    }+    if (count > 0 && (event.flags & EV_EOF) != 0) {+      return event.ident == (uintptr_t)watch_fd ? 1 : 0;+    }+  }+}++/* Both descriptors are watched with the read filter, which reports EV_EOF+ * when the peer of a socket closes and when a pipe's last writer does;+ * EV_CLEAR keeps a socket the client still sends on from waking the loop+ * more than once per arrival. */+int nn_wait_hangup(int watch_fd, int notify_fd) {+  struct kevent changes[2];+  int queue;+  int answer;+  int saved;++  queue = kqueue();+  if (queue < 0) {+    return -1;+  }+  EV_SET(&changes[0], (uintptr_t)watch_fd, EVFILT_READ, EV_ADD | EV_ENABLE | EV_CLEAR, 0, 0, NULL);+  EV_SET(&changes[1], (uintptr_t)notify_fd, EVFILT_READ, EV_ADD | EV_ENABLE | EV_CLEAR, 0, 0, NULL);+  answer = kevent(queue, changes, 2, NULL, 0, NULL) < 0 ? -1 : wait_for_eof(queue, watch_fd);+  saved = errno;+  (void)close(queue);+  errno = saved;+  return answer;+}++#elif !defined(_WIN32)++#include <poll.h>++/* POSIX reports POLLHUP whatever events are asked for, so none are, and a+ * client sending its next request does not wake the loop.  A descriptor+ * that is not open is reported as POLLNVAL, which would never clear, so it+ * ends the wait as an error. */+int nn_wait_hangup(int watch_fd, int notify_fd) {+  struct pollfd fds[2];++  for (;;) {+    fds[0].fd = watch_fd;+    fds[0].events = 0;+    fds[0].revents = 0;+    fds[1].fd = notify_fd;+    fds[1].events = 0;+    fds[1].revents = 0;+    if (poll(fds, 2, -1) < 0) {+      if (errno == EINTR || errno == EAGAIN) {+        continue;+      }+      return -1;+    }+    if ((fds[0].revents & POLLNVAL) != 0 || (fds[1].revents & POLLNVAL) != 0) {+      errno = EBADF;+      return -1;+    }+    if ((fds[0].revents & POLLHUP) != 0) {+      return 1;+    }+    if ((fds[1].revents & POLLHUP) != 0) {+      return 0;+    }+  }+}++#else /* _WIN32 */++/* The daemon on Windows serves a named pipe, which does not use this wait. */+int nn_wait_hangup(int watch_fd, int notify_fd) {+  (void)watch_fd;+  (void)notify_fd;+  errno = ENOSYS;+  return -1;+}++#endif
+ cbits/nn_hangup.h view
@@ -0,0 +1,17 @@+/* Waiting for a daemon's client to hang up, as upstream's daemon watches+ * each connection while it serves it, so the work for a client that has+ * gone can be stopped.  Windows compiles a stub that fails, because the+ * cabal c-sources entry is unconditional; the daemon there serves a named+ * pipe (Nix.Daemon.Pipe), which does not use this wait. */+#ifndef NN_HANGUP_H+#define NN_HANGUP_H++/* Block until the peer of the connected socket watch_fd hangs up, or until+ * every write end of the pipe whose read end is notify_fd is closed.+ * Returns 1 for the hangup, 0 for the pipe, and -1 with errno set when the+ * wait fails or either descriptor is not open.  On macOS the wait is a+ * kqueue read filter's end-of-file, and elsewhere poll's POLLHUP, as+ * upstream waits on each. */+int nn_wait_hangup(int watch_fd, int notify_fd);++#endif
cbits/nn_lambda.c view
@@ -2,78 +2,121 @@  * nn_lambda.c - Lambda closure structs for nova-nix.  *  * Each nn_lambda_t is a malloc'd struct holding the closure env,- * body bytecode index, and formals specification.  Tracked in a- * global array for bulk cleanup at evaluation end.+ * body bytecode index, and formals specification, tracked+ * (nn_tracker.h) for bulk cleanup at evaluation end.  */  #include "nn_lambda.h" #include "nn_assert.h"+#include "nn_region.h"  #include <stdlib.h> #include <string.h> -/* --- Global tracking for bulk cleanup --- */+/* Every lambda allocated, for bulk cleanup. */+static nn_tracker_t g_tracked; -static nn_lambda_t **g_tracked = NULL;-static uint32_t g_tracked_count = 0;-static uint32_t g_tracked_cap   = 0;+/* --- Shape --- */ -/* Returns 0, or -1 when the tracking array cannot grow. */-static int nn_lambda_track(nn_lambda_t *lam)+/* Where the shape's fields sit: the formals type in the top two bits,+ * the ellipsis flag below it, the count in the rest. */+#define NN_LAMBDA_EXTRA_SHIFT NN_LAMBDA_COUNT_BITS+#define NN_LAMBDA_TYPE_SHIFT  (NN_LAMBDA_COUNT_BITS + 1)+#define NN_LAMBDA_TYPE_MASK   UINT32_C(3)++/* C99-compatible compile-time checks: the type's two bits end the word,+ * and every formals type fits them. */+typedef char nn_lambda_type_bits_check_[(NN_LAMBDA_TYPE_SHIFT + 2 == 32) ? 1 : -1];+typedef char nn_lambda_type_range_check_[(NN_FORMALS_NAMED_SET <= NN_LAMBDA_TYPE_MASK) ? 1 : -1];++/* The most formals whose entries fit the UINT32_MAX byte limit used+ * across the C layer, which nn_lambda_new keeps a count within.  A C99+ * compile-time check that every such count fits the shape: */+#define NN_LAMBDA_ENTRIES_MAX (UINT32_MAX / sizeof(nn_formal_entry_t))+typedef char nn_lambda_count_range_check_[(NN_LAMBDA_ENTRIES_MAX <= NN_LAMBDA_MAX_FORMALS) ? 1 : -1];++/* Whether `formals_type` is one of the NN_FORMALS_* tags. */+static int is_formals_type(uint8_t formals_type) {-    if (g_tracked_count >= g_tracked_cap) {-        if (g_tracked_cap > UINT32_MAX / 2) return -1;-        uint32_t new_cap = g_tracked_cap ? g_tracked_cap * 2 : 256;-        nn_lambda_t **new_arr = (nn_lambda_t **)realloc(-            g_tracked, (size_t)new_cap * sizeof(nn_lambda_t *));-        if (!new_arr) return -1;-        g_tracked = new_arr;-        g_tracked_cap = new_cap;-    }-    g_tracked[g_tracked_count++] = lam;+    switch (formals_type) {+    case NN_FORMALS_NAME:+    case NN_FORMALS_SET:+    case NN_FORMALS_NAMED_SET:+        return 1;+    default:         return 0;     }+} +uint32_t+nn_lambda_shape(uint8_t formals_type, uint8_t allow_extra, uint32_t formal_count)+{+    return (((uint32_t)formals_type & NN_LAMBDA_TYPE_MASK) << NN_LAMBDA_TYPE_SHIFT)+         | ((uint32_t)(allow_extra != 0) << NN_LAMBDA_EXTRA_SHIFT)+         | (formal_count & NN_LAMBDA_MAX_FORMALS);+}++uint8_t+nn_lambda_shape_formals_type(uint32_t shape)+{+    return (uint8_t)((shape >> NN_LAMBDA_TYPE_SHIFT) & NN_LAMBDA_TYPE_MASK);+}++uint8_t+nn_lambda_shape_allow_extra(uint32_t shape)+{+    return (uint8_t)((shape >> NN_LAMBDA_EXTRA_SHIFT) & UINT32_C(1));+}++uint32_t+nn_lambda_shape_formal_count(uint32_t shape)+{+    return shape & NN_LAMBDA_MAX_FORMALS;+}+ /* --- Lifecycle --- */  nn_lambda_t * nn_lambda_new(struct nn_env *env, uint32_t body_bc_idx,               uint8_t formals_type, uint32_t name_sym,+              uint32_t lambda_name_sym,               uint8_t allow_extra, uint32_t formal_count) {+    NN_ASSERT(is_formals_type(formals_type), "nn_lambda_new: unknown formals type");+     /* The count is input-reachable (it scales with the source formal-     * list); computing the entries size in uint64_t and capping it at-     * the UINT32_MAX byte limit used across the C layer keeps the-     * malloc argument from wrapping size_t on any platform. */-    uint64_t entry_bytes64 = (uint64_t)formal_count * sizeof(nn_formal_entry_t);-    if (entry_bytes64 > UINT32_MAX) return NULL;+     * list); refusing one past NN_LAMBDA_ENTRIES_MAX keeps the entries'+     * bytes within the limit, the malloc argument from wrapping size_t on+     * any platform, and the count within the shape. */+    if (formal_count > NN_LAMBDA_ENTRIES_MAX) return NULL;+    size_t entry_bytes = (size_t)formal_count * sizeof(nn_formal_entry_t);      nn_lambda_t *lam = (nn_lambda_t *)malloc(sizeof(nn_lambda_t));     if (!lam) return NULL;      lam->env             = env;     lam->body_bc_idx     = body_bc_idx;-    lam->formals_type = formals_type;     lam->name_sym        = name_sym;-    lam->allow_extra  = allow_extra;-    lam->formal_count = formal_count;+    lam->lambda_name_sym = lambda_name_sym;+    lam->shape           = nn_lambda_shape(formals_type, allow_extra, formal_count);      if (formal_count > 0) {-        lam->entries = (nn_formal_entry_t *)malloc((size_t)entry_bytes64);+        lam->entries = (nn_formal_entry_t *)malloc(entry_bytes);         if (!lam->entries) {             free(lam);             return NULL;         }-        memset(lam->entries, 0, (size_t)entry_bytes64);+        memset(lam->entries, 0, entry_bytes);     } else {         lam->entries = NULL;     } -    if (nn_lambda_track(lam) != 0) {+    if (nn_tracker_add(&g_tracked, lam) != 0) {         free(lam->entries);         free(lam);         return NULL;     }+    if (nn_region_mode) nn_region_tracked(NN_REGION_LAMBDA, lam, g_tracked.count - 1, nn_lambda_bytes(lam));     return lam; } @@ -82,29 +125,31 @@                     uint32_t name_sym, uint32_t has_default,                     uint32_t default_bc_idx) {-    /* Bound stays live under NDEBUG: the fill index derives from-     * input-sized data crossing the FFI, so a violated bound must drop-     * the write, not run past the sized array. */-    NN_ASSERT(lam != NULL && lam->entries != NULL && idx < lam->formal_count,-              "nn_lambda_set_entry: idx out of bounds");-    if (lam == NULL || lam->entries == NULL || idx >= lam->formal_count) return;+    NN_ASSERT(idx < nn_lambda_formal_count(lam), "nn_lambda_set_entry: idx out of bounds");     lam->entries[idx].name_sym       = name_sym;     lam->entries[idx].has_default    = has_default;     lam->entries[idx].default_bc_idx = default_bc_idx; } +/* Free a lambda and its formal entries. */+static void+lambda_free(void *object)+{+    nn_lambda_t *lam = (nn_lambda_t *)object;+    free(lam->entries);+    free(lam);+}+ void nn_lambda_free_all(void) {-    uint32_t i;-    for (i = 0; i < g_tracked_count; i++) {-        free(g_tracked[i]->entries);-        free(g_tracked[i]);+    nn_tracker_free_all(&g_tracked, lambda_free); }-    free(g_tracked);-    g_tracked = NULL;-    g_tracked_count = 0;-    g_tracked_cap = 0;++void+nn_lambda_sweep(uint32_t from, nn_tracker_keep_t keep, void *ctx)+{+    nn_tracker_sweep(&g_tracked, from, keep, ctx, lambda_free); }  /* --- Accessors --- */@@ -124,7 +169,7 @@ uint8_t nn_lambda_formals_type(const nn_lambda_t *lam) {-    return lam->formals_type;+    return nn_lambda_shape_formals_type(lam->shape); }  uint32_t@@ -133,44 +178,55 @@     return lam->name_sym; } +uint32_t+nn_lambda_lambda_name_sym(const nn_lambda_t *lam)+{+    return lam->lambda_name_sym;+}+ uint8_t nn_lambda_allow_extra(const nn_lambda_t *lam) {-    return lam->allow_extra;+    return nn_lambda_shape_allow_extra(lam->shape); }  uint32_t nn_lambda_formal_count(const nn_lambda_t *lam) {-    return lam->formal_count;+    return nn_lambda_shape_formal_count(lam->shape); } -/* Entry reads keep their bound live under NDEBUG (see set_entry);- * a violated bound returns 0 rather than reading out of bounds. */- uint32_t nn_lambda_entry_name(const nn_lambda_t *lam, uint32_t idx) {-    NN_ASSERT(lam != NULL && lam->entries != NULL && idx < lam->formal_count,-              "nn_lambda_entry_name: idx out of bounds or no formals");-    if (lam == NULL || lam->entries == NULL || idx >= lam->formal_count) return 0;+    NN_ASSERT(idx < nn_lambda_formal_count(lam), "nn_lambda_entry_name: idx out of bounds");     return lam->entries[idx].name_sym; }  uint32_t nn_lambda_entry_has_default(const nn_lambda_t *lam, uint32_t idx) {-    NN_ASSERT(lam != NULL && lam->entries != NULL && idx < lam->formal_count,-              "nn_lambda_entry_has_default: idx out of bounds or no formals");-    if (lam == NULL || lam->entries == NULL || idx >= lam->formal_count) return 0;+    NN_ASSERT(idx < nn_lambda_formal_count(lam), "nn_lambda_entry_has_default: idx out of bounds");     return lam->entries[idx].has_default; }  uint32_t nn_lambda_entry_default(const nn_lambda_t *lam, uint32_t idx) {-    NN_ASSERT(lam != NULL && lam->entries != NULL && idx < lam->formal_count,-              "nn_lambda_entry_default: idx out of bounds or no formals");-    if (lam == NULL || lam->entries == NULL || idx >= lam->formal_count) return 0;+    NN_ASSERT(idx < nn_lambda_formal_count(lam), "nn_lambda_entry_default: idx out of bounds");     return lam->entries[idx].default_bc_idx;+}++/* --- Census --- */++const nn_tracker_t *+nn_lambda_tracked(void)+{+    return &g_tracked;+}++uint64_t+nn_lambda_bytes(const nn_lambda_t *lam)+{+    return sizeof(*lam) + (uint64_t)nn_lambda_formal_count(lam) * sizeof(nn_formal_entry_t); }
cbits/nn_lambda.h view
@@ -2,26 +2,27 @@  * nn_lambda.h - Lambda closure structs for nova-nix.  *  * Stores lambda closures entirely in C: captured environment (nn_env_t*),- * body bytecode index, and formal parameter specification.  Replaces- * StablePtr NixValue for VLambda on the GHC heap (~25% of remaining- * heap after M6) with a C-native tag 9 in the thunk system.+ * body bytecode index, and formal parameter specification.  A thunk+ * holds one under NN_VALUE_LAMBDA, so a closure takes nothing on the GHC+ * heap.  *  * Formals are stored as a type tag (Name/Set/NamedSet) plus an array  * of (symbol, has_default, default_bc_idx) entries for set patterns.- * Interned symbols avoid any string allocation - pointer equality- * for name comparison.+ * Names are interned symbols, compared as integers.  *- * Lambda structs are malloc'd and tracked for bulk cleanup via- * nn_lambda_free_all().  Formal entry arrays use malloc (small, typ.- * 1-20 entries).  All freed at evaluation end.+ * Lambda structs and their formal entry arrays are malloc'd, and each+ * lambda is tracked for bulk cleanup via nn_lambda_free_all().  *  * Lifecycle: constructed during evaluation, freed via- * nn_lambda_free_all() at arena teardown.  Not thread-safe.+ * nn_lambda_free_all() at arena teardown, or by nn_lambda_sweep when the+ * region collector finds it unreached.  Not thread-safe.  */  #ifndef NN_LAMBDA_H #define NN_LAMBDA_H +#include "nn_tracker.h"+ #include <stdint.h>  /* Forward declarations */@@ -35,43 +36,77 @@  /* --- Types --- */ -/* A single formal entry: name + optional default bytecode index. */+/* A single formal entry: name + the kind of its default + the default's+ * bytecode index.  The kinds are the Haskell side's+ * (Nix.Eval.CBytecode.formalNoDefault and its siblings): 0 = required,+ * 1 = has a default, 2 = has a default that is a variable naming a slot+ * of the call's frame, whose cell the formal's slot takes. */ typedef struct nn_formal_entry {     uint32_t name_sym;       /* interned symbol ID */-    uint32_t has_default;    /* 0 = required, 1 = has default */+    uint32_t has_default;    /* the default's kind */     uint32_t default_bc_idx; /* bytecode index of default (valid if has_default) */ } nn_formal_entry_t; -/* Lambda closure: env + body + formals specification.- * Packed for minimal size: pointers first, then uint32s, then small- * fields - no internal padding.  formal_count is a full uint32_t- * because the formal list scales with the source expression (a- * narrower count would wrap and undersize the entries array). */+/* A lambda's shape: its formals type, its ellipsis flag and its formal+ * count in one word, the type in the top two bits, the flag in the bit+ * below them and the count in the rest.  The count is input-reachable+ * (it scales with the source formal list); nn_lambda_new refuses every+ * count whose entries would pass the UINT32_MAX byte limit, which is+ * every count above UINT32_MAX / 12, well below NN_LAMBDA_MAX_FORMALS,+ * so no count reaches the flag bits (nn_lambda.c checks this at compile+ * time). */+#define NN_LAMBDA_COUNT_BITS  29+#define NN_LAMBDA_MAX_FORMALS ((UINT32_C(1) << NN_LAMBDA_COUNT_BITS) - 1)++/* Lambda closure: env + body + formals specification.  Two pointers and+ * four words with no padding: a closure is allocated per lambda value,+ * so its size is held at NN_LAMBDA_BYTES, the size on the 64-bit+ * targets nn_thunk.h requires.  lambda_name_sym is the name a set+ * pattern's call errors give the function, the attribute it is bound to,+ * or NN_SYMBOL_INVALID for an anonymous one; a Name lambda holds+ * NN_SYMBOL_INVALID there. */ typedef struct nn_lambda {     struct nn_env         *env;          /* captured closure environment */     nn_formal_entry_t     *entries;      /* formal entries (malloc'd, or NULL) */     uint32_t               body_bc_idx;  /* bytecode index of lambda body */     uint32_t               name_sym;     /* symbol for Name/NamedSet binding */-    uint32_t               formal_count; /* number of formal entries */-    uint8_t                formals_type; /* NN_FORMALS_NAME/SET/NAMED_SET */-    uint8_t                allow_extra;  /* 1 if ellipsis (...) present */+    uint32_t               lambda_name_sym; /* the function's own name */+    uint32_t               shape;        /* nn_lambda_shape() */ } nn_lambda_t; +#define NN_LAMBDA_BYTES 32++/* C99-compatible compile-time check of the size above. */+typedef char nn_lambda_size_check_[(sizeof(nn_lambda_t) == NN_LAMBDA_BYTES) ? 1 : -1];++/* --- Shape --- */++/* Pack a shape.  The type is taken mod 4, any nonzero flag as 1 and the+ * count mod 2^NN_LAMBDA_COUNT_BITS; nn_lambda_new takes only a type and+ * a count that fit. */+uint32_t nn_lambda_shape(uint8_t formals_type, uint8_t allow_extra,+                         uint32_t formal_count);++/* Unpack a shape's fields. */+uint8_t  nn_lambda_shape_formals_type(uint32_t shape);+uint8_t  nn_lambda_shape_allow_extra(uint32_t shape);+uint32_t nn_lambda_shape_formal_count(uint32_t shape);+ /* --- Lifecycle --- */  /* Allocate a new lambda closure.  The entries array is allocated  * internally (formal_count entries).  Fill entries via- * nn_lambda_set_entry() after construction.- * Returns NULL on allocation failure or if the entries array size- * would overflow - the caller must check. */+ * nn_lambda_set_entry() after construction.  formals_type is one of the+ * NN_FORMALS_* tags, and any other aborts (NN_ASSERT).+ * Returns NULL on allocation failure, or when the entries would pass+ * the UINT32_MAX byte limit - the caller must check. */ nn_lambda_t *nn_lambda_new(struct nn_env *env, uint32_t body_bc_idx,                            uint8_t formals_type, uint32_t name_sym,+                           uint32_t lambda_name_sym,                            uint8_t allow_extra, uint32_t formal_count);  /* Set a formal entry at the given index (for construction).- * idx must be < formal_count.  A NULL struct or out-of-range idx is- * dropped (asserts in debug builds) rather than writing out of- * bounds - the bound stays live under NDEBUG. */+ * idx must be < formal_count: an index past it aborts (NN_ASSERT). */ void nn_lambda_set_entry(nn_lambda_t *lam, uint32_t idx,                          uint32_t name_sym, uint32_t has_default,                          uint32_t default_bc_idx);@@ -87,14 +122,29 @@ uint32_t       nn_lambda_body(const nn_lambda_t *lam); uint8_t        nn_lambda_formals_type(const nn_lambda_t *lam); uint32_t       nn_lambda_name_sym(const nn_lambda_t *lam);+uint32_t       nn_lambda_lambda_name_sym(const nn_lambda_t *lam); uint8_t        nn_lambda_allow_extra(const nn_lambda_t *lam); uint32_t       nn_lambda_formal_count(const nn_lambda_t *lam); -/* Read formal entry fields by index (must be < formal_count).- * Out-of-range reads return 0 (asserts in debug builds) rather than- * reading out of bounds. */+/* Read formal entry fields by index, which must be < formal_count: an+ * index past it aborts (NN_ASSERT). */ uint32_t nn_lambda_entry_name(const nn_lambda_t *lam, uint32_t idx); uint32_t nn_lambda_entry_has_default(const nn_lambda_t *lam, uint32_t idx); uint32_t nn_lambda_entry_default(const nn_lambda_t *lam, uint32_t idx);++/* --- Census (nn_stats.h) --- */++/* Every lambda allocated and not yet freed: the module's own tracker,+ * whose array moves when the next lambda is created and is freed by+ * nn_lambda_free_all. */+const nn_tracker_t *nn_lambda_tracked(void);++/* Free the lambdas from place `from` of the tracker on that `keep`+ * refuses, and close up the rest (nn_tracker_sweep). */+void nn_lambda_sweep(uint32_t from, nn_tracker_keep_t keep, void *ctx);++/* Bytes a lambda holds from the allocator: its struct and its formal+ * entries. */+uint64_t nn_lambda_bytes(const nn_lambda_t *lam);  #endif /* NN_LAMBDA_H */
cbits/nn_list.c view
@@ -1,38 +1,21 @@ /*  * nn_list.c - Contiguous array of thunk pointers for lists.  *- * Each nn_list_t is a small header (malloc'd, tracked) pointing to- * a contiguous items array (page-allocated via nn_env_alloc_slots).- * Bulk cleanup frees all headers; the page allocator frees items.+ * Each nn_list_t is a small header (malloc'd and tracked, nn_tracker.h)+ * pointing to a contiguous items array (page-allocated via+ * nn_env_alloc_items).  Bulk cleanup frees all headers; the page+ * allocator frees items.  */  #include "nn_list.h" #include "nn_env.h" #include "nn_assert.h"+#include "nn_region.h"  #include <stdlib.h> -/* --- Global tracking for bulk cleanup --- */--static nn_list_t **g_tracked = NULL;-static uint32_t g_tracked_count = 0;-static uint32_t g_tracked_cap   = 0;--/* Returns 0, or -1 when the tracking array cannot grow. */-static int nn_list_track(nn_list_t *list)-{-    if (g_tracked_count >= g_tracked_cap) {-        if (g_tracked_cap > UINT32_MAX / 2) return -1;-        uint32_t new_cap = g_tracked_cap ? g_tracked_cap * 2 : 256;-        nn_list_t **new_arr = (nn_list_t **)realloc(-            g_tracked, (size_t)new_cap * sizeof(nn_list_t *));-        if (!new_arr) return -1;-        g_tracked = new_arr;-        g_tracked_cap = new_cap;-    }-    g_tracked[g_tracked_count++] = list;-    return 0;-}+/* Every header allocated, for bulk cleanup. */+static nn_tracker_t g_tracked;  /* --- Lifecycle --- */ @@ -45,18 +28,17 @@     nn_list_t *list = (nn_list_t *)malloc(sizeof(nn_list_t));     if (!list) return -1; -    /* Items array via the env page allocator (O(1) bump allocation).-     * nn_env_alloc_slots returns void**, which we cast to nn_thunk**.-     * All slots are zero-initialized (NULL pointers).  When tracking-     * fails the items array stays in its page, which only nn_env_destroy-     * releases. */-    list->items = (struct nn_thunk **)nn_env_alloc_slots(count);+    /* The items array is zeroed in an env page.  When tracking fails it+     * stays there, unreached, until the region collector frees its lines+     * or nn_env_destroy releases the page. */+    list->items = (struct nn_thunk **)nn_env_alloc_items(count);     list->count = count; -    if (!list->items || nn_list_track(list) != 0) {+    if (!list->items || nn_tracker_add(&g_tracked, list) != 0) {         free(list);         return -1;     }+    if (nn_region_mode) nn_region_list(list, g_tracked.count - 1, NULL);      *out = list;     return 0;@@ -73,10 +55,11 @@      rest->items = list->items + n;     rest->count = list->count - n;-    if (nn_list_track(rest) != 0) {+    if (nn_tracker_add(&g_tracked, rest) != 0) {         free(rest);         return -1;     }+    if (nn_region_mode) nn_region_list(rest, g_tracked.count - 1, list);      *out = rest;     return 0;@@ -85,14 +68,13 @@ void nn_list_free_all(void) {-    uint32_t i;-    for (i = 0; i < g_tracked_count; i++) {-        free(g_tracked[i]);+    nn_tracker_free_all(&g_tracked, free); }-    free(g_tracked);-    g_tracked = NULL;-    g_tracked_count = 0;-    g_tracked_cap = 0;++void+nn_list_sweep(uint32_t from, nn_tracker_keep_t keep, void *ctx)+{+    nn_tracker_sweep(&g_tracked, from, keep, ctx, free); }  /* --- Access --- */@@ -115,4 +97,12 @@ {     NN_ASSERT(index < list->count, "nn_list_set: index out of bounds");     list->items[index] = thunk;+}++/* --- Census --- */++const nn_tracker_t *+nn_list_tracked(void)+{+    return &g_tracked; }
cbits/nn_list.h view
@@ -1,13 +1,16 @@ /*  * nn_list.h - Contiguous array of thunk pointers for nova-nix lists.  *- * Replaces Haskell's [Thunk] (linked-list cons cells, ~48 bytes per- * element on the GHC heap) with a flat C array of nn_thunk_t* pointers- * (8 bytes per element, cache-friendly layout).+ * A flat C array of nn_thunk_t* pointers, 8 bytes per element in one+ * contiguous run, against the ~48 bytes per element of the cons cells a+ * Haskell [Thunk] takes on the GHC heap.  *- * The items array is allocated via nn_env_alloc_slots (page-based bump+ * The items array is allocated via nn_env_alloc_items (page-based bump  * allocator).  The nn_list_t header is malloc'd and tracked for bulk- * cleanup via nn_list_free_all().  Both are freed at evaluation end.+ * cleanup via nn_list_free_all().  Both are freed at arena teardown,+ * unless the region collector frees them first: a header through+ * nn_list_sweep, an items array with the lines of the page that hold it+ * (nn_region.h).  *  * Lists are immutable after construction: allocate with nn_list_new,  * fill via nn_list_set, then read with nn_list_get/nn_list_count.@@ -18,12 +21,15 @@  * failure: each returns 0 or -1 and hands the list back through `out`.  *  * Lifecycle: constructed during evaluation, freed via nn_list_free_all()- * at arena teardown.  Not thread-safe - single-threaded evaluation only.+ * at arena teardown or by nn_list_sweep.  Not thread-safe -+ * single-threaded evaluation only.  */  #ifndef NN_LIST_H #define NN_LIST_H +#include "nn_tracker.h"+ #include <stdint.h>  /* Forward declaration - nn_thunk_t is defined in nn_thunk.h */@@ -48,7 +54,7 @@  /* The elements of `list` from index `n` on, as a new tracked header over  * the same items array: O(1) whatever the length, where a copy would- * add count - n slots to pages nothing frees before evaluation end.+ * add count - n slots to the env pages.  * Returns 0 with *out the suffix, or NULL when no element remains  * (`list` empty or n >= count); returns -1 with *out NULL when the  * header cannot be allocated. */@@ -71,5 +77,19 @@ /* Set the thunk pointer at the given index (for construction).  * Index must be < nn_list_count(list). */ void nn_list_set(nn_list_t *list, uint32_t index, struct nn_thunk *thunk);++/* --- Census (nn_stats.h) --- */++/* Every header allocated and not yet freed: the module's own tracker,+ * whose array moves when the next header is created and is freed by+ * nn_list_free_all.  A header nn_list_drop made shares its source's+ * items array and ends where the source ends, so headers that end at one+ * address share one array, which the longest of them spans. */+const nn_tracker_t *nn_list_tracked(void);++/* Free the headers from place `from` of the tracker on that `keep`+ * refuses, and close up the rest (nn_tracker_sweep).  An items array is+ * in an env page, which a header's free leaves alone. */+void nn_list_sweep(uint32_t from, nn_tracker_keep_t keep, void *ctx);  #endif /* NN_LIST_H */
+ cbits/nn_primop.c view
@@ -0,0 +1,97 @@+/*+ * nn_primop.c - A builtin's partial application for nova-nix.+ *+ * Each nn_primop_app_t is one malloc'd block, its argument cells inline+ * after the header, tracked (nn_tracker.h) for bulk cleanup at+ * evaluation end.+ */++#include "nn_primop.h"+#include "nn_assert.h"+#include "nn_region.h"++#include <stdlib.h>+#include <string.h>++/* Every application allocated, for bulk cleanup. */+static nn_tracker_t g_tracked;++/* --- Lifecycle --- */++nn_primop_app_t *+nn_primop_app_new(uint32_t primop, uint16_t forced,+                  struct nn_thunk *const *args, uint16_t taken)+{+    nn_primop_app_t *app;+    size_t arg_bytes;+    NN_ASSERT(taken > 0 && taken <= NN_PRIMOP_APP_MAX_ARGS,+              "nn_primop_app_new: an application takes 1 to NN_PRIMOP_APP_MAX_ARGS arguments");+    NN_ASSERT(args != NULL, "nn_primop_app_new: no argument cells");+    arg_bytes = (size_t)taken * sizeof(struct nn_thunk *);+    app = (nn_primop_app_t *)malloc(sizeof(nn_primop_app_t) + arg_bytes);+    if (!app) return NULL;+    app->primop = primop;+    app->taken = taken;+    app->forced = forced;+    memcpy(app->args, args, arg_bytes);+    if (nn_tracker_add(&g_tracked, app) != 0) {+        free(app);+        return NULL;+    }+    if (nn_region_mode)+        nn_region_tracked(NN_REGION_PRIMOP_APP, app, g_tracked.count - 1, nn_primop_app_bytes(app));+    return app;+}++void+nn_primop_app_free_all(void)+{+    nn_tracker_free_all(&g_tracked, free);+}++void+nn_primop_app_sweep(uint32_t from, nn_tracker_keep_t keep, void *ctx)+{+    nn_tracker_sweep(&g_tracked, from, keep, ctx, free);+}++/* --- Accessors --- */++uint32_t+nn_primop_app_primop(const nn_primop_app_t *app)+{+    return app->primop;+}++uint16_t+nn_primop_app_taken(const nn_primop_app_t *app)+{+    return app->taken;+}++uint16_t+nn_primop_app_forced(const nn_primop_app_t *app)+{+    return app->forced;+}++struct nn_thunk *+nn_primop_app_arg(const nn_primop_app_t *app, uint16_t i)+{+    NN_ASSERT(i < app->taken, "nn_primop_app_arg: index past the arguments taken");+    return app->args[i];+}++/* --- Census --- */++const nn_tracker_t *+nn_primop_app_tracked(void)+{+    return &g_tracked;+}++uint64_t+nn_primop_app_bytes(const nn_primop_app_t *app)+{+    return sizeof(*app) + (uint64_t)app->taken * sizeof(struct nn_thunk *);+}
+ cbits/nn_primop.h view
@@ -0,0 +1,80 @@+/*+ * nn_primop.h - A builtin's partial application for nova-nix.+ *+ * A builtin applied to fewer arguments than it takes is a value: the+ * builtin and the cells of the arguments it has taken, as upstream's+ * tPrimOpApp is a primop and the values applied to it (value.hh at+ * 2.24.9).  A thunk holds one under NN_VALUE_PRIMOP_APP; a builtin with+ * no argument taken is its index, inline under NN_VALUE_PRIMOP+ * (nn_thunk.h).  The builtin is its index in the evaluator's table+ * (Nix.Eval.Builtin), which C does not interpret.+ *+ * Each argument is a cell, so the value graph stays in C: a mark follows+ * the cells like a list's items.  Which arguments were taken forced is+ * recorded beside them, so the evaluator reads back the value it stored.+ *+ * Applications are malloc'd and tracked for bulk cleanup via+ * nn_primop_app_free_all() at arena teardown.  Not thread-safe.+ */++#ifndef NN_PRIMOP_H+#define NN_PRIMOP_H++#include "nn_tracker.h"++#include <stdint.h>++struct nn_thunk;++/* The most arguments one application holds: one bit each in `forced`. */+#define NN_PRIMOP_APP_MAX_ARGS 16u++/* A builtin and the arguments it has taken, first to last.  Bit i of+ * `forced` is set when argument i was taken forced, so its cell holds+ * the value it was taken as; a clear bit is an argument held as the+ * thunk it arrived as. */+typedef struct nn_primop_app {+    uint32_t         primop;+    uint16_t         taken;+    uint16_t         forced;+    struct nn_thunk *args[];+} nn_primop_app_t;++/* --- Lifecycle --- */++/* A partial application of `primop` to the `taken` cells at `args`.+ * Returns NULL on allocation failure.  `taken` is 1 to+ * NN_PRIMOP_APP_MAX_ARGS, and `args` holds that many cells: a count+ * outside that range, or NULL `args`, aborts (NN_ASSERT).  A builtin+ * with none taken is a NN_VALUE_PRIMOP cell, not an application. */+nn_primop_app_t *nn_primop_app_new(uint32_t primop, uint16_t forced,+                                   struct nn_thunk *const *args, uint16_t taken);++/* Free every tracked application.  Call once at evaluation end. */+void nn_primop_app_free_all(void);++/* --- Accessors --- */++uint32_t nn_primop_app_primop(const nn_primop_app_t *app);+uint16_t nn_primop_app_taken(const nn_primop_app_t *app);+uint16_t nn_primop_app_forced(const nn_primop_app_t *app);++/* Argument `i`'s cell; `i` must be below the arguments taken, and an+ * index past them aborts (NN_ASSERT). */+struct nn_thunk *nn_primop_app_arg(const nn_primop_app_t *app, uint16_t i);++/* --- Census (nn_stats.h) --- */++/* Every application allocated and not yet freed: the module's own+ * tracker, whose array moves when the next application is made and is+ * freed by nn_primop_app_free_all. */+const nn_tracker_t *nn_primop_app_tracked(void);++/* Free the applications from place `from` of the tracker on that `keep`+ * refuses, and close up the rest (nn_tracker_sweep). */+void nn_primop_app_sweep(uint32_t from, nn_tracker_keep_t keep, void *ctx);++/* Bytes an application holds from the allocator. */+uint64_t nn_primop_app_bytes(const nn_primop_app_t *app);++#endif /* NN_PRIMOP_H */
+ cbits/nn_region.c view
@@ -0,0 +1,2459 @@+/*+ * nn_region.c - Regions: the collector and the census (nn_region.h).+ *+ * Marks are bits the census keeps beside the data layer: a bit per unit+ * of each block (a thunk cell, NN_ENV_ALIGNMENT bytes of an env page,+ * NN_STR_ALIGNMENT bytes of strings) and a bit per place in each tracker.+ * A survivor's bits cover its whole extent, so whether a block or a part+ * of one holds a survivor is a scan of its bits.  Between closes every+ * mark is clear: a close marks only objects of its own region, and clears+ * its region's bits as it retires them.  A second bit per unit and place+ * remembers what a close found unreached.+ *+ * Each tenure collector marks with the same bits, after the census's own+ * mark at a close has retired its region, and keeps three of its own: a+ * unit or place it has settled, tenuring or freeing it, one it has freed,+ * and one a close has remembered for a region around, so that it is+ * remembered once.  Collecting, only the collector's are kept, and no+ * census mark runs.+ *+ * A block also keeps, per line, the number of the span that last handed+ * it out and whether the collector has freed it, and the collector keeps+ * each bump kind's blocks with free lines for refills.  A region's part+ * of a span is the runs of the span's lines that no later span has+ * taken: a line a refill hands out again is retired with its new span.+ *+ * The address index maps each NN_REGION_UNIT_BYTES of address space a+ * block covers to that block.  Every block is at least a unit, so no+ * block lies inside a unit without reaching its edge, and at most two+ * blocks touch a unit: the one over its first byte and the one over its+ * last.  The tracked objects are found by address in a table of their+ * own.  Both are open-addressing tables kept at most half full.+ */++#include "nn_region.h"++#include "nn_assert.h"+#include "nn_attrset.h"+#include "nn_ctxstr.h"+#include "nn_env.h"+#include "nn_graph.h"+#include "nn_lambda.h"+#include "nn_list.h"+#include "nn_primop.h"+#include "nn_roots.h"+#include "nn_str.h"+#include "nn_thunk.h"++#include <stdlib.h>+#include <string.h>++/* --- Constants --- */++#define NN_REGION_UNIT_SHIFT 18+#define NN_REGION_UNIT_BYTES ((uint64_t)1 << NN_REGION_UNIT_SHIFT)++/* No block, and no slot of the address index. */+#define NN_REGION_NONE UINT32_MAX++/* The collector's line, the census's finest: what a close frees and a+ * refill hands out at a time, and what a span number is kept for. */+#define NN_REGION_LINE ((uint64_t)NN_REGION_LINE_FIRST >> (NN_REGION_LINE_GRAINS - 1))++/* The blocks with free lines a refill looks at in vain before the+ * allocator makes a block, so that a refill costs a bounded scan however+ * fragmented the free lines are.  Any free line holds a request of a line+ * or less, so only a larger one looks in vain. */+#define NN_REGION_REFILL_BLOCKS 4u++/* Collecting, the span table drops the spans that hold no line once it+ * holds NN_REGION_SPAN_GROWTH times what it kept the last time it did,+ * and at least NN_REGION_SPAN_FLOOR, so that each drop's scan, at most a+ * span's lines for each span kept, is paid for by the spans begun since+ * the last. */+#define NN_REGION_SPAN_FLOOR  4096u+#define NN_REGION_SPAN_GROWTH 2u++/* Under AddressSanitizer a freed line is poisoned until a refill hands+ * it out again, so that a read of it fails where a pointer the collector+ * missed reads it. */+#if defined(__SANITIZE_ADDRESS__)+#define NN_REGION_ASAN 1+#elif defined(__has_feature)+#if __has_feature(address_sanitizer)+#define NN_REGION_ASAN 1+#endif+#endif+#ifdef NN_REGION_ASAN+#include <sanitizer/asan_interface.h>+#define NN_REGION_POISON(p, n)   ASAN_POISON_MEMORY_REGION((p), (n))+#define NN_REGION_UNPOISON(p, n) ASAN_UNPOISON_MEMORY_REGION((p), (n))+#else+#define NN_REGION_POISON(p, n)   ((void)(p), (void)(n))+#define NN_REGION_UNPOISON(p, n) ((void)(p), (void)(n))+#endif++/* The low bits of a record: one set for a with-scope entry, clear for a+ * cell; and in a tenure collector's records, one set once a close of its+ * has read the record.  Both are pointer-aligned, so the bits are+ * otherwise zero. */+#define NN_REGION_RECORD_WITH  ((uintptr_t)1)+#define NN_REGION_RECORD_READ  ((uintptr_t)2)+#define NN_REGION_RECORD_FLAGS (NN_REGION_RECORD_WITH | NN_REGION_RECORD_READ)++/* The first capacity of every table, which doubles from there.  A power+ * of two, as the address and object tables' probes need.  What a close+ * remembers for a frame starts smaller: a frame slot keeps its buffer, and+ * each depth and tenure collector has one. */+#define NN_REGION_INITIAL 1024u+#define NN_REGION_ENTRIES_INITIAL 16u++/* Each block grain's block is a quarter of the one before: this many+ * bits shorter. */+#define NN_REGION_GRAIN_SHIFT 2u++/* Multiplicative hashing's constant, 2^64 divided by the golden ratio. */+#define NN_REGION_HASH 0x9E3779B97F4A7C15ull++/* An env page's unit is a pointer, a record's flags fit in the low bits+ * a pointer's alignment leaves clear, and the thresholds fit in 64+ * bits. */+typedef char nn_region_env_unit_check_[(NN_ENV_ALIGNMENT == sizeof(void *)) ? 1 : -1];+typedef char nn_region_record_flags_check_[(sizeof(void *) > NN_REGION_RECORD_FLAGS) ? 1 : -1];+typedef char nn_region_threshold_check_[(NN_REGION_THRESHOLDS < 30) ? 1 : -1];++/* --- Types --- */++/* A tenure collector's bits, a bit per unit or place: `tenured` for one+ * no mark of its enters again but a full one, tenured or freed. */+typedef struct {+    uint8_t *tenured;+    uint8_t *freed;+    uint8_t *remembered;+} tenure_bits_t;++typedef struct {+    uintptr_t     start;   /* the block's first byte of data */+    uintptr_t     end;     /* one past its capacity */+    uint8_t      *marks;   /* a bit per unit: reached by the close under way */+    uint8_t      *died;    /* a bit per unit: found unreached by a close */+    tenure_bits_t tenure[NN_REGION_TENURE_VARIANTS];+    uint32_t     *spans;   /* a span number per line: the room that last handed it out */+    uint8_t      *free;    /* a bit per line: freed by the collector and not handed out since */+    uint32_t      lines;   /* whole lines its capacity holds */+    uint32_t      free_count;+    uint32_t      hint;    /* no line below it is free */+    int           recycling; /* whether it is on its kind's list of blocks with free lines */+    int           kind;+} block_t;++/* A room an allocator bumped from, a new block or lines a refill handed+ * out, numbered in the order the rooms started: from `start` to below+ * `limit` bytes into its block, and bumped up to `end` once it ended. */+typedef struct {+    uint32_t number;+    uint32_t block;+    uint64_t start;+    uint64_t limit;+    uint64_t end;+} span_t;++/* A unit of address space and the blocks that touch it. */+typedef struct {+    uintptr_t unit;    /* UINTPTR_MAX for an empty slot */+    uint32_t  blocks[2];+} unit_slot_t;++/* A tracked object, its place in its tracker and its kind; for a list+ * header, also the first entry of the items array its elements are the+ * tail of. */+typedef struct {+    uintptr_t object;  /* 0 for an empty slot */+    uintptr_t first;+    uint32_t  position;+    int       kind;+} object_slot_t;++/* A tracked kind's marks and died bits, by place. */+typedef struct {+    uint8_t      *marks;+    uint8_t      *died;+    tenure_bits_t tenure[NN_REGION_TENURE_VARIANTS];+    uint32_t      capacity; /* places the bits have room for */+} places_t;++/* What a close remembered for a region around it: an object of an+ * NN_GRAPH object kind, a string, or an array of an NN_GRAPH array kind+ * with its owner and length; and where its remembered bit is, a unit of+ * a block or a place of a tracked kind. */+typedef enum { ENTRY_OBJECT, ENTRY_STRING, ENTRY_ARRAY } entry_what_t;++typedef struct {+    const void  *target;+    const void  *owner;+    uint64_t     index;    /* the unit or place */+    uint32_t     block;    /* NN_REGION_NONE for a place */+    uint32_t     count;+    int          kind;     /* the NN_GRAPH object or array kind */+    int          tracked;  /* a place's tracked kind */+    entry_what_t what;+} entry_t;++/* What a tenure collector does at a close: nothing, below its threshold;+ * mark what no close of its inside tenured; mark the whole region, where+ * what closes inside tenured since it was last marked whole passes its+ * budget; or, at an outermost close, take the census's own mark of the+ * whole region. */+typedef enum { TENURE_NONE, TENURE_YOUNG, TENURE_FULL, TENURE_OUTERMOST } tenure_action_t;++/* An open region's share of a tenure collector: where its records start;+ * the bytes in it that closes inside tenured or freed, and of them+ * tracked objects'; the bytes they freed at each grain, and of them+ * tracked objects'; the bytes they tenured that no mark of the whole has+ * reached since; and what closes inside remembered for it. */+typedef struct {+    uint32_t records;+    uint64_t unchecked;+    uint64_t tenured;+    uint64_t tenured_tracked;+    uint64_t freed[NN_REGION_GRAINS];+    uint64_t freed_tracked;+    entry_t *entries;+    uint32_t entry_count;+    uint32_t entry_cap;+} frame_tenure_t;++/* A tenure collector's records, which a close it does not mark at passes+ * on more of than the census's own; its figures; the bytes it has freed+ * at each grain; and the entries remembered and not yet read. */+typedef struct {+    uintptr_t *records;+    uint32_t   record_count;+    uint32_t   record_cap;+    uint64_t   figures[NN_REGION_TENURE_FIGURES];+    uint64_t   freed[NN_REGION_GRAINS];+    uint64_t   held;+} tenure_t;++/* An open region: what each allocator had handed out as it opened. */+typedef struct {+    uint32_t spans;                                  /* the number the first span after it opened takes */+    uint32_t current_span[NN_REGION_BUMP_KINDS];     /* the span each bump kind bumped from */+    uint64_t current_used[NN_REGION_BUMP_KINDS];     /* and how far into its block it had bumped */+    uint32_t tracked[NN_REGION_TRACKED_KINDS];       /* each tracker's count */+    uint64_t tracked_bytes;+    uint64_t allocated;+    uint32_t records;+    uint32_t root_thunks;+    uint32_t root_envs;+    /* Bytes the simulated collector freed inside this region, at closes+     * of the regions inside it, under each threshold at each grain. */+    uint64_t freed[NN_REGION_THRESHOLDS][NN_REGION_GRAINS];+    frame_tenure_t t[NN_REGION_TENURE_VARIANTS];+} frame_t;++/* The entries of an items array before the ones a list spans, from unit+ * `from` to below `to` of a block: kept with the array, and marked once+ * the mark has followed everything, so that no visit of a list over the+ * whole array finds them marked and passes over what they point at. */+typedef struct {+    uint64_t from;+    uint64_t to;+    uint32_t block;+} head_t;++/* An object a mark pushed, and for a tenure collector's whether the close+ * tenures it, so that the pointers it holds are remembered. */+typedef struct {+    const void *object;+    int         kind;+    int         remember;+} work_t;++/* Whether an object is younger than a region, older, or in no block the+ * census numbers. */+typedef enum { AGE_YOUNGER, AGE_OLDER, AGE_OUTSIDE } age_t;++/* --- State --- */++int nn_region_mode = NN_REGION_OFF;++static struct {+    int failed;++    block_t    *blocks;+    uint32_t    block_count;+    uint32_t    block_cap;+    uint32_t    last;               /* the block the last lookup found */++    /* The spans an open region's part takes in, oldest first, and each+     * bump kind's current one: every span begun since the last close of+     * an outermost region (spans_trim) that may still hold a line+     * (spans_drop). */+    span_t     *spans;+    uint32_t    span_count;+    uint32_t    span_cap;+    uint32_t    span_next;          /* the number the next span takes */+    uint32_t    span_drop_at;       /* the count at which spans_drop runs */+    uint32_t    span_most;          /* the most it has held since the last trim */+    uint32_t    span_most_ended;    /* the most it held before the last trim */+    uint32_t    current_span[NN_REGION_BUMP_KINDS];++    /* Each bump kind's blocks with free lines, and where its next refill+     * looks first. */+    uint32_t   *recycle[NN_REGION_BUMP_KINDS];+    uint32_t    recycle_count[NN_REGION_BUMP_KINDS];+    uint32_t    recycle_cap[NN_REGION_BUMP_KINDS];+    uint32_t    recycle_at[NN_REGION_BUMP_KINDS];++    unit_slot_t *units;+    uint32_t     unit_cap;+    uint32_t     unit_used;++    object_slot_t *objects;+    uint32_t       object_cap;+    uint32_t       object_used;+    places_t       places[NN_REGION_TRACKED_KINDS];+    uint64_t       tracked_bytes;++    uintptr_t *records;+    uint32_t   record_count;+    uint32_t   record_cap;++    frame_t  *frames;+    uint32_t  frame_count;+    uint32_t  frame_cap;++    work_t   *work;+    uint32_t  work_count;+    uint32_t  work_cap;++    head_t   *heads;+    uint32_t  head_count;+    uint32_t  head_cap;++    uint8_t  *live;                 /* scratch: a flag per finest line */+    uint64_t  live_cap;++    /* The close under way; the tenure collector whose mark it is, or -1+     * for the census's own, and whether that mark is of the whole region;+     * and whether the pointers the mark finds where no later close looks+     * are remembered: those in an object it enters or a cell a record+     * names, and not those of a root or of what was remembered before. */+    const frame_t *closing;+    uint64_t surviving;+    uint64_t surviving_tracked;+    uint64_t entered;+    uint64_t examined;+    int      tv;+    int      full;+    int      remembering;++    uint64_t enclosed;              /* bytes the outermost regions allocated */+    uint64_t totals[NN_REGION_TOTALS];+    uint64_t classes[NN_REGION_SIZE_CLASSES][NN_REGION_CLASS_FIGURES];+    uint64_t thresholds[NN_REGION_THRESHOLDS][NN_REGION_THRESHOLD_FIGURES];+    uint64_t freed[NN_REGION_THRESHOLDS][NN_REGION_GRAINS];++    tenure_t t[NN_REGION_TENURE_VARIANTS];+} c;++/* The bytes each tenure collector lets closes inside a region tenure+ * before a close marks the region whole, or 0 for none but the outermost.+ * The collector is the one with NN_REGION_COLLECTOR_BUDGET. */+#define NN_REGION_MIB ((uint64_t)1 << 20)+#define NN_REGION_COLLECTOR        1+#define NN_REGION_COLLECTOR_BUDGET NN_REGION_MIB+static const uint64_t tenure_budgets[NN_REGION_TENURE_VARIANTS] = {+    0, NN_REGION_COLLECTOR_BUDGET, 16 * NN_REGION_MIB, 256 * NN_REGION_MIB+};++/* Whether regions run for the collector, and whether tenure collector v+ * runs: every one under a census, only the collector collecting. */+static int collecting(void)+{+    return nn_region_mode == NN_REGION_COLLECT;+}++static int active(int v)+{+    return !collecting() || v == NN_REGION_COLLECTOR;+}++static void fail(void)+{+    c.failed = 1;+    c.totals[NN_REGION_TOTAL_FAILED] = 1;+}++/* An array of `size`-byte elements with room for `need`, doubling its+ * capacity *cap from `initial` as it grows: the array, moved or not, or+ * NULL with the array and *cap unchanged. */+static void *reserve_from(void *array, uint32_t *cap, size_t size, uint32_t need, uint32_t initial)+{+    uint32_t grown = *cap ? *cap : initial;+    void *moved;+    if (need <= *cap) return array;+    while (grown < need) {+        if (grown > UINT32_MAX / 2) return NULL;+        grown *= 2;+    }+    moved = realloc(array, (size_t)grown * size);+    if (!moved) return NULL;+    *cap = grown;+    return moved;+}++static void *reserve(void *array, uint32_t *cap, size_t size, uint32_t need)+{+    return reserve_from(array, cap, size, need, NN_REGION_INITIAL);+}++/* --- Bits --- */++static uint8_t *bits_new(uint64_t bits)+{+    return (uint8_t *)calloc((size_t)(bits / 8 + 1), 1);+}++static int bit_get(const uint8_t *bits, uint64_t i)+{+    return (bits[i / 8] >> (i % 8)) & 1u;+}++static void bit_set(uint8_t *bits, uint64_t i)+{+    bits[i / 8] |= (uint8_t)(1u << (i % 8));+}++static void bits_set(uint8_t *bits, uint64_t from, uint64_t to)+{+    uint64_t i;+    for (i = from; i < to; i++) bit_set(bits, i);+}++static void bits_clear(uint8_t *bits, uint64_t from, uint64_t to)+{+    uint64_t i;+    for (i = from; i < to; i++) bits[i / 8] &= (uint8_t)~(1u << (i % 8));+}++/* Whether any bit from `from` to below `to` is set. */+static int bits_any(const uint8_t *bits, uint64_t from, uint64_t to)+{+    uint64_t i = from;+    for (; i < to && i % 8 != 0; i++)+        if (bit_get(bits, i)) return 1;+    for (; i + 8 <= to; i += 8)+        if (bits[i / 8]) return 1;+    for (; i < to; i++)+        if (bit_get(bits, i)) return 1;+    return 0;+}++/* Whether every bit from `from` to below `to` is set. */+static int bits_all(const uint8_t *bits, uint64_t from, uint64_t to)+{+    uint64_t i = from;+    for (; i < to && i % 8 != 0; i++)+        if (!bit_get(bits, i)) return 0;+    for (; i + 8 <= to; i += 8)+        if (bits[i / 8] != 0xFFu) return 0;+    for (; i < to; i++)+        if (!bit_get(bits, i)) return 0;+    return 1;+}++static uint32_t ones(uint8_t byte)+{+    uint32_t n = 0;+    for (; byte; byte &= (uint8_t)(byte - 1)) n++;+    return n;+}++/* A close's retirement of the units or places from `from` to below `to`:+ * each one unmarked has died, and every mark is cleared.  The bits around+ * the range belong to objects outside the region and are left alone. */+static void bits_retire(uint8_t *marks, uint8_t *died, uint64_t from, uint64_t to)+{+    uint64_t i = from;+    for (; i < to && i % 8 != 0; i++) {+        uint8_t mask = (uint8_t)(1u << (i % 8));+        if (!(marks[i / 8] & mask)) died[i / 8] |= mask;+        marks[i / 8] &= (uint8_t)~mask;+    }+    for (; i + 8 <= to; i += 8) {+        died[i / 8] |= (uint8_t)~marks[i / 8];+        marks[i / 8] = 0;+    }+    for (; i < to; i++) {+        uint8_t mask = (uint8_t)(1u << (i % 8));+        if (!(marks[i / 8] & mask)) died[i / 8] |= mask;+        marks[i / 8] &= (uint8_t)~mask;+    }+}++/* The bits of eight units or places from `j` * 8 at a tenure collector's+ * retirement (bits_tenure), `mask` saying which of them it retires: each+ * its mark left unmarked is freed, if it was untenured, or for a mark of+ * the whole region if it was not freed before; every one is tenured, and+ * every mark cleared.  Returns the ones it freed. */+static uint8_t byte_tenure(uint8_t *marks, const tenure_bits_t *t, int full, uint64_t j, uint8_t mask)+{+    uint8_t open = (uint8_t)(~(full ? t->freed[j] : t->tenured[j]) & mask);+    uint8_t lost = (uint8_t)(open & ~marks[j]);+    t->freed[j] |= lost;+    t->tenured[j] |= mask;+    marks[j] &= (uint8_t)~mask;+    return lost;+}++/* A tenure collector's retirement of the units or places from `from` to+ * below `to` at a close where it marked (byte_tenure), counting in+ * *reached each it freed that the census's own mark at the close reached,+ * which it did if the census, retiring the region first, left its died+ * bit clear. */+static void bits_tenure(uint8_t *marks, const uint8_t *died, const tenure_bits_t *t, int full, uint64_t from,+                        uint64_t to, uint64_t *reached)+{+    uint64_t i = from;+    for (; i < to && i % 8 != 0; i++) {+        uint8_t mask = (uint8_t)(1u << (i % 8));+        *reached += ones((uint8_t)(byte_tenure(marks, t, full, i / 8, mask) & ~died[i / 8]));+    }+    for (; i + 8 <= to; i += 8) *reached += ones((uint8_t)(byte_tenure(marks, t, full, i / 8, 0xFFu) & ~died[i / 8]));+    for (; i < to; i++) {+        uint8_t mask = (uint8_t)(1u << (i % 8));+        *reached += ones((uint8_t)(byte_tenure(marks, t, full, i / 8, mask) & ~died[i / 8]));+    }+}++/* A tenure collector's retirement at an outermost close, from the+ * census's own mark of the whole region before the census retires it:+ * each unit or place the mark left unmarked is freed, and every one is+ * tenured. */+static void bits_tenure_full(const uint8_t *marks, const tenure_bits_t *t, uint64_t from, uint64_t to)+{+    uint64_t i = from;+    for (; i < to && i % 8 != 0; i++) {+        if (!bit_get(marks, i)) bit_set(t->freed, i);+        bit_set(t->tenured, i);+    }+    for (; i + 8 <= to; i += 8) {+        t->freed[i / 8] |= (uint8_t)~marks[i / 8];+        t->tenured[i / 8] = 0xFFu;+    }+    for (; i < to; i++) {+        if (!bit_get(marks, i)) bit_set(t->freed, i);+        bit_set(t->tenured, i);+    }+}++/* --- Kinds --- */++/* The bytes a mark bit of a bump kind's block stands for. */+static uint64_t unit_bytes(int kind)+{+    switch (kind) {+    case NN_REGION_THUNK_BLOCK: return sizeof(nn_thunk_t);+    case NN_REGION_ENV_PAGE:    return NN_ENV_ALIGNMENT;+    default:                    return NN_STR_ALIGNMENT;+    }+}++/* The block size a bump kind's allocator makes when no object needs a+ * larger one. */+static uint64_t block_bytes(int kind)+{+    switch (kind) {+    case NN_REGION_THUNK_BLOCK: return (uint64_t)NN_THUNK_BLOCK_CELLS * sizeof(nn_thunk_t);+    case NN_REGION_ENV_PAGE:    return NN_ENV_PAGE_SIZE;+    default:                    return NN_STR_BLOCK_BYTES;+    }+}++/* A grain's liveness is read from the finest line's (dead_grains), so+ * every grain is a whole number of the next: each kind's unit divides the+ * finest line, each line is twice the next, and each kind's block is a+ * whole number of the longest line times the block grains' quarterings,+ * which makes every block grain exact and its smallest a whole number of+ * the longest line. */+#define NN_REGION_BLOCK_MULTIPLE \+    ((uint64_t)NN_REGION_LINE_FIRST << (NN_REGION_GRAIN_SHIFT * (NN_REGION_BLOCK_GRAINS - 1)))+typedef char nn_region_line_halves_check_[(NN_REGION_LINE_FIRST % (1u << (NN_REGION_LINE_GRAINS - 1)) == 0) ? 1 : -1];+typedef char nn_region_thunk_line_check_[(NN_REGION_LINE % sizeof(nn_thunk_t) == 0) ? 1 : -1];+typedef char nn_region_env_line_check_[(NN_REGION_LINE % NN_ENV_ALIGNMENT == 0) ? 1 : -1];+typedef char nn_region_str_line_check_[(NN_REGION_LINE % NN_STR_ALIGNMENT == 0) ? 1 : -1];+typedef char nn_region_thunk_grain_check_[+    (((uint64_t)NN_THUNK_BLOCK_CELLS * sizeof(nn_thunk_t)) % NN_REGION_BLOCK_MULTIPLE == 0) ? 1 : -1];+typedef char nn_region_env_grain_check_[(NN_ENV_PAGE_SIZE % NN_REGION_BLOCK_MULTIPLE == 0) ? 1 : -1];+typedef char nn_region_str_grain_check_[(NN_STR_BLOCK_BYTES % NN_REGION_BLOCK_MULTIPLE == 0) ? 1 : -1];++uint64_t nn_region_grain_bytes(int kind, uint32_t grain)+{+    if (grain == 0 || grain >= NN_REGION_GRAINS) return 0;+    if (grain <= NN_REGION_BLOCK_GRAINS) return block_bytes(kind) >> (NN_REGION_GRAIN_SHIFT * (grain - 1));+    return (uint64_t)NN_REGION_LINE_FIRST >> (grain - 1 - NN_REGION_BLOCK_GRAINS);+}++uint64_t nn_region_threshold_bytes(uint32_t k)+{+    if (k == 0) return 0;+    return (uint64_t)NN_REGION_THRESHOLD_FIRST << (NN_REGION_GRAIN_SHIFT * (k - 1));+}++static uint32_t tracker_count(int kind)+{+    switch (kind) {+    case NN_REGION_SET:        return nn_attrset_tracked()->count;+    case NN_REGION_LIST:       return nn_list_tracked()->count;+    case NN_REGION_LAMBDA:     return nn_lambda_tracked()->count;+    case NN_REGION_PRIMOP_APP: return nn_primop_app_tracked()->count;+    default:                   return nn_ctxstr_tracked()->count;+    }+}++static uint64_t tracked_bytes(int kind, const void *object)+{+    switch (kind) {+    case NN_REGION_SET:        return nn_attrset_bytes((const nn_attrset_t *)object);+    case NN_REGION_LIST:       return sizeof(nn_list_t);+    case NN_REGION_LAMBDA:     return nn_lambda_bytes((const nn_lambda_t *)object);+    case NN_REGION_PRIMOP_APP: return nn_primop_app_bytes((const nn_primop_app_t *)object);+    default:                   return nn_ctxstr_bytes((const nn_ctxstr_t *)object);+    }+}++/* Every byte the data layer has handed out for objects. */+static uint64_t allocated_now(void)+{+    return nn_thunk_cells_allocated() * sizeof(nn_thunk_t) + nn_env_bytes_allocated()+         + nn_str_values()->bytes + c.tracked_bytes;+}++/* --- The address index --- */++static uint32_t hash(uint64_t key, uint32_t cap)+{+    return (uint32_t)((key * NN_REGION_HASH) >> 32) & (cap - 1);+}++/* The slot of a unit, or of the empty slot where it would go. */+static unit_slot_t *unit_slot(unit_slot_t *slots, uint32_t cap, uintptr_t unit)+{+    uint32_t i = hash((uint64_t)unit, cap);+    while (slots[i].unit != UINTPTR_MAX && slots[i].unit != unit) i = (i + 1) & (cap - 1);+    return &slots[i];+}++static unit_slot_t *units_new(uint32_t cap)+{+    uint32_t i;+    unit_slot_t *slots = (unit_slot_t *)malloc((size_t)cap * sizeof(unit_slot_t));+    if (!slots) return NULL;+    for (i = 0; i < cap; i++) slots[i].unit = UINTPTR_MAX;+    return slots;+}++/* Index a unit's block.  Returns 0 or -1. */+static int unit_add(uintptr_t unit, uint32_t block)+{+    unit_slot_t *slot;+    if ((uint64_t)(c.unit_used + 1) * 2 > c.unit_cap) {+        uint32_t cap = c.unit_cap * 2, i;+        unit_slot_t *slots;+        if (c.unit_cap > UINT32_MAX / 2 || !(slots = units_new(cap))) return -1;+        for (i = 0; i < c.unit_cap; i++)+            if (c.units[i].unit != UINTPTR_MAX) *unit_slot(slots, cap, c.units[i].unit) = c.units[i];+        free(c.units);+        c.units = slots;+        c.unit_cap = cap;+    }+    slot = unit_slot(c.units, c.unit_cap, unit);+    if (slot->unit == UINTPTR_MAX) {+        slot->unit = unit;+        slot->blocks[0] = block;+        slot->blocks[1] = NN_REGION_NONE;+        c.unit_used++;+        return 0;+    }+    NN_ASSERT(slot->blocks[1] == NN_REGION_NONE, "nn_region_block: a third block touches a unit");+    slot->blocks[1] = block;+    return 0;+}++/* The block of a bump kind a pointer is in, or NN_REGION_NONE. */+static uint32_t block_of(uintptr_t p, int kind)+{+    const unit_slot_t *slot;+    int i;+    if (c.last != NN_REGION_NONE && p >= c.blocks[c.last].start && p < c.blocks[c.last].end)+        return c.blocks[c.last].kind == kind ? c.last : NN_REGION_NONE;+    slot = unit_slot(c.units, c.unit_cap, p >> NN_REGION_UNIT_SHIFT);+    if (slot->unit == UINTPTR_MAX) return NN_REGION_NONE;+    for (i = 0; i < 2; i++) {+        uint32_t b = slot->blocks[i];+        if (b != NN_REGION_NONE && p >= c.blocks[b].start && p < c.blocks[b].end) {+            c.last = b;+            return c.blocks[b].kind == kind ? b : NN_REGION_NONE;+        }+    }+    return NN_REGION_NONE;+}++/* --- The tracked objects' table --- */++static object_slot_t *object_slot(object_slot_t *slots, uint32_t cap, uintptr_t object)+{+    /* malloc aligns every object, so the low bits carry no information. */+    uint32_t i = hash((uint64_t)object >> 4, cap);+    while (slots[i].object != 0 && slots[i].object != object) i = (i + 1) & (cap - 1);+    return &slots[i];+}++static int object_add(uintptr_t object, uint32_t position, int kind, uintptr_t first)+{+    object_slot_t *slot;+    if ((uint64_t)(c.object_used + 1) * 2 > c.object_cap) {+        uint32_t cap = c.object_cap * 2, i;+        object_slot_t *slots;+        if (c.object_cap > UINT32_MAX / 2) return -1;+        slots = (object_slot_t *)calloc((size_t)cap, sizeof(object_slot_t));+        if (!slots) return -1;+        for (i = 0; i < c.object_cap; i++)+            if (c.objects[i].object != 0) *object_slot(slots, cap, c.objects[i].object) = c.objects[i];+        free(c.objects);+        c.objects = slots;+        c.object_cap = cap;+    }+    slot = object_slot(c.objects, c.object_cap, object);+    if (slot->object == 0) c.object_used++;+    slot->object = object;+    slot->first = first;+    slot->position = position;+    slot->kind = kind;+    return 0;+}++/* Take a tracked object out of the table, moving back each slot after it+ * that its probe passed through it to reach. */+static void object_remove(uintptr_t object)+{+    uint32_t cap = c.object_cap;+    uint32_t hole = (uint32_t)(object_slot(c.objects, cap, object) - c.objects), next = hole;+    if (c.objects[hole].object == 0) return;+    for (;;) {+        uint32_t home;+        next = (next + 1) & (cap - 1);+        if (c.objects[next].object == 0) break;+        home = hash((uint64_t)c.objects[next].object >> 4, cap);+        /* A slot whose probe starts after the hole and at or before it+         * never passed through the hole. */+        if (hole <= next ? (hole < home && home <= next) : (hole < home || home <= next)) continue;+        c.objects[hole] = c.objects[next];+        hole = next;+    }+    c.objects[hole].object = 0;+    c.object_used--;+}++/* Grow an array of bits from `old_bytes` to `bytes`, the new ones clear. */+static int bits_grow(uint8_t **bits, size_t old_bytes, size_t bytes)+{+    uint8_t *grown = (uint8_t *)realloc(*bits, bytes);+    if (!grown) return -1;+    memset(grown + old_bytes, 0, bytes - old_bytes);+    *bits = grown;+    return 0;+}++/* Room in a tracked kind's bits for `need` places. */+static int places_reserve(places_t *places, uint32_t need)+{+    uint32_t cap = places->capacity ? places->capacity : NN_REGION_INITIAL;+    /* A first allocation has no old bytes to keep. */+    size_t old_bytes = places->capacity ? (size_t)places->capacity / 8 + 1 : 0, bytes;+    int v;+    if (need <= places->capacity) return 0;+    while (cap < need) {+        if (cap > UINT32_MAX / 2) return -1;+        cap *= 2;+    }+    bytes = (size_t)cap / 8 + 1;+    if (bits_grow(&places->marks, old_bytes, bytes) != 0 || bits_grow(&places->died, old_bytes, bytes) != 0)+        return -1;+    for (v = 0; v < NN_REGION_TENURE_VARIANTS; v++) {+        tenure_bits_t *t = &places->tenure[v];+        if (!active(v)) continue;+        if (bits_grow(&t->tenured, old_bytes, bytes) != 0 || bits_grow(&t->freed, old_bytes, bytes) != 0+            || bits_grow(&t->remembered, old_bytes, bytes) != 0)+            return -1;+    }+    places->capacity = cap;+    return 0;+}++/* --- Spans and lines --- */++/* Where the allocator of a bump kind bumps from next, in bytes into its+ * current block. */+static uint64_t cursor_of(int kind)+{+    switch (kind) {+    case NN_REGION_THUNK_BLOCK: return nn_thunk_cursor();+    case NN_REGION_ENV_PAGE:    return nn_env_cursor();+    default:                    return nn_str_cursor();+    }+}++/* The span numbered n, or NULL when it is no longer kept. */+static span_t *span_numbered(uint32_t n)+{+    uint32_t lo = 0, hi = c.span_count;+    while (lo < hi) {+        uint32_t mid = lo + (hi - lo) / 2;+        if (c.spans[mid].number < n)+            lo = mid + 1;+        else+            hi = mid;+    }+    return lo < c.span_count && c.spans[lo].number == n ? &c.spans[lo] : NULL;+}++/* The first kept span numbered n or after. */+static uint32_t span_index_from(uint32_t n)+{+    uint32_t lo = 0, hi = c.span_count;+    while (lo < hi) {+        uint32_t mid = lo + (hi - lo) / 2;+        if (c.spans[mid].number < n)+            lo = mid + 1;+        else+            hi = mid;+    }+    return lo;+}++/* Whether a span is the room its kind bumps from now. */+static int span_current(const span_t *s)+{+    return s->number == c.current_span[c.blocks[s->block].kind];+}++/* How far a span has bumped: to the allocator's cursor while it is+ * current, to where it ended otherwise. */+static uint64_t span_end(const span_t *s)+{+    return span_current(s) ? cursor_of(c.blocks[s->block].kind) : s->end;+}++/* Below which offset a span's lines take no more objects: the line the+ * cursor is in still does while the span is current; an ended span's+ * last line is settled, the rest of it unallocated, unless it runs past+ * the block's last whole line. */+static uint64_t span_settled(const span_t *s)+{+    const block_t *blk = &c.blocks[s->block];+    uint64_t whole = (uint64_t)blk->lines * NN_REGION_LINE;+    uint64_t settled;+    if (span_current(s)) return cursor_of(blk->kind) / NN_REGION_LINE * NN_REGION_LINE;+    settled = (s->end + NN_REGION_LINE - 1) / NN_REGION_LINE * NN_REGION_LINE;+    return settled < whole ? settled : whole;+}++/* Put a block on its kind's list of blocks with free lines. */+static void recycle(block_t *blk)+{+    int kind = blk->kind;+    uint32_t *list;+    if (blk->recycling) return;+    list = (uint32_t *)reserve_from(c.recycle[kind], &c.recycle_cap[kind], sizeof(uint32_t),+                                    c.recycle_count[kind] + 1, NN_REGION_ENTRIES_INITIAL);+    if (!list) {+        fail();+        return;+    }+    c.recycle[kind] = list;+    c.recycle[kind][c.recycle_count[kind]++] = (uint32_t)(blk - c.blocks);+    blk->recycling = 1;+}++/* Free a line of a block for a refill to hand out. */+static void free_line(block_t *blk, uint64_t line)+{+    if (bit_get(blk->free, line)) return;+    bit_set(blk->free, line);+    blk->free_count++;+    if (line < blk->hint) blk->hint = (uint32_t)line;+    NN_REGION_POISON((void *)(blk->start + line * NN_REGION_LINE), NN_REGION_LINE);+    recycle(blk);+}++/* End a bump kind's current span where its allocator stopped.+ * Collecting, the whole lines past that it never bumped into are free+ * again. */+static void span_stop(int kind, uint64_t cursor)+{+    span_t *s;+    block_t *blk;+    uint64_t line;+    if (c.current_span[kind] == NN_REGION_NONE) return;+    s = span_numbered(c.current_span[kind]);+    c.current_span[kind] = NN_REGION_NONE;+    if (!s) return;+    s->end = cursor;+    if (!collecting()) return;+    blk = &c.blocks[s->block];+    for (line = (cursor + NN_REGION_LINE - 1) / NN_REGION_LINE; line < s->limit / NN_REGION_LINE; line++)+        free_line(blk, line);+    /* The line the cursor stopped in takes no more objects now, and a+     * close may have freed every one it holds while it still could. */+    line = cursor / NN_REGION_LINE;+    if (cursor % NN_REGION_LINE != 0 && line * NN_REGION_LINE >= s->start && line < blk->lines+        && blk->spans[line] == s->number+        && bits_all(blk->tenure[NN_REGION_COLLECTOR].freed, line * NN_REGION_LINE / unit_bytes(blk->kind),+                    cursor / unit_bytes(blk->kind)))+        free_line(blk, line);+}++/* Whether a span holds a line: one that carries its number and is not+ * free, or the part of a line past its block's last whole one, which is+ * never freed.  A span that holds none gives a close nothing to retire,+ * its lines being free or another span's. */+static int span_holds(const span_t *s)+{+    const block_t *blk = &c.blocks[s->block];+    uint64_t line, last = (s->limit + NN_REGION_LINE - 1) / NN_REGION_LINE;+    for (line = s->start / NN_REGION_LINE; line < last; line++)+        if (blk->spans[line] == s->number && (line >= blk->lines || !bit_get(blk->free, line))) return 1;+    return 0;+}++/* Drop from the table every span but the current ones that holds no+ * line, in order, and run again once it holds NN_REGION_SPAN_GROWTH+ * times what it keeps.  It runs only as a span begins, where no pointer+ * into the table is held. */+static void spans_drop(void)+{+    uint32_t i, kept = 0;+    uint64_t next;+    for (i = 0; i < c.span_count; i++)+        if (span_current(&c.spans[i]) || span_holds(&c.spans[i])) c.spans[kept++] = c.spans[i];+    c.span_count = kept;+    next = (uint64_t)kept * NN_REGION_SPAN_GROWTH;+    c.span_drop_at = next < NN_REGION_SPAN_FLOOR ? NN_REGION_SPAN_FLOOR : next > UINT32_MAX ? UINT32_MAX : (uint32_t)next;+}++/* Start a span of block b from `start` to below `limit` bytes in, as its+ * kind's current one when `current`, the previous one ended first; one+ * that is not current is a block's single object, ended at its limit.+ * Returns 0 or -1. */+static int span_begin(uint32_t b, uint64_t start, uint64_t limit, int current)+{+    block_t *blk = &c.blocks[b];+    span_t *spans, *span;+    uint64_t line, last;+    if (current) span_stop(blk->kind, cursor_of(blk->kind));+    if (collecting() && c.span_count >= c.span_drop_at) spans_drop();+    spans = (span_t *)reserve(c.spans, &c.span_cap, sizeof(span_t), c.span_count + 1);+    if (!spans || c.span_next == NN_REGION_NONE) return -1;+    c.spans = spans;+    span = &c.spans[c.span_count++];+    if (c.span_count > c.span_most) c.span_most = c.span_count;+    span->number = c.span_next++;+    span->block = b;+    span->start = start;+    span->limit = limit;+    span->end = current ? start : limit;+    last = (limit + NN_REGION_LINE - 1) / NN_REGION_LINE;+    for (line = start / NN_REGION_LINE; line < last; line++) blk->spans[line] = span->number;+    if (current) c.current_span[blk->kind] = span->number;+    return 0;+}++/* The first run of a block's free lines at least `lines` long: its first+ * line and length, or 0 for none.  The scan starts at the block's hint+ * and moves it up to the first free line it meets. */+static int free_run(block_t *blk, uint64_t lines, uint64_t *first, uint64_t *count)+{+    uint64_t line = blk->hint;+    int met = 0;+    while (line < blk->lines) {+        uint64_t end;+        if (line % 8 == 0 && blk->free[line / 8] == 0) {+            line += 8;+            continue;+        }+        if (!bit_get(blk->free, line)) {+            line++;+            continue;+        }+        if (!met) {+            blk->hint = (uint32_t)line;+            met = 1;+        }+        for (end = line; end < blk->lines && bit_get(blk->free, end); end++) {}+        if (end - line >= lines) {+            *first = line;+            *count = end - line;+            return 1;+        }+        line = end;+    }+    if (!met) blk->hint = blk->lines;+    return 0;+}++/* Hand out a block's free lines from `first` for `count` lines: cleared+ * of every bit a close left on their units, for objects younger than+ * every open region. */+static void hand_out(block_t *blk, uint64_t first, uint64_t count)+{+    uint64_t unit = unit_bytes(blk->kind);+    uint64_t from = first * NN_REGION_LINE / unit, to = (first + count) * NN_REGION_LINE / unit;+    tenure_bits_t *t = &blk->tenure[NN_REGION_COLLECTOR];+    NN_ASSERT(!bits_any(t->remembered, from, to), "nn_region_refill: a free line holds a remembered unit");+    NN_ASSERT(!bits_any(blk->marks, from, to), "nn_region_refill: a free line holds a marked unit");+    bits_clear(t->tenured, from, to);+    bits_clear(t->freed, from, to);+    bits_clear(blk->died, from, to);+    bits_clear(blk->free, first, first + count);+    blk->free_count -= (uint32_t)count;+    if (first == blk->hint) blk->hint = (uint32_t)(first + count);+    NN_REGION_UNPOISON((void *)(blk->start + first * NN_REGION_LINE), count * NN_REGION_LINE);+}++int nn_region_refill(int kind, uint64_t cursor, uint64_t need, const char **data, uint64_t *start,+                     uint64_t *limit)+{+    uint64_t lines = (need + NN_REGION_LINE - 1) / NN_REGION_LINE, first, count;+    uint32_t looked = 0;+    if (!collecting() || c.failed) return -1;+    span_stop(kind, cursor);+    while (c.recycle_count[kind] > 0 && looked < NN_REGION_REFILL_BLOCKS && !c.failed) {+        uint32_t at = c.recycle_at[kind] % c.recycle_count[kind];+        uint32_t b = c.recycle[kind][at];+        block_t *blk = &c.blocks[b];+        if (blk->free_count == 0) {+            c.recycle[kind][at] = c.recycle[kind][--c.recycle_count[kind]];+            blk->recycling = 0;+            continue;+        }+        if (free_run(blk, lines, &first, &count)) {+            hand_out(blk, first, count);+            if (span_begin(b, first * NN_REGION_LINE, (first + count) * NN_REGION_LINE, 1) != 0) {+                fail();+                return -1;+            }+            *data = (const char *)blk->start;+            *start = first * NN_REGION_LINE;+            *limit = (first + count) * NN_REGION_LINE;+            return 0;+        }+        c.recycle_at[kind] = at + 1;+        looked++;+    }+    return -1;+}++/* As an outermost region closes no part takes a span in, so only the+ * current ones are kept, spans_drop runs again from its floor, and the+ * stretch since the last trim ends with the most spans it held. */+static void spans_trim(void)+{+    uint32_t i, kept = 0;+    for (i = 0; i < c.span_count; i++)+        if (span_current(&c.spans[i])) c.spans[kept++] = c.spans[i];+    c.span_count = kept;+    c.span_drop_at = NN_REGION_SPAN_FLOOR;+    c.span_most_ended = c.span_most;+    c.span_most = kept;+}++/* --- Lifecycle --- */++static void tenure_bits_free(tenure_bits_t *t)+{+    int v;+    for (v = 0; v < NN_REGION_TENURE_VARIANTS; v++) {+        free(t[v].tenured);+        free(t[v].freed);+        free(t[v].remembered);+    }+}++static void release(void)+{+    uint32_t i;+    int v;+    for (i = 0; i < c.block_count; i++) {+        free(c.blocks[i].marks);+        free(c.blocks[i].died);+        free(c.blocks[i].spans);+        free(c.blocks[i].free);+        tenure_bits_free(c.blocks[i].tenure);+    }+    for (i = 0; i < NN_REGION_BUMP_KINDS; i++) free(c.recycle[i]);+    free(c.spans);+    for (i = 0; i < NN_REGION_TRACKED_KINDS; i++) {+        free(c.places[i].marks);+        free(c.places[i].died);+        tenure_bits_free(c.places[i].tenure);+    }+    for (i = 0; i < c.frame_cap; i++)+        for (v = 0; v < NN_REGION_TENURE_VARIANTS; v++) free(c.frames[i].t[v].entries);+    for (v = 0; v < NN_REGION_TENURE_VARIANTS; v++) free(c.t[v].records);+    free(c.blocks);+    free(c.units);+    free(c.objects);+    free(c.records);+    free(c.frames);+    free(c.work);+    free(c.heads);+    free(c.live);+    memset(&c, 0, sizeof(c));+    nn_region_mode = NN_REGION_OFF;+}++int nn_region_begin(int mode)+{+    int k;+    NN_ASSERT(!nn_thunk_live() && !nn_env_live() && !nn_str_live(),+              "nn_region_begin: the arena is live");+    NN_ASSERT(mode == NN_REGION_CENSUS || mode == NN_REGION_COLLECT, "nn_region_begin: no such mode");+    release();+    /* The bits a block or a tracked kind gets depend on the mode. */+    nn_region_mode = mode;+    c.units = units_new(NN_REGION_INITIAL);+    c.objects = (object_slot_t *)calloc(NN_REGION_INITIAL, sizeof(object_slot_t));+    if (!c.units || !c.objects) {+        release();+        return -1;+    }+    c.unit_cap = NN_REGION_INITIAL;+    c.object_cap = NN_REGION_INITIAL;+    for (k = 0; k < NN_REGION_BUMP_KINDS; k++) c.current_span[k] = NN_REGION_NONE;+    c.span_drop_at = NN_REGION_SPAN_FLOOR;+    c.last = NN_REGION_NONE;+    c.tv = -1;+    return 0;+}++void nn_region_end(void)+{+    release();+}++/* --- The allocators' half --- */++void nn_region_block(int kind, const char *data, uint64_t capacity, int current)+{+    block_t *blocks, *b;+    uint32_t index = c.block_count;+    uintptr_t unit, last;+    if (c.failed) return;+    NN_ASSERT(capacity >= NN_REGION_UNIT_BYTES, "nn_region_block: a block smaller than the index's unit");+    blocks = (block_t *)reserve(c.blocks, &c.block_cap, sizeof(block_t), index + 1);+    if (!blocks) {+        fail();+        return;+    }+    c.blocks = blocks;+    b = &c.blocks[index];+    b->start = (uintptr_t)data;+    b->end = b->start + (uintptr_t)capacity;+    b->kind = kind;+    b->marks = NULL;+    b->died = NULL;+    memset(b->tenure, 0, sizeof(b->tenure));+    b->spans = NULL;+    b->free = NULL;+    b->lines = (uint32_t)(capacity / NN_REGION_LINE);+    b->free_count = 0;+    b->hint = b->lines;+    b->recycling = 0;+    c.block_count++;+    /* Nothing in a block of code is ever marked. */+    if (kind != NN_REGION_CODE_BLOCK) {+        uint64_t units = capacity / unit_bytes(kind);+        int v;+        b->marks = bits_new(units);+        b->died = bits_new(units);+        b->spans = (uint32_t *)malloc((size_t)((capacity + NN_REGION_LINE - 1) / NN_REGION_LINE) * sizeof(uint32_t));+        b->free = bits_new(b->lines);+        if (!b->marks || !b->died || !b->spans || !b->free) {+            fail();+            return;+        }+        for (v = 0; v < NN_REGION_TENURE_VARIANTS; v++) {+            tenure_bits_t *t = &b->tenure[v];+            if (!active(v)) continue;+            t->tenured = bits_new(units);+            t->freed = bits_new(units);+            t->remembered = bits_new(units);+            if (!t->tenured || !t->freed || !t->remembered) {+                fail();+                return;+            }+        }+    }+    last = (b->end - 1) >> NN_REGION_UNIT_SHIFT;+    for (unit = b->start >> NN_REGION_UNIT_SHIFT; unit <= last; unit++) {+        if (unit_add(unit, index) != 0) {+            fail();+            return;+        }+    }+    if (kind < NN_REGION_BUMP_KINDS && span_begin(index, 0, capacity, current) != 0) fail();+}++static void track(int kind, const void *object, uint32_t position, uint64_t bytes, uintptr_t first)+{+    if (c.failed) return;+    if (object_add((uintptr_t)object, position, kind, first) != 0+        || places_reserve(&c.places[kind], position + 1) != 0) {+        fail();+        return;+    }+    c.tracked_bytes += bytes;+}++void nn_region_tracked(int kind, const void *object, uint32_t position, uint64_t bytes)+{+    track(kind, object, position, bytes, 0);+}++void nn_region_list(const void *list, uint32_t position, const void *of)+{+    uintptr_t first = (uintptr_t)((const nn_list_t *)list)->items;+    if (of) {+        const object_slot_t *slot = object_slot(c.objects, c.object_cap, (uintptr_t)of);+        if (slot->object == (uintptr_t)of && slot->kind == NN_REGION_LIST) first = slot->first;+    }+    track(NN_REGION_LIST, list, position, sizeof(nn_list_t), first);+}++void nn_region_tracked_grew(uint64_t bytes)+{+    c.tracked_bytes += bytes;+}++static void record(uintptr_t r)+{+    uintptr_t *records;+    int v;+    if (c.failed || c.frame_count == 0) return;+    if (!collecting()) {+        records = (uintptr_t *)reserve(c.records, &c.record_cap, sizeof(uintptr_t), c.record_count + 1);+        if (!records) {+            fail();+            return;+        }+        c.records = records;+        c.records[c.record_count++] = r;+        if (c.record_count > c.totals[NN_REGION_TOTAL_RECORDS])+            c.totals[NN_REGION_TOTAL_RECORDS] = c.record_count;+    }+    for (v = 0; v < NN_REGION_TENURE_VARIANTS; v++) {+        tenure_t *t = &c.t[v];+        if (!active(v)) continue;+        records = (uintptr_t *)reserve(t->records, &t->record_cap, sizeof(uintptr_t), t->record_count + 1);+        if (!records) {+            fail();+            return;+        }+        t->records = records;+        t->records[t->record_count++] = r;+        if (t->record_count > t->figures[NN_REGION_TENURE_RECORDS]) t->figures[NN_REGION_TENURE_RECORDS] = t->record_count;+    }+}++void nn_region_record_cell(const struct nn_thunk *cell)+{+    record((uintptr_t)cell);+}++void nn_region_record_with(void *const *entry)+{+    record((uintptr_t)entry | NN_REGION_RECORD_WITH);+}++/* --- Age --- */++/* An object is younger than a region when the span its line was last+ * handed out in started after the region opened, or is the one its kind+ * bumped from as the region opened and the object lies at or past where+ * the cursor was then.  A refill hands out lines in a span of their own,+ * so what it puts in a line an older object left is younger than every+ * region open. */+static age_t bump_age(const frame_t *f, uint32_t b, uintptr_t p)+{+    const block_t *blk = &c.blocks[b];+    uint64_t offset = (uint64_t)(p - blk->start);+    uint32_t n = blk->spans[offset / NN_REGION_LINE];+    if (n >= f->spans) return AGE_YOUNGER;+    if (n == f->current_span[blk->kind] && offset >= f->current_used[blk->kind]) return AGE_YOUNGER;+    return AGE_OLDER;+}++/* The age of what a record names: a cell, or a with-scope entry in an+ * env page. */+static age_t record_age(const frame_t *f, uintptr_t r)+{+    int with = (r & NN_REGION_RECORD_WITH) != 0;+    uintptr_t p = r & ~NN_REGION_RECORD_FLAGS;+    uint32_t b = block_of(p, with ? NN_REGION_ENV_PAGE : NN_REGION_THUNK_BLOCK);+    if (b == NN_REGION_NONE) return AGE_OUTSIDE;+    return bump_age(f, b, p);+}++/* The block and unit of what a record names, or NN_REGION_NONE. */+static uint32_t record_unit(uintptr_t r, uint64_t *unit)+{+    int with = (r & NN_REGION_RECORD_WITH) != 0;+    uintptr_t p = r & ~NN_REGION_RECORD_FLAGS;+    uint32_t b = block_of(p, with ? NN_REGION_ENV_PAGE : NN_REGION_THUNK_BLOCK);+    if (b != NN_REGION_NONE) *unit = (uint64_t)(p - c.blocks[b].start) / unit_bytes(c.blocks[b].kind);+    return b;+}++/* --- What the tenure collector remembers --- */++static void bit_clear(uint8_t *bits, uint64_t i)+{+    bits[i / 8] &= (uint8_t)~(1u << (i % 8));+}++/* The innermost region around the closing one that an object of a block+ * or a tracked place is younger than, or -1 for none.  Each region opened+ * after the one around it, so an object younger than a region is younger+ * than every region around it too. */+static int32_t holder_bump(uint32_t b, uintptr_t p)+{+    int32_t lo = 0, hi = (int32_t)c.frame_count - 2, found = -1;+    while (lo <= hi) {+        int32_t mid = lo + (hi - lo) / 2;+        if (bump_age(&c.frames[mid], b, p) == AGE_YOUNGER) {+            found = mid;+            lo = mid + 1;+        } else {+            hi = mid - 1;+        }+    }+    return found;+}++static int32_t holder_place(int tracked, uint32_t position)+{+    int32_t lo = 0, hi = (int32_t)c.frame_count - 2, found = -1;+    while (lo <= hi) {+        int32_t mid = lo + (hi - lo) / 2;+        if (position >= c.frames[mid].tracked[tracked]) {+            found = mid;+            lo = mid + 1;+        } else {+            hi = mid - 1;+        }+    }+    return found;+}++/* Remember an entry for the region at frame `at`, for the tenure+ * collector whose mark is under way, once: `remembered` is the bits its+ * index is in. */+static void remember(int32_t at, const entry_t *entry, uint8_t *remembered)+{+    frame_tenure_t *ft = &c.frames[at].t[c.tv];+    tenure_t *t = &c.t[c.tv];+    entry_t *entries;+    if (bit_get(remembered, entry->index)) return;+    entries = (entry_t *)reserve_from(ft->entries, &ft->entry_cap, sizeof(entry_t), ft->entry_count + 1,+                                      NN_REGION_ENTRIES_INITIAL);+    if (!entries) {+        fail();+        return;+    }+    ft->entries = entries;+    ft->entries[ft->entry_count++] = *entry;+    bit_set(remembered, entry->index);+    t->figures[NN_REGION_TENURE_REMEMBERED]++;+    if (++t->held > t->figures[NN_REGION_TENURE_HELD]) t->figures[NN_REGION_TENURE_HELD] = t->held;+}++static void remember_unit(int32_t at, entry_what_t what, int kind, const void *target, const void *owner,+                          uint32_t count, uint32_t b, uint64_t u)+{+    entry_t entry;+    entry.target = target;+    entry.owner = owner;+    entry.index = u;+    entry.block = b;+    entry.count = count;+    entry.kind = kind;+    entry.tracked = 0;+    entry.what = what;+    remember(at, &entry, c.blocks[b].tenure[c.tv].remembered);+}++static void remember_place(int32_t at, int kind, int tracked, const void *target, uint32_t position)+{+    entry_t entry;+    entry.target = target;+    entry.owner = NULL;+    entry.index = position;+    entry.block = NN_REGION_NONE;+    entry.count = 0;+    entry.kind = kind;+    entry.tracked = tracked;+    entry.what = ENTRY_OBJECT;+    remember(at, &entry, c.places[tracked].tenure[c.tv].remembered);+}++/* A pointer a tenure collector's mark found, in an object it entered or+ * a cell a record names, to a unit of a block older than the closing+ * region: remembered for the innermost region around that the unit is+ * younger than, unless it is tenured.  No later close but a mark of the+ * whole looks inside the object, which this close tenures, or reads the+ * record, which it drops, so no later close finds the pointer otherwise.+ * A tenured unit stays tenured in every region around, and needs none. */+static void boundary_unit(entry_what_t what, int kind, const void *target, const void *owner, uint32_t count,+                          uint32_t b, uintptr_t p)+{+    block_t *blk = &c.blocks[b];+    uint64_t unit = unit_bytes(blk->kind);+    uint64_t offset = (uint64_t)(p - blk->start);+    int32_t at;+    if (!c.remembering) return;+    if (offset % unit != 0) {+        c.totals[NN_REGION_TOTAL_UNPLACED]++;+        return;+    }+    if (bit_get(blk->tenure[c.tv].tenured, offset / unit)) return;+    at = holder_bump(b, p);+    if (at >= 0) remember_unit(at, what, kind, target, owner, count, b, offset / unit);+}++/* The same for a tracked object older than the closing region. */+static void boundary_place(int kind, int tracked, const void *target, uint32_t position)+{+    int32_t at;+    if (!c.remembering || bit_get(c.places[tracked].tenure[c.tv].tenured, position)) return;+    at = holder_place(tracked, position);+    if (at >= 0) remember_place(at, kind, tracked, target, position);+}+++static void entry_forget(const entry_t *entry, int v)+{+    uint8_t *remembered = entry->block != NN_REGION_NONE ? c.blocks[entry->block].tenure[v].remembered+                                                         : c.places[entry->tracked].tenure[v].remembered;+    bit_clear(remembered, entry->index);+}++/* Drop what was remembered for a region, which no close reads. */+static void entries_drop(frame_t *f, int v)+{+    frame_tenure_t *ft = &f->t[v];+    uint32_t i;+    for (i = 0; i < ft->entry_count; i++) entry_forget(&ft->entries[i], v);+    c.t[v].held -= ft->entry_count;+    ft->entry_count = 0;+}++/* --- The mark --- */++static void work_push(int kind, const void *object, int remember)+{+    work_t *work = (work_t *)reserve(c.work, &c.work_cap, sizeof(work_t), c.work_count + 1);+    if (!work) {+        fail();+        return;+    }+    c.work = work;+    c.work[c.work_count].object = object;+    c.work[c.work_count].kind = kind;+    c.work[c.work_count].remember = remember;+    c.work_count++;+}++static void resurrect(int v, uint64_t bytes)+{+    c.t[v].figures[NN_REGION_TENURE_RESURRECTED]++;+    c.t[v].figures[NN_REGION_TENURE_RESURRECTED_BYTES] += bytes;+}++/* A survivor of `bytes` whose died bit is `died`, and whose tenure+ * collectors' bits are `t` at index `i`.  Only the census's own mark+ * counts what died: a tenure collector's takes its tenured objects for+ * reached, and may enter what they hold that the census's mark found+ * unreached.  The census's mark counts what any tenure collector freed,+ * and a tenure collector's mark of the whole what it freed itself, which+ * its other marks pass over as tenured. */+static void survive(uint64_t bytes, int died, const tenure_bits_t *t, uint64_t i)+{+    int v;+    c.surviving += bytes;+    if (c.tv < 0) {+        if (died) {+            c.totals[NN_REGION_TOTAL_RESURRECTED]++;+            c.totals[NN_REGION_TOTAL_RESURRECTED_BYTES] += bytes;+        }+        for (v = 0; v < NN_REGION_TENURE_VARIANTS; v++)+            if (bit_get(t[v].freed, i)) resurrect(v, bytes);+        return;+    }+    if (bit_get(t[c.tv].freed, i)) {+        NN_ASSERT(!collecting(), "nn_region_close: the collector's mark reached what it freed");+        resurrect(c.tv, bytes);+    }+}++/* Whether a tenure collector's mark under way passes over a unit or place+ * it reaches in the closing region: one it tenured, unless the mark is of+ * the whole region. */+static int passes_over(const tenure_bits_t *t, uint64_t i)+{+    return !c.full && bit_get(t->tenured, i);+}++static int is_static(int kind, const void *object)+{+    if (kind == NN_GRAPH_THUNK) return nn_thunk_is_static((const nn_thunk_t *)object);+    if (kind == NN_GRAPH_ENV) return object == nn_env_empty();+    if (kind == NN_GRAPH_ATTRSET) return object == nn_attrset_empty();+    return 0;+}++/* Reach a thunk cell or an env: mark its extent when it is younger than+ * the closing region, one a tenure collector's mark does not pass over,+ * and unmarked, and push it. */+static void reach_bump(int kind, const void *object)+{+    int block_kind = kind == NN_GRAPH_THUNK ? NN_REGION_THUNK_BLOCK : NN_REGION_ENV_PAGE;+    uintptr_t p = (uintptr_t)object;+    uint32_t b = block_of(p, block_kind);+    uint64_t unit, offset, u, bytes;+    block_t *blk;+    if (b == NN_REGION_NONE) {+        c.totals[NN_REGION_TOTAL_UNPLACED]++;+        return;+    }+    if (bump_age(c.closing, b, p) != AGE_YOUNGER) {+        if (c.tv >= 0) boundary_unit(ENTRY_OBJECT, kind, object, NULL, 0, b, p);+        return;+    }+    blk = &c.blocks[b];+    unit = unit_bytes(block_kind);+    offset = (uint64_t)(p - blk->start);+    u = offset / unit;+    if (offset % unit != 0) {+        c.totals[NN_REGION_TOTAL_UNPLACED]++;+        return;+    }+    if (c.tv >= 0 && passes_over(&blk->tenure[c.tv], u)) return;+    if (bit_get(blk->marks, u)) return;+    bytes = kind == NN_GRAPH_THUNK ? sizeof(nn_thunk_t) : nn_env_bytes((const nn_env_t *)object);+    bits_set(blk->marks, u, u + bytes / unit);+    survive(bytes, bit_get(blk->died, u), blk->tenure, u);+    work_push(kind, object, c.tv >= 0);+}++static int tracked_kind(int kind)+{+    switch (kind) {+    case NN_GRAPH_ATTRSET:    return NN_REGION_SET;+    case NN_GRAPH_LIST:       return NN_REGION_LIST;+    case NN_GRAPH_LAMBDA:     return NN_REGION_LAMBDA;+    case NN_GRAPH_PRIMOP_APP: return NN_REGION_PRIMOP_APP;+    default:                  return NN_REGION_CTXSTR;+    }+}++/* Reach a tracked object: mark its place when it is younger than the+ * closing region, one a tenure collector's mark does not pass over, and+ * unmarked, and push it. */+static void reach_tracked(int kind, const void *object)+{+    int tracked = tracked_kind(kind);+    const object_slot_t *slot = object_slot(c.objects, c.object_cap, (uintptr_t)object);+    places_t *places = &c.places[tracked];+    uint64_t bytes;+    if (slot->object == 0 || slot->kind != tracked) {+        NN_ASSERT(!collecting(), "nn_region_close: the collector's mark reached a tracked object it holds no place for");+        c.totals[NN_REGION_TOTAL_UNPLACED]++;+        return;+    }+    if (slot->position < c.closing->tracked[tracked]) {+        if (c.tv >= 0) boundary_place(kind, tracked, object, slot->position);+        return;+    }+    if (c.tv >= 0 && passes_over(&places->tenure[c.tv], slot->position)) return;+    if (bit_get(places->marks, slot->position)) return;+    bit_set(places->marks, slot->position);+    bytes = tracked_bytes(tracked, object);+    c.surviving_tracked += bytes;+    survive(bytes, bit_get(places->died, slot->position), places->tenure, slot->position);+    work_push(kind, object, c.tv >= 0);+}++static void visit_object(void *ctx, int kind, const void *object)+{+    (void)ctx;+    c.examined++;+    if (is_static(kind, object)) return;+    if (kind == NN_GRAPH_THUNK || kind == NN_GRAPH_ENV)+        reach_bump(kind, object);+    else+        reach_tracked(kind, object);+}++/* A string of the code's is outside every region, as code is. */+static void visit_string(void *ctx, const nn_str_t *s)+{+    uintptr_t p = (uintptr_t)s;+    uint32_t b;+    uint64_t offset, u, bytes;+    block_t *blk;+    (void)ctx;+    c.examined++;+    if (s == nn_str_empty()) return;+    b = block_of(p, NN_REGION_STR_BLOCK);+    if (b == NN_REGION_NONE) {+        if (block_of(p, NN_REGION_CODE_BLOCK) == NN_REGION_NONE) c.totals[NN_REGION_TOTAL_UNPLACED]++;+        return;+    }+    if (bump_age(c.closing, b, p) != AGE_YOUNGER) {+        if (c.tv >= 0) boundary_unit(ENTRY_STRING, 0, s, NULL, 0, b, p);+        return;+    }+    blk = &c.blocks[b];+    offset = (uint64_t)(p - blk->start);+    u = offset / NN_STR_ALIGNMENT;+    if (c.tv >= 0 && passes_over(&blk->tenure[c.tv], u)) return;+    if (bit_get(blk->marks, u)) return;+    bytes = nn_str_object_bytes(s);+    bits_set(blk->marks, u, u + bytes / NN_STR_ALIGNMENT);+    survive(bytes, bit_get(blk->died, u), blk->tenure, u);+}++static void visit_symbol(void *ctx, uint32_t sym)+{+    (void)ctx;+    (void)sym;+}++static void visit_unknown(void *ctx)+{+    (void)ctx;+    c.totals[NN_REGION_TOTAL_UNPLACED]++;+}++static void visit_array(void *ctx, int kind, const void *owner, void *const *base, uint32_t count);++static const nn_graph_visitor_t visitor = {+    visit_object, visit_array, visit_string, visit_symbol, visit_unknown+};++/* The elements of a list's items array before the ones it spans: kept+ * with the array, which an allocator frees whole, and not followed, as+ * the list cannot reach them (head_t). */+static void keep_head(const block_t *blk, const void *list, uintptr_t p)+{+    const object_slot_t *slot = object_slot(c.objects, c.object_cap, (uintptr_t)list);+    head_t *heads;+    if (slot->object != (uintptr_t)list || slot->first < blk->start || slot->first >= p) return;+    heads = (head_t *)reserve(c.heads, &c.head_cap, sizeof(head_t), c.head_count + 1);+    if (!heads) {+        fail();+        return;+    }+    c.heads = heads;+    c.heads[c.head_count].from = (slot->first - blk->start) / NN_ENV_ALIGNMENT;+    c.heads[c.head_count].to = (p - blk->start) / NN_ENV_ALIGNMENT;+    c.heads[c.head_count].block = (uint32_t)(blk - c.blocks);+    c.head_count++;+}++/* Mark the heads kept, once the mark has followed everything. */+static void mark_heads(void)+{+    uint32_t i;+    for (i = 0; i < c.head_count; i++) {+        block_t *blk = &c.blocks[c.heads[i].block];+        uint64_t u;+        for (u = c.heads[i].from; u < c.heads[i].to; u++) {+            if (bit_get(blk->marks, u)) continue;+            bit_set(blk->marks, u);+            survive(sizeof(void *), bit_get(blk->died, u), blk->tenure, u);+        }+    }+    c.head_count = 0;+}++/* An array of the env pages, entry by entry: several list headers can+ * span parts of one items array, so each entry is marked on its own.  An+ * array is allocated whole, so its entries are tenured together, and what+ * a tenure collector's mark finds in them is remembered as for an object+ * it entered. */+static void visit_array(void *ctx, int kind, const void *owner, void *const *base, uint32_t count)+{+    uintptr_t p = (uintptr_t)base;+    uint32_t b, i;+    uint64_t u;+    block_t *blk;+    int remembering = c.remembering;+    c.examined++;+    b = block_of(p, NN_REGION_ENV_PAGE);+    if (b == NN_REGION_NONE) {+        c.totals[NN_REGION_TOTAL_UNPLACED]++;+        return;+    }+    if (bump_age(c.closing, b, p) != AGE_YOUNGER) {+        if (c.tv >= 0) boundary_unit(ENTRY_ARRAY, kind, base, owner, count, b, p);+        return;+    }+    blk = &c.blocks[b];+    u = (uint64_t)(p - blk->start) / NN_ENV_ALIGNMENT;+    if (c.tv >= 0) {+        if (passes_over(&blk->tenure[c.tv], u)) return;+        c.remembering = 1;+    }+    if (kind == NN_GRAPH_ITEMS) keep_head(blk, owner, p);+    for (i = 0; i < count; i++, u++) {+        if (bit_get(blk->marks, u)) continue;+        bit_set(blk->marks, u);+        survive(sizeof(void *), bit_get(blk->died, u), blk->tenure, u);+        nn_graph_entry(kind, base[i], &visitor, ctx);+    }+    c.remembering = remembering;+}++/* What a record names holds: a cell's value, or a with-scope entry's set+ * or thunk. */+static void visit_record(uintptr_t r)+{+    if (r & NN_REGION_RECORD_WITH)+        nn_graph_entry(NN_GRAPH_WITH_SCOPES, *(void *const *)(r & ~NN_REGION_RECORD_FLAGS), &visitor, NULL);+    else+        nn_graph_children(NN_GRAPH_THUNK, (const void *)(r & ~NN_REGION_RECORD_FLAGS), &visitor, NULL);+}++/* The roots registered since a region opened, and then what the mark+ * pushed, each remembering what it points at as the close tenures it. */+static void mark_rest(const frame_t *f)+{+    uint32_t i, n;+    c.remembering = 0;+    for (i = f->root_thunks, n = nn_roots_thunk_count(); i < n; i++)+        visit_object(NULL, NN_GRAPH_THUNK, nn_roots_thunk(i));+    for (i = f->root_envs, n = nn_roots_env_count(); i < n; i++)+        visit_object(NULL, NN_GRAPH_ENV, nn_roots_env(i));+    while (c.work_count > 0 && !c.failed) {+        work_t item = c.work[--c.work_count];+        c.entered++;+        c.remembering = item.remember;+        nn_graph_children(item.kind, item.object, &visitor, NULL);+    }+    c.remembering = 0;+    mark_heads();+}++/* Mark from the closing region's records of older objects and the roots+ * registered since it opened. */+static void mark(const frame_t *f)+{+    uint32_t i;+    for (i = f->records; i < c.record_count; i++) {+        uintptr_t r = c.records[i];+        age_t age = record_age(f, r);+        if (age == AGE_OUTSIDE) c.totals[NN_REGION_TOTAL_UNPLACED]++;+        if (age == AGE_OLDER) visit_record(r);+    }+    mark_rest(f);+}++static void entry_visit(const entry_t *entry)+{+    switch (entry->what) {+    case ENTRY_OBJECT:+        visit_object(NULL, entry->kind, entry->target);+        break;+    case ENTRY_STRING:+        visit_string(NULL, (const nn_str_t *)entry->target);+        break;+    default:+        visit_array(NULL, entry->kind, entry->owner, (void *const *)entry->target, entry->count);+        break;+    }+}++/* A tenure collector's mark at a close.  Its roots are the records of+ * cells and entries the mark does not enter, which it reads, what closes+ * inside remembered for the region, and the roots registered since it+ * opened, and it enters only what is younger than the region and+ * untenured.  A mark of the whole region enters what is younger than it,+ * and its roots are every record of a cell or entry older than it and the+ * registered roots: a cell or entry inside the region it enters itself if+ * it is reached, and so with whatever else holds a remembered pointer.+ * Otherwise only records no close of its has read are roots, those of a+ * cell or entry older than the region or tenured: a cell or entry is+ * stored into once, so what an earlier close read of it is tenured or+ * remembered for the region it is untenured in.  Every record a close of+ * its has seen counts as read: no later close but a mark of the whole+ * reads it, and what the cell or entry it names holds is remembered for+ * the regions around where it is untenured. */+static void tenure_mark(frame_t *f, int v, int full)+{+    frame_tenure_t *ft = &f->t[v];+    tenure_t *t = &c.t[v];+    uint32_t i;+    c.tv = v;+    c.full = full;+    c.remembering = 1;+    for (i = ft->records; i < t->record_count; i++) {+        uintptr_t r = t->records[i];+        uint64_t u = 0;+        uint32_t b = record_unit(r, &u);+        if (b == NN_REGION_NONE) continue;+        t->records[i] = r | NN_REGION_RECORD_READ;+        if (bump_age(f, b, r & ~NN_REGION_RECORD_FLAGS) == AGE_YOUNGER+            && (full || !bit_get(c.blocks[b].tenure[v].tenured, u)))+            continue;+        if (!full && (r & NN_REGION_RECORD_READ)) continue;+        visit_record(r);+    }+    for (i = 0; i < ft->entry_count; i++) {+        entry_forget(&ft->entries[i], v);+        if (!full) entry_visit(&ft->entries[i]);+    }+    t->held -= ft->entry_count;+    ft->entry_count = 0;+    mark_rest(f);+    c.full = 0;+    c.tv = -1;+}++/* --- Retiring a region --- */++/* The finest lines a block's part from `from` bytes to `used` covers,+ * from the one numbered *first to below *count, with room in the scratch+ * flags for one each.  Returns 0 or -1. */+static int live_span(const block_t *blk, uint64_t from, uint64_t used, uint64_t *first, uint64_t *count)+{+    uint64_t finest = nn_region_grain_bytes(blk->kind, NN_REGION_GRAINS - 1);+    *first = (from + finest - 1) / finest;+    *count = (used + finest - 1) / finest;+    if (*count > *first && *count - *first > c.live_cap) {+        uint8_t *live = (uint8_t *)realloc(c.live, (size_t)(*count - *first));+        if (!live) return -1;+        c.live = live;+        c.live_cap = *count - *first;+    }+    return 0;+}++/* Add to dead[g] the bytes of each block or line of grain g wholly in a+ * block's part from `from` bytes to `used` that no scratch flag of a+ * finest line in it says is live. */+static void dead_grains(const block_t *blk, uint64_t from, uint64_t used, uint64_t first, uint64_t count, uint64_t *dead)+{+    uint64_t finest = nn_region_grain_bytes(blk->kind, NN_REGION_GRAINS - 1);+    uint64_t j;+    uint32_t g;+    for (g = 1; g < NN_REGION_GRAINS; g++) {+        uint64_t size = nn_region_grain_bytes(blk->kind, g);+        uint64_t ratio = size / finest;+        uint64_t big;+        for (big = (from + size - 1) / size; big * size < used; big++) {+            uint64_t end = (big + 1) * size < used ? (big + 1) * size : used;+            int live = 0;+            for (j = big * ratio; j < (big + 1) * ratio && j < count && !live; j++) live = c.live[j - first];+            if (!live) dead[g] += end - big * size;+        }+    }+}++/* byte_tenure over the units from `from` to below `to`: whether it freed+ * any. */+static int tenure_range(uint8_t *marks, const tenure_bits_t *t, int full, uint64_t from, uint64_t to)+{+    uint64_t i = from;+    uint8_t lost = 0;+    for (; i < to && i % 8 != 0; i++) lost |= byte_tenure(marks, t, full, i / 8, (uint8_t)(1u << (i % 8)));+    for (; i + 8 <= to; i += 8) lost |= byte_tenure(marks, t, full, i / 8, 0xFFu);+    for (; i < to; i++) lost |= byte_tenure(marks, t, full, i / 8, (uint8_t)(1u << (i % 8)));+    return lost != 0;+}++/* The collector's retirement of a block's units from `from` bytes in to+ * `used`, a line at a time: a line below `settled`, where no more objects+ * go, is free once this close frees the last of its units, the ones past+ * `used` never handed out.  The units of a line below `from` are older+ * objects of the same span, as a span starts on a line, so a line this+ * region shares with closes before it is free once theirs and its own are+ * all freed.  A line whose last unit a close freed while the cursor was+ * in it is freed by a later close that frees a unit in it, or by+ * span_stop when its span ends with the cursor still in it. */+static void collect_retire_block(block_t *blk, uint64_t from, uint64_t used, uint64_t settled, int full)+{+    uint64_t unit = unit_bytes(blk->kind), at = from;+    tenure_bits_t *t = &blk->tenure[NN_REGION_COLLECTOR];+    while (at < used) {+        uint64_t line = at / NN_REGION_LINE;+        uint64_t stop = (line + 1) * NN_REGION_LINE < used ? (line + 1) * NN_REGION_LINE : used;+        if (tenure_range(blk->marks, t, full, at / unit, stop / unit) && (line + 1) * NN_REGION_LINE <= settled+            && line < blk->lines && bits_all(t->freed, line * NN_REGION_LINE / unit, stop / unit))+            free_line(blk, line);+        at = stop;+    }+}++/* Retire a block's units from `from` bytes in, the closing region's part+ * of it, and add to dead[g] the bytes of each block or line of grain g+ * wholly in that part that holds no survivor. */+static int retire_block(block_t *blk, uint64_t from, uint64_t used, uint64_t *dead)+{+    uint64_t unit = unit_bytes(blk->kind);+    uint64_t finest = nn_region_grain_bytes(blk->kind, NN_REGION_GRAINS - 1);+    uint64_t first, count, j;+    if (used <= from) return 0;+    if (live_span(blk, from, used, &first, &count) != 0) return -1;+    for (j = first; j < count; j++) {+        uint64_t end = (j + 1) * finest < used ? (j + 1) * finest : used;+        c.live[j - first] = (uint8_t)bits_any(blk->marks, j * finest / unit, end / unit);+    }+    dead_grains(blk, from, used, first, count, dead);+    bits_retire(blk->marks, blk->died, from / unit, used / unit);+    return 0;+}++/* Tenure collector v's retirement of a block's units from `from` bytes+ * in at a close where it marked (bits_tenure), adding to dead[g] the+ * bytes of each block or line of grain g wholly in that part in which it+ * has freed every unit; or, at an outermost close, where it takes the+ * census's own mark of the whole region, before the census retires it,+ * freeing what that mark left unmarked. */+static int tenure_retire_block(block_t *blk, uint64_t from, uint64_t used, uint64_t settled, tenure_action_t action,+                               int v, uint64_t *dead, uint64_t *reached)+{+    uint64_t unit = unit_bytes(blk->kind);+    uint64_t finest = nn_region_grain_bytes(blk->kind, NN_REGION_GRAINS - 1);+    uint64_t first, count, j;+    if (used <= from) return 0;+    if (action == TENURE_OUTERMOST) {+        bits_tenure_full(blk->marks, &blk->tenure[v], from / unit, used / unit);+        return 0;+    }+    if (collecting()) {+        collect_retire_block(blk, from, used, settled, action == TENURE_FULL);+        return 0;+    }+    bits_tenure(blk->marks, blk->died, &blk->tenure[v], action == TENURE_FULL, from / unit, used / unit, reached);+    if (live_span(blk, from, used, &first, &count) != 0) return -1;+    for (j = first; j < count; j++) {+        uint64_t end = (j + 1) * finest < used ? (j + 1) * finest : used;+        c.live[j - first] = (uint8_t)!bits_all(blk->tenure[v].freed, j * finest / unit, end / unit);+    }+    dead_grains(blk, from, used, first, count, dead);+    return 0;+}++/* The next run of a span's own lines from `at` bytes in, to below `end`:+ * its start, with *to past its last byte, or `end` for none.  A line a+ * refill handed out again is a newer span's. */+static uint64_t span_run(const span_t *s, uint64_t at, uint64_t end, uint64_t *to)+{+    const block_t *blk = &c.blocks[s->block];+    while (at < end && blk->spans[at / NN_REGION_LINE] != s->number) at = (at / NN_REGION_LINE + 1) * NN_REGION_LINE;+    *to = at;+    while (*to < end && blk->spans[*to / NN_REGION_LINE] == s->number) *to = (*to / NN_REGION_LINE + 1) * NN_REGION_LINE;+    if (*to > end) *to = end;+    return at < end ? at : end;+}++/* The closing region's part of a span, from `from` bytes in. */+static void retire_span(const span_t *s, uint64_t from, uint64_t *dead)+{+    uint64_t end = span_end(s), to, at = from > s->start ? from : s->start;+    while (!c.failed && (at = span_run(s, at, end, &to)) < end) {+        if (retire_block(&c.blocks[s->block], at, to, dead) != 0) fail();+        at = to;+    }+}++/* The spans a region's part takes in: the one each bump kind bumped from+ * as it opened, from where the cursor was, and every one after.  One the+ * table no longer keeps holds no line, so its part is empty. */+static const span_t *opening_span(const frame_t *f, int kind)+{+    return f->current_span[kind] == NN_REGION_NONE ? NULL : span_numbered(f->current_span[kind]);+}++/* Retire every span the closing region allocated in, and every tracked+ * object it made. */+static void retire(const frame_t *f, uint64_t *dead)+{+    uint32_t i;+    int k;+    for (k = 0; k < NN_REGION_BUMP_KINDS && !c.failed; k++) {+        const span_t *opening = opening_span(f, k);+        if (opening) retire_span(opening, f->current_used[k], dead);+    }+    for (i = span_index_from(f->spans); i < c.span_count && !c.failed; i++) retire_span(&c.spans[i], c.spans[i].start, dead);+    /* Every object a tracker gained while the census ran has a place in+     * the bits; one it held before has none and is in no region. */+    for (k = 0; k < NN_REGION_TRACKED_KINDS; k++) {+        uint32_t end = tracker_count(k);+        if (end > c.places[k].capacity) end = c.places[k].capacity;+        if (f->tracked[k] < end)+            bits_retire(c.places[k].marks, c.places[k].died, f->tracked[k], end);+    }+}++/* The collector's sweep of a tracked kind's places from `from` to below+ * `end`, the closing region's, once its close has settled them: it frees+ * the objects whose places it freed, and the rest close up in order,+ * tenured, behind the places before `from`.  No close remembers one of+ * them: a pointer into the region a close inside found is remembered+ * for the region itself, whose mark has forgotten it, reading it first+ * unless the mark is of the whole. */+static int sweep_keep(void *ctx, void *object, uint32_t place, uint32_t kept_at)+{+    const tenure_bits_t *bits = (const tenure_bits_t *)ctx;+    if (bit_get(bits->freed, place)) {+        object_remove((uintptr_t)object);+        return 0;+    }+    if (kept_at != place) object_slot(c.objects, c.object_cap, (uintptr_t)object)->position = kept_at;+    return 1;+}++static void sweep(int kind, uint32_t from, uint32_t end)+{+    tenure_bits_t *bits = &c.places[kind].tenure[NN_REGION_COLLECTOR];+    uint32_t kept;+    NN_ASSERT(!bits_any(bits->remembered, from, end), "nn_region_close: a place the sweep moves is remembered");+    switch (kind) {+    case NN_REGION_SET:        nn_attrset_sweep(from, sweep_keep, bits); break;+    case NN_REGION_LIST:       nn_list_sweep(from, sweep_keep, bits); break;+    case NN_REGION_LAMBDA:     nn_lambda_sweep(from, sweep_keep, bits); break;+    case NN_REGION_PRIMOP_APP: nn_primop_app_sweep(from, sweep_keep, bits); break;+    default:                   nn_ctxstr_sweep(from, sweep_keep, bits); break;+    }+    kept = tracker_count(kind);+    bits_set(bits->tenured, from, kept);+    bits_clear(bits->tenured, kept, end);+    bits_clear(bits->freed, from, end);+}++/* Tenure collector v's retirement of the closing region's part of a+ * span, from `from` bytes in (tenure_retire_block). */+static void tenure_retire_span(const span_t *s, uint64_t from, tenure_action_t action, int v, uint64_t *dead,+                               uint64_t *reached)+{+    uint64_t end = span_end(s), settled = span_settled(s), to, at = from > s->start ? from : s->start;+    while (!c.failed && (at = span_run(s, at, end, &to)) < end) {+        if (tenure_retire_block(&c.blocks[s->block], at, to, settled, action, v, dead, reached) != 0) fail();+        at = to;+    }+}++/* Tenure collector v's retirement of every span the closing region+ * allocated in, and every tracked object it made. */+static void tenure_retire(const frame_t *f, tenure_action_t action, int v, uint64_t *dead, uint64_t *reached)+{+    uint32_t i;+    int k;+    for (k = 0; k < NN_REGION_BUMP_KINDS && !c.failed; k++) {+        const span_t *opening = opening_span(f, k);+        if (opening) tenure_retire_span(opening, f->current_used[k], action, v, dead, reached);+    }+    for (i = span_index_from(f->spans); i < c.span_count && !c.failed; i++)+        tenure_retire_span(&c.spans[i], c.spans[i].start, action, v, dead, reached);+    for (k = 0; k < NN_REGION_TRACKED_KINDS && !c.failed; k++) {+        places_t *places = &c.places[k];+        uint32_t end = tracker_count(k);+        if (end > places->capacity) end = places->capacity;+        if (f->tracked[k] >= end) continue;+        if (action == TENURE_OUTERMOST)+            bits_tenure_full(places->marks, &places->tenure[v], f->tracked[k], end);+        else+            bits_tenure(places->marks, places->died, &places->tenure[v], action == TENURE_FULL, f->tracked[k], end,+                        reached);+        if (collecting()) sweep(k, f->tracked[k], end);+    }+}++/* --- Figures --- */++static uint32_t size_class(uint64_t bytes)+{+    uint32_t n = 0;+    while (bytes > 0 && n < NN_REGION_SIZE_CLASSES - 1) {+        bytes >>= 1;+        n++;+    }+    return n;+}++static void count_close(uint64_t allocated, uint32_t records)+{+    uint64_t *row = c.classes[size_class(allocated)];+    row[NN_REGION_CLASS_CLOSES]++;+    row[NN_REGION_CLASS_ALLOCATED] += allocated;+    row[NN_REGION_CLASS_SURVIVING] += c.surviving;+    row[NN_REGION_CLASS_ENTERED] += c.entered;+    row[NN_REGION_CLASS_EXAMINED] += c.examined;+    row[NN_REGION_CLASS_RECORDS] += records;+    c.totals[NN_REGION_TOTAL_CLOSES]++;+}++/* The simulated collector at this close.  The bytes held peak just before+ * a close frees, so each close first counts what is held.  Under a+ * threshold the region reaches, the close frees what died in it less what+ * the closes inside it freed, and the region around it learns that all+ * of it is freed; under one it does not reach, it frees nothing and passes+ * on what the closes inside it freed.  What died in a region includes+ * everything that died in the regions inside it unless a close reached it+ * again, which the census counts as resurrected. */+static void simulate(const frame_t *f, frame_t *parent, uint64_t allocated, const uint64_t *dead)+{+    uint64_t now = allocated_now();+    uint32_t k, g;+    for (k = 0; k < NN_REGION_THRESHOLDS; k++) {+        int marks = allocated >= nn_region_threshold_bytes(k);+        uint64_t *row = c.thresholds[k];+        if (marks) {+            row[NN_REGION_THRESHOLD_CLOSES]++;+            row[NN_REGION_THRESHOLD_ENTERED] += c.entered;+            row[NN_REGION_THRESHOLD_EXAMINED] += c.examined;+        }+        for (g = 0; g < NN_REGION_GRAINS; g++) {+            uint64_t held = now - c.freed[k][g];+            uint64_t inside = f->freed[k][g];+            uint64_t up = inside;+            if (held > row[NN_REGION_THRESHOLD_PEAK + g]) row[NN_REGION_THRESHOLD_PEAK + g] = held;+            if (marks && dead[g] > inside) {+                c.freed[k][g] += dead[g] - inside;+                up = dead[g];+            }+            if (parent) parent->freed[k][g] += up;+        }+    }+}++/* Keep for the region around the closing one the records of objects+ * older than it too. */+static void pass_records(const frame_t *f, const frame_t *parent)+{+    uint32_t kept = f->records, i;+    if (parent) {+        for (i = f->records; i < c.record_count; i++)+            if (record_age(parent, c.records[i]) == AGE_OLDER) c.records[kept++] = c.records[i];+    }+    c.record_count = kept;+}++/* Keep for the region around the closing one tenure collector v's+ * records of cells and entries older than it, which a mark of the whole+ * region around reads, and of those no close has read that are tenured+ * and not freed, which its next close that marks reads. */+static void pass_tenure_records(const frame_t *f, const frame_t *parent, int v)+{+    tenure_t *t = &c.t[v];+    uint32_t kept = f->t[v].records, i;+    if (parent) {+        for (i = f->t[v].records; i < t->record_count; i++) {+            uintptr_t r = t->records[i];+            uint64_t u = 0;+            uint32_t b = record_unit(r, &u);+            const tenure_bits_t *bits;+            if (b == NN_REGION_NONE) continue;+            bits = &c.blocks[b].tenure[v];+            if (bump_age(parent, b, r & ~NN_REGION_RECORD_FLAGS) != AGE_YOUNGER+                || (!(r & NN_REGION_RECORD_READ) && bit_get(bits->tenured, u) && !bit_get(bits->freed, u)))+                t->records[kept++] = r;+        }+    }+    t->record_count = kept;+}++/* What tenure collector v does at the close of a region that allocated+ * `allocated` bytes. */+static tenure_action_t tenure_action(const frame_t *f, const frame_t *parent, int v, uint64_t allocated)+{+    if (allocated < nn_region_threshold_bytes(NN_REGION_TENURE_THRESHOLD)) return TENURE_NONE;+    if (!parent) return collecting() ? TENURE_FULL : TENURE_OUTERMOST;+    if (tenure_budgets[v] != 0 && f->t[v].unchecked >= tenure_budgets[v]) return TENURE_FULL;+    return TENURE_YOUNG;+}++/* Tenure collector v at this close, after the census's own has counted+ * and retired the region.  The bytes it holds peak just before it frees.+ * Where it marks, it frees what died in the region less what it freed+ * inside, as simulate does, and the region around takes on the whole+ * region as tenured or freed, and what it tenured as unchecked unless its+ * mark was of the whole.  `dead` is what died in the region, by the+ * census's own mark. */+static void tenure_close(frame_t *f, frame_t *parent, tenure_action_t action, int v, uint64_t allocated,+                         uint64_t tracked, const uint64_t *dead)+{+    frame_tenure_t *ft = &f->t[v];+    tenure_t *t = &c.t[v];+    uint64_t lost[NN_REGION_GRAINS], lost_tracked = 0, reached = 0, unchecked = 0;+    uint32_t g;+    memset(lost, 0, sizeof(lost));+    /* The peaks are the census's figures, which collecting keeps none of. */+    if (!collecting()) {+        uint64_t now = allocated_now();+        for (g = 0; g < NN_REGION_GRAINS; g++) {+            uint64_t held = now - t->freed[g];+            if (held > t->figures[NN_REGION_TENURE_PEAK + g]) t->figures[NN_REGION_TENURE_PEAK + g] = held;+        }+    }+    if (action == TENURE_YOUNG || action == TENURE_FULL) {+        int full = action == TENURE_FULL;+        /* What the mark may reach: what the closes inside left untenured,+         * or for a mark of the whole what they left unfreed. */+        uint64_t open = allocated - (full ? ft->freed[0] : ft->tenured);+        uint64_t open_tracked = tracked - (full ? ft->freed_tracked : ft->tenured_tracked);+        c.surviving = 0;+        c.surviving_tracked = 0;+        c.entered = 0;+        c.examined = 0;+        tenure_mark(f, v, full);+        if (!c.failed) tenure_retire(f, action, v, lost, &reached);+        if (c.failed) return;+        /* A mark of the whole that reaches what was freed counts it as+         * resurrected, so only the region bounds what it reaches. */+        NN_ASSERT(full ? c.surviving <= allocated && c.surviving_tracked <= tracked+                       : c.surviving <= open && c.surviving_tracked <= open_tracked,+                  "nn_region_close: more survives than the tenure collector's mark could reach");+        if (full) {+            lost_tracked = tracked - c.surviving_tracked;+            lost[0] = allocated - c.surviving;+        } else {+            lost_tracked = ft->freed_tracked + open_tracked - c.surviving_tracked;+            lost[0] = ft->freed[0] + open - c.surviving;+            unchecked = ft->unchecked + c.surviving;+        }+        for (g = 1; g < NN_REGION_GRAINS; g++) lost[g] += lost_tracked;+        t->figures[NN_REGION_TENURE_REACHED] += reached;+    } else if (action == TENURE_OUTERMOST) {+        /* The census's mark of the whole region is this close's, and its+         * counts are still the close's. */+        memcpy(lost, dead, sizeof(lost));+        lost_tracked = tracked - c.surviving_tracked;+    }+    if (action != TENURE_NONE) {+        t->figures[NN_REGION_TENURE_CLOSES]++;+        t->figures[NN_REGION_TENURE_ENTERED] += c.entered;+        t->figures[NN_REGION_TENURE_EXAMINED] += c.examined;+        if (action != TENURE_YOUNG) {+            t->figures[NN_REGION_TENURE_FULL]++;+            if (lost[0] > ft->freed[0]) t->figures[NN_REGION_TENURE_FULL_FREED] += lost[0] - ft->freed[0];+        }+        /* What it freed inside died, so only a premise the counts would+         * show broken makes it more than what died. */+        for (g = 0; g < NN_REGION_GRAINS; g++)+            if (lost[g] > ft->freed[g]) t->freed[g] += lost[g] - ft->freed[g];+    }+    /* A region below the threshold holds none past it, as what a region+     * holds allocated in it, so no close inside it marked: it tenured,+     * freed and remembered nothing. */+    NN_ASSERT(action != TENURE_NONE || (ft->tenured == 0 && ft->unchecked == 0 && ft->entry_count == 0),+              "nn_region_close: a region below the threshold holds what a close that marked left");+    if (!parent) {+        entries_drop(f, v);+    } else if (action != TENURE_NONE) {+        frame_tenure_t *pt = &parent->t[v];+        pt->tenured += allocated;+        pt->tenured_tracked += tracked;+        for (g = 0; g < NN_REGION_GRAINS; g++) pt->freed[g] += lost[g];+        pt->freed_tracked += lost_tracked;+        pt->unchecked += unchecked;+    }+    pass_tenure_records(f, parent, v);+}++/* --- The evaluator's half --- */++void nn_region_open(void)+{+    frame_t *frames, *f;+    uint32_t cap = c.frame_cap;+    int k, v;+    if (!nn_region_mode || c.failed) return;+    frames = (frame_t *)reserve(c.frames, &c.frame_cap, sizeof(frame_t), c.frame_count + 1);+    if (!frames) {+        fail();+        return;+    }+    /* A frame keeps its entries' buffer from one region to the next. */+    if (c.frame_cap > cap) memset(frames + cap, 0, (size_t)(c.frame_cap - cap) * sizeof(frame_t));+    c.frames = frames;+    f = &c.frames[c.frame_count++];+    f->spans = c.span_next;+    for (k = 0; k < NN_REGION_BUMP_KINDS; k++) {+        f->current_span[k] = c.current_span[k];+        f->current_used[k] = c.current_span[k] == NN_REGION_NONE ? 0 : cursor_of(k);+    }+    for (k = 0; k < NN_REGION_TRACKED_KINDS; k++) f->tracked[k] = tracker_count(k);+    f->tracked_bytes = c.tracked_bytes;+    f->allocated = allocated_now();+    f->records = c.record_count;+    nn_roots_mark(&f->root_thunks, &f->root_envs);+    /* What the census simulates is the census's alone. */+    if (!collecting()) memset(f->freed, 0, sizeof(f->freed));+    for (v = 0; v < NN_REGION_TENURE_VARIANTS; v++) {+        frame_tenure_t *ft = &f->t[v];+        if (!active(v)) continue;+        ft->records = c.t[v].record_count;+        ft->unchecked = 0;+        ft->tenured = 0;+        ft->tenured_tracked = 0;+        memset(ft->freed, 0, sizeof(ft->freed));+        ft->freed_tracked = 0;+        ft->entry_count = 0;+    }+    if (c.frame_count > c.totals[NN_REGION_TOTAL_DEPTH]) c.totals[NN_REGION_TOTAL_DEPTH] = c.frame_count;+}++/* A census's close: its own mark, and then every tenure collector's. */+static void census_close(frame_t *f, frame_t *parent)+{+    uint64_t allocated, tracked, dead[NN_REGION_GRAINS];+    uint32_t g, records;+    tenure_action_t actions[NN_REGION_TENURE_VARIANTS];+    int v;+    c.surviving = 0;+    c.surviving_tracked = 0;+    c.entered = 0;+    c.examined = 0;+    records = c.record_count - f->records;+    allocated = allocated_now() - f->allocated;+    tracked = c.tracked_bytes - f->tracked_bytes;+    for (v = 0; v < NN_REGION_TENURE_VARIANTS; v++) actions[v] = tenure_action(f, parent, v, allocated);++    mark(f);+    for (v = 0; v < NN_REGION_TENURE_VARIANTS && !c.failed; v++)+        if (actions[v] == TENURE_OUTERMOST) tenure_retire(f, actions[v], v, NULL, NULL);+    memset(dead, 0, sizeof(dead));+    if (!c.failed) retire(f, dead);+    if (c.failed) return;+    NN_ASSERT(c.surviving <= allocated && c.surviving_tracked <= tracked,+              "nn_region_close: more survives than the region allocated");+    dead[0] = allocated - c.surviving;+    for (g = 1; g < NN_REGION_GRAINS; g++) dead[g] += tracked - c.surviving_tracked;++    count_close(allocated, records);+    if (!parent) c.enclosed += allocated;+    simulate(f, parent, allocated, dead);+    pass_records(f, parent);+    for (v = 0; v < NN_REGION_TENURE_VARIANTS && !c.failed; v++)+        tenure_close(f, parent, actions[v], v, allocated, tracked, dead);+}++/* The collector's close: its tenure collector's alone, which frees. */+static void collect_close(frame_t *f, frame_t *parent)+{+    uint64_t allocated = allocated_now() - f->allocated;+    uint64_t tracked = c.tracked_bytes - f->tracked_bytes;+    tenure_close(f, parent, tenure_action(f, parent, NN_REGION_COLLECTOR, allocated), NN_REGION_COLLECTOR,+                 allocated, tracked, NULL);+}++void nn_region_close(void)+{+    frame_t *f, *parent;+    if (!nn_region_mode || c.failed) return;+    NN_ASSERT(c.frame_count > 0, "nn_region_close: no region is open");+    f = &c.frames[c.frame_count - 1];+    parent = c.frame_count > 1 ? &c.frames[c.frame_count - 2] : NULL;+    c.closing = f;+    if (collecting())+        collect_close(f, parent);+    else+        census_close(f, parent);+    if (c.failed) return;+    c.closing = NULL;+    c.frame_count--;+    if (c.frame_count == 0) spans_trim();+}++/* --- Reading the figures --- */++void nn_region_totals(uint64_t *totals)+{+    uint64_t allocated = nn_region_mode ? allocated_now() : 0;+    memcpy(totals, c.totals, sizeof(c.totals));+    totals[NN_REGION_TOTAL_ALLOCATED] = allocated;+    totals[NN_REGION_TOTAL_OUTSIDE] = allocated > c.enclosed ? allocated - c.enclosed : 0;+}++void nn_region_classes(uint64_t *figures)+{+    memcpy(figures, c.classes, sizeof(c.classes));+}++/* The bytes held now count toward each peak too: nothing has freed them+ * since the last close. */+void nn_region_thresholds(uint64_t *figures)+{+    uint64_t now = nn_region_mode ? allocated_now() : 0;+    uint32_t k, g;+    memcpy(figures, c.thresholds, sizeof(c.thresholds));+    for (k = 0; k < NN_REGION_THRESHOLDS; k++) {+        for (g = 0; g < NN_REGION_GRAINS; g++) {+            uint64_t *peak = &figures[k * NN_REGION_THRESHOLD_FIGURES + NN_REGION_THRESHOLD_PEAK + g];+            if (now > c.freed[k][g] && now - c.freed[k][g] > *peak) *peak = now - c.freed[k][g];+        }+    }+}++uint64_t nn_region_tenure_budget(uint32_t variant)+{+    return variant < NN_REGION_TENURE_VARIANTS ? tenure_budgets[variant] : 0;+}++uint32_t nn_region_spans_begun(void)+{+    return c.span_next;+}++uint32_t nn_region_spans_most(void)+{+    return c.span_most_ended;+}++uint64_t nn_region_lines_lost(void)+{+    uint64_t lost = 0, line;+    uint32_t b;+    if (!collecting()) return 0;+    for (b = 0; b < c.block_count; b++) {+        const block_t *blk = &c.blocks[b];+        uint64_t per;+        if (blk->kind >= NN_REGION_BUMP_KINDS || !blk->free) continue;+        per = NN_REGION_LINE / unit_bytes(blk->kind);+        for (line = 0; line < blk->lines; line++)+            if (!bit_get(blk->free, line)+                && bits_all(blk->tenure[NN_REGION_COLLECTOR].freed, line * per, (line + 1) * per))+                lost++;+    }+    return lost;+}++void nn_region_tenure(uint32_t variant, uint64_t *figures)+{+    uint64_t now = nn_region_mode ? allocated_now() : 0;+    const tenure_t *t;+    uint32_t g;+    if (variant >= NN_REGION_TENURE_VARIANTS) return;+    t = &c.t[variant];+    memcpy(figures, t->figures, sizeof(t->figures));+    for (g = 0; g < NN_REGION_GRAINS; g++) {+        uint64_t *peak = &figures[NN_REGION_TENURE_PEAK + g];+        if (now > t->freed[g] && now - t->freed[g] > *peak) *peak = now - t->freed[g];+    }+}
+ cbits/nn_region.h view
@@ -0,0 +1,304 @@+/*+ * nn_region.h - Regions: the C data layer's collector, which frees, at+ * the end of the forces of thunks it marks at (The collector, below), what+ * they allocated that nothing reaches, and a census that measures what it+ * and other collectors would free there, freeing nothing.+ *+ * A region is the extent of one force: everything the data layer+ * allocates from the force's start to the store of its value, inner+ * forces included.  Once the force returns, an object it allocated is+ * reachable only through an object older than the force that the force+ * wrote a pointer into (the forced cell, a cell an inner force memoized,+ * a with-scope entry resolved to a set) or through a root registered+ * during it (nn_roots.h).  Regions record every such write: each store+ * into a cell (nn_thunk.h) and each resolved with-scope entry+ * (nn_env_resolve_with).  At a region's close the census marks from the+ * records of objects older than the region and from the roots registered+ * since it opened, and stops at every object older than the region.  What+ * the mark does not reach is what a collector would free at that close.+ * The census frees nothing and writes nothing in the data layer.+ *+ * Age.  Objects are bumped from rooms of blocks (thunk blocks, env pages,+ * blocks of the value string arena): a new block, or, collecting, a run+ * of a block's free lines.  Each room is a span, numbered as it starts,+ * each line of a block keeps the number of the span that last handed it+ * out, and an address index finds the block of any pointer into one.  An+ * object is younger than a region when its line's span started after the+ * region opened, or is the one its allocator bumped from as the region+ * opened and the object lies at or past where the allocator had bumped+ * to then.  An object malloc'd on its own and tracked (nn_tracker.h) is+ * younger when its place in its tracker is at or past the tracker's+ * count as the region opened.+ *+ * A close passes to the region around it the records of objects older+ * than that region as well, and drops the rest: a write into an object+ * the enclosing region made needs no record there.+ *+ * Figures.  Each close counts the bytes its region allocated, the bytes+ * the mark reached in it, the objects the mark entered and the pointers+ * it examined, by size class: the bit length of the bytes allocated.  The+ * census also simulates a collector that marks only the regions that+ * allocated at least a threshold of bytes, a smaller one passing what it+ * allocated to the region around it unexamined.  For each threshold it+ * gives the closes that mark, their work, and the most bytes held at+ * once, by grain: freeing every object nothing reaches; freeing only+ * whole blocks that hold nothing reached, at the allocators' block sizes+ * and at each of four sizes a quarter of the one before; or freeing only+ * the lines of a block that hold nothing reached, as a collector reusing+ * free lines in place would.+ *+ * A check of the premise.  A unit of a block or a tracked object a close+ * finds unreached is marked as having died, and a later close that+ * reaches it counts it as resurrected: a pointer the records and roots+ * did not hold reached it, and a collector freeing at the first close+ * would have left that pointer dangling.+ *+ * Tenure.  Every mark above enters again, at each close around a region,+ * what the region's close found reached.  The census also simulates+ * collectors that do not: at the closes of regions that allocated at+ * least the tenure threshold, each marks only what no such close of its+ * inside the region tenured, and then tenures the whole region.  A+ * tenured object counts as reached until a close marks its region whole:+ * the outermost close around it, past the threshold, which takes the+ * census's own mark, or for a collector with a budget, any close whose+ * region holds at least that many tenured bytes which no mark of the+ * whole has reached since.  Besides the roots, two kinds of pointer reach an+ * untenured object from outside what a close marks, and the census holds+ * both: a store into a cell or with-scope entry that is tenured or older+ * than the region, kept as a record that the first such close reads; and+ * a pointer that an object a close's mark enters, or a cell a record+ * names, holds into a region around that it is younger than and+ * untenured in, which the close remembers for that region, since no later+ * close but a mark of the whole looks inside the object or reads the+ * record again.  A mark of the whole region reads every record of a cell+ * or entry older than it, which the census keeps for as long as one is,+ * and no remembered pointer: it looks inside everything in the region+ * that holds one.  It counts these+ * collectors' work and the most bytes they hold as for the others, and+ * the bytes their marks of the whole free, and checks that they free+ * nothing the census's own mark at the same close reached, and nothing a+ * later close reaches.+ *+ * The collector.  Collecting, regions run one of the tenure collectors+ * above and nothing else: the one with a budget of 1 MiB, whose close of+ * an outermost region is a mark of the whole by its own mark.  At each+ * close where it marks, it frees the tracked objects of the region its+ * mark left unreached, and the region's part of each tracker closes up+ * behind the places before it (nn_tracker_sweep), so that a tracker's+ * order stays age order and every open region's count stays its start.+ * It frees too each line of the region's spans once every unit in it is+ * freed, those its mark left unreached with those closes before it+ * freed, a line being NN_REGION_LINE_FIRST >>+ * (NN_REGION_LINE_GRAINS - 1) bytes from a multiple of that into its+ * block, and an allocator whose room is full bumps next from a run of a+ * block's free lines (nn_region_refill), in a span of its own, so that+ * what it puts there is younger than every region open.  Its marks are+ * the census's premise at work, so one that reaches a unit it freed, or+ * a tracked object it holds no place for, aborts (NN_ASSERT).  What it+ * freed and then gave to another object, a line a refill handed out+ * again or a tracked object's address the allocator reused, passes for+ * that one: under AddressSanitizer a free line is poisoned until a+ * refill hands it out and a freed address is held back from reuse, which+ * is what catches a read of either.+ *+ * Regions run from before the arena's init to after its teardown+ * (nn_region_begin and nn_region_end), so that they number every block+ * and place every tracked object.  When one of their tables cannot grow+ * they stop: a census stops counting and says so+ * (NN_REGION_TOTAL_FAILED), and the collector stops freeing, leaving+ * everything after to the arena's teardown.  Not thread-safe.+ */++#ifndef NN_REGION_H+#define NN_REGION_H++#include <stdint.h>++struct nn_thunk;++/* --- Kinds the allocators name --- */++/* Blocks objects are bumped from. */+#define NN_REGION_THUNK_BLOCK 0+#define NN_REGION_ENV_PAGE    1+#define NN_REGION_STR_BLOCK   2+#define NN_REGION_BUMP_KINDS  3++/* Blocks of the compiled code's strings, outside every region as code is+ * (nn_bytecode.h): indexed so that a string the census meets is placed+ * in a block of values, in one of code, or counted as unplaced. */+#define NN_REGION_CODE_BLOCK  3++/* Objects malloc'd one at a time and tracked. */+#define NN_REGION_SET           0+#define NN_REGION_LIST          1+#define NN_REGION_LAMBDA        2+#define NN_REGION_PRIMOP_APP    3+#define NN_REGION_CTXSTR        4+#define NN_REGION_TRACKED_KINDS 5++/* What regions run for: nothing, a census, or the collector. */+#define NN_REGION_OFF     0+#define NN_REGION_CENSUS  1+#define NN_REGION_COLLECT 2++/* The mode regions run in, NN_REGION_OFF while none run.  The+ * allocators' hooks below are called only while they run. */+extern int nn_region_mode;++/* --- Lifecycle --- */++/* Start regions in NN_REGION_CENSUS or NN_REGION_COLLECT, while no arena+ * is live (NN_ASSERT).  Returns 0, or -1 with none running when their+ * tables cannot be allocated. */+int nn_region_begin(int mode);++/* Stop them and release their tables, after the arena's teardown. */+void nn_region_end(void);++/* --- The allocators' half --- */++/* A block of `capacity` bytes from `data`, made for objects of a bump+ * kind or for the code's strings, and whether its allocator now bumps+ * from it, called while the allocator's cursor is still where it stopped+ * in the room it leaves (nn_thunk_cursor, nn_env_cursor, nn_str_cursor).+ * Every block is at least the address index's unit (NN_ASSERT). */+void nn_region_block(int kind, const char *data, uint64_t capacity, int current);++/* Collecting, the room the allocator of a bump kind bumps from next, once+ * the one it bumps from, which it stopped in at `cursor` bytes into its+ * block, has no room for `need` bytes: a run of at least that many bytes+ * of lines a close freed.  Returns 0 with the block's data in *data and+ * the room from *start to below *limit bytes into it, or -1 when there+ * is none, and the allocator makes a block.  Either way the allocator+ * bumps no more from the room it stopped in, whose lines past `cursor`+ * this may have freed. */+int nn_region_refill(int kind, uint64_t cursor, uint64_t need, const char **data, uint64_t *start,+                     uint64_t *limit);++/* A tracked object of a tracked kind, at `position` in its tracker,+ * holding `bytes`; and bytes a tracked object took on as it grew. */+void nn_region_tracked(int kind, const void *object, uint32_t position, uint64_t bytes);+void nn_region_tracked_grew(uint64_t bytes);++/* A list header at `position` in its tracker: a new list's, or one that+ * `of` dropped elements of (nn_list_drop), whose items are the tail of+ * the array `of` spans.  An allocator frees an items array whole, so the+ * census keeps the whole array while any list over it is reached, and+ * follows only the elements each list spans. */+void nn_region_list(const void *list, uint32_t position, const void *of);++/* A pointer stored into a cell, and into a with-scope entry. */+void nn_region_record_cell(const struct nn_thunk *cell);+void nn_region_record_with(void *const *entry);++/* --- The evaluator's half --- */++/* Open a region as a force starts, and close the innermost as it ends,+ * after its value is stored or as it throws.  Nothing while no regions+ * run. */+void nn_region_open(void);+void nn_region_close(void);++/* --- Figures --- */++/* The census's totals, NN_REGION_TOTALS of them. */+#define NN_REGION_TOTAL_CLOSES            0  /* regions closed */+#define NN_REGION_TOTAL_ALLOCATED         1  /* bytes allocated since the census began */+#define NN_REGION_TOTAL_OUTSIDE           2  /* of those, bytes no region has allocated */+#define NN_REGION_TOTAL_DEPTH             3  /* the most regions open at once */+#define NN_REGION_TOTAL_RECORDS           4  /* the most records held at once */+#define NN_REGION_TOTAL_UNPLACED          5  /* pointers the census could not place */+#define NN_REGION_TOTAL_RESURRECTED       6  /* objects and array entries reached after a close found them unreached */+#define NN_REGION_TOTAL_RESURRECTED_BYTES 7+#define NN_REGION_TOTAL_FAILED            8  /* nonzero when a table could not grow */+#define NN_REGION_TOTALS                  9++/* Closes by size class: class 0 allocated nothing, class n from 2^(n-1)+ * bytes to under 2^n, and the last class everything from its floor up.+ * For each, NN_REGION_CLASS_FIGURES figures. */+#define NN_REGION_SIZE_CLASSES 48+#define NN_REGION_CLASS_CLOSES    0+#define NN_REGION_CLASS_ALLOCATED 1  /* bytes */+#define NN_REGION_CLASS_SURVIVING 2  /* bytes reached at the close */+#define NN_REGION_CLASS_ENTERED   3  /* objects the mark entered */+#define NN_REGION_CLASS_EXAMINED  4  /* pointers the mark examined */+#define NN_REGION_CLASS_RECORDS   5  /* records the close read */+#define NN_REGION_CLASS_FIGURES   6++/* Thresholds: 0, then NN_REGION_THRESHOLD_FIRST bytes, each after it+ * four times the one before. */+#define NN_REGION_THRESHOLDS      9+#define NN_REGION_THRESHOLD_FIRST 4096u++/* Grains: 0 frees single objects; grain g from 1 to+ * NN_REGION_BLOCK_GRAINS frees whole blocks of the allocator's block size+ * divided by 4^(g-1); each of the NN_REGION_LINE_GRAINS after them frees+ * lines, the first of NN_REGION_LINE_FIRST bytes and each after it half+ * the one before.  A line is a block's bytes from a multiple of its size+ * in. */+#define NN_REGION_BLOCK_GRAINS 5+#define NN_REGION_LINE_GRAINS  2+#define NN_REGION_LINE_FIRST   256u+#define NN_REGION_GRAINS       (1 + NN_REGION_BLOCK_GRAINS + NN_REGION_LINE_GRAINS)++/* For each threshold, NN_REGION_THRESHOLD_FIGURES figures: the closes+ * that mark, the objects they entered, the pointers they examined, and+ * then the most bytes held at once at each grain. */+#define NN_REGION_THRESHOLD_CLOSES   0+#define NN_REGION_THRESHOLD_ENTERED  1+#define NN_REGION_THRESHOLD_EXAMINED 2+#define NN_REGION_THRESHOLD_PEAK     3+#define NN_REGION_THRESHOLD_FIGURES  (NN_REGION_THRESHOLD_PEAK + NN_REGION_GRAINS)++/* The tenure collectors, NN_REGION_TENURE_VARIANTS of them, mark at the+ * closes of regions that allocated at least the bytes of this threshold,+ * and NN_REGION_TENURE_FIGURES figures count what each did. */+#define NN_REGION_TENURE_VARIANTS  4+#define NN_REGION_TENURE_THRESHOLD 2+#define NN_REGION_TENURE_CLOSES            0   /* closes that mark */+#define NN_REGION_TENURE_FULL              1   /* of them, those that mark the whole region */+#define NN_REGION_TENURE_ENTERED           2   /* objects the marks entered */+#define NN_REGION_TENURE_EXAMINED          3   /* pointers they examined */+#define NN_REGION_TENURE_RECORDS           4   /* the most records held at once */+#define NN_REGION_TENURE_REMEMBERED        5   /* pointers closes remembered for regions around them */+#define NN_REGION_TENURE_HELD              6   /* the most remembered at once */+#define NN_REGION_TENURE_REACHED           7   /* units and places freed that the close's own mark reached */+#define NN_REGION_TENURE_RESURRECTED       8   /* objects and array entries a later close reached once freed */+#define NN_REGION_TENURE_RESURRECTED_BYTES 9+#define NN_REGION_TENURE_FULL_FREED        10  /* bytes those freed, of objects freed one by one */+#define NN_REGION_TENURE_PEAK              11  /* the most bytes held at once, at each grain */+#define NN_REGION_TENURE_FIGURES           (NN_REGION_TENURE_PEAK + NN_REGION_GRAINS)++/* What is allocated outside every region is what the evaluator does+ * between forces, at the top of an evaluation or in a function it calls+ * there, which no close can free; read with no region open, it counts+ * none still open. */+void nn_region_totals(uint64_t *totals);+void nn_region_classes(uint64_t *figures);     /* NN_REGION_SIZE_CLASSES rows */+void nn_region_thresholds(uint64_t *figures);  /* NN_REGION_THRESHOLDS rows */+void nn_region_tenure(uint32_t variant, uint64_t *figures);  /* NN_REGION_TENURE_FIGURES */++/* The bytes a tenure collector lets closes inside a region tenure before+ * a close marks the region whole, or 0 for none but the outermost. */+uint64_t nn_region_tenure_budget(uint32_t variant);++/* The spans begun since the regions began, and the most the span table+ * held at once from the close of an outermost region before the last to+ * the last, which trim it.  Collecting, the table drops the spans that+ * hold no line, so under a long force whose lines are freed it holds+ * fewer at once than the force begins. */+uint32_t nn_region_spans_begun(void);+uint32_t nn_region_spans_most(void);++/* Collecting, the whole lines of the bump kinds' blocks whose every unit+ * a close freed but which are not free: none, as the collector frees a+ * line once the last unit in it is freed.  0 when not collecting. */+uint64_t nn_region_lines_lost(void);++/* The bytes of threshold k, and of a block or line of a bump kind at+ * grain g from 1. */+uint64_t nn_region_threshold_bytes(uint32_t k);+uint64_t nn_region_grain_bytes(int kind, uint32_t grain);++#endif /* NN_REGION_H */
+ cbits/nn_roots.c view
@@ -0,0 +1,89 @@+/*+ * nn_roots.c - The roots of an evaluation session (nn_roots.h).+ *+ * Two growable arrays, one per kind of root, doubling as they fill.+ */++#include "nn_roots.h"+#include "nn_assert.h"++#include <stdlib.h>++/* The first capacity of each array, which doubles from there. */+#define NN_ROOTS_INITIAL 64u++typedef struct {+    void   **items;+    uint32_t count;+    uint32_t cap;+} nn_root_list_t;++static nn_root_list_t g_thunks;+static nn_root_list_t g_envs;++/* Returns 0, or -1 when the list cannot grow. */+static int push(nn_root_list_t *list, void *root)+{+    if (!root) return 0;+    if (list->count == list->cap) {+        uint32_t cap;+        void **grown;+        if (list->cap > UINT32_MAX / 2) return -1;+        cap = list->cap ? list->cap * 2 : NN_ROOTS_INITIAL;+        grown = (void **)realloc(list->items, (size_t)cap * sizeof(void *));+        if (!grown) return -1;+        list->items = grown;+        list->cap = cap;+    }+    list->items[list->count++] = root;+    return 0;+}++static void release(nn_root_list_t *list)+{+    free(list->items);+    list->items = NULL;+    list->count = 0;+    list->cap = 0;+}++int nn_roots_add_thunk(struct nn_thunk *thunk) { return push(&g_thunks, thunk); }+int nn_roots_add_env(struct nn_env *env)       { return push(&g_envs, env); }++uint32_t nn_roots_thunk_count(void) { return g_thunks.count; }+uint32_t nn_roots_env_count(void)   { return g_envs.count; }++struct nn_thunk *+nn_roots_thunk(uint32_t index)+{+    NN_ASSERT(index < g_thunks.count, "nn_roots_thunk: index is past the registered roots");+    return (struct nn_thunk *)g_thunks.items[index];+}++struct nn_env *+nn_roots_env(uint32_t index)+{+    NN_ASSERT(index < g_envs.count, "nn_roots_env: index is past the registered roots");+    return (struct nn_env *)g_envs.items[index];+}++void+nn_roots_mark(uint32_t *thunks, uint32_t *envs)+{+    *thunks = g_thunks.count;+    *envs = g_envs.count;+}++void+nn_roots_release(uint32_t thunks, uint32_t envs)+{+    if (thunks < g_thunks.count) g_thunks.count = thunks;+    if (envs < g_envs.count) g_envs.count = envs;+}++void+nn_roots_clear(void)+{+    release(&g_thunks);+    release(&g_envs);+}
+ cbits/nn_roots.h view
@@ -0,0 +1,52 @@+/*+ * nn_roots.h - The roots of an evaluation session in the C data layer.+ *+ * A value Haskell keeps beyond one evaluation step points into the C+ * data layer from outside it, where no mark over the C graph can find+ * it.  Each such pointer is registered here when it is made: a session's+ * base environment as the session starts (its search path is reached+ * through builtins.nixPath in it), an imported file's value as the+ * import cache takes it, and each value a command line's --arg or+ * --argstr gives, as the executable makes it.  A census marks from the+ * registered roots when its caller names them (nn_stats_root_registered,+ * nn_stats.h), as upstream's collector scans the import cache it keeps in+ * traceable memory.+ *+ * Sessions nest, so roots do too: a session marks the registry as it+ * starts and releases back to the mark as it ends, forgetting every root+ * registered within it; the arena's teardown clears what is left.  Not+ * thread-safe.+ */++#ifndef NN_ROOTS_H+#define NN_ROOTS_H++#include <stdint.h>++struct nn_thunk;+struct nn_env;++/* Register a thunk cell or an environment as a root.  Returns 0, or -1+ * when the registry cannot grow; NULL registers nothing and returns 0. */+int nn_roots_add_thunk(struct nn_thunk *thunk);+int nn_roots_add_env(struct nn_env *env);++/* How many roots of each kind are registered, and the one at an index+ * below that count, in the order they were registered.  An index past+ * the count aborts (NN_ASSERT). */+uint32_t nn_roots_thunk_count(void);+uint32_t nn_roots_env_count(void);+struct nn_thunk *nn_roots_thunk(uint32_t index);+struct nn_env *nn_roots_env(uint32_t index);++/* The registry's size now, to release back to. */+void nn_roots_mark(uint32_t *thunks, uint32_t *envs);++/* Forget every root registered since the mark, which an earlier+ * nn_roots_mark returned with no release past it since. */+void nn_roots_release(uint32_t thunks, uint32_t envs);++/* Forget every root and release the registry's memory. */+void nn_roots_clear(void);++#endif /* NN_ROOTS_H */
+ cbits/nn_stats.c view
@@ -0,0 +1,933 @@+/*+ * nn_stats.c - A census of the C data layer (nn_stats.h).+ *+ * The index places a pointer in one of two ways.  Thunk cells, env page+ * allocations and strings sit in a few large regions (the arena's blocks,+ * the env pages, the string arenas' blocks): a region index sorts the+ * regions by address and gives each a run of bits, one per thunk cell,+ * per NN_ENV_ALIGNMENT bytes of page or per NN_STR_ALIGNMENT bytes of+ * strings, so a pointer finds its bit by a binary search over regions;+ * the code's strings are indexed only to be placed, as code is not+ * marked.  Sets, list headers, lambdas, builtins' partial applications+ * and strings with context are each their own allocation: an object+ * index sorts a copy of the module's tracker (nn_tracker.h) and gives+ * each object a bit, found by a binary search for its address.+ * Addresses are compared as uintptr_t, since C orders pointers only+ * within one object.+ *+ * A list's items array has no header of its own: the headers that end at+ * one address share the array the longest of them spans (nn_list.h), so+ * the index groups headers by that address.  The mark records, per array,+ * the lowest address it has scanned from; every header over the array is+ * a suffix of it, so a header reached later scans only the elements below+ * that address, and a chain of suffixes costs its longest one.+ *+ * The mark sets an object's bit as it first reaches it and pushes it on a+ * work stack, so each object is pushed once and entered once, and follows+ * the pointers nn_graph.h says each object holds.+ */++#include "nn_stats.h"++#include "nn_assert.h"+#include "nn_attrset.h"+#include "nn_bytecode.h"+#include "nn_ctxstr.h"+#include "nn_env.h"+#include "nn_graph.h"+#include "nn_lambda.h"+#include "nn_list.h"+#include "nn_primop.h"+#include "nn_roots.h"+#include "nn_str.h"+#include "nn_symbol.h"+#include "nn_thunk.h"++#include <stdlib.h>+#include <string.h>++/* --- Index types --- */++/* A run of address space and the bit its first unit has. */+typedef struct {+    uintptr_t start;+    uintptr_t end;        /* one past the last byte handed out */+    uint64_t  first_bit;+} nn_span_t;++/* Regions holding objects at multiples of `unit` bytes from each start. */+typedef struct {+    nn_span_t *spans;     /* ascending start */+    uint32_t   count;+    uint64_t   unit;+    uint8_t   *bits;+} nn_region_index_t;++/* Objects that are each an allocation of their own. */+typedef struct {+    uintptr_t *objects;   /* ascending address */+    uint32_t   count;+    uint8_t   *bits;+} nn_object_index_t;++/* An items array and how much of it the mark has scanned. */+typedef struct {+    uintptr_t end;        /* where every header over it ends */+    uintptr_t scanned;    /* the lowest address scanned from; end when none */+    uint32_t  length;     /* elements the array holds */+} nn_items_t;++/* An object the mark has reached and not yet entered. */+typedef struct {+    const void *object;+    uint8_t     kind;+} nn_work_t;++/* A list header's end address, length and place in the list index,+ * sorted to group headers by array. */+typedef struct {+    uintptr_t end;+    uint32_t  length;+    uint32_t  pos;+} nn_header_end_t;++/* --- Session state --- */++#define NN_STATS_WORK_INITIAL      4096u++static struct {+    int open;+    int failed;++    nn_region_index_t thunks;+    nn_region_index_t pages;+    nn_object_index_t sets;+    nn_object_index_t lists;+    nn_object_index_t lambdas;+    nn_object_index_t primop_apps;+    nn_object_index_t ctxstrs;+    nn_region_index_t strings;+    nn_region_index_t code_strings;++    nn_items_t *items;+    uint64_t    items_bytes;+    uint32_t   *list_items;   /* per list in index order: its items array */++    uint8_t *symbol_bits;+    uint32_t symbol_count;++    nn_work_t *work;+    size_t     work_count;+    size_t     work_cap;++    uint64_t allocated_count[NN_STATS_KIND_COUNT];+    uint64_t allocated_bytes[NN_STATS_KIND_COUNT];+    uint64_t reached_count[NN_STATS_KIND_COUNT];+    uint64_t reached_bytes[NN_STATS_KIND_COUNT];+    uint64_t overhead_bytes;+    uint64_t code_bytes;+    uint64_t visited_objects;+    uint64_t visited_bytes;+    uint64_t unplaced;+} g;++/* --- Counting by site --- */++int nn_stats_counting = 0;++/* Apart from the session: counting runs for the whole evaluation, and a+ * census reads it. */+static struct {+    int complete;   /* counting began before the env pages' first byte */+    uint64_t env_count[NN_STATS_ENV_SITES];+    uint64_t env_slots[NN_STATS_ENV_SITES];+    uint64_t env_bytes[NN_STATS_ENV_SITES];+    uint64_t env_sizes[NN_STATS_ENV_SIZES];+    uint64_t set_count[NN_STATS_SET_SITES];+    uint64_t set_shareable[NN_STATS_SET_SITES];+    uint64_t set_bytes[NN_STATS_SET_SITES];+    uint64_t update_copied;+} sites;++void nn_stats_count_sites(void)+{+    memset(&sites, 0, sizeof(sites));+    sites.complete = nn_env_bytes_allocated() == 0;+    nn_stats_counting = 1;+}++/* A site the evaluator never numbers is a defect in it, and aborts+ * (NN_ASSERT). */+void nn_stats_count_env(uint32_t site, uint32_t slots, uint64_t bytes)+{+    NN_ASSERT(site < NN_STATS_ENV_SITES, "nn_stats_count_env: unknown site");+    sites.env_count[site]++;+    sites.env_slots[site] += slots;+    sites.env_bytes[site] += bytes;+    sites.env_sizes[slots < NN_STATS_ENV_SIZES - 1 ? slots : NN_STATS_ENV_SIZES - 1]++;+}++void nn_stats_count_env_bytes(uint32_t site, uint64_t bytes)+{+    NN_ASSERT(site < NN_STATS_ENV_SITES, "nn_stats_count_env_bytes: unknown site");+    sites.env_bytes[site] += bytes;+}++void nn_stats_count_set(uint32_t site, uint64_t bytes, int shareable)+{+    NN_ASSERT(site < NN_STATS_SET_SITES, "nn_stats_count_set: unknown site");+    sites.set_count[site]++;+    sites.set_bytes[site] += bytes;+    if (shareable) sites.set_shareable[site]++;+}++void nn_stats_count_update(uint64_t copied)+{+    sites.update_copied += copied;+}++/* The first `max` of `n` figures from `from` to `to`.  No copy for none:+ * memcpy takes no NULL, whatever the length. */+static void copy_figures(uint64_t *to, const uint64_t *from, uint32_t n, uint32_t max)+{+    uint32_t k = max < n ? max : n;+    if (k > 0) memcpy(to, from, (size_t)k * sizeof(uint64_t));+}++uint32_t nn_stats_env_sites(uint64_t *envs, uint64_t *slots, uint64_t *bytes, uint32_t max)+{+    copy_figures(envs, sites.env_count, NN_STATS_ENV_SITES, max);+    copy_figures(slots, sites.env_slots, NN_STATS_ENV_SITES, max);+    copy_figures(bytes, sites.env_bytes, NN_STATS_ENV_SITES, max);+    return NN_STATS_ENV_SITES;+}++uint32_t nn_stats_env_sizes(uint64_t *envs, uint32_t max)+{+    copy_figures(envs, sites.env_sizes, NN_STATS_ENV_SIZES, max);+    return NN_STATS_ENV_SIZES;+}++uint32_t nn_stats_set_sites(uint64_t *sets, uint64_t *shareable, uint64_t *bytes, uint32_t max)+{+    copy_figures(sets, sites.set_count, NN_STATS_SET_SITES, max);+    copy_figures(shareable, sites.set_shareable, NN_STATS_SET_SITES, max);+    copy_figures(bytes, sites.set_bytes, NN_STATS_SET_SITES, max);+    return NN_STATS_SET_SITES;+}++uint64_t nn_stats_update_copied(void)+{+    return sites.update_copied;+}++/* Every env, when counting has covered every one; NN_STATS_UNCOUNTED+ * otherwise. */+static uint64_t counted_envs(void)+{+    uint64_t total = 0;+    uint32_t i;+    if (!nn_stats_counting || !sites.complete) return NN_STATS_UNCOUNTED;+    for (i = 0; i < NN_STATS_ENV_SITES; i++) total += sites.env_count[i];+    return total;+}++/* --- Bits --- */++/* A zeroed bitmap of `bits` bits; never a zero-byte request, whose answer+ * malloc may give as NULL. */+static uint8_t *bitmap_new(uint64_t bits)+{+    return (uint8_t *)calloc((size_t)(bits / 8 + 1), 1);+}++/* Set a bit; 1 when it was clear. */+static int bit_set(uint8_t *bits, uint64_t i)+{+    uint8_t mask = (uint8_t)(1u << (i % 8));+    if (bits[i / 8] & mask) return 0;+    bits[i / 8] |= mask;+    return 1;+}++static int bit_get(const uint8_t *bits, uint64_t i)+{+    return (bits[i / 8] >> (i % 8)) & 1u;+}++/* --- Ordering --- */++static int cmp_address(const void *a, const void *b)+{+    uintptr_t x = *(const uintptr_t *)a;+    uintptr_t y = *(const uintptr_t *)b;+    return (x > y) - (x < y);+}++static int cmp_span(const void *a, const void *b)+{+    uintptr_t x = ((const nn_span_t *)a)->start;+    uintptr_t y = ((const nn_span_t *)b)->start;+    return (x > y) - (x < y);+}++static int cmp_header_end(const void *a, const void *b)+{+    const nn_header_end_t *x = (const nn_header_end_t *)a;+    const nn_header_end_t *y = (const nn_header_end_t *)b;+    if (x->end != y->end) return (x->end > y->end) - (x->end < y->end);+    return (x->length < y->length) - (x->length > y->length);+}++static int cmp_u32(const void *a, const void *b)+{+    uint32_t x = *(const uint32_t *)a;+    uint32_t y = *(const uint32_t *)b;+    return (x > y) - (x < y);+}++/* --- Region index --- */++/* Sort the spans, number their units and allocate their bits.  The spans+ * array becomes the index's.  Returns 0 or -1. */+static int region_build(nn_region_index_t *r, nn_span_t *spans, uint32_t count, uint64_t unit)+{+    uint64_t bits = 0;+    uint32_t i;+    qsort(spans, count, sizeof(nn_span_t), cmp_span);+    for (i = 0; i < count; i++) {+        spans[i].first_bit = bits;+        bits += (uint64_t)(spans[i].end - spans[i].start) / unit;+    }+    r->spans = spans;+    r->count = count;+    r->unit = unit;+    r->bits = bitmap_new(bits);+    return r->bits ? 0 : -1;+}++/* The bit of the unit `p` starts, when `p` is a unit boundary inside a+ * span.  Returns 1 and writes *bit, or 0. */+static int region_find(const nn_region_index_t *r, uintptr_t p, uint64_t *bit)+{+    uint32_t lo = 0, hi = r->count;+    const nn_span_t *span;+    uint64_t offset;+    /* The last span starting at or below p. */+    while (lo < hi) {+        uint32_t mid = lo + (hi - lo) / 2;+        if (r->spans[mid].start <= p) lo = mid + 1;+        else hi = mid;+    }+    if (lo == 0) return 0;+    span = &r->spans[lo - 1];+    if (p >= span->end) return 0;+    offset = (uint64_t)(p - span->start);+    if (offset % r->unit != 0) return 0;+    *bit = span->first_bit + offset / r->unit;+    return 1;+}++static void region_free(nn_region_index_t *r)+{+    free(r->spans);+    free(r->bits);+    memset(r, 0, sizeof(*r));+}++/* --- Object index --- */++/* Index a module's tracked objects: their addresses, sorted, and a bit+ * each.  The tracker's array counts as overhead.  Returns 0 or -1. */+static int object_build(nn_object_index_t *o, const nn_tracker_t *tracker)+{+    uint32_t i;+    g.overhead_bytes += (uint64_t)tracker->capacity * sizeof(void *);+    o->count = tracker->count;+    o->objects = (uintptr_t *)malloc((size_t)o->count * sizeof(uintptr_t) + 1);+    o->bits = bitmap_new(o->count);+    if (!o->objects || !o->bits) return -1;+    for (i = 0; i < o->count; i++) o->objects[i] = (uintptr_t)tracker->objects[i];+    qsort(o->objects, o->count, sizeof(uintptr_t), cmp_address);+    return 0;+}++/* The position of the object at `p`.  Returns 1 and writes *pos, or 0. */+static int object_find(const nn_object_index_t *o, uintptr_t p, uint32_t *pos)+{+    uint32_t lo = 0, hi = o->count;+    while (lo < hi) {+        uint32_t mid = lo + (hi - lo) / 2;+        if (o->objects[mid] < p) lo = mid + 1;+        else if (o->objects[mid] > p) hi = mid;+        else { *pos = mid; return 1; }+    }+    return 0;+}++static void object_free(nn_object_index_t *o)+{+    free(o->objects);+    free(o->bits);+    memset(o, 0, sizeof(*o));+}++/* --- Building the index --- */++static int index_thunks(void)+{+    uint32_t n = nn_thunk_blocks(NULL, NULL, 0), i;+    uint64_t extent = 0;+    nn_thunk_t **slots = (nn_thunk_t **)malloc((size_t)n * sizeof(nn_thunk_t *) + 1);+    uint32_t *counts = (uint32_t *)malloc((size_t)n * sizeof(uint32_t) + 1);+    nn_span_t *spans = (nn_span_t *)malloc((size_t)n * sizeof(nn_span_t) + 1);+    int status = -1;+    if (slots && counts && spans) {+        nn_thunk_blocks(slots, counts, n);+        for (i = 0; i < n; i++) {+            spans[i].start = (uintptr_t)slots[i];+            spans[i].end = spans[i].start + (uintptr_t)counts[i] * sizeof(nn_thunk_t);+            extent += (uint64_t)counts[i] * sizeof(nn_thunk_t);+        }+        status = region_build(&g.thunks, spans, n, sizeof(nn_thunk_t));+        spans = NULL;+    }+    free(slots);+    free(counts);+    free(spans);+    /* Cells the evaluation allocated, which a collector reusing lines puts+     * where others were, so they can exceed what the blocks hold. */+    g.allocated_count[NN_STATS_THUNKS] = nn_thunk_cells_allocated();+    g.allocated_bytes[NN_STATS_THUNKS] = g.allocated_count[NN_STATS_THUNKS] * sizeof(nn_thunk_t);+    g.overhead_bytes += nn_thunk_reserved_bytes() - extent;+    return status;+}++static int index_pages(void)+{+    uint32_t n = nn_env_pages(NULL, NULL, 0), i;+    uint64_t extent = 0;+    char **data = (char **)malloc((size_t)n * sizeof(char *) + 1);+    uint32_t *used = (uint32_t *)malloc((size_t)n * sizeof(uint32_t) + 1);+    nn_span_t *spans = (nn_span_t *)malloc((size_t)n * sizeof(nn_span_t) + 1);+    int status = -1;+    if (data && used && spans) {+        nn_env_pages(data, used, n);+        for (i = 0; i < n; i++) {+            spans[i].start = (uintptr_t)data[i];+            spans[i].end = spans[i].start + used[i];+            extent += used[i];+        }+        status = region_build(&g.pages, spans, n, NN_ENV_ALIGNMENT);+        spans = NULL;+    }+    free(data);+    free(used);+    free(spans);+    g.overhead_bytes += nn_env_reserved_bytes() - extent;+    return status;+}++/* Index the list headers and group them by the items array they share. */+static int index_lists(void)+{+    uint32_t count, i, k;+    nn_header_end_t *ends;+    if (object_build(&g.lists, nn_list_tracked()) != 0) return -1;+    count = g.lists.count;+    g.allocated_count[NN_STATS_LISTS] = count;+    g.allocated_bytes[NN_STATS_LISTS] = (uint64_t)count * sizeof(nn_list_t);++    ends = (nn_header_end_t *)malloc((size_t)count * sizeof(nn_header_end_t) + 1);+    g.items = (nn_items_t *)malloc((size_t)count * sizeof(nn_items_t) + 1);+    g.list_items = (uint32_t *)malloc((size_t)count * sizeof(uint32_t) + 1);+    if (!ends || !g.items || !g.list_items) {+        free(ends);+        return -1;+    }+    for (i = 0; i < count; i++) {+        const nn_list_t *list = (const nn_list_t *)g.lists.objects[i];+        ends[i].end = (uintptr_t)list->items + (uintptr_t)list->count * sizeof(void *);+        ends[i].length = list->count;+        ends[i].pos = i;+    }+    /* By end, then longest first: each run is one array, led by the+     * header that spans all of it. */+    qsort(ends, count, sizeof(nn_header_end_t), cmp_header_end);+    k = 0;+    for (i = 0; i < count; i++) {+        if (i == 0 || ends[i].end != ends[i - 1].end) {+            g.items[k].end = ends[i].end;+            g.items[k].scanned = ends[i].end;+            g.items[k].length = ends[i].length;+            g.items_bytes += (uint64_t)ends[i].length * sizeof(void *);+            k++;+        }+        g.list_items[ends[i].pos] = k - 1;+    }+    g.allocated_bytes[NN_STATS_LISTS] += g.items_bytes;+    free(ends);+    return 0;+}++static int index_sets(void)+{+    const nn_tracker_t *tracked = nn_attrset_tracked();+    uint32_t i;+    g.allocated_count[NN_STATS_ATTRSETS] = tracked->count;+    for (i = 0; i < tracked->count; i++)+        g.allocated_bytes[NN_STATS_ATTRSETS] += nn_attrset_bytes((const nn_attrset_t *)tracked->objects[i]);+    return object_build(&g.sets, tracked);+}++static int index_lambdas(void)+{+    const nn_tracker_t *tracked = nn_lambda_tracked();+    uint32_t i;+    g.allocated_count[NN_STATS_LAMBDAS] = tracked->count;+    for (i = 0; i < tracked->count; i++)+        g.allocated_bytes[NN_STATS_LAMBDAS] += nn_lambda_bytes((const nn_lambda_t *)tracked->objects[i]);+    return object_build(&g.lambdas, tracked);+}++static int index_primop_apps(void)+{+    const nn_tracker_t *tracked = nn_primop_app_tracked();+    uint32_t i;+    g.allocated_count[NN_STATS_PRIMOP_APPS] = tracked->count;+    for (i = 0; i < tracked->count; i++)+        g.allocated_bytes[NN_STATS_PRIMOP_APPS] += nn_primop_app_bytes((const nn_primop_app_t *)tracked->objects[i]);+    return object_build(&g.primop_apps, tracked);+}++static int index_ctxstrs(void)+{+    const nn_tracker_t *tracked = nn_ctxstr_tracked();+    uint32_t i;+    g.allocated_count[NN_STATS_CTXSTRS] = tracked->count;+    for (i = 0; i < tracked->count; i++)+        g.allocated_bytes[NN_STATS_CTXSTRS] += nn_ctxstr_bytes((const nn_ctxstr_t *)tracked->objects[i]);+    return object_build(&g.ctxstrs, tracked);+}++/* Index an arena's strings, a bit per NN_STR_ALIGNMENT bytes its blocks+ * have handed out, and add those bytes to *used unless it is NULL.+ * Returns 0 or -1. */+static int index_str_arena(nn_region_index_t *r, const nn_str_arena_t *arena, uint64_t *used)+{+    uint32_t n = nn_str_arena_blocks(arena, NULL, NULL, 0), i;+    const char **starts = (const char **)malloc((size_t)n * sizeof(char *) + 1);+    uint64_t *block_used = (uint64_t *)malloc((size_t)n * sizeof(uint64_t) + 1);+    nn_span_t *spans = (nn_span_t *)malloc((size_t)n * sizeof(nn_span_t) + 1);+    int status = -1;+    if (starts && block_used && spans) {+        nn_str_arena_blocks(arena, starts, block_used, n);+        for (i = 0; i < n; i++) {+            spans[i].start = (uintptr_t)starts[i];+            spans[i].end = spans[i].start + (uintptr_t)block_used[i];+            if (used) *used += block_used[i];+        }+        status = region_build(r, spans, n, NN_STR_ALIGNMENT);+        spans = NULL;+    }+    free(starts);+    free(block_used);+    free(spans);+    return status;+}++/* The value arena's strings, counted, and the code's, placed only. */+static int index_strings(void)+{+    const nn_str_arena_t *values = nn_str_values();+    uint64_t used = 0;+    if (index_str_arena(&g.strings, values, &used) != 0) return -1;+    if (index_str_arena(&g.code_strings, nn_bc_strings(), NULL) != 0) return -1;+    g.allocated_count[NN_STATS_STRINGS] = values->count;+    g.allocated_bytes[NN_STATS_STRINGS] = values->bytes;+    g.overhead_bytes += nn_str_arena_reserved_bytes(values) - used;+    return 0;+}++/* --- Session --- */++int nn_stats_begin(void)+{+    uint64_t text, reserved;+    if (g.open) nn_stats_end();+    memset(&g, 0, sizeof(g));+    g.open = 1;++    if (index_thunks() != 0 || index_pages() != 0 || index_sets() != 0+        || index_lists() != 0 || index_lambdas() != 0 || index_primop_apps() != 0+        || index_ctxstrs() != 0+        || index_strings() != 0) {+        nn_stats_end();+        return -1;+    }++    /* The page bytes handed out are the envs, their with-scope arrays, the+     * list items arrays, every one of which nn_list_new takes from the+     * pages, and the deferred applications' cells. */+    NN_ASSERT(g.items_bytes + nn_env_app_bytes() <= nn_env_bytes_allocated(),+              "nn_stats_begin: list items or applications outside the env pages");+    g.allocated_count[NN_STATS_ENVS] = counted_envs();+    g.allocated_bytes[NN_STATS_ENVS] = nn_env_bytes_allocated() - g.items_bytes - nn_env_app_bytes();+    g.allocated_count[NN_STATS_APPS] = nn_env_app_count();+    g.allocated_bytes[NN_STATS_APPS] = nn_env_app_bytes();++    nn_symbol_footprint(&text, &reserved);+    g.symbol_count = nn_symbol_count();+    g.symbol_bits = bitmap_new((uint64_t)g.symbol_count + 1);+    if (!g.symbol_bits) {+        nn_stats_end();+        return -1;+    }+    g.allocated_count[NN_STATS_SYMBOLS] = g.symbol_count;+    g.allocated_bytes[NN_STATS_SYMBOLS] = text;++    g.overhead_bytes += reserved - text;+    g.code_bytes = nn_bc_reserved_bytes();+    return 0;+}++void nn_stats_end(void)+{+    region_free(&g.thunks);+    region_free(&g.pages);+    object_free(&g.sets);+    object_free(&g.lists);+    object_free(&g.lambdas);+    object_free(&g.primop_apps);+    object_free(&g.ctxstrs);+    region_free(&g.strings);+    region_free(&g.code_strings);+    free(g.items);+    free(g.list_items);+    free(g.symbol_bits);+    free(g.work);+    memset(&g, 0, sizeof(g));+}++/* --- What is allocated --- */++void nn_stats_allocated(uint64_t *counts, uint64_t *bytes)+{+    memcpy(counts, g.allocated_count, sizeof(g.allocated_count));+    memcpy(bytes, g.allocated_bytes, sizeof(g.allocated_bytes));+}++uint64_t nn_stats_overhead_bytes(void) { return g.overhead_bytes; }+uint64_t nn_stats_code_bytes(void)     { return g.code_bytes; }++/* --- Reaching objects --- */++static void work_push(uint8_t kind, const void *object)+{+    if (g.work_count == g.work_cap) {+        size_t cap = g.work_cap ? g.work_cap * 2 : NN_STATS_WORK_INITIAL;+        nn_work_t *grown = (nn_work_t *)realloc(g.work, cap * sizeof(nn_work_t));+        if (!grown) {+            g.failed = 1;+            return;+        }+        g.work = grown;+        g.work_cap = cap;+    }+    g.work[g.work_count].object = object;+    g.work[g.work_count].kind = kind;+    g.work_count++;+}++/* An object reached for the first time: its kind's figures and the+ * mark's own. */+static void count_reached(int kind, uint64_t bytes)+{+    g.reached_count[kind]++;+    g.reached_bytes[kind] += bytes;+    g.visited_objects++;+    g.visited_bytes += bytes;+}++/* The null, true, false and empty list cells, the builtins' cells, the+ * empty env and the empty set are statics, not allocations: reached and+ * neither counted nor entered, as they hold no pointer. */+static int is_static(int kind, const void *object)+{+    if (kind == NN_GRAPH_THUNK) return nn_thunk_is_static((const nn_thunk_t *)object);+    if (kind == NN_GRAPH_ENV) return object == nn_env_empty();+    if (kind == NN_GRAPH_ATTRSET) return object == nn_attrset_empty();+    return 0;+}++/* Reach an object of an NN_GRAPH_* object kind: mark it and push it when+ * it is new. */+static void reach(int kind, const void *object)+{+    uintptr_t p = (uintptr_t)object;+    uint64_t bit;+    uint32_t pos;+    if (!object || is_static(kind, object)) return;+    switch (kind) {+    case NN_GRAPH_THUNK:+        if (!region_find(&g.thunks, p, &bit)) break;+        if (bit_set(g.thunks.bits, bit)) {+            count_reached(NN_STATS_THUNKS, sizeof(nn_thunk_t));+            work_push((uint8_t)kind, object);+        }+        return;+    case NN_GRAPH_ENV:+        if (!region_find(&g.pages, p, &bit)) break;+        if (bit_set(g.pages.bits, bit)) {+            count_reached(NN_STATS_ENVS, nn_env_bytes((const nn_env_t *)object));+            work_push((uint8_t)kind, object);+        }+        return;+    case NN_GRAPH_ATTRSET:+        if (!object_find(&g.sets, p, &pos)) break;+        if (bit_set(g.sets.bits, pos)) {+            count_reached(NN_STATS_ATTRSETS, nn_attrset_bytes((const nn_attrset_t *)object));+            work_push((uint8_t)kind, object);+        }+        return;+    case NN_GRAPH_LIST:+        if (!object_find(&g.lists, p, &pos)) break;+        if (bit_set(g.lists.bits, pos)) {+            count_reached(NN_STATS_LISTS, sizeof(nn_list_t));+            work_push((uint8_t)kind, object);+        }+        return;+    case NN_GRAPH_LAMBDA:+        if (!object_find(&g.lambdas, p, &pos)) break;+        if (bit_set(g.lambdas.bits, pos)) {+            count_reached(NN_STATS_LAMBDAS, nn_lambda_bytes((const nn_lambda_t *)object));+            work_push((uint8_t)kind, object);+        }+        return;+    case NN_GRAPH_PRIMOP_APP:+        if (!object_find(&g.primop_apps, p, &pos)) break;+        if (bit_set(g.primop_apps.bits, pos)) {+            count_reached(NN_STATS_PRIMOP_APPS, nn_primop_app_bytes((const nn_primop_app_t *)object));+            work_push((uint8_t)kind, object);+        }+        return;+    case NN_GRAPH_CTXSTR:+        if (!object_find(&g.ctxstrs, p, &pos)) break;+        if (bit_set(g.ctxstrs.bits, pos)) {+            count_reached(NN_STATS_CTXSTRS, nn_ctxstr_bytes((const nn_ctxstr_t *)object));+            work_push((uint8_t)kind, object);+        }+        return;+    default:+        break;+    }+    g.unplaced++;+}++/* Reach a symbol.  0 is no symbol (an unnamed formal set). */+static void reach_symbol(uint32_t sym)+{+    if (sym == NN_SYMBOL_INVALID) return;+    if (sym > g.symbol_count) {+        g.unplaced++;+        return;+    }+    if (bit_set(g.symbol_bits, sym)) {+        g.reached_count[NN_STATS_SYMBOLS]++;+        g.reached_bytes[NN_STATS_SYMBOLS] += (uint64_t)nn_symbol_len(sym) + 1;+    }+}++/* Reach a string.  The empty string is a static, reached and not+ * counted, and a string of the code's is placed and not counted, as code+ * is not marked. */+static void reach_string(const nn_str_t *s)+{+    uintptr_t p = (uintptr_t)s;+    uint64_t bit;+    if (s == nn_str_empty()) return;+    if (region_find(&g.strings, p, &bit)) {+        if (bit_set(g.strings.bits, bit)) {+            g.reached_count[NN_STATS_STRINGS]++;+            g.reached_bytes[NN_STATS_STRINGS] += nn_str_object_bytes(s);+        }+        return;+    }+    if (region_find(&g.code_strings, p, &bit)) return;+    g.unplaced++;+}++/* Reach an env's with-scope array of `n` entries, which several envs may+ * share; 1 when it is new and its entries are to be followed. */+static int reach_array(void *const *array, uint32_t n)+{+    uint64_t bit;+    uint64_t bytes = (uint64_t)n * sizeof(void *);+    if (!region_find(&g.pages, (uintptr_t)array, &bit)) {+        g.unplaced++;+        return 0;+    }+    if (!bit_set(g.pages.bits, bit)) return 0;+    g.reached_bytes[NN_STATS_ENVS] += bytes;+    g.visited_objects++;+    g.visited_bytes += bytes;+    return 1;+}++/* Reach a deferred application's `n` cells, an array of the env pages+ * that one thunk holds; 1 when it is new and its cells are to be+ * followed. */+static int reach_app(void *const *cells, uint32_t n)+{+    uint64_t bit;+    if (!region_find(&g.pages, (uintptr_t)cells, &bit)) {+        g.unplaced++;+        return 0;+    }+    if (!bit_set(g.pages.bits, bit)) return 0;+    count_reached(NN_STATS_APPS, (uint64_t)n * sizeof(void *));+    return 1;+}++/* --- The visitor (nn_graph.h) --- */++static void visit_object(void *ctx, int kind, const void *object)+{+    (void)ctx;+    reach(kind, object);+}++static void visit_string(void *ctx, const nn_str_t *s)+{+    (void)ctx;+    reach_string(s);+}++static void visit_symbol(void *ctx, uint32_t sym)+{+    (void)ctx;+    reach_symbol(sym);+}++static void visit_unknown(void *ctx)+{+    (void)ctx;+    g.unplaced++;+}++static void visit_array(void *ctx, int kind, const void *owner, void *const *base, uint32_t count);++static const nn_graph_visitor_t visitor = {+    visit_object, visit_array, visit_string, visit_symbol, visit_unknown+};++/* A list's items: the elements of its array below the lowest address the+ * mark has scanned from, which every header over the array shares. */+static void scan_items(const nn_list_t *list)+{+    uint32_t pos, i, below;+    nn_items_t *items;+    uintptr_t start = (uintptr_t)list->items;+    if (!object_find(&g.lists, (uintptr_t)list, &pos)) return;+    items = &g.items[g.list_items[pos]];+    if (items->scanned == items->end) {+        uint64_t bytes = (uint64_t)items->length * sizeof(void *);+        g.reached_bytes[NN_STATS_LISTS] += bytes;+        g.visited_objects++;+        g.visited_bytes += bytes;+    }+    if (start >= items->scanned) return;+    below = (uint32_t)((items->scanned - start) / sizeof(void *));+    for (i = 0; i < below; i++) reach(NN_GRAPH_THUNK, list->items[i]);+    items->scanned = start;+}++/* An env's with-scope array and an application's cells are counted the+ * first time any owner reaches them, a list's items as far as it spans+ * them. */+static void visit_array(void *ctx, int kind, const void *owner, void *const *base, uint32_t count)+{+    uint32_t i;+    switch (kind) {+    case NN_GRAPH_WITH_SCOPES:+        if (reach_array(base, count))+            for (i = 0; i < count; i++) nn_graph_entry(kind, base[i], &visitor, ctx);+        return;+    case NN_GRAPH_APP_CELLS:+        if (reach_app(base, count))+            for (i = 0; i < count; i++) nn_graph_entry(kind, base[i], &visitor, ctx);+        return;+    case NN_GRAPH_ITEMS:+        scan_items((const nn_list_t *)owner);+        return;+    default:+        g.unplaced++;+        return;+    }+}++/* --- The mark --- */++void nn_stats_root_thunk(const void *thunk)   { if (g.open) reach(NN_GRAPH_THUNK, thunk); }+void nn_stats_root_env(const void *env)       { if (g.open) reach(NN_GRAPH_ENV, env); }+void nn_stats_root_attrset(const void *set)   { if (g.open) reach(NN_GRAPH_ATTRSET, set); }+void nn_stats_root_list(const void *list)     { if (g.open) reach(NN_GRAPH_LIST, list); }+void nn_stats_root_string(const void *str)    { if (g.open && str) reach_string((const nn_str_t *)str); }+void nn_stats_root_ctxstr(const void *ctxstr) { if (g.open) reach(NN_GRAPH_CTXSTR, ctxstr); }++void nn_stats_root_registered(void)+{+    uint32_t i, n;+    if (!g.open) return;+    for (i = 0, n = nn_roots_thunk_count(); i < n; i++) reach(NN_GRAPH_THUNK, nn_roots_thunk(i));+    for (i = 0, n = nn_roots_env_count(); i < n; i++) reach(NN_GRAPH_ENV, nn_roots_env(i));+}++int nn_stats_mark(void)+{+    if (!g.open) return -1;+    while (g.work_count > 0) {+        nn_work_t item = g.work[--g.work_count];+        nn_graph_children(item.kind, item.object, &visitor, NULL);+    }+    return g.failed ? -1 : 0;+}++void nn_stats_reached(uint64_t *counts, uint64_t *bytes)+{+    memcpy(counts, g.reached_count, sizeof(g.reached_count));+    memcpy(bytes, g.reached_bytes, sizeof(g.reached_bytes));+}++void nn_stats_visited(uint64_t *objects, uint64_t *bytes, uint64_t *unplaced)+{+    *objects = g.visited_objects;+    *bytes = g.visited_bytes;+    *unplaced = g.unplaced;+}++int nn_stats_reached_set_sizes(uint32_t *sizes, uint64_t *counts, uint32_t max,+                               uint32_t *distinct)+{+    uint32_t reached = 0, i;+    uint32_t *all = (uint32_t *)malloc((size_t)g.sets.count * sizeof(uint32_t) + 1);+    *distinct = 0;+    if (!all) return -1;+    for (i = 0; i < g.sets.count; i++) {+        if (bit_get(g.sets.bits, i))+            all[reached++] = nn_attrset_layer_count((const nn_attrset_t *)g.sets.objects[i]);+    }+    qsort(all, reached, sizeof(uint32_t), cmp_u32);+    for (i = 0; i < reached; i++) {+        if (i == 0 || all[i] != all[i - 1]) {+            if (*distinct < max) {+                sizes[*distinct] = all[i];+                counts[*distinct] = 0;+            }+            (*distinct)++;+        }+        if (*distinct <= max) counts[*distinct - 1]++;+    }+    free(all);+    return 0;+}
+ cbits/nn_stats.h view
@@ -0,0 +1,191 @@+/*+ * nn_stats.h - A census of the C data layer: what it holds by kind, and+ * what a set of roots reaches.+ *+ * The census reads what the allocators keep (the thunk blocks, the env+ * pages and the count and bytes of deferred applications' cells in them,+ * the tracked sets, list headers, lambdas, builtins' partial applications+ * and strings with context, the string arena's blocks and count of+ * strings, the symbol table).  Of those, only the count and bytes of+ * applications' cells and the count of strings are kept for the census+ * alone, so a process that never takes one pays for it those counters and+ * the test of nn_stats_counting below.+ *+ * A census is a session.  nn_stats_begin counts what is allocated and+ * indexes every object; the caller names roots and calls nn_stats_mark,+ * which follows every pointer from them; nn_stats_end releases the index.+ * The mark frees and writes nothing in the data layer: its marks are bits+ * of its own.  It dereferences only a pointer it places: a tracked+ * object's address, or a unit boundary within what a block or page has+ * handed out (a thunk cell, NN_ENV_ALIGNMENT bytes of a page,+ * NN_STR_ALIGNMENT bytes of strings), which it reads as the start of an+ * object of the pointer's kind.  It counts any other pointer it meets as+ * unplaced, which a graph the mark models in full never holds.  Every+ * value lives in C (nn_thunk.h), so the mark reaches all a root holds+ * without the caller.+ *+ * One session at a time, between the arena's init and destroy, with no+ * allocation in the data layer while it is open.  Not thread-safe.+ *+ * Every env and attribute set allocation also names its site: the+ * construct or builtin that makes it, which the evaluator numbers+ * (Nix.Eval.AllocSite).  Once nn_stats_count_sites turns counting on, the+ * allocators count each allocation under its site, and `//` counts the+ * entries it copies; until then an allocation reads nn_stats_counting and+ * does nothing more.+ */++#ifndef NN_STATS_H+#define NN_STATS_H++#include <stdint.h>++/* --- Kinds: the index of each kind's figures --- */++#define NN_STATS_THUNKS     0  /* thunk cells in the arena's blocks */+#define NN_STATS_ENVS       1  /* envs with their slots, and with-scope arrays */+#define NN_STATS_ATTRSETS   2  /* attribute sets: header, keys, positions, values */+#define NN_STATS_LISTS      3  /* list headers and the items arrays they span */+#define NN_STATS_LAMBDAS    4  /* lambda closures and their formal entries */+#define NN_STATS_PRIMOP_APPS 5 /* builtins' partial applications (nn_primop.h) */+#define NN_STATS_APPS       6  /* deferred applications' cells (nn_thunk.h) */+#define NN_STATS_CTXSTRS    7  /* strings with context */+#define NN_STATS_STRINGS    8  /* string and path bytes in the value arena (nn_str.h) */+#define NN_STATS_SYMBOLS    9  /* interned names */+#define NN_STATS_KIND_COUNT 10++/* A count no allocator keeps: the env pages hold envs and with-scope+ * arrays side by side with no record of which is which, so without+ * counting by site from the arena's first allocation the bytes are known+ * and the number of envs is not. */+#define NN_STATS_UNCOUNTED UINT64_MAX++/* --- Sites --- */++/* How many sites the evaluator numbers for envs and for attribute sets:+ * a site is below its bound.  Nix.Eval.AllocSite enumerates exactly+ * these many. */+#define NN_STATS_ENV_SITES 10u+#define NN_STATS_SET_SITES 23u++/* Envs by the slots they hold: one bucket for each count below+ * NN_STATS_ENV_SIZES - 1, and the last for every larger count. */+#define NN_STATS_ENV_SIZES 33u++/* Nonzero while the allocators count by site. */+extern int nn_stats_counting;++/* Turn counting by site on, every figure from zero.  The counts cover+ * every env and set allocated from then on; nn_stats_allocated reports+ * the number of envs only when counting began before the env pages+ * handed out their first byte. */+void nn_stats_count_sites(void);++/* The allocators' half, called only while nn_stats_counting is nonzero.+ * An env counts once, with the slots it holds and its bytes, and every+ * other byte the env pages hand out for envs (with-scope arrays) counts+ * under the site it is for; a set counts once+ * with the bytes it holds once built, and as shareable when it is made+ * equal to a set that already exists, which upstream would not make: one+ * made with room for no entries or by removal from a set with none,+ * either of which equals the shared empty set (nn_attrset_empty), or a+ * union one of whose operands has none, which equals the other.  A set+ * made with room for entries that ends up holding none is not shareable:+ * upstream makes that set too.  The evaluator gives the shared set or+ * the other operand in each of these cases, so a shareable count above 0+ * is a set it should not have made. */+void nn_stats_count_env(uint32_t site, uint32_t slots, uint64_t bytes);+void nn_stats_count_env_bytes(uint32_t site, uint64_t bytes);+void nn_stats_count_set(uint32_t site, uint64_t bytes, int shareable);++/* nn_attrset_update's half, called only while nn_stats_counting is+ * nonzero: the entries it copied into the set it made, which upstream+ * counts in nrOpUpdateValuesCopied. */+void nn_stats_count_update(uint64_t copied);++/* What counting has found since nn_stats_count_sites, zero where it has+ * never run: per env site the envs, their slots and their bytes; per+ * slot count the envs; per set site the sets, the shareable ones among+ * them and their bytes.  Each writes its figures for the first `max`+ * sites or slot counts and returns how many there are+ * (NN_STATS_ENV_SITES, NN_STATS_ENV_SIZES, NN_STATS_SET_SITES). */+uint32_t nn_stats_env_sites(uint64_t *envs, uint64_t *slots, uint64_t *bytes, uint32_t max);+uint32_t nn_stats_env_sizes(uint64_t *envs, uint32_t max);+uint32_t nn_stats_set_sites(uint64_t *sets, uint64_t *shareable, uint64_t *bytes, uint32_t max);++/* The entries `//` has copied since nn_stats_count_sites, zero where+ * counting has never run. */+uint64_t nn_stats_update_copied(void);++/* --- Session --- */++/* Count what is allocated and index every object for the mark.  Returns+ * 0, or -1 with no session open when the index cannot be allocated.  A+ * session already open is ended first. */+int nn_stats_begin(void);++/* Release the session's index.  Nothing in the data layer changes. */+void nn_stats_end(void);++/* --- What is allocated --- */++/* Objects and the bytes they hold, by kind (NN_STATS_KIND_COUNT entries+ * each): for thunk cells, envs and strings every one the evaluation+ * allocated, which a collector reusing lines may have put where others+ * were, and for the tracked kinds those still allocated.  The env count+ * is NN_STATS_UNCOUNTED unless counting by site has covered every env+ * (nn_stats_count_sites). */+void nn_stats_allocated(uint64_t *counts, uint64_t *bytes);++/* Bytes the allocators hold that no object ever has: block and page+ * headers and the tails past where each block's allocations reached, the+ * tracking arrays, and the symbol table beyond its text. */+uint64_t nn_stats_overhead_bytes(void);++/* Bytes the bytecode store holds, its strings included.  Code is freed+ * only as the session ends, so the mark does not look at it, and a string+ * of the code's that a value points at is placed and not counted. */+uint64_t nn_stats_code_bytes(void);++/* --- The mark --- */++/* Name a root.  NULL names nothing.  A root the index cannot place is+ * counted as unplaced and not followed. */+void nn_stats_root_thunk(const void *thunk);+void nn_stats_root_env(const void *env);+void nn_stats_root_attrset(const void *set);+void nn_stats_root_list(const void *list);+void nn_stats_root_string(const void *str);+void nn_stats_root_ctxstr(const void *ctxstr);++/* Name every root the session has registered (nn_roots.h). */+void nn_stats_root_registered(void);++/* Follow every pointer from the roots named since the last call.  Marks+ * accumulate across calls.  Returns 0, or -1 when the work stack could+ * not grow, after which the session's figures are incomplete. */+int nn_stats_mark(void);++/* Objects the mark has reached and the bytes they hold, by kind.  An+ * env's with-scope array counts in the bytes of the first env over it+ * reached and not in its count; a list's items array counts in the bytes+ * of the first header over it reached. */+void nn_stats_reached(uint64_t *counts, uint64_t *bytes);++/* The mark's own work: the objects it has entered (thunks, envs,+ * with-scope arrays, sets, list headers, items arrays, lambdas, partial+ * applications, deferred applications' cells, strings with context;+ * strings and symbols hold no pointer, and are marked and not entered)+ * and their bytes, and the pointers it could not place. */+void nn_stats_visited(uint64_t *objects, uint64_t *bytes, uint64_t *unplaced);++/* The reached attribute sets by the number of entries each holds in its+ * own arrays (nn_attrset_layer_count), in ascending order of that number:+ * up to `max` distinct sizes go to `sizes`, with how many reached sets+ * have each in `counts`, and the number of distinct sizes, which may+ * exceed `max`, to *distinct.  Returns 0, or -1 when the sizes cannot be+ * sorted for want of memory.  Read after the last mark. */+int nn_stats_reached_set_sizes(uint32_t *sizes, uint64_t *counts, uint32_t max,+                               uint32_t *distinct);++#endif /* NN_STATS_H */
+ cbits/nn_str.c view
@@ -0,0 +1,232 @@+/*+ * nn_str.c - String arenas (nn_str.h).+ *+ * A block holds the strings bumped from it, one after another, each+ * padded to NN_STR_ALIGNMENT.  A string larger than NN_STR_LARGE_BYTES+ * gets a block of its own, sized to it, so a fresh shared block is+ * started only for a string no larger than that, and the room a shared+ * block leaves unused at its end is under NN_STR_LARGE_BYTES.+ */++#include "nn_str.h"++#include "nn_region.h"++#include <stdint.h>+#include <stdlib.h>+#include <string.h>++/* --- Blocks --- */++struct nn_str_block {+    nn_str_block_t *next;+    uint64_t        used;      /* one past the last byte ever handed out */+    uint64_t        capacity;  /* bytes data holds */+    char            data[];+};++/* Strings start on NN_STR_ALIGNMENT boundaries from data, so data itself+ * must start on one.  C99 compile-time check: */+typedef char nn_str_block_align_check_[+    (offsetof(nn_str_block_t, data) % NN_STR_ALIGNMENT == 0) ? 1 : -1];++/* A block with room for `capacity` bytes of strings, or NULL. */+static nn_str_block_t *block_new(uint64_t capacity)+{+    nn_str_block_t *b;+    if (capacity > (uint64_t)SIZE_MAX - offsetof(nn_str_block_t, data)) return NULL;+    b = (nn_str_block_t *)malloc(offsetof(nn_str_block_t, data) + (size_t)capacity);+    if (!b) return NULL;+    b->next = NULL;+    b->used = 0;+    b->capacity = capacity;+    return b;+}++/* Bytes a string of `len` bytes takes in a block.  len is at most+ * NN_STR_MAX_LEN, so the sum cannot wrap uint64_t. */+static uint64_t object_bytes(uint64_t len)+{+    uint64_t raw = (uint64_t)offsetof(nn_str_t, bytes) + len;+    return (raw + NN_STR_ALIGNMENT - 1) / NN_STR_ALIGNMENT * NN_STR_ALIGNMENT;+}++/* --- The empty string --- */++static nn_str_t g_empty = { 0 };++nn_str_t *nn_str_empty(void)+{+    return &g_empty;+}++/* --- Arenas --- */++/* The value arena.  The one other arena is the code's (nn_bytecode.h),+ * whose strings a census of regions places outside every region. */+static nn_str_arena_t g_values;++/* Tell regions of a block, while the arena's current room is still the+ * one it had. */+static void block_made(const nn_str_arena_t *arena, const nn_str_block_t *b, int current)+{+    if (nn_region_mode)+        nn_region_block(arena == &g_values ? NN_REGION_STR_BLOCK : NN_REGION_CODE_BLOCK,+                        b->data, b->capacity, current);+}++/* Bump from the room the collector names next, with space for `need`+ * bytes, or from a new block. */+static int refill(nn_str_arena_t *arena, uint64_t need)+{+    const char *data;+    uint64_t start, limit;+    nn_str_block_t *b;+    if (arena == &g_values && nn_region_mode == NN_REGION_COLLECT) {+        /* The room ends here even if no block follows (nn_region_refill). */+        arena->limit = arena->cursor;+        if (nn_region_refill(NN_REGION_STR_BLOCK, arena->cursor, need, &data, &start, &limit) == 0) {+            arena->current = (nn_str_block_t *)(void *)(data - offsetof(nn_str_block_t, data));+            arena->cursor = start;+            arena->limit = limit;+            return 0;+        }+    }+    b = block_new(NN_STR_BLOCK_BYTES);+    if (!b) return -1;+    b->next = arena->blocks;+    arena->blocks = b;+    block_made(arena, b, 1);+    arena->current = b;+    arena->cursor = 0;+    arena->limit = b->capacity;+    return 0;+}++nn_str_t *nn_str_arena_new(nn_str_arena_t *arena, const char *bytes, size_t len)+{+    uint64_t need;+    nn_str_block_t *b;+    nn_str_t *s;++    if ((uint64_t)len > NN_STR_MAX_LEN) return NULL;+    if (len == 0) return &g_empty;++    need = object_bytes((uint64_t)len);+    if (need > NN_STR_LARGE_BYTES) {+        b = block_new(need);+        if (!b) return NULL;+        b->next = arena->blocks;+        arena->blocks = b;+        block_made(arena, b, 0);+        b->used = need;+        s = (nn_str_t *)b->data;+    } else {+        if ((!arena->current || arena->limit - arena->cursor < need) && refill(arena, need) != 0) return NULL;+        b = arena->current;+        s = (nn_str_t *)(b->data + arena->cursor);+        arena->cursor += need;+        if (arena->cursor > b->used) b->used = arena->cursor;+    }++    s->len = (uint32_t)len;+    memcpy(s->bytes, bytes, len);+    arena->count++;+    arena->bytes += need;+    return s;+}++void nn_str_arena_free(nn_str_arena_t *arena)+{+    nn_str_block_t *b = arena->blocks;+    while (b) {+        nn_str_block_t *next = b->next;+        free(b);+        b = next;+    }+    memset(arena, 0, sizeof(*arena));+}++/* --- The value arena --- */++static int g_live;++void nn_str_init(void)+{+    g_live = 1;+}++int nn_str_live(void)+{+    return g_live;+}++void nn_str_destroy(void)+{+    nn_str_arena_free(&g_values);+    g_live = 0;+}++nn_str_t *nn_str_new(const char *bytes, size_t len)+{+    if (!g_live) return NULL;+    return nn_str_arena_new(&g_values, bytes, len);+}++/* --- Reading --- */++uint32_t nn_str_len(const nn_str_t *s)+{+    return s->len;+}++const char *nn_str_bytes(const nn_str_t *s)+{+    return s->bytes;+}++/* --- Census --- */++const nn_str_arena_t *nn_str_values(void)+{+    return &g_values;+}++uint64_t nn_str_object_bytes(const nn_str_t *s)+{+    return object_bytes((uint64_t)s->len);+}++uint32_t nn_str_arena_blocks(const nn_str_arena_t *arena,+                             const char **starts, uint64_t *used, uint32_t max)+{+    const nn_str_block_t *b;+    uint32_t n = 0;+    for (b = arena->blocks; b; b = b->next) {+        if (n < max) {+            starts[n] = b->data;+            used[n] = b->used;+        }+        n++;+    }+    return n;+}++uint64_t nn_str_cursor(void)+{+    return g_values.cursor;+}++uint64_t nn_str_arena_bytes(const nn_str_arena_t *arena)+{+    return arena->bytes;+}++uint64_t nn_str_arena_reserved_bytes(const nn_str_arena_t *arena)+{+    const nn_str_block_t *b;+    uint64_t total = 0;+    for (b = arena->blocks; b; b = b->next)+        total += (uint64_t)offsetof(nn_str_block_t, data) + b->capacity;+    return total;+}
+ cbits/nn_str.h view
@@ -0,0 +1,145 @@+/*+ * nn_str.h - The bytes of string and path values for nova-nix.+ *+ * A string value is a byte string: any byte, NUL included, with no+ * encoding assumed.  A path value's bytes are its UTF-8 text.  Each is one+ * nn_str_t, its length and then its bytes, never written once made.  A+ * thunk cell holding a string or a path points at its nn_str_t, and so+ * does a string with context for its text and its context's store paths+ * and output names (nn_ctxstr.h), so whatever refers to a string's bytes+ * holds their address.+ *+ * Nothing here interns.  Two equal strings made twice are two objects, as+ * upstream copies a string value's bytes for each value it makes+ * (makeImmutableString and Value::mkString in eval.cc at 2.24.9, and+ * StringData::make at 2.36.0).  The symbol table (nn_symbol.h) holds+ * names alone, so a string value never takes a symbol, and never moves+ * the place of a name interned after it.  Upstream hands every empty+ * string the one static "" (makeImmutableString); here every empty string+ * is nn_str_empty().+ *+ * Strings are made in arenas: blocks a string is bumped from, freed+ * together.  An nn_str_t never moves.  Each string starts on an+ * NN_STR_ALIGNMENT boundary, and within one room the next one starts+ * nn_str_object_bytes after it; while the region collector runs a block+ * can hold several rooms with unused bytes between them.  The values an+ * evaluation makes live in the value arena (nn_str_new); the bytecode keeps+ * its literals' bytes in an arena of its own, freed with the code+ * (nn_bytecode.h).+ *+ * A string's length is a uint32_t, so a string holds at most UINT32_MAX+ * bytes, the per-allocation limit used across the C data layer.+ *+ * Lifecycle: nn_str_init() before evaluation, nn_str_destroy() after.+ * Not thread-safe - single-threaded evaluation only.+ */++#ifndef NN_STR_H+#define NN_STR_H++#include <stddef.h>+#include <stdint.h>++/* --- Types --- */++/* A string's bytes: len of them, with no terminator. */+typedef struct nn_str {+    uint32_t len;+    char     bytes[];+} nn_str_t;++/* Every string starts on a multiple of this many bytes from its block's+ * start: the alignment of its length. */+#define NN_STR_ALIGNMENT ((uint64_t)sizeof(uint32_t))++/* The longest string an arena makes. */+#define NN_STR_MAX_LEN ((uint64_t)UINT32_MAX)++/* The bytes of a block strings share.  A string that takes more than a+ * quarter of one gets a block of its own, sized to it. */+#define NN_STR_BLOCK_BYTES ((uint64_t)1 << 20)+#define NN_STR_LARGE_BYTES (NN_STR_BLOCK_BYTES / 4)++typedef struct nn_str_block nn_str_block_t;++/* An arena of strings.  An all-zero one is empty and ready to use.+ * Strings that fit a shared block are bumped from a room of the current+ * block, from the cursor to below the limit: a new block, or, in the+ * value arena while the region collector runs, lines of a block it freed+ * (nn_region_refill). */+typedef struct {+    nn_str_block_t *blocks;   /* every block, newest first */+    nn_str_block_t *current;  /* the block strings that fit one are bumped from */+    uint64_t        cursor;   /* bytes into it */+    uint64_t        limit;+    uint64_t        count;    /* strings made, the empty string not counted */+    uint64_t        bytes;    /* the bytes they take, padding included */+} nn_str_arena_t;++/* --- Arenas --- */++/* Copy len bytes into a new string in the arena.  (NULL, 0) is the empty+ * string, which is nn_str_empty() and takes no room.  Returns NULL when+ * len is past NN_STR_MAX_LEN, refused before a byte is read, or when the+ * allocator refuses a block; the arena then holds the strings it held,+ * though while the region collector runs the room it bumped from has+ * ended (nn_region_refill). */+nn_str_t *nn_str_arena_new(nn_str_arena_t *arena, const char *bytes, size_t len);++/* Free every block.  The arena is empty after, and every string it made+ * is gone. */+void nn_str_arena_free(nn_str_arena_t *arena);++/* --- The value arena --- */++/* Start the value arena.  Called only while it is not live (nn_str_live+ * is 0), as a second init would leak the live arena's blocks; outside+ * the init .. destroy window nn_str_new returns NULL. */+void nn_str_init(void);++/* Nonzero between nn_str_init and nn_str_destroy. */+int nn_str_live(void);++/* End the value arena, freeing every string it made. */+void nn_str_destroy(void);++/* nn_str_arena_new in the value arena, or NULL outside its window. */+nn_str_t *nn_str_new(const char *bytes, size_t len);++/* The empty string: a static, not in any arena, valid in and outside+ * every window. */+nn_str_t *nn_str_empty(void);++/* --- Reading --- */++uint32_t    nn_str_len(const nn_str_t *s);+const char *nn_str_bytes(const nn_str_t *s);++/* --- Census (nn_stats.h) --- */++/* The value arena. */+const nn_str_arena_t *nn_str_values(void);++/* Bytes a string takes in its block: its length, its bytes and the+ * padding to the next NN_STR_ALIGNMENT boundary. */+uint64_t nn_str_object_bytes(const nn_str_t *s);++/* An arena's blocks: for each of the first `max`, where its strings start+ * and one past the last byte it has ever handed out go to `starts` and+ * `used`.  Returns the number of blocks, which may exceed `max`. */+uint32_t nn_str_arena_blocks(const nn_str_arena_t *arena,+                             const char **starts, uint64_t *used, uint32_t max);++/* Bytes an arena holds from the allocator: every block, header and+ * unused tail included. */+uint64_t nn_str_arena_reserved_bytes(const nn_str_arena_t *arena);++/* Bytes an arena's strings took as they were made, padding included,+ * which a collector reusing lines can put where others were. */+uint64_t nn_str_arena_bytes(const nn_str_arena_t *arena);++/* Where the next string that fits a shared block comes from in the value+ * arena's current block, in bytes from its first byte (nn_region.h). */+uint64_t nn_str_cursor(void);++#endif /* NN_STR_H */
cbits/nn_symbol.c view
@@ -6,12 +6,11 @@  * no per-string malloc/free).  Symbols are 1-indexed uint32_t  * values; 0 is the invalid sentinel.  *- * The table doubles when load exceeds 75%.  Deletion is not+ * The table doubles before its load reaches 75%.  Deletion is not  * supported - symbols live for the entire evaluation lifetime.  */  #include "nn_symbol.h"-#include "nn_assert.h"  #include <stdio.h> #include <stdlib.h>@@ -19,18 +18,22 @@  /* --- Configuration --- */ -#define NN_SYMBOL_DEFAULT_CAPACITY   4096-#define NN_SYMBOL_MAX_INITIAL        (UINT32_C(1) << 30)  /* slot table is twice this */+#define NN_SYMBOL_INITIAL_CAPACITY   4096u #define NN_SYMBOL_LOAD_PERCENT         75 #define NN_SYMBOL_ARENA_INITIAL  (256 * 1024)  /* 256 KB */ +/* The slot table starts at twice the entries, and its mask needs a power+ * of two.  C99-compatible compile-time check: */+typedef char nn_symbol_capacity_check_[+    ((NN_SYMBOL_INITIAL_CAPACITY & (NN_SYMBOL_INITIAL_CAPACITY - 1)) == 0) ? 1 : -1];+ /* --- Internal types --- */ -/* Per-symbol metadata stored in a flat array indexed by symbol ID. */+/* Per-symbol metadata stored in a flat array indexed by symbol ID.  The+ * hash lives in the symbol's slot, where a probe compares it. */ typedef struct {     uint32_t offset;    /* byte offset into string arena */     uint32_t len;       /* byte length of the string */-    uint32_t hash;      /* cached FNV-1a hash */ } nn_symbol_entry_t;  /* Hash table slot: maps hash -> symbol ID.  Empty slots have id == 0. */@@ -142,30 +145,18 @@  /* --- Public API --- */ -void nn_symbol_init(uint32_t initial_capacity)+void nn_symbol_init(void) {-    if (g_sym.slots) nn_symbol_destroy();--    uint32_t cap = NN_SYMBOL_DEFAULT_CAPACITY;-    if (initial_capacity > cap) {-        /* Round up to a power of two.  The hint is clamped so that the-         * rounding and the slot table's doubling cannot wrap uint32_t. */-        uint32_t want = initial_capacity < NN_SYMBOL_MAX_INITIAL-                            ? initial_capacity : NN_SYMBOL_MAX_INITIAL;-        while (cap < want) cap *= 2;-    }--    memset(&g_sym, 0, sizeof(g_sym));--    /* Entry array (1-indexed, so allocate cap+1 but we just use cap). */-    g_sym.entries_cap = cap;+    /* Entry 0 is unused, so the entries hold one symbol fewer than their+     * capacity before entries_reserve grows the array. */+    g_sym.entries_cap = NN_SYMBOL_INITIAL_CAPACITY;     g_sym.entries = (nn_symbol_entry_t *)calloc(-        (size_t)cap, sizeof(nn_symbol_entry_t));+        (size_t)g_sym.entries_cap, sizeof(nn_symbol_entry_t));     if (!g_sym.entries) { fprintf(stderr, "nn_symbol_init: entries alloc failed\n"); abort(); }     g_sym.count = 0;      /* Hash table at 2x entries for low load factor. */-    g_sym.slots_cap = cap * 2;+    g_sym.slots_cap = NN_SYMBOL_INITIAL_CAPACITY * 2;     g_sym.slots_mask = g_sym.slots_cap - 1;     g_sym.slots = (nn_slot_t *)calloc(         (size_t)g_sym.slots_cap, sizeof(nn_slot_t));@@ -203,11 +194,11 @@      * Refused here, before a byte of str is read. */     if ((uint64_t)len > UINT32_MAX) return NN_SYMBOL_INVALID; -    /* An empty string arrives from Haskell's zero-copy marshalling as-     * (NULL, 0).  memcpy/memcmp require valid pointers even for a zero-     * length, so normalize at the boundary.  Empty symbols are reachable-     * from evaluated input ({ "" = 1; }), so the branch survives release-     * builds. */+    /* (NULL, 0) is the empty string (nn_symbol.h), and memcpy/memcmp+     * require valid pointers even for a zero length, so an empty string+     * is read from a literal instead.  Empty symbols are reachable from+     * evaluated input ({ "" = 1; }), so this is a case to handle, not an+     * invariant to assert. */     if (len == 0) {         str = "";     }@@ -255,7 +246,6 @@      g_sym.entries[new_id].offset = offset;     g_sym.entries[new_id].len = (uint32_t)len;-    g_sym.entries[new_id].hash = hash;      g_sym.slots[idx].hash = hash;     g_sym.slots[idx].id = new_id;@@ -278,4 +268,14 @@ uint32_t nn_symbol_count(void) {     return g_sym.count;+}++/* --- Census --- */++void nn_symbol_footprint(uint64_t *text, uint64_t *reserved)+{+    *text = g_sym.arena_used;+    *reserved = g_sym.arena_cap+              + (uint64_t)g_sym.entries_cap * sizeof(nn_symbol_entry_t)+              + (uint64_t)g_sym.slots_cap * sizeof(nn_slot_t); }
cbits/nn_symbol.h view
@@ -28,8 +28,8 @@  /* --- Types --- */ -/* An interned symbol: index into the global symbol table.- * 0 is reserved as the invalid/empty sentinel. */+/* An interned symbol: index into the global symbol table.  0 is the+ * invalid sentinel; the empty string interns as an ordinary symbol. */ typedef uint32_t nn_symbol_t;  /* Invalid symbol constant. */@@ -40,12 +40,11 @@  /* --- Lifecycle --- */ -/* Initialize the global symbol table, destroying a live one first.- * Must be called before any nn_symbol_intern() calls; outside the- * init .. destroy window nn_symbol_intern() returns NN_SYMBOL_INVALID.- * initial_capacity is the expected number of unique symbols (hint for- * pre-allocation; 0 uses default). */-void nn_symbol_init(uint32_t initial_capacity);+/* Initialize the global symbol table.  Called only while the table is+ * not live (nn_symbol_live is 0), as a second init would leak the live+ * table, and before any nn_symbol_intern() call: outside the init ..+ * destroy window nn_symbol_intern() returns NN_SYMBOL_INVALID. */+void nn_symbol_init(void);  /* Nonzero between nn_symbol_init and nn_symbol_destroy. */ int nn_symbol_live(void);@@ -66,24 +65,26 @@  * is refused before any byte of str is read. */ nn_symbol_t nn_symbol_intern(const char *str, size_t len); -/* Return the string data for a symbol.  The pointer is valid until- * nn_symbol_destroy().  Returns NULL for NN_SYMBOL_INVALID. */+/* Return the string data for a symbol, valid until the next+ * nn_symbol_intern (which can move the table's bytes) or+ * nn_symbol_destroy().  Returns NULL for NN_SYMBOL_INVALID and for an id+ * the table does not hold. */ const char *nn_symbol_text(nn_symbol_t sym);  /* Return the byte length of a symbol's string.- * Returns 0 for NN_SYMBOL_INVALID. */+ * Returns 0 for NN_SYMBOL_INVALID and for an id the table does not hold. */ size_t nn_symbol_len(nn_symbol_t sym); -/* --- Comparison --- */--/* Symbols are equal iff their uint32_t values are equal.- * No function call needed - just use == directly.- * This macro exists for documentation purposes. */-#define nn_symbol_eq(a, b) ((a) == (b))- /* --- Diagnostics --- */  /* Return the number of unique symbols currently interned. */ uint32_t nn_symbol_count(void);++/* --- Census (nn_stats.h) --- */++/* The bytes the table holds: in its string arena, each symbol's text+ * and terminator (*text), and from the allocator, the arena, entry and+ * hash tables at their capacities (*reserved). */+void nn_symbol_footprint(uint64_t *text, uint64_t *reserved);  #endif /* NN_SYMBOL_H */
cbits/nn_thunk.c view
@@ -2,9 +2,12 @@  * nn_thunk.c - Arena-allocated thunk memoization cells.  *  * Chunked bump allocator: linked list of blocks, each containing a- * contiguous array of nn_thunk_t slots.  When the current block is- * full, a new block is allocated (same capacity).  Pointers into any- * block remain valid until the arena is destroyed.+ * contiguous array of nn_thunk_t slots.  Slots are bumped from a room:+ * a new block, or, while the region collector runs, lines of a block it+ * freed (nn_region_refill).  When the room is full, the collector names+ * the next one, or a new block is allocated (same capacity).  A pointer+ * into a block stays valid until the collector frees its line or the+ * arena is destroyed.  *  * Memory layout per block:  *   [nn_thunk_block header] [slot 0] [slot 1] ... [slot N-1]@@ -14,278 +17,309 @@  */  #include "nn_thunk.h"+#include "nn_assert.h"+#include "nn_env.h"+#include "nn_region.h" +#include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> -/* --- Constants --- */--#define NN_THUNK_DEFAULT_BLOCK_CAPACITY 65536u  /* 64k thunks = 1 MB */- /* --- Internal types --- */  struct nn_thunk_block {     struct nn_thunk_block *next;      /* NULL for newest block */-    uint32_t               count;     /* slots used in this block */-    uint32_t               capacity;  /* total slots in this block */+    uint32_t               count;     /* one past the last slot ever handed out */     nn_thunk_t             slots[];   /* C99 flexible array member */ }; -struct nn_thunk_arena {-    struct nn_thunk_block *head;           /* first block (for iteration) */-    struct nn_thunk_block *current;        /* newest block (for allocation) */-    uint32_t               total;          /* total thunks across all blocks */-    uint32_t               block_capacity; /* slots per new block */-};--/* --- Global arena --- */+/* --- Global state --- */ -static struct nn_thunk_arena *g_arena = NULL;+/* The first block and the newest, for iteration and for linking a new+ * one, and the block slots are bumped from, with its room: from the+ * cursor to below the limit.  NULL outside the init .. destroy window. */+static struct nn_thunk_block *g_first_block = NULL;+static struct nn_thunk_block *g_last_block = NULL;+static struct nn_thunk_block *g_current_block = NULL;+static uint32_t g_cursor = 0;+static uint32_t g_limit = 0;+static uint64_t g_cells_allocated = 0;  /* --- Internal helpers --- */  static struct nn_thunk_block *-alloc_block(uint32_t capacity)+alloc_block(void) {     struct nn_thunk_block *block = (struct nn_thunk_block *)malloc(-        sizeof(struct nn_thunk_block) + (size_t)capacity * sizeof(nn_thunk_t));+        sizeof(struct nn_thunk_block)+        + (size_t)NN_THUNK_BLOCK_CELLS * sizeof(nn_thunk_t));     if (!block) return NULL;     block->next = NULL;     block->count = 0;-    block->capacity = capacity;+    if (nn_region_mode)+        nn_region_block(NN_REGION_THUNK_BLOCK, (const char *)block->slots,+                        (uint64_t)NN_THUNK_BLOCK_CELLS * sizeof(nn_thunk_t), 1);     return block; } +/* Bump from the room the collector names next, or from a new block. */+static int+refill(void)+{+    const char *data;+    uint64_t start, limit;+    struct nn_thunk_block *block;+    if (nn_region_mode == NN_REGION_COLLECT+        && nn_region_refill(NN_REGION_THUNK_BLOCK, (uint64_t)g_cursor * sizeof(nn_thunk_t), sizeof(nn_thunk_t),+                            &data, &start, &limit) == 0) {+        g_current_block = (struct nn_thunk_block *)(void *)(data - offsetof(struct nn_thunk_block, slots));+        g_cursor = (uint32_t)(start / sizeof(nn_thunk_t));+        g_limit = (uint32_t)(limit / sizeof(nn_thunk_t));+        return 0;+    }+    block = alloc_block();+    if (!block) return -1;+    g_last_block->next = block;+    g_last_block = block;+    g_current_block = block;+    g_cursor = 0;+    g_limit = NN_THUNK_BLOCK_CELLS;+    return 0;+}+ static nn_thunk_t *-arena_alloc(struct nn_thunk_arena *arena)+arena_alloc(void) {-    /* No arena before nn_thunk_init or after nn_thunk_destroy.  Report+    nn_thunk_t *t;+    /* No blocks before nn_thunk_init or after nn_thunk_destroy.  Report      * it through the NULL the callers already check for rather than      * dereferencing it; nn_arena_live is how the Haskell boundary tells      * this apart from exhaustion. */-    if (!arena) return NULL;+    if (!g_current_block) return NULL; -    /* Current block full - allocate a new one */-    if (arena->current->count >= arena->current->capacity) {-        struct nn_thunk_block *block = alloc_block(arena->block_capacity);-        if (!block) return NULL;-        arena->current->next = block;-        arena->current = block;-    }-    nn_thunk_t *t = &arena->current->slots[arena->current->count];-    arena->current->count++;-    arena->total++;+    if (g_cursor >= g_limit && refill() != 0) return NULL;+    t = &g_current_block->slots[g_cursor++];+    if (g_cursor > g_current_block->count) g_current_block->count = g_cursor;+    g_cells_allocated++;     return t; }  /* --- Lifecycle --- */  void-nn_thunk_init(uint32_t initial_capacity)+nn_thunk_init(void) {-    /* Destroy existing arena if re-initializing */-    if (g_arena) {-        nn_thunk_destroy();-    }--    uint32_t cap = initial_capacity > 0 ? initial_capacity-                                        : NN_THUNK_DEFAULT_BLOCK_CAPACITY;--    /* An allocation failure here would leave g_arena NULL and the first-     * thunk allocation would dereference it - fail loudly at startup-     * instead (same policy as nn_env_init). */-    g_arena = (struct nn_thunk_arena *)malloc(sizeof(struct nn_thunk_arena));-    if (!g_arena) {-        fprintf(stderr, "nn_thunk_init: arena alloc failed\n");-        abort();-    }--    struct nn_thunk_block *first = alloc_block(cap);-    if (!first) {+    /* Fail loudly at startup rather than start with no arena, which+     * every allocation would then refuse (same policy as nn_env_init). */+    g_first_block = alloc_block();+    if (!g_first_block) {         fprintf(stderr, "nn_thunk_init: block alloc failed\n");         abort();     }--    g_arena->head = first;-    g_arena->current = first;-    g_arena->total = 0;-    g_arena->block_capacity = cap;+    g_last_block = g_first_block;+    g_current_block = g_first_block;+    g_cursor = 0;+    g_limit = NN_THUNK_BLOCK_CELLS;+    g_cells_allocated = 0; }  int nn_thunk_live(void) {-    return g_arena != NULL;+    return g_first_block != NULL; }  void nn_thunk_destroy(void) {-    if (!g_arena) return;--    struct nn_thunk_block *block = g_arena->head;+    struct nn_thunk_block *block = g_first_block;     while (block) {         struct nn_thunk_block *next = block->next;         free(block);         block = next;     }--    free(g_arena);-    g_arena = NULL;+    g_first_block = NULL;+    g_last_block = NULL;+    g_current_block = NULL;+    g_cursor = 0;+    g_limit = 0;+    g_cells_allocated = 0; }  /* --- Allocation --- */  nn_thunk_t *-nn_thunk_new_bc(uint32_t bc_idx, void *env_ptr)+nn_thunk_new_bc(uint32_t bc_idx, void *env) {-    nn_thunk_t *t = arena_alloc(g_arena);+    nn_thunk_t *t;+    NN_ASSERT(bc_idx != NN_THUNK_NO_CODE, "nn_thunk_new_bc: bc_idx is NN_THUNK_NO_CODE");+    t = arena_alloc();     if (!t) return NULL;     t->state = NN_THUNK_PENDING;     t->val_tag = 0;+    t->form = NN_PENDING_CODE;     t->_pad = 0;     t->bc_idx = bc_idx;-    t->payload = env_ptr;+    t->payload = env;     return t; } +/* A PENDING application of the `count` cells at `cells`, the function's+ * first, copied into an array of the env pages. */+static nn_thunk_t *+new_apply(nn_thunk_t *const *cells, uint32_t count, uint8_t form)+{+    uint32_t i;+    void **held;+    nn_thunk_t *t;+    for (i = 0; i < count; i++)+        NN_ASSERT(cells[i] != NULL, "nn_thunk_new_apply1/2: a cell is NULL");+    held = nn_env_alloc_app_cells(count);+    if (!held) return NULL;+    t = arena_alloc();+    if (!t) return NULL;+    for (i = 0; i < count; i++) held[i] = cells[i];+    t->state = NN_THUNK_PENDING;+    t->val_tag = 0;+    t->form = form;+    t->_pad = 0;+    t->bc_idx = 0;+    t->payload = held;+    return t;+}++nn_thunk_t *+nn_thunk_new_apply1(nn_thunk_t *fn, nn_thunk_t *arg)+{+    nn_thunk_t *cells[2];+    cells[0] = fn;+    cells[1] = arg;+    return new_apply(cells, 2, NN_PENDING_APPLY1);+}++nn_thunk_t *+nn_thunk_new_apply2(nn_thunk_t *fn, nn_thunk_t *first, nn_thunk_t *second)+{+    nn_thunk_t *cells[3];+    cells[0] = fn;+    cells[1] = first;+    cells[2] = second;+    return new_apply(cells, 3, NN_PENDING_APPLY2);+}+ uint32_t nn_thunk_get_bc_idx(const nn_thunk_t *thunk) {-    return thunk->bc_idx;+    return thunk->form == NN_PENDING_CODE ? thunk->bc_idx : NN_THUNK_NO_CODE; } -int-nn_thunk_set_payload(nn_thunk_t *thunk, void *payload)+uint8_t+nn_thunk_pending_form(const nn_thunk_t *thunk) {-    if (thunk->state != NN_THUNK_PENDING) return 0;-    thunk->payload = payload;-    return 1;+    return thunk->form; } +/* The caller reads the form first and asks only for a cell the+ * application holds, so any other request is a defect. */ nn_thunk_t *-nn_thunk_new_computed(void *value)+nn_thunk_apply_cell(const nn_thunk_t *thunk, uint32_t i) {-    nn_thunk_t *t = arena_alloc(g_arena);+    NN_ASSERT(thunk->state != NN_THUNK_COMPUTED,+              "nn_thunk_apply_cell: the thunk is COMPUTED");+    NN_ASSERT(thunk->form == NN_PENDING_APPLY1 || thunk->form == NN_PENDING_APPLY2,+              "nn_thunk_apply_cell: the thunk is no application");+    NN_ASSERT(i <= thunk->form, "nn_thunk_apply_cell: i is past the application's cells");+    return ((nn_thunk_t *const *)thunk->payload)[i];+}++/* A new COMPUTED cell holding `payload` under `tag`, or NULL when the+ * arena cannot hand one out. */+static nn_thunk_t *+new_computed(uint8_t tag, void *payload)+{+    nn_thunk_t *t = arena_alloc();     if (!t) return NULL;     t->state = NN_THUNK_COMPUTED;-    t->val_tag = NN_VALUE_PTR;+    t->val_tag = tag;+    t->form = 0;     t->_pad = 0;     t->bc_idx = 0;-    t->payload = value;+    t->payload = payload;     return t; }  nn_thunk_t * nn_thunk_new_computed_int(int64_t value) {-    nn_thunk_t *t = arena_alloc(g_arena);-    if (!t) return NULL;-    t->state = NN_THUNK_COMPUTED;-    t->val_tag = NN_VALUE_INT;-    t->_pad = 0;-    t->bc_idx = 0;-    t->payload = (void *)(intptr_t)value;-    return t;+    return new_computed(NN_VALUE_INT, (void *)(intptr_t)value); } +/* The double's bytes are copied over the made cell's payload, so that no+ * pointer is formed from them. */ nn_thunk_t * nn_thunk_new_computed_float(double value) {-    nn_thunk_t *t = arena_alloc(g_arena);-    if (!t) return NULL;-    t->state = NN_THUNK_COMPUTED;-    t->val_tag = NN_VALUE_FLOAT;-    t->_pad = 0;-    t->bc_idx = 0;-    memcpy(&t->payload, &value, sizeof(double));+    nn_thunk_t *t = new_computed(NN_VALUE_FLOAT, NULL);+    if (t) memcpy(&t->payload, &value, sizeof(double));     return t; }  nn_thunk_t *-nn_thunk_new_computed_str(uint32_t symbol)+nn_thunk_new_computed_primop(uint32_t primop) {-    nn_thunk_t *t = arena_alloc(g_arena);-    if (!t) return NULL;-    t->state = NN_THUNK_COMPUTED;-    t->val_tag = NN_VALUE_STR;-    t->_pad = 0;-    t->bc_idx = 0;-    t->payload = (void *)(intptr_t)symbol;-    return t;+    return new_computed(NN_VALUE_PRIMOP, (void *)(uintptr_t)primop); }  nn_thunk_t *-nn_thunk_new_computed_path(uint32_t symbol)+nn_thunk_new_computed_str(void *str) {-    nn_thunk_t *t = arena_alloc(g_arena);-    if (!t) return NULL;-    t->state = NN_THUNK_COMPUTED;-    t->val_tag = NN_VALUE_PATH;-    t->_pad = 0;-    t->bc_idx = 0;-    t->payload = (void *)(intptr_t)symbol;-    return t;+    return new_computed(NN_VALUE_STR, str); }  nn_thunk_t *+nn_thunk_new_computed_path(void *str)+{+    return new_computed(NN_VALUE_PATH, str);+}++nn_thunk_t * nn_thunk_new_computed_list(void *list) {-    nn_thunk_t *t = arena_alloc(g_arena);-    if (!t) return NULL;-    t->state = NN_THUNK_COMPUTED;-    t->val_tag = NN_VALUE_LIST;-    t->_pad = 0;-    t->bc_idx = 0;-    t->payload = list;-    return t;+    return new_computed(NN_VALUE_LIST, list); }  nn_thunk_t * nn_thunk_new_computed_attrs(void *attrset) {-    nn_thunk_t *t = arena_alloc(g_arena);-    if (!t) return NULL;-    t->state = NN_THUNK_COMPUTED;-    t->val_tag = NN_VALUE_ATTRS;-    t->_pad = 0;-    t->bc_idx = 0;-    t->payload = attrset;-    return t;+    return new_computed(NN_VALUE_ATTRS, attrset); }  nn_thunk_t * nn_thunk_new_computed_ctxstr(void *ctxstr) {-    nn_thunk_t *t = arena_alloc(g_arena);-    if (!t) return NULL;-    t->state = NN_THUNK_COMPUTED;-    t->val_tag = NN_VALUE_CTXSTR;-    t->_pad = 0;-    t->bc_idx = 0;-    t->payload = ctxstr;-    return t;+    return new_computed(NN_VALUE_CTXSTR, ctxstr); }  nn_thunk_t * nn_thunk_new_computed_lambda(void *lambda) {-    nn_thunk_t *t = arena_alloc(g_arena);-    if (!t) return NULL;-    t->state = NN_THUNK_COMPUTED;-    t->val_tag = NN_VALUE_LAMBDA;-    t->_pad = 0;-    t->bc_idx = 0;-    t->payload = lambda;-    return t;+    return new_computed(NN_VALUE_LAMBDA, lambda); } +nn_thunk_t *+nn_thunk_new_computed_primop_app(void *app)+{+    return new_computed(NN_VALUE_PRIMOP_APP, app);+}+ /* --- Shared constants --- */ -static nn_thunk_t g_null_cell  = { NN_THUNK_COMPUTED, NN_VALUE_NULL, 0, 0, NULL };-static nn_thunk_t g_true_cell  = { NN_THUNK_COMPUTED, NN_VALUE_BOOL, 0, 0, (void *)(intptr_t)1 };-static nn_thunk_t g_false_cell = { NN_THUNK_COMPUTED, NN_VALUE_BOOL, 0, 0, NULL };+static nn_thunk_t g_null_cell  = { NN_THUNK_COMPUTED, NN_VALUE_NULL, 0, 0, 0, NULL };+static nn_thunk_t g_true_cell  = { NN_THUNK_COMPUTED, NN_VALUE_BOOL, 0, 0, 0, (void *)(intptr_t)1 };+static nn_thunk_t g_false_cell = { NN_THUNK_COMPUTED, NN_VALUE_BOOL, 0, 0, 0, NULL };+/* An empty list is the NULL list (nn_list.h). */+static nn_thunk_t g_empty_list_cell = { NN_THUNK_COMPUTED, NN_VALUE_LIST, 0, 0, 0, NULL };  nn_thunk_t * nn_thunk_null(void)@@ -299,6 +333,41 @@     return value ? &g_true_cell : &g_false_cell; } +nn_thunk_t *+nn_thunk_empty_list(void)+{+    return &g_empty_list_cell;+}++/* Zero until asked for, which is PENDING: nn_thunk_primop fills a cell+ * before it hands it out. */+static nn_thunk_t g_primop_cells[NN_PRIMOP_CELLS];++nn_thunk_t *+nn_thunk_primop(uint32_t primop)+{+    nn_thunk_t *cell;+    if (primop >= NN_PRIMOP_CELLS) return NULL;+    cell = &g_primop_cells[primop];+    if (cell->state != NN_THUNK_COMPUTED) {+        cell->val_tag = NN_VALUE_PRIMOP;+        cell->payload = (void *)(uintptr_t)primop;+        cell->state = NN_THUNK_COMPUTED;+    }+    return cell;+}++int+nn_thunk_is_static(const nn_thunk_t *thunk)+{+    /* Compared as integers: the cell may be in no array of these. */+    uintptr_t p = (uintptr_t)thunk;+    uintptr_t cells = (uintptr_t)g_primop_cells;+    return thunk == &g_null_cell || thunk == &g_true_cell || thunk == &g_false_cell+        || thunk == &g_empty_list_cell+        || (p >= cells && p - cells < sizeof(g_primop_cells));+}+ /* --- State queries --- */  uint8_t@@ -340,39 +409,9 @@ }  uint32_t-nn_thunk_get_str(const nn_thunk_t *thunk)-{-    return (uint32_t)(intptr_t)thunk->payload;-}--uint32_t-nn_thunk_get_path(const nn_thunk_t *thunk)-{-    return (uint32_t)(intptr_t)thunk->payload;-}--void *-nn_thunk_get_list(const nn_thunk_t *thunk)-{-    return thunk->payload;-}--void *-nn_thunk_get_attrs(const nn_thunk_t *thunk)-{-    return thunk->payload;-}--void *-nn_thunk_get_ctxstr(const nn_thunk_t *thunk)-{-    return thunk->payload;-}--void *-nn_thunk_get_lambda(const nn_thunk_t *thunk)+nn_thunk_get_primop(const nn_thunk_t *thunk) {-    return thunk->payload;+    return (uint32_t)(uintptr_t)thunk->payload; }  /* --- State transitions --- */@@ -397,32 +436,49 @@     return 1; } -int-nn_thunk_set_computed(nn_thunk_t *thunk, void *value)+/* Whether a value of this tag holds a pointer into the data layer. */+static int+holds_object(uint8_t tag) {+    switch (tag) {+    case NN_VALUE_INT:+    case NN_VALUE_FLOAT:+    case NN_VALUE_BOOL:+    case NN_VALUE_NULL:+    case NN_VALUE_PRIMOP:+        return 0;+    default:+        return 1;+    }+}++/* Store `payload` under `tag` in a cell not yet COMPUTED: 1, or 0 with+ * the cell unchanged when it already is.  A store of an object is a write+ * of a pointer into a cell that may be older than the force making it,+ * which a census of regions records (nn_region.h). */+static int+set_computed(nn_thunk_t *thunk, uint8_t tag, void *payload)+{     if (thunk->state == NN_THUNK_COMPUTED) return 0;     thunk->state = NN_THUNK_COMPUTED;-    thunk->val_tag = NN_VALUE_PTR;-    thunk->payload = value;+    thunk->val_tag = tag;+    thunk->payload = payload;+    if (nn_region_mode && holds_object(tag)) nn_region_record_cell(thunk);     return 1; }  int nn_thunk_set_computed_int(nn_thunk_t *thunk, int64_t value) {-    if (thunk->state == NN_THUNK_COMPUTED) return 0;-    thunk->state = NN_THUNK_COMPUTED;-    thunk->val_tag = NN_VALUE_INT;-    thunk->payload = (void *)(intptr_t)value;-    return 1;+    return set_computed(thunk, NN_VALUE_INT, (void *)(intptr_t)value); } +/* The double's bytes are copied over the payload once the cell is+ * COMPUTED, as in nn_thunk_new_computed_float. */ int nn_thunk_set_computed_float(nn_thunk_t *thunk, double value) {-    if (thunk->state == NN_THUNK_COMPUTED) return 0;-    thunk->state = NN_THUNK_COMPUTED;-    thunk->val_tag = NN_VALUE_FLOAT;+    if (!set_computed(thunk, NN_VALUE_FLOAT, NULL)) return 0;     memcpy(&thunk->payload, &value, sizeof(double));     return 1; }@@ -430,145 +486,100 @@ int nn_thunk_set_computed_bool(nn_thunk_t *thunk, uint8_t value) {-    if (thunk->state == NN_THUNK_COMPUTED) return 0;-    thunk->state = NN_THUNK_COMPUTED;-    thunk->val_tag = NN_VALUE_BOOL;-    thunk->payload = (void *)(intptr_t)value;-    return 1;+    return set_computed(thunk, NN_VALUE_BOOL, (void *)(intptr_t)value); }  int nn_thunk_set_computed_null(nn_thunk_t *thunk) {-    if (thunk->state == NN_THUNK_COMPUTED) return 0;-    thunk->state = NN_THUNK_COMPUTED;-    thunk->val_tag = NN_VALUE_NULL;-    thunk->payload = NULL;-    return 1;+    return set_computed(thunk, NN_VALUE_NULL, NULL); }  int-nn_thunk_set_computed_str(nn_thunk_t *thunk, uint32_t symbol)+nn_thunk_set_computed_str(nn_thunk_t *thunk, void *str) {-    if (thunk->state == NN_THUNK_COMPUTED) return 0;-    thunk->state = NN_THUNK_COMPUTED;-    thunk->val_tag = NN_VALUE_STR;-    thunk->payload = (void *)(intptr_t)symbol;-    return 1;+    return set_computed(thunk, NN_VALUE_STR, str); }  int-nn_thunk_set_computed_path(nn_thunk_t *thunk, uint32_t symbol)+nn_thunk_set_computed_path(nn_thunk_t *thunk, void *str) {-    if (thunk->state == NN_THUNK_COMPUTED) return 0;-    thunk->state = NN_THUNK_COMPUTED;-    thunk->val_tag = NN_VALUE_PATH;-    thunk->payload = (void *)(intptr_t)symbol;-    return 1;+    return set_computed(thunk, NN_VALUE_PATH, str); }  int nn_thunk_set_computed_list(nn_thunk_t *thunk, void *list) {-    if (thunk->state == NN_THUNK_COMPUTED) return 0;-    thunk->state = NN_THUNK_COMPUTED;-    thunk->val_tag = NN_VALUE_LIST;-    thunk->payload = list;-    return 1;+    return set_computed(thunk, NN_VALUE_LIST, list); }  int nn_thunk_set_computed_attrs(nn_thunk_t *thunk, void *attrset) {-    if (thunk->state == NN_THUNK_COMPUTED) return 0;-    thunk->state = NN_THUNK_COMPUTED;-    thunk->val_tag = NN_VALUE_ATTRS;-    thunk->payload = attrset;-    return 1;+    return set_computed(thunk, NN_VALUE_ATTRS, attrset); }  int nn_thunk_set_computed_ctxstr(nn_thunk_t *thunk, void *ctxstr) {-    if (thunk->state == NN_THUNK_COMPUTED) return 0;-    thunk->state = NN_THUNK_COMPUTED;-    thunk->val_tag = NN_VALUE_CTXSTR;-    thunk->payload = ctxstr;-    return 1;+    return set_computed(thunk, NN_VALUE_CTXSTR, ctxstr); }  int nn_thunk_set_computed_lambda(nn_thunk_t *thunk, void *lambda) {-    if (thunk->state == NN_THUNK_COMPUTED) return 0;-    thunk->state = NN_THUNK_COMPUTED;-    thunk->val_tag = NN_VALUE_LAMBDA;-    thunk->payload = lambda;-    return 1;+    return set_computed(thunk, NN_VALUE_LAMBDA, lambda); } -/* --- Arena diagnostics / cleanup iteration --- */--uint32_t-nn_thunk_count(void)+int+nn_thunk_set_computed_primop(nn_thunk_t *thunk, uint32_t primop) {-    return g_arena ? g_arena->total : 0;+    return set_computed(thunk, NN_VALUE_PRIMOP, (void *)(uintptr_t)primop); } -nn_thunk_t *-nn_thunk_get(uint32_t index)+int+nn_thunk_set_computed_primop_app(nn_thunk_t *thunk, void *app) {-    if (!g_arena || index >= g_arena->total) return NULL;--    struct nn_thunk_block *block = g_arena->head;-    while (block) {-        if (index < block->count) {-            return &block->slots[index];-        }-        index -= block->count;-        block = block->next;-    }-    return NULL;  /* unreachable if index < total */+    return set_computed(thunk, NN_VALUE_PRIMOP_APP, app); } -/* --- Bulk StablePtr collection (single block-list pass, O(total)) --- */+/* --- Census --- */  uint32_t-nn_thunk_count_stableptrs(void)+nn_thunk_blocks(nn_thunk_t **slots, uint32_t *counts, uint32_t max) {-    uint32_t count = 0;+    uint32_t n = 0;     struct nn_thunk_block *block;-    uint32_t i;-    if (!g_arena) return 0;-    for (block = g_arena->head; block; block = block->next) {-        for (i = 0; i < block->count; i++) {-            const nn_thunk_t *t = &block->slots[i];-            if (t->state == NN_THUNK_PENDING || t->state == NN_THUNK_BLACKHOLE) {-                if (t->payload) count++;-            } else if (t->state == NN_THUNK_COMPUTED && t->val_tag == NN_VALUE_PTR) {-                if (t->payload) count++;-            }+    for (block = g_first_block; block; block = block->next) {+        if (n < max) {+            slots[n] = block->slots;+            counts[n] = block->count;         }+        n++;     }-    return count;+    return n; } -uint32_t-nn_thunk_collect_stableptrs(void **output, uint32_t max_count)+uint64_t+nn_thunk_reserved_bytes(void) {-    uint32_t written = 0;+    uint64_t bytes = 0;     struct nn_thunk_block *block;-    uint32_t i;-    if (!g_arena) return 0;-    for (block = g_arena->head; block && written < max_count; block = block->next) {-        for (i = 0; i < block->count && written < max_count; i++) {-            const nn_thunk_t *t = &block->slots[i];-            if (t->state == NN_THUNK_PENDING || t->state == NN_THUNK_BLACKHOLE) {-                if (t->payload) output[written++] = t->payload;-            } else if (t->state == NN_THUNK_COMPUTED && t->val_tag == NN_VALUE_PTR) {-                if (t->payload) output[written++] = t->payload;+    for (block = g_first_block; block; block = block->next) {+        bytes += sizeof(struct nn_thunk_block)+               + (uint64_t)NN_THUNK_BLOCK_CELLS * sizeof(nn_thunk_t);     }+    return bytes; }++uint64_t+nn_thunk_cells_allocated(void)+{+    return g_cells_allocated; }-    return written;++uint64_t+nn_thunk_cursor(void)+{+    return (uint64_t)g_cursor * sizeof(nn_thunk_t); }
cbits/nn_thunk.h view
@@ -2,24 +2,31 @@  * nn_thunk.h - Arena-allocated thunk memoization cells for nova-nix.  *  * Thunks are the core memoization mechanism in Nix evaluation.  Each- * thunk starts as PENDING (holding a bytecode index + C environment- * pointer) and transitions to COMPUTED (holding the result value) on- * first force.  A BLACKHOLE state detects infinite recursion.+ * thunk starts as PENDING (holding a bytecode index and the C environment+ * it runs in, or a deferred application's cells) and transitions to+ * COMPUTED (holding the result value) on first force.  A BLACKHOLE state+ * detects infinite recursion.  *- * Replaces Haskell's IORef ThunkCell (~56 bytes on GHC heap, all GC-- * traced) with a 16-byte C struct in an arena (invisible to GHC GC).- * For 8M thunks: ~450 MB less GHC heap pressure.+ * Each thunk is a 16-byte C struct in an arena, invisible to GHC's GC.  *- * Arena: chunked bump allocator.  Thunks are never individually freed -- * the entire arena is destroyed at evaluation end.  Pointers into the- * arena remain valid until nn_thunk_destroy().+ * Arena: chunked bump allocator.  The region collector frees a line of+ * thunks once nothing reaches any of them, and hands it out again+ * (nn_region.h); the rest are freed at once when the arena is destroyed.+ * A pointer to a thunk stays valid while the thunk is reachable, and+ * until nn_thunk_destroy() while no collector runs.  *- * PENDING payloads are StablePtr Env (~16 bytes on GHC heap).  The- * StablePtr is necessary for knot-tying: deferred env construction in- * recursive lets/attrs requires Haskell laziness.  Freed on force.- * COMPUTED payloads are either inline scalars (int/float/bool/null via- * val_tag 0-3), C-native pointers (str/path/list/attrs/ctxstr/lambda- * via val_tag 4-9), or StablePtrs (for VBuiltin/VDrv via tag 255).+ * A PENDING payload is the nn_env_t * the code runs in, or the cells of+ * a deferred application, a builtin's per-element application of a+ * function (map, mapAttrs and the like) as upstream's app value is a+ * function and its argument (value.hh at 2.24.9); either lives in the env+ * pages, so a pending thunk holds no reference into the GHC heap.  A+ * recursive frame (rec attrs, let, a formals set) is allocated with its+ * slot array before the thunks that point at it, and its slots are+ * filled after, as upstream allocates env2 before filling its values.+ * COMPUTED payloads are inline scalars (int/float/bool/null via val_tag+ * 0-3), C objects (str/path/list/attrs/ctxstr/lambda via val_tag 4-9, a+ * builtin's partial application via 11), or a builtin's index (10), so+ * every value lives in C and holds nothing in GHC's heap.  *  * Lifecycle: nn_thunk_init() before evaluation, nn_thunk_destroy()  * after.  Not thread-safe - single-threaded evaluation only.@@ -36,105 +43,146 @@ #define NN_THUNK_COMPUTED  1 #define NN_THUNK_BLACKHOLE 2 +/* --- Pending forms (valid when state is PENDING or BLACKHOLE) --- */++/* Code: the instruction at bc_idx, run in the env at payload. */+#define NN_PENDING_CODE   0+/* A deferred application of a function to one argument, or to two in+ * turn, as upstream's mapAttrs nests two app values: the payload is the+ * cells, the function's first, one more than the form's number of+ * arguments (nn_env_alloc_app_cells). */+#define NN_PENDING_APPLY1 1+#define NN_PENDING_APPLY2 2+ /* --- Value tags (valid when state == COMPUTED) --- */  #define NN_VALUE_INT     0   /* payload = (void*)(intptr_t)int64_value */ #define NN_VALUE_FLOAT   1   /* payload = memcpy'd double */ #define NN_VALUE_BOOL    2   /* payload = (void*)(intptr_t)(0 or 1) */ #define NN_VALUE_NULL    3   /* payload = NULL */-#define NN_VALUE_STR     4   /* payload = (void*)(intptr_t)nn_symbol_t (no context) */-#define NN_VALUE_PATH    5   /* payload = (void*)(intptr_t)nn_symbol_t */+#define NN_VALUE_STR     4   /* payload = nn_str_t* (no context) */+#define NN_VALUE_PATH    5   /* payload = nn_str_t* (the path's UTF-8 text) */ #define NN_VALUE_LIST    6   /* payload = nn_list_t* */ #define NN_VALUE_ATTRS   7   /* payload = nn_attrset_t* */ #define NN_VALUE_CTXSTR  8   /* payload = nn_ctxstr_t* (string with context) */ #define NN_VALUE_LAMBDA  9   /* payload = nn_lambda_t* (lambda closure) */-#define NN_VALUE_PTR     255 /* payload = StablePtr NixValue (complex types) */+#define NN_VALUE_PRIMOP  10  /* payload = (void*)(uintptr_t)builtin index */+#define NN_VALUE_PRIMOP_APP 11 /* payload = nn_primop_app_t* (nn_primop.h) */  /* --- Types --- */ -/* A thunk: mutable cell holding either a pending expression or a- * computed value.  16 bytes: state(1) + val_tag(1) + _pad(2) +- * bc_idx(4) + payload(8).  val_tag is valid only when state == COMPUTED.+/* A thunk: mutable cell holding either pending work or a computed value.+ * 16 bytes: state(1) + val_tag(1) + form(1) + _pad(1) + bc_idx(4) ++ * payload(8).  val_tag is valid only when state == COMPUTED, and form+ * only when it is PENDING or BLACKHOLE.  *- * PENDING:   bc_idx = bytecode instruction index- *            payload = StablePtr Env (Haskell-side, for knot-tying)+ * PENDING:   form selects interpretation of bc_idx and payload:+ *            CODE: bc_idx = bytecode instruction index,+ *                  payload = nn_env_t * the code runs in+ *            APPLY1, APPLY2: payload = the application's cells,+ *                  bc_idx unused  * COMPUTED:  val_tag selects interpretation of payload:  *            INT/BOOL: (intptr_t) cast of scalar  *            FLOAT: memcpy'd double  *            NULL: ignored- *            PTR: StablePtr to Haskell NixValue (complex types)- * BLACKHOLE: bc_idx/payload = stale from PENDING (do not dereference) */+ *            PRIMOP: (uintptr_t) cast of the builtin's index+ *            others: a pointer to the C object+ * BLACKHOLE: form, bc_idx and payload as they were PENDING, kept for+ *            nn_thunk_mark_pending, which puts the thunk back to work */ typedef struct nn_thunk {     uint8_t   state;     uint8_t   val_tag;-    uint16_t  _pad;-    uint32_t  bc_idx;    /* PENDING: bytecode index; otherwise stale (never read) */+    uint8_t   form;      /* PENDING and BLACKHOLE: an NN_PENDING_* form */+    uint8_t   _pad;+    uint32_t  bc_idx;    /* PENDING code: bytecode index; otherwise never read */     void     *payload; } nn_thunk_t; +/* C99-compatible compile-time check of the 16 bytes above. */+typedef char nn_thunk_size_check_[(sizeof(nn_thunk_t) == 16) ? 1 : -1];+ /* Nix integers are int64_t, stored inline via (intptr_t) cast into payload.  * This requires pointers to be at least 64 bits.  32-bit targets would  * silently truncate large integers.  C99-compatible compile-time check: */ typedef char nn_thunk_ptr_size_check_[(sizeof(void *) >= sizeof(int64_t)) ? 1 : -1]; +/* --- Blocks --- */++/* The cells each block of the arena holds. */+#define NN_THUNK_BLOCK_CELLS 65536u+ /* --- Lifecycle --- */ -/* Initialize the global thunk arena.  initial_capacity is the number- * of thunks to pre-allocate per block (0 uses default: 65536 = 1 MB).- * Must be called once before any thunk allocation (nn_thunk_new_bc or- * the computed-value constructors); outside the init .. destroy window- * every allocator returns NULL. */-void nn_thunk_init(uint32_t initial_capacity);+/* Initialize the global thunk arena with its first block.  Called only+ * while the arena is not live (nn_thunk_live is 0), as a second init+ * would leak the live arena's blocks, and before any thunk allocation:+ * outside the init .. destroy window every allocator returns NULL. */+void nn_thunk_init(void);  /* Nonzero between nn_thunk_init and nn_thunk_destroy. */ int nn_thunk_live(void); -/* Destroy the global thunk arena, freeing all block memory.- * Does NOT free payload StablePtrs - caller must iterate and free- * them first (via nn_thunk_count/nn_thunk_get).- * All nn_thunk_t pointers become invalid after this call. */+/* Destroy the global thunk arena, freeing all block memory.  The+ * objects a cell points to belong to their own allocators.  Every+ * nn_thunk_t pointer into the arena becomes invalid after this call; the+ * static cells (below) do not. */ void nn_thunk_destroy(void);  /* --- Allocation --- */ +/* No instruction's index, which nn_thunk_get_bc_idx answers for a thunk+ * that runs none: the bytecode emitters answer it only for an append+ * that failed (nn_bytecode.h). */+#define NN_THUNK_NO_CODE UINT32_MAX+ /* Allocate a new PENDING thunk with a bytecode index + env payload.- * Returns a pointer into arena memory, valid until nn_thunk_destroy().- * bc_idx is the root instruction index in the bytecode store.- * env_ptr is a StablePtr Env from Haskell (required for knot-tying;- * raw Ptr would force the env at allocation time, breaking laziness). */-nn_thunk_t *nn_thunk_new_bc(uint32_t bc_idx, void *env_ptr);+ * Returns a pointer into arena memory, valid as the arena's are, or NULL+ * when the thunk cannot be allocated.+ * bc_idx is the root instruction index in the bytecode store, never+ * NN_THUNK_NO_CODE (asserted).+ * env is the nn_env_t * the code runs in.  It must already exist, but+ * its slots need not be filled yet: nothing reads them until the thunk+ * is forced. */+nn_thunk_t *nn_thunk_new_bc(uint32_t bc_idx, void *env); -/* Read the bytecode index from a PENDING thunk. */+/* Allocate a new PENDING thunk deferring the application of the function+ * in `fn` to the argument in `arg`, or, for nn_thunk_new_apply2, to+ * `first` and then the result to `second`.  No cell is NULL (asserted).+ * Returns NULL when the thunk or its cells cannot be allocated. */+nn_thunk_t *nn_thunk_new_apply1(nn_thunk_t *fn, nn_thunk_t *arg);+nn_thunk_t *nn_thunk_new_apply2(nn_thunk_t *fn, nn_thunk_t *first, nn_thunk_t *second);++/* Read the bytecode index of a PENDING or BLACKHOLE code thunk, or+ * NN_THUNK_NO_CODE for an application, so that one read tells a code+ * thunk, nearly every thunk forced, from the rest. */ uint32_t nn_thunk_get_bc_idx(const nn_thunk_t *thunk); -/* Set the payload of a PENDING thunk.  Used for deferred env fixup in- * knot-tying (rec attrs, let, formal defaults): allocate the thunk- * with NULL payload first, then fill the env pointer once the- * knot-tied env is constructed.  Returns 1, or 0 with the thunk- * unchanged if it is not PENDING. */-int nn_thunk_set_payload(nn_thunk_t *thunk, void *payload);+/* Read the form of a PENDING or BLACKHOLE thunk (NN_PENDING_*). */+uint8_t nn_thunk_pending_form(const nn_thunk_t *thunk); -/* Allocate a new pre-COMPUTED thunk from the arena (StablePtr payload).- * value is an opaque pointer (StablePtr to Haskell NixValue).- * val_tag is set to NN_VALUE_PTR. */-nn_thunk_t *nn_thunk_new_computed(void *value);+/* Cell `i` of a PENDING or BLACKHOLE application, the function's at 0.+ * A thunk of another state or form, or `i` past its cells, aborts+ * (NN_ASSERT). */+nn_thunk_t *nn_thunk_apply_cell(const nn_thunk_t *thunk, uint32_t i); -/* Allocate pre-COMPUTED thunks with inline scalar values (no StablePtr). */+/* Allocate pre-COMPUTED thunks with inline scalar values. */ nn_thunk_t *nn_thunk_new_computed_int(int64_t value); nn_thunk_t *nn_thunk_new_computed_float(double value);+nn_thunk_t *nn_thunk_new_computed_primop(uint32_t primop); -/* Allocate pre-COMPUTED thunks with C-native complex values (no StablePtr). */-nn_thunk_t *nn_thunk_new_computed_str(uint32_t symbol);-nn_thunk_t *nn_thunk_new_computed_path(uint32_t symbol);+/* Allocate pre-COMPUTED thunks pointing at C objects. */+nn_thunk_t *nn_thunk_new_computed_str(void *str);+nn_thunk_t *nn_thunk_new_computed_path(void *str); nn_thunk_t *nn_thunk_new_computed_list(void *list); nn_thunk_t *nn_thunk_new_computed_attrs(void *attrset); nn_thunk_t *nn_thunk_new_computed_ctxstr(void *ctxstr); nn_thunk_t *nn_thunk_new_computed_lambda(void *lambda);+nn_thunk_t *nn_thunk_new_computed_primop_app(void *app);  /* --- Shared constants --- */ -/* The COMPUTED null, true and false cells, as upstream shares one vNull,- * vTrue and vFalse per EvalState.  They are file-scope statics, not+/* The COMPUTED null, true and false cells and the empty list's, as+ * upstream shares one vNull, vTrue, vFalse and vEmptyList per EvalState.  They are file-scope statics, not  * arena memory, so each has one address in every init .. destroy window  * and outside all of them: a constant built from one before  * nn_thunk_init, or kept across nn_thunk_destroy, still reads correctly.@@ -142,30 +190,45 @@  * them.  nn_thunk_bool answers the true cell for any nonzero value. */ nn_thunk_t *nn_thunk_null(void); nn_thunk_t *nn_thunk_bool(uint8_t value);+nn_thunk_t *nn_thunk_empty_list(void); +/* The builtins the static cells can name: one more than the highest+ * index nn_thunk_primop answers for. */+#define NN_PRIMOP_CELLS 256u++/* The COMPUTED cell of the builtin at `primop`, as upstream binds one+ * value per primop (EvalState::addPrimOp at 2.24.9): a static, like the+ * null and Boolean cells, so the builtin bound in every environment is+ * the one cell, valid in every init .. destroy window and outside all of+ * them.  NULL for an index from NN_PRIMOP_CELLS on.  A cell is filled the+ * first time it is asked for, with values that never change after, so+ * nothing reads one in another state. */+nn_thunk_t *nn_thunk_primop(uint32_t primop);++/* Nonzero for a static cell: the null, true, false and empty list cells+ * and the builtins' cells, which no arena holds. */+int nn_thunk_is_static(const nn_thunk_t *thunk);+ /* --- State queries --- */  /* Read the current state (NN_THUNK_PENDING/COMPUTED/BLACKHOLE). */ uint8_t nn_thunk_state(const nn_thunk_t *thunk); -/* Read the payload pointer.  Meaning depends on state + val_tag. */+/* Read the payload pointer.  For a COMPUTED thunk of a C object (val_tag+ * 4-9 and 11) it is that object, for the reader to cast to the type its+ * tag names; for a PENDING or BLACKHOLE one, its env or its application's+ * cells. */ void *nn_thunk_payload(const nn_thunk_t *thunk);  /* Read the value tag (valid when state == COMPUTED). */ uint8_t nn_thunk_value_tag(const nn_thunk_t *thunk); -/* Read inline scalar values from a COMPUTED thunk. */+/* Read inline values from a COMPUTED thunk: a scalar or a builtin's+ * index. */ int64_t  nn_thunk_get_int(const nn_thunk_t *thunk); double   nn_thunk_get_float(const nn_thunk_t *thunk); uint8_t  nn_thunk_get_bool(const nn_thunk_t *thunk);--/* Read C-native complex values from a COMPUTED thunk. */-uint32_t nn_thunk_get_str(const nn_thunk_t *thunk);-uint32_t nn_thunk_get_path(const nn_thunk_t *thunk);-void    *nn_thunk_get_list(const nn_thunk_t *thunk);-void    *nn_thunk_get_attrs(const nn_thunk_t *thunk);-void    *nn_thunk_get_ctxstr(const nn_thunk_t *thunk);-void    *nn_thunk_get_lambda(const nn_thunk_t *thunk);+uint32_t nn_thunk_get_primop(const nn_thunk_t *thunk);  /* --- State transitions --- */ @@ -175,48 +238,48 @@ int nn_thunk_mark_blackhole(nn_thunk_t *thunk);  /* Transition BLACKHOLE -> PENDING (a force threw and was caught upstream).- * Payload + bc_idx are preserved, so the thunk is re-forceable; matches C+++ * Form, payload and bc_idx are preserved, so the thunk is re-forceable; matches C++  * Nix restoring a thunk after a caught exception during force.  * Returns 1 on success, 0 if thunk is not BLACKHOLE. */ int nn_thunk_mark_pending(nn_thunk_t *thunk);  /* Set a non-COMPUTED thunk to COMPUTED, the setter naming the value- * kind: a StablePtr NixValue (NN_VALUE_PTR), an inline scalar, or a- * C-native complex value.  Accepts PENDING or BLACKHOLE state (skips- * blackhole for direct memoization).  The pending payload is overwritten,- * not handed back: a NULL return could not tell a refusal from a NULL- * payload, and the caller already read the payload to evaluate the- * thunk, so it frees the StablePtr itself.  Returns 1, or 0 with the- * thunk unchanged if it is already COMPUTED. */-int nn_thunk_set_computed(nn_thunk_t *thunk, void *value);+ * kind: an inline scalar, a builtin's index, or a C object.  Accepts PENDING or BLACKHOLE state (skips+ * blackhole for direct memoization).  The pending payload is overwritten:+ * it is an env or an application's cells, which the env pages own, so+ * there is nothing to hand back or free.  Returns 1, or 0 with the thunk+ * unchanged if it is already COMPUTED. */ int nn_thunk_set_computed_int(nn_thunk_t *thunk, int64_t value); int nn_thunk_set_computed_float(nn_thunk_t *thunk, double value); int nn_thunk_set_computed_bool(nn_thunk_t *thunk, uint8_t value); int nn_thunk_set_computed_null(nn_thunk_t *thunk);-int nn_thunk_set_computed_str(nn_thunk_t *thunk, uint32_t symbol);-int nn_thunk_set_computed_path(nn_thunk_t *thunk, uint32_t symbol);+int nn_thunk_set_computed_str(nn_thunk_t *thunk, void *str);+int nn_thunk_set_computed_path(nn_thunk_t *thunk, void *str); int nn_thunk_set_computed_list(nn_thunk_t *thunk, void *list); int nn_thunk_set_computed_attrs(nn_thunk_t *thunk, void *attrset); int nn_thunk_set_computed_ctxstr(nn_thunk_t *thunk, void *ctxstr); int nn_thunk_set_computed_lambda(nn_thunk_t *thunk, void *lambda);+int nn_thunk_set_computed_primop(nn_thunk_t *thunk, uint32_t primop);+int nn_thunk_set_computed_primop_app(nn_thunk_t *thunk, void *app); -/* --- Arena diagnostics / cleanup iteration --- */+/* --- Census (nn_stats.h) --- */ -/* Total thunks allocated across all blocks. */-uint32_t nn_thunk_count(void);+/* The arena's blocks, oldest first: for each of the first `max`, its+ * first slot and one past the last slot it has ever handed out go to+ * `slots` and `counts`.+ * Returns the number of blocks, which may exceed `max`; 0 outside the+ * init .. destroy window. */+uint32_t nn_thunk_blocks(nn_thunk_t **slots, uint32_t *counts, uint32_t max); -/* Get a thunk by global index (0-based, across all blocks).- * Used for StablePtr cleanup iteration before nn_thunk_destroy().- * Index must be < nn_thunk_count(). */-nn_thunk_t *nn_thunk_get(uint32_t index);+/* Bytes the arena holds from the allocator: every block, header and+ * unused slots included. */+uint64_t nn_thunk_reserved_bytes(void); -/* Single-pass (O(total)) collection of Haskell StablePtr payloads across the- * whole arena.  Walks the block list directly - nn_thunk_get is O(blocks) per- * call, so index-based iteration would be O(total * blocks).  StablePtr- * sources: PENDING/BLACKHOLE payload, and COMPUTED + NN_VALUE_PTR payload.- * nn_thunk_collect_stableptrs writes up to max_count pointers into `output`- * and returns the count written.  These back the nn_arena_* teardown helpers. */-uint32_t nn_thunk_count_stableptrs(void);-uint32_t nn_thunk_collect_stableptrs(void **output, uint32_t max_count);+/* The cells the arena has handed out since nn_thunk_init. */+uint64_t nn_thunk_cells_allocated(void);++/* Where the next cell comes from in the block cells are bumped from, in+ * bytes from its first slot (nn_region.h). */+uint64_t nn_thunk_cursor(void);  #endif /* NN_THUNK_H */
+ cbits/nn_tracker.c view
@@ -0,0 +1,55 @@+/*+ * nn_tracker.c - The record of every object of one kind (nn_tracker.h).+ *+ * A pointer array that doubles as it fills.+ */++#include "nn_tracker.h"++#include "nn_arena.h"++#include <stdlib.h>++/* The first capacity of the array, which doubles from there. */+#define NN_TRACKER_INITIAL_CAPACITY 256u++int nn_tracker_add(nn_tracker_t *tracker, void *object)+{+    if (!nn_arena_live()) return -1;+    if (tracker->count == tracker->capacity) {+        uint32_t cap;+        void **grown;+        if (tracker->capacity > UINT32_MAX / 2) return -1;+        cap = tracker->capacity ? tracker->capacity * 2 : NN_TRACKER_INITIAL_CAPACITY;+        grown = (void **)realloc(tracker->objects, (size_t)cap * sizeof(void *));+        if (!grown) return -1;+        tracker->objects = grown;+        tracker->capacity = cap;+    }+    tracker->objects[tracker->count++] = object;+    return 0;+}++void nn_tracker_sweep(nn_tracker_t *tracker, uint32_t from, nn_tracker_keep_t keep, void *ctx,+                      void (*free_object)(void *))+{+    uint32_t i, kept = from;+    for (i = from; i < tracker->count; i++) {+        void *object = tracker->objects[i];+        if (keep(ctx, object, i, kept))+            tracker->objects[kept++] = object;+        else+            free_object(object);+    }+    tracker->count = kept;+}++void nn_tracker_free_all(nn_tracker_t *tracker, void (*free_object)(void *))+{+    uint32_t i;+    for (i = 0; i < tracker->count; i++) free_object(tracker->objects[i]);+    free(tracker->objects);+    tracker->objects = NULL;+    tracker->count = 0;+    tracker->capacity = 0;+}
+ cbits/nn_tracker.h view
@@ -0,0 +1,55 @@+/*+ * nn_tracker.h - The record of every object of one kind the C data layer+ * allocates on its own.+ *+ * Attribute sets, list headers, lambdas, builtins' partial applications+ * and strings with context are malloc'd one object at a time, a set, and+ * a lambda with formals, in more than one block.  Each kind keeps a tracker,+ * adds every object to it as the object is made, and frees them all at once+ * at arena teardown through its own free function.  A census (nn_stats.h)+ * reads the objects back from it, and the region collector (nn_region.h)+ * frees the objects a close finds unreached through a sweep, which keeps the+ * rest in the order they were added.+ *+ * A tracker takes objects only while an evaluation session holds the+ * arena (nn_arena.h).  An object made outside every session would sit+ * below every region and be freed by the next session's teardown under+ * whoever held it, so each kind's allocator reports failure there, as+ * the sub-arenas' allocators do.+ *+ * Not thread-safe - single-threaded evaluation only.+ */++#ifndef NN_TRACKER_H+#define NN_TRACKER_H++#include <stdint.h>++/* The objects of one kind, in the order they were added.  An all-zero+ * tracker is empty and ready to use.  `objects` moves when an add grows+ * it, and is NULL while the tracker is empty. */+typedef struct {+    void   **objects;+    uint32_t count;+    uint32_t capacity;   /* objects the array has room for */+} nn_tracker_t;++/* Add an object.  Returns 0, or -1 with the tracker unchanged outside an+ * evaluation session (nn_arena_live is 0) or when its array cannot grow. */+int nn_tracker_add(nn_tracker_t *tracker, void *object);++/* Free every object with `free_object`, and then the array: the tracker+ * is empty after. */+void nn_tracker_free_all(nn_tracker_t *tracker, void (*free_object)(void *));++/* Whether to keep an object a sweep meets at `place`, told the place it+ * takes if kept. */+typedef int (*nn_tracker_keep_t)(void *ctx, void *object, uint32_t place, uint32_t kept_at);++/* Sweep the objects from `from` on, in order: each `keep` refuses is+ * freed with `free_object`, and the kept ones close up behind the ones+ * before `from`, which stay where they are. */+void nn_tracker_sweep(nn_tracker_t *tracker, uint32_t from, nn_tracker_keep_t keep, void *ctx,+                      void (*free_object)(void *));++#endif /* NN_TRACKER_H */
cbits/nn_winfs.c view
@@ -3,56 +3,1180 @@ #ifdef _WIN32  #include <windows.h>-#include <winternl.h>--/* FileCaseSensitiveInformation and its flag are absent from older SDK and- * MinGW headers; both values are fixed ABI, defined locally. */-enum { NN_FILE_CASE_SENSITIVE_INFORMATION = 71 };--#ifndef FILE_CS_FLAG_CASE_SENSITIVE_DIR-#define FILE_CS_FLAG_CASE_SENSITIVE_DIR 0x00000001-#endif--typedef struct nn_file_case_sensitive_info {-  ULONG flags;-} nn_file_case_sensitive_info;--typedef NTSTATUS(NTAPI *nn_nt_set_information_file)(HANDLE, PIO_STATUS_BLOCK,-                                                    PVOID, ULONG, ULONG);--int nn_dir_set_case_sensitive(const wchar_t *path) {-  HMODULE ntdll;-  nn_nt_set_information_file set_information_file;-  HANDLE dir;-  nn_file_case_sensitive_info info;-  IO_STATUS_BLOCK iosb;-  NTSTATUS status;--  /* NtSetInformationFile is the documented route to the per-directory-   * flag (fsutil and WSL use it); resolved dynamically because it lives-   * in ntdll, which is always loaded but not in the link line. */-  ntdll = GetModuleHandleW(L"ntdll.dll");-  if (ntdll == NULL) {-    return 0;-  }-  set_information_file =-      (nn_nt_set_information_file)GetProcAddress(ntdll, "NtSetInformationFile");-  if (set_information_file == NULL) {-    return 0;-  }--  dir = CreateFileW(path, FILE_WRITE_ATTRIBUTES,-                    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,-                    NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);-  if (dir == INVALID_HANDLE_VALUE) {-    return 0;-  }--  info.flags = FILE_CS_FLAG_CASE_SENSITIVE_DIR;-  status = set_information_file(dir, &iosb, &info, sizeof info,-                                NN_FILE_CASE_SENSITIVE_INFORMATION);-  CloseHandle(dir);-  return status >= 0 ? 1 : 0;+#include <aclapi.h>+#include <authz.h>+#include <sddl.h>+#include <stdlib.h>+#include <string.h>+#include <winternl.h>++/* FileCaseSensitiveInformation and its flag are absent from older SDK and+ * MinGW headers; both values are fixed ABI, defined locally. */+enum { NN_FILE_CASE_SENSITIVE_INFORMATION = 71 };++#ifndef FILE_CS_FLAG_CASE_SENSITIVE_DIR+#define FILE_CS_FLAG_CASE_SENSITIVE_DIR 0x00000001+#endif++typedef struct nn_file_case_sensitive_info {+  ULONG flags;+} nn_file_case_sensitive_info;++typedef NTSTATUS(NTAPI *nn_nt_set_information_file)(HANDLE, PIO_STATUS_BLOCK,+                                                    PVOID, ULONG, ULONG);++int nn_dir_set_case_sensitive(const wchar_t *path) {+  HMODULE ntdll;+  nn_nt_set_information_file set_information_file;+  HANDLE dir;+  nn_file_case_sensitive_info info;+  IO_STATUS_BLOCK iosb;+  NTSTATUS status;++  /* NtSetInformationFile is the documented route to the per-directory+   * flag (fsutil and WSL use it); resolved dynamically because it lives+   * in ntdll, which is always loaded but not in the link line. */+  ntdll = GetModuleHandleW(L"ntdll.dll");+  if (ntdll == NULL) {+    return 0;+  }+  set_information_file =+      (nn_nt_set_information_file)GetProcAddress(ntdll, "NtSetInformationFile");+  if (set_information_file == NULL) {+    return 0;+  }++  dir = CreateFileW(path, FILE_WRITE_ATTRIBUTES,+                    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,+                    NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);+  if (dir == INVALID_HANDLE_VALUE) {+    return 0;+  }++  info.flags = FILE_CS_FLAG_CASE_SENSITIVE_DIR;+  status = set_information_file(dir, &iosb, &info, sizeof info,+                                NN_FILE_CASE_SENSITIVE_INFORMATION);+  CloseHandle(dir);+  return status >= 0 ? 1 : 0;+}++/* The user of the token, in the string form ConvertSidToStringSidW+ * writes, written to *sid for the caller to release with LocalFree. */+static DWORD token_user_sid(HANDLE token, wchar_t **sid,+                            const char **failed) {+  /* A TOKEN_USER is followed in the buffer by the SID it points at, which+   * is at most SECURITY_MAX_SID_SIZE bytes, so one call fills it.  The+   * union aligns the buffer for the structure. */+  union {+    TOKEN_USER user;+    BYTE bytes[sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE];+  } buffer;+  DWORD size;++  if (!GetTokenInformation(token, TokenUser, &buffer, sizeof buffer, &size)) {+    *failed = "GetTokenInformation";+    return GetLastError();+  }+  if (!ConvertSidToStringSidW(buffer.user.User.Sid, sid)) {+    *failed = "ConvertSidToStringSidW";+    *sid = NULL;+    return GetLastError();+  }+  return ERROR_SUCCESS;+}++unsigned long nn_token_user_sid(wchar_t **sid, const char **failed) {+  HANDLE token;+  DWORD error;++  *sid = NULL;+  *failed = NULL;+  if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) {+    *failed = "OpenProcessToken";+    return GetLastError();+  }+  error = token_user_sid(token, sid, failed);+  CloseHandle(token);+  return error;+}++unsigned long nn_dir_create_sddl(const wchar_t *path, const wchar_t *sddl) {+  PSECURITY_DESCRIPTOR descriptor = NULL;+  SECURITY_ATTRIBUTES attributes;+  DWORD error = ERROR_SUCCESS;++  if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(+          sddl, SDDL_REVISION_1, &descriptor, NULL)) {+    return GetLastError();+  }+  attributes.nLength = sizeof attributes;+  attributes.lpSecurityDescriptor = descriptor;+  attributes.bInheritHandle = FALSE;+  if (!CreateDirectoryW(path, &attributes)) {+    error = GetLastError();+  }+  LocalFree(descriptor);+  return error;+}++unsigned long nn_entry_security(const wchar_t *path, void **descriptor,+                                unsigned long *length, const char **failed) {+  HANDLE entry;+  PSECURITY_DESCRIPTOR read = NULL;+  DWORD error;++  *descriptor = NULL;+  *length = 0;+  *failed = NULL;+  /* READ_CONTROL is the one right reading an owner and a DACL takes.+   * FILE_FLAG_BACKUP_SEMANTICS lets a directory be opened at all, and+   * FILE_FLAG_OPEN_REPARSE_POINT opens a link itself, not what it leads+   * to. */+  entry = CreateFileW(path, READ_CONTROL,+                      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,+                      NULL, OPEN_EXISTING,+                      FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,+                      NULL);+  if (entry == INVALID_HANDLE_VALUE) {+    *failed = "CreateFileW";+    return GetLastError();+  }+  error =+      GetSecurityInfo(entry, SE_FILE_OBJECT,+                      OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,+                      NULL, NULL, NULL, NULL, &read);+  CloseHandle(entry);+  if (error != ERROR_SUCCESS) {+    *failed = "GetSecurityInfo";+    return error;+  }+  *descriptor = read;+  *length = GetSecurityDescriptorLength(read);+  return ERROR_SUCCESS;+}++/* Whether this process's token is granted access by the owner and DACL of+ * a descriptor, as AccessCheck decides.  AccessCheck takes an impersonation+ * token, so the process's is duplicated as one.  *granted is set only when+ * the check is made. */+static unsigned long descriptor_grants(PSECURITY_DESCRIPTOR descriptor,+                                       DWORD access, int *granted,+                                       const char **failed) {+  HANDLE process_token = NULL;+  HANDLE token = NULL;+  GENERIC_MAPPING mapping;+  PRIVILEGE_SET privileges;+  DWORD privileges_length = sizeof privileges;+  DWORD granted_access = 0;+  BOOL allowed = FALSE;+  DWORD error = ERROR_SUCCESS;++  if (!OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE,+                        &process_token)) {+    *failed = "OpenProcessToken";+    return GetLastError();+  }+  if (!DuplicateToken(process_token, SecurityImpersonation, &token)) {+    *failed = "DuplicateToken";+    error = GetLastError();+    CloseHandle(process_token);+    return error;+  }+  CloseHandle(process_token);+  mapping.GenericRead = FILE_GENERIC_READ;+  mapping.GenericWrite = FILE_GENERIC_WRITE;+  mapping.GenericExecute = FILE_GENERIC_EXECUTE;+  mapping.GenericAll = FILE_ALL_ACCESS;+  if (AccessCheck(descriptor, token, access, &mapping, &privileges,+                  &privileges_length, &granted_access, &allowed)) {+    *granted = allowed ? 1 : 0;+  } else {+    *failed = "AccessCheck";+    error = GetLastError();+  }+  CloseHandle(token);+  return error;+}++unsigned long nn_dir_access(const wchar_t *path, unsigned long access,+                            int *granted, const char **failed) {+  HANDLE directory;+  PSECURITY_DESCRIPTOR descriptor = NULL;+  DWORD error;++  *granted = 0;+  *failed = NULL;+  /* READ_CONTROL is the one right reading the owner, group and DACL takes,+   * and AccessCheck wants the owner and the group both.+   * FILE_FLAG_BACKUP_SEMANTICS lets a directory be opened at all. */+  directory = CreateFileW(path, READ_CONTROL,+                          FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,+                          NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);+  if (directory == INVALID_HANDLE_VALUE) {+    *failed = "CreateFileW";+    return GetLastError();+  }+  error = GetSecurityInfo(directory, SE_FILE_OBJECT,+                          OWNER_SECURITY_INFORMATION |+                              GROUP_SECURITY_INFORMATION |+                              DACL_SECURITY_INFORMATION,+                          NULL, NULL, NULL, NULL, &descriptor);+  CloseHandle(directory);+  if (error != ERROR_SUCCESS) {+    *failed = "GetSecurityInfo";+    return error;+  }+  error = descriptor_grants(descriptor, access, granted, failed);+  LocalFree(descriptor);+  return error;+}++/* A local account's name, qualified by the computer's NetBIOS name so+ * the lookup searches this machine's accounts alone and never a domain's,+ * fits in this many characters with room to spare: a NetBIOS name is at+ * most 15 and a local account's name at most 256. */+enum { NN_QUALIFIED_NAME_CHARS = 300 };++/* Write name qualified by the computer's name (COMPUTER\name) to+ * qualified, which holds NN_QUALIFIED_NAME_CHARS characters.  Returns+ * ERROR_INSUFFICIENT_BUFFER, leaving *failed alone, where the qualified+ * name is longer than any account's, which so names none. */+static DWORD qualified_local_name(const wchar_t *name, wchar_t *qualified,+                                  const char **failed) {+  DWORD computerChars = MAX_COMPUTERNAME_LENGTH + 1;+  size_t nameChars = wcslen(name);++  if (!GetComputerNameW(qualified, &computerChars)) {+    *failed = "GetComputerNameW";+    return GetLastError();+  }+  if (computerChars + 1 + nameChars + 1 > NN_QUALIFIED_NAME_CHARS) {+    return ERROR_INSUFFICIENT_BUFFER;+  }+  qualified[computerChars] = L'\\';+  wmemcpy(qualified + computerChars + 1, name, nameChars + 1);+  return ERROR_SUCCESS;+}++unsigned long nn_local_group_sid(const wchar_t *name, wchar_t **sid,+                                 const char **failed) {+  wchar_t qualified[NN_QUALIFIED_NAME_CHARS];+  union {+    SID sid;+    BYTE bytes[SECURITY_MAX_SID_SIZE];+  } found;+  DWORD sidSize = sizeof found;+  wchar_t domain[MAX_COMPUTERNAME_LENGTH + 1];+  DWORD domainChars = MAX_COMPUTERNAME_LENGTH + 1;+  SID_NAME_USE use;+  DWORD error;++  *sid = NULL;+  *failed = NULL;+  error = qualified_local_name(name, qualified, failed);+  if (error == ERROR_INSUFFICIENT_BUFFER) {+    *failed = "nn_local_group_sid";+    return ERROR_INVALID_PARAMETER;+  }+  if (error != ERROR_SUCCESS) {+    return error;+  }+  if (!LookupAccountNameW(NULL, qualified, &found.sid, &sidSize, domain,+                          &domainChars, &use)) {+    error = GetLastError();+    if (error == ERROR_NONE_MAPPED) {+      return ERROR_SUCCESS;+    }+    *failed = "LookupAccountNameW";+    return error;+  }+  if (use != SidTypeAlias) {+    return ERROR_SUCCESS;+  }+  if (!ConvertSidToStringSidW(&found.sid, sid)) {+    *failed = "ConvertSidToStringSidW";+    *sid = NULL;+    return GetLastError();+  }+  return ERROR_SUCCESS;+}++unsigned long nn_descriptor_from_sddl(const wchar_t *sddl, void **descriptor) {+  PSECURITY_DESCRIPTOR made = NULL;++  *descriptor = NULL;+  if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(+          sddl, SDDL_REVISION_1, &made, NULL)) {+    return GetLastError();+  }+  *descriptor = made;+  return ERROR_SUCCESS;+}++unsigned long nn_entry_set_owner_dacl(const wchar_t *path, void *descriptor,+                                      const char **failed) {+  PSID owner = NULL;+  PACL dacl = NULL;+  BOOL present = FALSE;+  BOOL defaulted = FALSE;+  HANDLE entry;+  DWORD error;++  *failed = NULL;+  if (!GetSecurityDescriptorOwner(descriptor, &owner, &defaulted)) {+    *failed = "GetSecurityDescriptorOwner";+    return GetLastError();+  }+  if (!GetSecurityDescriptorDacl(descriptor, &present, &dacl, &defaulted)) {+    *failed = "GetSecurityDescriptorDacl";+    return GetLastError();+  }+  /* WRITE_OWNER and WRITE_DAC are the rights the two writes take, and+   * READ_CONTROL lets the write read what it keeps.  The flags open a+   * directory, and a link itself rather than what it leads to. */+  entry = CreateFileW(path, READ_CONTROL | WRITE_DAC | WRITE_OWNER,+                      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,+                      NULL, OPEN_EXISTING,+                      FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,+                      NULL);+  if (entry == INVALID_HANDLE_VALUE) {+    *failed = "CreateFileW";+    return GetLastError();+  }+  error = SetSecurityInfo(entry, SE_FILE_OBJECT,+                          OWNER_SECURITY_INFORMATION |+                              DACL_SECURITY_INFORMATION |+                              PROTECTED_DACL_SECURITY_INFORMATION,+                          owner, NULL, dacl, NULL);+  CloseHandle(entry);+  if (error != ERROR_SUCCESS) {+    *failed = "SetSecurityInfo";+  }+  return error;+}++unsigned long nn_job_die_on_unhandled_exception(void *job, const char **failed) {+  JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits;++  *failed = NULL;+  /* The limits are set as a whole, so the job's own, the process+   * library's KILL_ON_JOB_CLOSE among them, are read first and kept. */+  if (!QueryInformationJobObject(job, JobObjectExtendedLimitInformation,+                                 &limits, sizeof limits, NULL)) {+    *failed = "QueryInformationJobObject";+    return GetLastError();+  }+  limits.BasicLimitInformation.LimitFlags |=+      JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION;+  if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation,+                               &limits, sizeof limits)) {+    *failed = "SetInformationJobObject";+    return GetLastError();+  }+  return ERROR_SUCCESS;+}++/* What each direction of a pipe instance holds before a write waits for+ * the reader. */+enum { NN_PIPE_BUFFER_BYTES = 65536 };++/* How long, in milliseconds, a client waits for an instance of the pipe+ * while every one is busy, and how many such waits it makes before it+ * gives up.  The daemon makes its next instance as soon as a client+ * connects to the last, so a client finds none free only in that moment,+ * and a wait runs out only where the daemon has stopped making them.  A+ * client can be sent back to wait by another that takes the instance that+ * freed, so it waits again, but not for ever. */+enum { NN_PIPE_BUSY_WAIT_MS = 5000, NN_PIPE_OPEN_ATTEMPTS = 4 };++/* An account's or a domain's name fits in this many characters with its+ * NUL: a user's or a group's name is at most 256 (UNLEN, GNLEN), and a+ * domain's DNS name at most 255. */+enum { NN_ACCOUNT_CHARS = 257 };++/* Begin an overlapped operation's record, with the manual-reset event the+ * system sets as the operation ends. */+static DWORD overlapped_begin(OVERLAPPED *overlapped, const char **failed) {+  memset(overlapped, 0, sizeof *overlapped);+  overlapped->hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);+  if (overlapped->hEvent == NULL) {+    *failed = "CreateEventW";+    return GetLastError();+  }+  return ERROR_SUCCESS;+}++/* Wait for the overlapped operation begun on handle to end, or for stop to+ * be set, which cancels it.  The operation is waited for to its end+ * either way, since the system writes its record until then; one that+ * ended before the cancel keeps its result.  *transferred gets the bytes+ * it moved.  An operation that failed leaves *failed as the caller set it,+ * naming the operation. */+static DWORD overlapped_finish(HANDLE handle, OVERLAPPED *overlapped,+                               HANDLE stop, DWORD *transferred,+                               const char **failed) {+  HANDLE events[2];+  DWORD woken;+  DWORD waitError = ERROR_SUCCESS;++  events[0] = overlapped->hEvent;+  events[1] = stop;+  woken = WaitForMultipleObjects(2, events, FALSE, INFINITE);+  if (woken == WAIT_FAILED) {+    waitError = GetLastError();+  }+  if (woken != WAIT_OBJECT_0) {+    (void)CancelIoEx(handle, overlapped);+  }+  if (!GetOverlappedResult(handle, overlapped, transferred, TRUE)) {+    if (waitError != ERROR_SUCCESS) {+      *failed = "WaitForMultipleObjects";+      return waitError;+    }+    return GetLastError();+  }+  return ERROR_SUCCESS;+}++unsigned long nn_pipe_create(const wchar_t *name, int first,+                             const wchar_t *sddl, void **pipe,+                             const char **failed) {+  PSECURITY_DESCRIPTOR descriptor = NULL;+  SECURITY_ATTRIBUTES attributes;+  DWORD openMode = PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED;+  HANDLE made;+  DWORD error = ERROR_SUCCESS;++  *pipe = NULL;+  *failed = NULL;+  if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(+          sddl, SDDL_REVISION_1, &descriptor, NULL)) {+    *failed = "ConvertStringSecurityDescriptorToSecurityDescriptorW";+    return GetLastError();+  }+  /* Not inheritable, so no process the daemon starts, a builder among+   * them, holds a client's connection open. */+  attributes.nLength = sizeof attributes;+  attributes.lpSecurityDescriptor = descriptor;+  attributes.bInheritHandle = FALSE;+  if (first) {+    openMode |= FILE_FLAG_FIRST_PIPE_INSTANCE;+  }+  made = CreateNamedPipeW(+      name, openMode,+      PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT |+          PIPE_REJECT_REMOTE_CLIENTS,+      PIPE_UNLIMITED_INSTANCES, NN_PIPE_BUFFER_BYTES, NN_PIPE_BUFFER_BYTES,+      NN_PIPE_BUSY_WAIT_MS, &attributes);+  if (made == INVALID_HANDLE_VALUE) {+    *failed = "CreateNamedPipeW";+    error = GetLastError();+  } else {+    *pipe = made;+  }+  LocalFree(descriptor);+  return error;+}++unsigned long nn_pipe_accept(void *pipe, void *stop, const char **failed) {+  OVERLAPPED overlapped;+  DWORD unused;+  DWORD error;++  *failed = NULL;+  error = overlapped_begin(&overlapped, failed);+  if (error != ERROR_SUCCESS) {+    return error;+  }+  for (;;) {+    *failed = "ConnectNamedPipe";+    (void)ResetEvent(overlapped.hEvent);+    if (ConnectNamedPipe(pipe, &overlapped)) {+      error = ERROR_SUCCESS;+    } else {+      error = GetLastError();+      if (error == ERROR_IO_PENDING) {+        error = overlapped_finish(pipe, &overlapped, stop, &unused, failed);+      } else if (error == ERROR_PIPE_CONNECTED) {+        /* The client connected between the instance's making and this+         * call. */+        error = ERROR_SUCCESS;+      }+    }+    if (error != ERROR_NO_DATA) {+      break;+    }+    /* The client closed its end before the instance waited for it, and+     * the instance takes no other client until it is disconnected. */+    if (!DisconnectNamedPipe(pipe)) {+      *failed = "DisconnectNamedPipe";+      error = GetLastError();+      break;+    }+  }+  CloseHandle(overlapped.hEvent);+  if (error == ERROR_SUCCESS) {+    *failed = NULL;+  }+  return error;+}++unsigned long nn_pipe_read(void *pipe, void *buffer, unsigned long size,+                           void *stop, unsigned long *got,+                           const char **failed) {+  OVERLAPPED overlapped;+  DWORD read = 0;+  DWORD error;++  *got = 0;+  *failed = NULL;+  error = overlapped_begin(&overlapped, failed);+  if (error != ERROR_SUCCESS) {+    return error;+  }+  *failed = "ReadFile";+  /* A read that ends at once and one that is pending alike leave their+   * result in the record, which overlapped_finish reads. */+  if (ReadFile(pipe, buffer, size, NULL, &overlapped) ||+      (error = GetLastError()) == ERROR_IO_PENDING) {+    error = overlapped_finish(pipe, &overlapped, stop, &read, failed);+  }+  CloseHandle(overlapped.hEvent);+  *got = read;+  if (error == ERROR_SUCCESS) {+    *failed = NULL;+  }+  return error;+}++unsigned long nn_pipe_write(void *pipe, const void *buffer,+                            unsigned long size, void *stop,+                            const char **failed) {+  OVERLAPPED overlapped;+  const char *rest = buffer;+  DWORD left = size;+  DWORD written;+  DWORD error;++  *failed = NULL;+  error = overlapped_begin(&overlapped, failed);+  if (error != ERROR_SUCCESS) {+    return error;+  }+  while (error == ERROR_SUCCESS && left > 0) {+    written = 0;+    *failed = "WriteFile";+    if (WriteFile(pipe, rest, left, NULL, &overlapped) ||+        (error = GetLastError()) == ERROR_IO_PENDING) {+      error = overlapped_finish(pipe, &overlapped, stop, &written, failed);+    }+    /* A write that takes nothing would leave the loop running forever. */+    if (error == ERROR_SUCCESS && written == 0) {+      error = ERROR_WRITE_FAULT;+    }+    rest += written;+    left -= written;+  }+  CloseHandle(overlapped.hEvent);+  if (error == ERROR_SUCCESS) {+    *failed = NULL;+  }+  return error;+}++/* Whether a token's group is one an access check grants by: enabled, and+ * not held for deny only, as a filtered administrator's token holds+ * Administrators. */+static int group_grants(DWORD attributes) {+  return (attributes & SE_GROUP_ENABLED) != 0 &&+         (attributes & SE_GROUP_USE_FOR_DENY_ONLY) == 0;+}++/* Every group, for a list of groups that is kept whole. */+static int group_any(DWORD attributes) {+  (void)attributes;+  return 1;+}++/* Put the string form of sid, NUL included, at out + *at, within the+ * capacity characters out holds, or with out NULL only count it; either+ * way *at moves past it. */+static DWORD sid_put(PSID sid, wchar_t *out, DWORD capacity, DWORD *at,+                     const char **failed) {+  wchar_t *text;+  DWORD length;++  if (!ConvertSidToStringSidW(sid, &text)) {+    *failed = "ConvertSidToStringSidW";+    return GetLastError();+  }+  length = (DWORD)wcslen(text) + 1;+  if (out != NULL) {+    if (length > capacity - *at) {+      LocalFree(text);+      *failed = "nn_pipe_client";+      return ERROR_INSUFFICIENT_BUFFER;+    }+    wmemcpy(out + *at, text, length);+  }+  *at += length;+  LocalFree(text);+  return ERROR_SUCCESS;+}++/* Each of the token's groups the test keeps, through sid_put. */+static DWORD groups_put(const TOKEN_GROUPS *groups, int (*keep)(DWORD),+                        wchar_t *out, DWORD capacity, DWORD *at,+                        const char **failed) {+  DWORD index;+  DWORD error = ERROR_SUCCESS;++  for (index = 0; error == ERROR_SUCCESS && index < groups->GroupCount;+       index++) {+    if (keep(groups->Groups[index].Attributes)) {+      error = sid_put(groups->Groups[index].Sid, out, capacity, at, failed);+    }+  }+  return error;+}++/* The token's user and each of its groups group_grants keeps, through+ * sid_put. */+static DWORD sids_put(const TOKEN_USER *user, const TOKEN_GROUPS *groups,+                      wchar_t *out, DWORD capacity, DWORD *at,+                      const char **failed) {+  DWORD error = sid_put(user->User.Sid, out, capacity, at, failed);++  if (error == ERROR_SUCCESS) {+    error = groups_put(groups, group_grants, out, capacity, at, failed);+  }+  return error;+}++/* The token's groups, in a buffer for the caller to release with+ * LocalFree. */+static DWORD token_groups(HANDLE token, TOKEN_GROUPS **groups,+                          const char **failed) {+  DWORD size = 0;+  DWORD error;++  *groups = NULL;+  /* The groups take as much room as the token has groups, which the+   * first call asks. */+  if (!GetTokenInformation(token, TokenGroups, NULL, 0, &size)) {+    error = GetLastError();+    if (error != ERROR_INSUFFICIENT_BUFFER) {+      *failed = "GetTokenInformation";+      return error;+    }+  }+  *groups = LocalAlloc(LMEM_FIXED, size);+  if (*groups == NULL) {+    *failed = "LocalAlloc";+    return GetLastError();+  }+  if (!GetTokenInformation(token, TokenGroups, *groups, size, &size)) {+    *failed = "GetTokenInformation";+    error = GetLastError();+    LocalFree(*groups);+    *groups = NULL;+    return error;+  }+  return ERROR_SUCCESS;+}++/* The SIDs a token names its holder by, as nn_pipe_client writes them,+ * and whether the token is restricted. */+static DWORD token_sids(HANDLE token, int *restricted, wchar_t **sids,+                        unsigned long *chars, const char **failed) {+  /* A TOKEN_USER is followed in the buffer by the SID it points at, as in+   * token_user_sid. */+  union {+    TOKEN_USER user;+    BYTE bytes[sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE];+  } user;+  TOKEN_GROUPS *groups;+  wchar_t *out;+  DWORD size = 0;+  DWORD total = 0;+  DWORD written = 0;+  DWORD error;++  if (!GetTokenInformation(token, TokenUser, &user, sizeof user, &size)) {+    *failed = "GetTokenInformation";+    return GetLastError();+  }+  *restricted = IsTokenRestricted(token) ||+                (user.user.User.Attributes & SE_GROUP_USE_FOR_DENY_ONLY) != 0;+  error = token_groups(token, &groups, failed);+  if (error != ERROR_SUCCESS) {+    return error;+  }+  error = sids_put(&user.user, groups, NULL, 0, &total, failed);+  if (error == ERROR_SUCCESS) {+    out = LocalAlloc(LMEM_FIXED, total * sizeof(wchar_t));+    if (out == NULL) {+      *failed = "LocalAlloc";+      error = GetLastError();+    } else {+      error = sids_put(&user.user, groups, out, total, &written, failed);+      if (error == ERROR_SUCCESS) {+        *sids = out;+        *chars = written;+      } else {+        LocalFree(out);+      }+    }+  }+  LocalFree(groups);+  return error;+}++unsigned long nn_pipe_client(void *pipe, unsigned long *process,+                             int *restricted, wchar_t **sids,+                             unsigned long *chars, const char **failed) {+  ULONG client;+  HANDLE token = NULL;+  DWORD error = ERROR_SUCCESS;++  *process = 0;+  *restricted = 0;+  *sids = NULL;+  *chars = 0;+  *failed = NULL;+  if (!GetNamedPipeClientProcessId(pipe, &client)) {+    *failed = "GetNamedPipeClientProcessId";+    return GetLastError();+  }+  if (!ImpersonateNamedPipeClient(pipe)) {+    *failed = "ImpersonateNamedPipeClient";+    return GetLastError();+  }+  /* Opened as the process rather than as the client, whose token a client+   * that lets itself be identified but not impersonated cannot open. */+  if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &token)) {+    *failed = "OpenThreadToken";+    error = GetLastError();+  }+  /* The thread goes on to run the caller's code, none of which may run as+   * the client, and Windows' guidance for a thread that cannot stop+   * impersonating is to end the process. */+  if (!RevertToSelf()) {+    abort();+  }+  if (error != ERROR_SUCCESS) {+    return error;+  }+  error = token_sids(token, restricted, sids, chars, failed);+  CloseHandle(token);+  if (error == ERROR_SUCCESS) {+    *process = client;+  }+  return error;+}++unsigned long nn_pipe_open(const wchar_t *name, unsigned long access,+                           void **pipe, const char **failed) {+  HANDLE opened;+  DWORD error;+  int attempt;++  *pipe = NULL;+  *failed = NULL;+  for (attempt = 1;; attempt++) {+    /* SECURITY_IDENTIFICATION lets the daemon read who the client is, and+     * not act as it. */+    opened = CreateFileW(name, access, 0, NULL, OPEN_EXISTING,+                         FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT |+                             SECURITY_IDENTIFICATION,+                         NULL);+    if (opened != INVALID_HANDLE_VALUE) {+      *pipe = opened;+      return ERROR_SUCCESS;+    }+    error = GetLastError();+    if (error != ERROR_PIPE_BUSY || attempt == NN_PIPE_OPEN_ATTEMPTS) {+      *failed = "CreateFileW";+      return error;+    }+    /* Another client may take the instance that frees before this one+     * opens it, which only sends this one back to wait.  A wait that runs+     * out says that every instance stayed busy, which is the open's+     * failure. */+    if (!WaitNamedPipeW(name, NMPWAIT_USE_DEFAULT_WAIT)) {+      error = GetLastError();+      if (error == ERROR_SEM_TIMEOUT) {+        *failed = "CreateFileW";+        return ERROR_PIPE_BUSY;+      }+      *failed = "WaitNamedPipeW";+      return error;+    }+  }+}++unsigned long nn_pipe_owner(void *pipe, wchar_t **sid, const char **failed) {+  PSID owner = NULL;+  PSECURITY_DESCRIPTOR descriptor = NULL;+  DWORD error;++  *sid = NULL;+  *failed = NULL;+  /* The owner the pipe's creator gave it. */+  error = GetSecurityInfo(pipe, SE_KERNEL_OBJECT, OWNER_SECURITY_INFORMATION,+                          &owner, NULL, NULL, NULL, &descriptor);+  if (error != ERROR_SUCCESS) {+    *failed = "GetSecurityInfo";+    return error;+  }+  if (owner != NULL && !ConvertSidToStringSidW(owner, sid)) {+    *failed = "ConvertSidToStringSidW";+    *sid = NULL;+    error = GetLastError();+  }+  LocalFree(descriptor);+  return error;+}++unsigned long nn_pipe_integrity(void *pipe, unsigned long *level,+                                const char **failed) {+  PACL sacl = NULL;+  PSECURITY_DESCRIPTOR descriptor = NULL;+  DWORD index;+  DWORD error;++  *level = SECURITY_MANDATORY_MEDIUM_RID;+  *failed = NULL;+  error = GetSecurityInfo(pipe, SE_KERNEL_OBJECT, LABEL_SECURITY_INFORMATION,+                          NULL, NULL, NULL, &sacl, &descriptor);+  if (error != ERROR_SUCCESS) {+    *failed = "GetSecurityInfo";+    return error;+  }+  /* The label is an entry of the SACL whose SID's last subauthority is the+   * level; the SACL read for the label alone holds no other kind. */+  for (index = 0; sacl != NULL && index < sacl->AceCount; index++) {+    void *entry;+    SYSTEM_MANDATORY_LABEL_ACE *label;+    PSID sid;++    if (!GetAce(sacl, index, &entry)) {+      *failed = "GetAce";+      error = GetLastError();+      break;+    }+    label = entry;+    if (label->Header.AceType == SYSTEM_MANDATORY_LABEL_ACE_TYPE) {+      sid = (PSID)&label->SidStart;+      *level = *GetSidSubAuthority(+          sid, (DWORD)(*GetSidSubAuthorityCount(sid) - 1));+      break;+    }+  }+  LocalFree(descriptor);+  return error;+}++/* Whether the token holds the group enabled, not for deny only, and with+ * the right to own objects as it: the way an elevated administrator's+ * token holds Administrators, and a filtered one, which holds the group+ * for deny only, does not. */+static int token_owns_as_group(const TOKEN_GROUPS *groups, PSID group) {+  DWORD index;+  DWORD attributes;++  for (index = 0; index < groups->GroupCount; index++) {+    if (EqualSid(groups->Groups[index].Sid, group)) {+      attributes = groups->Groups[index].Attributes;+      return (attributes & SE_GROUP_ENABLED) != 0 &&+             (attributes & SE_GROUP_OWNER) != 0 &&+             (attributes & SE_GROUP_USE_FOR_DENY_ONLY) == 0;+    }+  }+  return 0;+}++unsigned long nn_token_pipe_owner(void *token, wchar_t **sid,+                                  const char **failed) {+  HANDLE opened = NULL;+  union {+    SID sid;+    BYTE bytes[SECURITY_MAX_SID_SIZE];+  } administrators;+  DWORD administratorsSize = sizeof administrators;+  TOKEN_GROUPS *groups = NULL;+  DWORD error;++  *sid = NULL;+  *failed = NULL;+  if (token == NULL) {+    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &opened)) {+      *failed = "OpenProcessToken";+      return GetLastError();+    }+    token = opened;+  }+  if (!CreateWellKnownSid(WinBuiltinAdministratorsSid, NULL,+                          &administrators.sid, &administratorsSize)) {+    *failed = "CreateWellKnownSid";+    error = GetLastError();+  } else {+    error = token_groups(token, &groups, failed);+  }+  if (error == ERROR_SUCCESS) {+    if (!token_owns_as_group(groups, &administrators.sid)) {+      error = token_user_sid(token, sid, failed);+    } else if (!ConvertSidToStringSidW(&administrators.sid, sid)) {+      *failed = "ConvertSidToStringSidW";+      *sid = NULL;+      error = GetLastError();+    }+    LocalFree(groups);+  }+  if (opened != NULL) {+    CloseHandle(opened);+  }+  return error;+}++unsigned long nn_pipe_present(const wchar_t *path, const wchar_t *name,+                              int *present, const char **failed) {+  WIN32_FIND_DATAW found;+  HANDLE search;+  DWORD error = ERROR_SUCCESS;++  *present = 0;+  *failed = NULL;+  /* A search of the pipes' namespace lists the pipes whose names match;+   * opening the pipe or asking its attributes would connect to an+   * instance.  A name holding a wildcard matches others, so each found+   * name is compared with the one asked for. */+  search = FindFirstFileW(path, &found);+  if (search == INVALID_HANDLE_VALUE) {+    /* The pipes' namespace answers a search that matches nothing with+     * ERROR_NO_MORE_FILES, where a directory on disk answers+     * ERROR_FILE_NOT_FOUND. */+    error = GetLastError();+    if (error == ERROR_FILE_NOT_FOUND || error == ERROR_NO_MORE_FILES) {+      return ERROR_SUCCESS;+    }+    *failed = "FindFirstFileW";+    return error;+  }+  do {+    if (CompareStringOrdinal(found.cFileName, -1, name, -1, TRUE) ==+        CSTR_EQUAL) {+      *present = 1;+    }+  } while (!*present && FindNextFileW(search, &found));+  if (!*present) {+    error = GetLastError();+    if (error == ERROR_NO_MORE_FILES) {+      error = ERROR_SUCCESS;+    } else {+      *failed = "FindNextFileW";+    }+  }+  FindClose(search);+  return error;+}++/* Whether an account whose name resolved to this type is of the kind+ * asked for.  SYSTEM, LOCAL SERVICE and a service's virtual account are+ * filed as well-known groups yet are the users processes run as, so a user+ * may be one. */+static int use_fits(SID_NAME_USE use, int kind) {+  if (kind == NN_ACCOUNT_USER) {+    return use == SidTypeUser || use == SidTypeWellKnownGroup;+  }+  return use == SidTypeGroup || use == SidTypeAlias ||+         use == SidTypeWellKnownGroup;+}++unsigned long nn_account_sid(const wchar_t *name, int kind, wchar_t **sid,+                             const char **failed) {+  wchar_t qualified[NN_QUALIFIED_NAME_CHARS];+  const wchar_t *searched = name;+  union {+    SID sid;+    BYTE bytes[SECURITY_MAX_SID_SIZE];+  } found;+  DWORD sidSize = sizeof found;+  wchar_t domain[NN_ACCOUNT_CHARS];+  DWORD domainChars = NN_ACCOUNT_CHARS;+  SID_NAME_USE use;+  DWORD error;++  *sid = NULL;+  *failed = NULL;+  /* A name that names no domain is searched for among this machine's+   * accounts alone: handed to LookupAccountNameW bare, it falls through to+   * the domain the machine belongs to. */+  if (wcspbrk(name, L"\\@") == NULL) {+    error = qualified_local_name(name, qualified, failed);+    if (error == ERROR_INSUFFICIENT_BUFFER) {+      return ERROR_SUCCESS;+    }+    if (error != ERROR_SUCCESS) {+      return error;+    }+    searched = qualified;+  }+  if (!LookupAccountNameW(NULL, searched, &found.sid, &sidSize, domain,+                          &domainChars, &use)) {+    error = GetLastError();+    if (error == ERROR_NONE_MAPPED) {+      return ERROR_SUCCESS;+    }+    *failed = "LookupAccountNameW";+    return error;+  }+  if (!use_fits(use, kind)) {+    return ERROR_SUCCESS;+  }+  if (!ConvertSidToStringSidW(&found.sid, sid)) {+    error = GetLastError();+    *failed = "ConvertSidToStringSidW";+    *sid = NULL;+    return error;+  }+  return ERROR_SUCCESS;+}++/* The groups of the account whose SID is given, from the access check's+ * own source for them, in a buffer for the caller to release with+ * LocalFree. */+static DWORD account_context_groups(PSID user, TOKEN_GROUPS **groups,+                                    const char **failed) {+  AUTHZ_RESOURCE_MANAGER_HANDLE manager = NULL;+  AUTHZ_CLIENT_CONTEXT_HANDLE context = NULL;+  LUID identifier = {0, 0};+  DWORD size = 0;+  DWORD error = ERROR_SUCCESS;++  *groups = NULL;+  /* No audit event is made for a context that only reads groups. */+  if (!AuthzInitializeResourceManager(AUTHZ_RM_FLAG_NO_AUDIT, NULL, NULL, NULL,+                                      NULL, &manager)) {+    *failed = "AuthzInitializeResourceManager";+    return GetLastError();+  }+  if (!AuthzInitializeContextFromSid(0, user, manager, NULL, identifier, NULL,+                                     &context)) {+    *failed = "AuthzInitializeContextFromSid";+    error = GetLastError();+  } else {+    /* The first call asks how much room the groups take. */+    (void)AuthzGetInformationFromContext(context, AuthzContextInfoGroupsSids,+                                         0, &size, NULL);+    *groups = LocalAlloc(LMEM_FIXED, size);+    if (*groups == NULL) {+      *failed = "LocalAlloc";+      error = GetLastError();+    } else if (!AuthzGetInformationFromContext(+                   context, AuthzContextInfoGroupsSids, size, &size,+                   *groups)) {+      *failed = "AuthzGetInformationFromContext";+      error = GetLastError();+      LocalFree(*groups);+      *groups = NULL;+    }+    AuthzFreeContext(context);+  }+  AuthzFreeResourceManager(manager);+  return error;+}++unsigned long nn_account_groups(const wchar_t *sid, wchar_t **sids,+                                unsigned long *chars, const char **failed) {+  PSID user = NULL;+  TOKEN_GROUPS *groups = NULL;+  wchar_t *out;+  DWORD total = 0;+  DWORD written = 0;+  DWORD error;++  *sids = NULL;+  *chars = 0;+  *failed = NULL;+  if (!ConvertStringSidToSidW(sid, &user)) {+    *failed = "ConvertStringSidToSidW";+    return GetLastError();+  }+  error = account_context_groups(user, &groups, failed);+  LocalFree(user);+  if (error != ERROR_SUCCESS) {+    return error;+  }+  error = groups_put(groups, group_any, NULL, 0, &total, failed);+  if (error == ERROR_SUCCESS) {+    /* One more than the groups' text, so an account in no group still gets+     * a buffer to release. */+    out = LocalAlloc(LMEM_FIXED, ((size_t)total + 1) * sizeof(wchar_t));+    if (out == NULL) {+      *failed = "LocalAlloc";+      error = GetLastError();+    } else {+      error = groups_put(groups, group_any, out, total, &written, failed);+      if (error == ERROR_SUCCESS) {+        *sids = out;+        *chars = written;+      } else {+        LocalFree(out);+      }+    }+  }+  LocalFree(groups);+  return error;+}++unsigned long nn_account_name(const wchar_t *sid, wchar_t **name,+                              const char **failed) {+  PSID binary = NULL;+  wchar_t account[NN_ACCOUNT_CHARS];+  DWORD accountChars = NN_ACCOUNT_CHARS;+  wchar_t domain[NN_ACCOUNT_CHARS];+  DWORD domainChars = NN_ACCOUNT_CHARS;+  SID_NAME_USE use;+  size_t accountLength;+  size_t domainLength;+  size_t prefix;+  wchar_t *joined;+  DWORD error;++  *name = NULL;+  *failed = NULL;+  if (!ConvertStringSidToSidW(sid, &binary)) {+    *failed = "ConvertStringSidToSidW";+    return GetLastError();+  }+  if (!LookupAccountSidW(NULL, binary, account, &accountChars, domain,+                         &domainChars, &use)) {+    error = GetLastError();+    LocalFree(binary);+    if (error == ERROR_NONE_MAPPED) {+      return ERROR_SUCCESS;+    }+    *failed = "LookupAccountSidW";+    return error;+  }+  LocalFree(binary);+  accountLength = wcslen(account);+  domainLength = wcslen(domain);+  prefix = domainLength > 0 ? domainLength + 1 : 0;+  joined = LocalAlloc(LMEM_FIXED,+                      (prefix + accountLength + 1) * sizeof(wchar_t));+  if (joined == NULL) {+    *failed = "LocalAlloc";+    return GetLastError();+  }+  if (domainLength > 0) {+    wmemcpy(joined, domain, domainLength);+    joined[domainLength] = L'\\';+  }+  wmemcpy(joined + prefix, account, accountLength + 1);+  *name = joined;+  return ERROR_SUCCESS; }  #else /* !_WIN32 */
cbits/nn_winfs.h view
@@ -1,8 +1,12 @@-/* Platform filesystem capabilities the store layer probes at runtime.- * Windows-only functionality.  Every other platform compiles the constant- * 0 stub because the cabal c-sources entry is unconditional and the C99- * strict job lints every C file under cbits on Linux; the Haskell side- * picks the platform's answer at compile time and never calls the stub. */+/* Platform calls the library makes on Windows: the filesystem+ * capabilities the store layer uses, the limits of a builder's job, and+ * the daemon's named pipe with the accounts its clients are named by.+ * The cabal c-sources entry is unconditional and the C99 strict job+ * lints every C file under cbits on Linux, so every other platform+ * compiles a constant 0 stub of the case-sensitivity call; the Haskell+ * side picks the platform's answer at compile time and never calls it.+ * The access-control, job, pipe and account calls are declared and+ * defined on Windows alone, the only platform that calls them. */ #ifndef NN_WINFS_H #define NN_WINFS_H @@ -16,5 +20,200 @@  * input (NAR trees choose which directories need it), so the failure  * path is a live branch, never an assert. */ int nn_dir_set_case_sensitive(const wchar_t *path);++#ifdef _WIN32++/* The SID of the user this process runs as, its token's user, in the+ * string form ConvertSidToStringSidW writes ("S-1-5-21-..."), written to+ * *sid for the caller to release with LocalFree.  Returns 0, or the+ * Win32 error code of the call that failed, with *failed naming that+ * call (a static string) and *sid NULL. */+unsigned long nn_token_user_sid(wchar_t **sid, const char **failed);++/* Create the directory at path with the security descriptor the SDDL+ * string describes, in the one CreateDirectoryW call that makes it, so+ * the directory never exists with the access control list its parent+ * would pass down.  Returns 0, or the Win32 error code (a DWORD) of the+ * step that failed: ERROR_ALREADY_EXISTS when anything already has the+ * name, a file as well as a directory. */+unsigned long nn_dir_create_sddl(const wchar_t *path, const wchar_t *sddl);++/* The owner and DACL of the entry at path itself, a link read as itself+ * and not followed, as the self-relative security descriptor+ * GetSecurityInfo returns, written to *descriptor for the caller to+ * release with LocalFree, with its length in bytes in *length.  Returns+ * 0, or the Win32 error code of the call that failed, with *failed naming+ * that call (a static string) and *descriptor NULL: ERROR_FILE_NOT_FOUND+ * or ERROR_PATH_NOT_FOUND from CreateFileW when nothing has the name. */+unsigned long nn_entry_security(const wchar_t *path, void **descriptor,+                                unsigned long *length, const char **failed);++/* Whether this process's token is granted the access rights given+ * (winnt.h's FILE_LIST_DIRECTORY, FILE_ADD_FILE and the like, ORed) by the+ * owner and DACL of the directory at path, a link followed.  The rights+ * are checked against the descriptor and the directory is not opened for+ * them, since an open made for backup intent passes whatever the DACL says+ * for a token whose backup or restore privilege is enabled, and a write+ * does not.  Returns 0 and sets *granted to 1 or 0, or returns the Win32+ * error code of the call that failed, named in *failed (ERROR_FILE_NOT_FOUND+ * or ERROR_PATH_NOT_FOUND where nothing has the name). */+unsigned long nn_dir_access(const wchar_t *path, unsigned long access,+                            int *granted, const char **failed);++/* The SID of the local group the name names on this machine, in the+ * string form ConvertSidToStringSidW writes, written to *sid for the+ * caller to release with LocalFree; *sid is NULL where the machine has no+ * local group of that name, none at all or an account of another kind.+ * Returns 0, or the Win32 error code of the call that failed, with+ * *failed naming that call (a static string) and *sid NULL. */+unsigned long nn_local_group_sid(const wchar_t *name, wchar_t **sid,+                                 const char **failed);++/* The self-relative security descriptor the SDDL string describes,+ * written to *descriptor for the caller to release with LocalFree.+ * Returns 0, or the Win32 error code. */+unsigned long nn_descriptor_from_sddl(const wchar_t *sddl, void **descriptor);++/* Give the entry at path itself, a link not followed, the owner and the+ * DACL, protected, of the security descriptor given.  Returns 0, or the+ * Win32 error code of the call that failed, with *failed naming that+ * call (a static string). */+unsigned long nn_entry_set_owner_dacl(const wchar_t *path, void *descriptor,+                                      const char **failed);++/* Add JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION to the limits of the+ * job whose handle is given, keeping the others, so that a process of+ * the job that meets an unhandled exception ends with the exception's+ * code as its exit code, and Windows Error Reporting is not invoked.+ * Returns 0, or the Win32 error code of the call that failed, with+ * *failed naming that call (a static string). */+unsigned long nn_job_die_on_unhandled_exception(void *job, const char **failed);++/* The daemon's named pipe.  Every handle is opened for overlapped I/O, so+ * one connection can be read and written at once from two threads, and+ * every call that waits also wakes when the event stop is set, which+ * cancels what it waited on: the caller sets stop to interrupt it.  Each+ * returns 0, or the Win32 error code of the call that failed with *failed+ * naming that call (a static string): ERROR_OPERATION_ABORTED when stop+ * was set first. */++/* Create an instance of the pipe at name (\\.\pipe\NAME): duplex, in byte+ * mode, refusing clients on other machines, with the security descriptor+ * the SDDL string describes.  With first nonzero it is created with+ * FILE_FLAG_FIRST_PIPE_INSTANCE, so it fails with ERROR_ACCESS_DENIED+ * where the pipe already exists.  *pipe gets the instance's handle. */+unsigned long nn_pipe_create(const wchar_t *name, int first,+                             const wchar_t *sddl, void **pipe,+                             const char **failed);++/* Wait until a client connects to the instance.  A client that connected+ * and closed its end before the wait is dropped and waited past. */+unsigned long nn_pipe_accept(void *pipe, void *stop, const char **failed);++/* Read up to size bytes into buffer, waiting until some arrive; *got gets+ * how many.  ERROR_BROKEN_PIPE once the other end has closed and all it+ * wrote has been read. */+unsigned long nn_pipe_read(void *pipe, void *buffer, unsigned long size,+                           void *stop, unsigned long *got,+                           const char **failed);++/* Write all size bytes of buffer, waiting until the pipe takes them. */+unsigned long nn_pipe_write(void *pipe, const void *buffer,+                            unsigned long size, void *stop,+                            const char **failed);++/* Who the client connected to the instance is, read from its token by+ * impersonating it, which the pipe allows as soon as the client has+ * connected, before it has sent anything: *process gets its process ID;+ * *restricted is nonzero for a restricted token or one whose user is held+ * for deny only; and *sids gets the token's user and then each group the+ * token holds enabled and not for deny only, each SID in the string form+ * ConvertSidToStringSidW writes and ended by a NUL, *chars wide characters+ * in all, for the caller to release with LocalFree.  The impersonation and+ * its end are this one call, so the calling thread runs nothing else as+ * the client. */+unsigned long nn_pipe_client(void *pipe, unsigned long *process,+                             int *restricted, wchar_t **sids,+                             unsigned long *chars, const char **failed);++/* Open a client's end of the pipe at name, asking for the access given,+ * and letting the daemon identify the client but not act as it.  While+ * every instance is busy it waits for one, for as long as the daemon's+ * instances say and up to a fixed number of times, and gives+ * ERROR_PIPE_BUSY if none frees. */+unsigned long nn_pipe_open(const wchar_t *name, unsigned long access,+                           void **pipe, const char **failed);++/* The SID of the account that owns the pipe the handle is open to, in the+ * string form ConvertSidToStringSidW writes, written to *sid for the+ * caller to release with LocalFree; *sid is NULL where the pipe has no+ * owner.  Reading it takes READ_CONTROL on the handle, which the access+ * nn_pipe_open is given includes. */+unsigned long nn_pipe_owner(void *pipe, wchar_t **sid, const char **failed);++/* The integrity level of the pipe the handle is open to, its mandatory+ * label's RID (0x2000 for Medium, 0x1000 for Low), written to *level: that+ * of its label where it has one, and Medium where it has none, as Windows+ * reads an object with no label.  A pipe a process running at Low makes+ * has the Low label, and one a process running at Medium or above makes+ * has none, so the level says whether a process below Medium made it.+ * Reading it takes READ_CONTROL on the handle. */+unsigned long nn_pipe_integrity(void *pipe, unsigned long *level,+                                const char **failed);++/* The SID a daemon running with the token makes its pipe's owner, in the+ * string form ConvertSidToStringSidW writes, written to *sid for the+ * caller to release with LocalFree: BUILTIN\Administrators where the token+ * holds that group enabled, not for deny only, and with the right to own+ * objects as it, which is how an elevated administrator's token holds it,+ * and the token's user otherwise.  A process without the restore+ * privilege can give an object it makes no other owner than its token's+ * user or a group its token holds that way.  The token is the handle of+ * one opened for TOKEN_QUERY, or NULL for this process's. */+unsigned long nn_token_pipe_owner(void *token, wchar_t **sid,+                                  const char **failed);++/* Whether the pipe at path (\\.\pipe\NAME, NAME given apart as name)+ * exists, read from the listing of the machine's pipes, which connects to+ * no instance and does not wait: *present gets 1 or 0.  The name is+ * compared as Windows compares a pipe's, ignoring case. */+unsigned long nn_pipe_present(const wchar_t *path, const wchar_t *name,+                              int *present, const char **failed);++/* Which kind of account nn_account_sid is to find: a user, among which+ * the well-known accounts that run processes (SYSTEM, a service's virtual+ * account), or a group, local, global or well-known. */+enum { NN_ACCOUNT_USER = 0, NN_ACCOUNT_GROUP = 1 };++/* The SID an account's name names, as LookupAccountNameW finds one, in the+ * string form ConvertSidToStringSidW writes, to *sid for the caller to+ * release with LocalFree.  A name with no backslash and no @ is an account+ * of this machine alone, which a domain's accounts of the same name never+ * answer, so a domain does not decide who a bare name is; NAME@DOMAIN and+ * DOMAIN\NAME name the domain.  *sid is NULL where no account of the kind+ * has the name: ERROR_NONE_MAPPED, a name too long for any account, and an+ * account of another kind.  Any other failure is returned as one, so a+ * lookup that could not be made is not taken for an answer. */+unsigned long nn_account_sid(const wchar_t *name, int kind, wchar_t **sid,+                             const char **failed);++/* Every group the account whose SID is given in string form belongs to, as+ * Windows computes them for a logon of the account (local groups, domain+ * groups they nest in, and the well-known groups of every logon), from the+ * account itself and so whatever token a client presents: each SID in the+ * string form ConvertSidToStringSidW writes and ended by a NUL, *chars+ * wide characters in all, written to *sids for the caller to release with+ * LocalFree.  Returns the Win32 error code of the call that failed where+ * Windows cannot say, as for an account it does not know. */+unsigned long nn_account_groups(const wchar_t *sid, wchar_t **sids,+                                unsigned long *chars, const char **failed);++/* The name of the account whose SID is given in string form, DOMAIN\NAME+ * or NAME where the account has no domain, to *name for the caller to+ * release with LocalFree; *name is NULL where no account has the SID. */+unsigned long nn_account_name(const wchar_t *sid, wchar_t **name,+                              const char **failed);++#endif  #endif
+ cli/Nix/Cli/Args.hs view
@@ -0,0 +1,923 @@+-- | The command line's grammar: the argument vector parsed into the+-- command to run and the flags that shape it.+--+-- What each command and flag means is documented in "Nix.Cli.Reference",+-- which @--help@ prints.  The test suite checks every flag that reference+-- lists against this parser: each command listed for a flag accepts it,+-- and the flag takes the values its entry names, and none when it names+-- none.  The parser also accepts some flags where they have no effect,+-- such as @--strict@ before @build@, which the reference does not list.+module Nix.Cli.Args+  ( CliOpts (..),+    Command (..),+    storeFlagOf,+    Target (..),+    fileTarget,+    AutoArg (..),+    OutLink (..),+    outLinkFor,+    DevelopArgs (..),+    DevEnvFormat (..),+    TrustFormat (..),+    PushArgs (..),+    ProfileSelection (..),+    RemoveSelection (..),+    RemoveMatcher (..),+    ListFormat (..),+    JsonLayout (..),+    parseArgs,+  )+where++import Data.List.NonEmpty (NonEmpty (..))+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (listToMaybe)+import Data.Set (Set)+import qualified Data.Set as Set+import qualified Data.Text as T+import Nix.Builder.Sandbox (SandboxMode (..))+import Nix.Daemon.Listen (TrustOverride (..))+import Nix.Daemon.StoreChoice (StoreFlag (..))+import Nix.Develop.Shell (EnvironmentBase (..))+import Nix.Profile.Generation (Changes (..))++-- | Parsed CLI options.+data CliOpts = CliOpts+  { optNixPaths :: ![T.Text],+    -- | @--arg@ and @--argstr@: what a function the target evaluates to+    -- is called with, by name as the command line spells it.  A later+    -- flag for a name replaces an earlier one, as upstream's+    -- @insert_or_assign@ does (in the @--arg@ and @--argstr@ handlers of the+    -- @MixEvalArgs@ constructor, common-eval-args.cc).+    optAutoArgs :: !(Map String AutoArg),+    optStrict :: !Bool,+    optAterm :: !Bool,+    -- | The store the command uses, as @--store@ spells it: @auto@,+    -- @daemon@, @unix:\/\/PATH@, @local@ or a store directory.  It+    -- overrides the @store@ setting and @NIX_REMOTE@, and is read as the+    -- store by the commands that open it ("Nix.Daemon.StoreChoice").+    optStore :: !(Maybe FilePath),+    -- | Binary cache URL to substitute from before building.+    optSubstituter :: !(Maybe String),+    -- | A public key (@name:base64@) trusted for every substituter's+    -- signatures, the configured ones included.+    optTrustedKey :: !(Maybe String),+    -- | @SYSTEM=PATH@ launchers for derivations this machine cannot execute+    -- directly, e.g. @x86_64-windows=/path/to/wine@.+    optExecWrappers :: ![String],+    -- | @--restrict-eval@: upstream's restrict-eval, turned on for this run.+    optRestrictEval :: !Bool,+    -- | @--pure-eval@: upstream's pure-eval, turned on for this run.+    optPureEval :: !Bool,+    -- | @--trace-verbose@: upstream's trace-verbose, turned on for this run.+    optTraceVerbose :: !Bool,+    -- | @--no-allow-import-from-derivation@: upstream's+    -- allow-import-from-derivation, turned off for this run.+    optNoAllowImportFromDerivation :: !Bool,+    -- | @--fallback@: upstream's fallback, turned on for this run.+    optFallback :: !Bool,+    -- | @--keep-failed@ or @-K@: upstream's keep-failed, turned on for this+    -- run.+    optKeepFailed :: !Bool,+    -- | @--check@: the build checks its derivation, as @nix-build --check@+    -- does.+    optCheck :: !Bool,+    -- | @--read-write-mode@: @eval@ writes what evaluation makes to the+    -- store and builds or substitutes what a path's context names, as+    -- @nix-instantiate --eval --read-write-mode@ does; without it, eval+    -- realises those with every substitution refused.+    optReadWriteMode :: !Bool,+    -- | @--sandbox@, @--no-sandbox@ or @--relaxed-sandbox@, the last given:+    -- upstream's @sandbox@ on this run.+    optSandbox :: !(Maybe SandboxMode),+    -- | Each @--extra-experimental-features@ value, in order: features+    -- turned on for this run beside those the configuration turns on.+    optExtraExperimentalFeatures :: ![String],+    optCommand :: !Command+  }+  deriving (Eq, Show)++-- | The command an invocation runs.+data Command+  = -- | @eval@: evaluate the target and print its value, or under+    -- @--aterm@ the ATerm of the derivation it evaluates to.+    CmdEval !Target+  | CmdBuild !Target !(Maybe T.Text) !OutLink+  | -- | @develop@: start a shell with the build environment of the+    -- target's derivation, at the attribute path when one is given.+    CmdDevelop !Target !(Maybe T.Text) !DevelopArgs+  | -- | @print-dev-env@: print that environment, with JSON laid out as+    -- the layout says.+    CmdPrintDevEnv !Target !(Maybe T.Text) !DevEnvFormat !JsonLayout+  | -- | @trust@: report what the closure of the target's derivation, at+    -- the attribute path when one is given, relies on, in the format+    -- given, with JSON laid out as the layout says.+    CmdTrust !Target !(Maybe T.Text) !TrustFormat !JsonLayout+  | CmdPush !PushArgs+  | CmdStoreDelete ![String]+  | -- | @store gc@: collect, or with the flag only list the roots.+    CmdStoreGc !Bool+  | -- | @profile add@: add the target's derivation, built, or a store+    -- path a file argument leads to, to a profile, with the attribute+    -- path when one is given, and the priority @--priority@ gives, as the+    -- command line spells it.+    CmdProfileAdd !Target !(Maybe T.Text) !ProfileSelection !(Maybe String)+  | -- | @profile remove@: take what the selection selects off a profile.+    CmdProfileRemove !ProfileSelection !RemoveSelection+  | -- | @profile list@: print what a profile holds.+    CmdProfileList !ProfileSelection !ListFormat+  | -- | @profile history@: print a profile's generations and what+    -- changed in each.+    CmdProfileHistory !ProfileSelection+  | -- | @profile rollback@: switch a profile to the generation before the+    -- current one, or to the one @--to@ names, each @--to@ as the command+    -- line spells it, in order.+    CmdProfileRollback !ProfileSelection ![String] !Changes+  | -- | @profile wipe-history@: delete a profile's generations but the+    -- current one, or with @--older-than@, as the command line spells its+    -- age, those older than that but the newest of them.+    CmdProfileWipeHistory !ProfileSelection !(Maybe String) !Changes+  | -- | @key generate-secret@: print a new secret key with the name+    -- @--key-name@ gives, as the command line spells it.+    CmdKeyGenerateSecret !String+  | -- | @key convert-secret-to-public@: print the public key of the+    -- secret key on standard input.+    CmdKeyConvertSecretToPublic+  | -- | @daemon@: serve the store to clients over a socket, trusting them+    -- as the override says, at the socket path given, as the command line+    -- spells it, or the default one.+    CmdDaemon !TrustOverride !(Maybe String)+  | -- | No command given, or @eval@ given no target.  Usage on stderr,+    -- non-zero: a bare invocation is+    -- a usage error, and a caller testing the exit status must see one.+    CmdUsage+  | -- | @--help@.  The same text on stdout, zero: it is a request that+    -- succeeded, and pipeable without redirecting stderr.+    CmdHelp+  | CmdVersion+  deriving (Eq, Show)++-- | How a command's @--store@ flag sets the @store@ setting, which only a+-- command that reaches a daemon makes use of.  @develop@, @print-dev-env@+-- and the profile commands that change a profile model upstream's @nix@+-- command, whose flag is the one every setting has ('SettingFlag').  The+-- rest take it as a value alone ('ValueFlag'): @eval@ and @build@ model+-- @nix-instantiate@ and @nix-build@, whose flag does not mark the setting,+-- and the others reach no daemon or have no upstream command.+storeFlagOf :: Command -> StoreFlag+storeFlagOf (CmdDevelop {}) = SettingFlag+storeFlagOf (CmdPrintDevEnv {}) = SettingFlag+storeFlagOf (CmdProfileAdd {}) = SettingFlag+storeFlagOf (CmdProfileRemove {}) = SettingFlag+storeFlagOf (CmdEval {}) = ValueFlag+storeFlagOf (CmdBuild {}) = ValueFlag+storeFlagOf (CmdTrust {}) = ValueFlag+storeFlagOf (CmdPush {}) = ValueFlag+storeFlagOf (CmdStoreDelete {}) = ValueFlag+storeFlagOf (CmdStoreGc {}) = ValueFlag+storeFlagOf (CmdProfileList {}) = ValueFlag+storeFlagOf (CmdProfileHistory {}) = ValueFlag+storeFlagOf (CmdProfileRollback {}) = ValueFlag+storeFlagOf (CmdProfileWipeHistory {}) = ValueFlag+storeFlagOf (CmdKeyGenerateSecret {}) = ValueFlag+storeFlagOf CmdKeyConvertSecretToPublic = ValueFlag+storeFlagOf (CmdDaemon {}) = ValueFlag+storeFlagOf CmdUsage = ValueFlag+storeFlagOf CmdHelp = ValueFlag+storeFlagOf CmdVersion = ValueFlag++-- | Where a command's expression comes from.  A name or an expression is+-- the argument as 'System.Environment.getArgs' gave it, whose bytes the+-- command reads ("Nix.Environment"'s @argumentBytes@), as upstream reads+-- the bytes it was given.+data Target+  = -- | A @.nix@ file, or a directory standing for its @default.nix@, as+    -- upstream's @resolveExprPath@ reads one (eval.cc).  Relative paths+    -- inside it resolve beside the file.+    TargetFile !FilePath+  | -- | @\<NAME\>@: the file the search path finds for the name, found+    -- and read as @import \<NAME\>@ in an expression finds and reads it.+    TargetSearchPath !String+  | -- | An inline expression.  Relative paths inside it resolve against the+    -- working directory, since there is no file to sit beside.+    TargetExpr !String+  deriving (Eq, Show)++-- | The target a file argument names: a search path lookup when it is+-- longer than two characters and written in angle brackets, as upstream's+-- @lookupFileArg@ reads one (common-eval-args.cc), and otherwise a file or+-- directory.+fileTarget :: String -> Target+fileTarget arg = case arg of+  '<' : rest+    | '>' : nameReversed@(_ : _) <- reverse rest -> TargetSearchPath (reverse nameReversed)+  _ -> TargetFile arg++-- | A value the function a target evaluates to is called with, the+-- argument as 'System.Environment.getArgs' gave it, whose bytes the+-- command reads.+data AutoArg+  = -- | @--arg@: an expression, evaluated in the root environment when+    -- the function uses it, its relative paths resolved against the+    -- working directory.+    AutoArgExpr !String+  | -- | @--argstr@: a string holding the argument's bytes.+    AutoArgString !String+  deriving (Eq, Show)++-- | Where a build links its output.+data OutLink+  = -- | Link it from a name made from this path ('outLinkFor'), and+    -- register the link as a GC root.+    OutLinkAt !FilePath+  | -- | @--no-out-link@: link nothing.  nix-build links into a temporary+    -- directory it deletes on exit (@main_nix_build@ in nix-build.cc), which+    -- leaves a dangling record that its next collection removes+    -- (@LocalStore::findRoots@ in gc.cc); linking nothing leaves the same,+    -- less the record.+    NoOutLink+  deriving (Eq, Show)++-- | What a build links its output from until a flag says otherwise:+-- nix-build's @.\/result@ (@main_nix_build@ in nix-build.cc).+defaultOutLink :: OutLink+defaultOutLink = OutLinkAt "result"++-- | The output whose link is the out-link's path itself.+unsuffixedOutput :: T.Text+unsuffixedOutput = "out"++-- | The link a build of the named output creates, if any: the out-link's+-- path for the output @out@, and the path with @-NAME@ appended for any+-- other, as nix-build names its links (@main_nix_build@ in nix-build.cc).+-- nix-build also appends @-2@, @-3@ and so on for the second and later+-- derivations it builds; a build here builds one.+outLinkFor :: OutLink -> T.Text -> Maybe FilePath+outLinkFor outLink outputName = case outLink of+  NoOutLink -> Nothing+  OutLinkAt path+    | outputName == unsuffixedOutput -> Just path+    | otherwise -> Just (path <> "-" <> T.unpack outputName)++-- | The profile a profile command works on.+data ProfileSelection+  = -- | The default profile.+    DefaultProfile+  | -- | The profile @--profile@ names, as the command line spells it.+    ProfileAt !FilePath+  deriving (Eq, Show)++-- | What @profile remove@ takes off.  Upstream refuses a line that+-- selects nothing, and @--all@ beside any other selector, as usage errors+-- (@MixProfileElementMatchers::getMatchingElementNames@ in profile.cc), so+-- neither is a selection.+data RemoveSelection+  = -- | @--all@: every element.+    RemoveAll+  | -- | The elements any of these select, the flags' first.+    RemoveSome !(NonEmpty RemoveMatcher)+  deriving (Eq, Show)++-- | One selector of @profile remove@, as the command line spells it.+data RemoveMatcher+  = -- | An element's name or a store path an element holds.+    RemoveNamed !String+  | -- | @--regex@: the elements whose identifier a pattern matches.+    RemoveRegex !String+  deriving (Eq, Show)++-- | How @profile list@ prints.+data ListFormat+  = -- | Upstream's lines for each element.+    ListText+  | -- | @--json@: the manifest's JSON, laid out so.+    ListJson !JsonLayout+  deriving (Eq, Show)++-- | How @profile list --json@, @print-dev-env --json@ and @trust --json@+-- lay out their JSON, as upstream's @MixPrintJSON@ chooses (common-args.hh,+-- from 2.34.9): @--pretty@ and @--no-pretty@ set it, the last one given+-- winning.+data JsonLayout+  = -- | Indented when stdout is a terminal, on one line otherwise:+    -- upstream's default.+    IndentedOnTerminal+  | -- | @--pretty@: indented.+    Indented+  | -- | @--no-pretty@: on one line.+    Compact+  deriving (Eq, Show)++-- | What @profile list@ is printing while its line is parsed.+data ListOutput = TextOutput | JsonOutput++-- | A selector of @profile remove@ while its line is parsed.+data Selected = SelectedAll | Selected !RemoveMatcher++-- | A command that changes which generation of a profile is current, or+-- which generations it has, taking one value flag and @--dry-run@.+data GenerationCommand+  = -- | @profile rollback@, whose flag is @--to@.+    RollsBack+  | -- | @profile wipe-history@, whose flag is @--older-than@.+    WipesHistory++-- | The words that select a generation command.+generationWord :: GenerationCommand -> String+generationWord kind = case kind of+  RollsBack -> "profile rollback"+  WipesHistory -> "profile wipe-history"++-- | The flag a generation command takes a value with.+generationValueFlag :: GenerationCommand -> String+generationValueFlag kind = case kind of+  RollsBack -> "--to"+  WipesHistory -> "--older-than"++-- | What @develop@ runs in place of an interactive shell, and how it+-- changes the shell's environment, as the command line gives them, each+-- name, value and word as 'System.Environment.getArgs' gave it.  The+-- refusals upstream makes only once the environment is built,+-- @--command@ beside a phase and an environment flag that makes no sense+-- with @--ignore-env@ or without it, are made then here too+-- ("Nix.Develop.Shell").+data DevelopArgs = DevelopArgs+  { -- | @--command@: every argument after it.+    daCommand :: !(Maybe (NonEmpty String)),+    -- | The phase @--phase@ or a phase flag named, the last one given.+    daPhase :: !(Maybe String),+    -- | @--ignore-env@.+    daEnvironmentBase :: !EnvironmentBase,+    -- | @--keep-env-var@'s names.+    daKeep :: !(Set String),+    -- | @--unset-env-var@'s names.+    daUnset :: !(Set String),+    -- | @--set-env-var@'s names, each with its value.+    daSet :: !(Map String String)+  }+  deriving (Eq, Show)++-- | @develop@'s arguments before any flag is parsed: an interactive shell+-- in the caller's environment.+emptyDevelopArgs :: DevelopArgs+emptyDevelopArgs = DevelopArgs Nothing Nothing CallerEnvironment Set.empty Set.empty Map.empty++-- | What @print-dev-env@ prints.+data DevEnvFormat+  = -- | The script that sets the environment.+    DevEnvScript+  | -- | @--json@: the environment as JSON.+    DevEnvJson+  deriving (Eq, Show)++-- | What @trust@ prints.+data TrustFormat+  = -- | The report's lines.+    TrustLines+  | -- | @--json@: the report as one JSON document.+    TrustJson+  deriving (Eq, Show)++-- | A command that evaluates one target to a derivation.+data TargetCommand+  = -- | @build@, which builds it.+    BuildsTarget+  | -- | @develop@, which starts a shell with its build environment.+    DevelopsTarget+  | -- | @print-dev-env@, which prints that environment.+    PrintsDevEnv+  | -- | @trust@, which reports what its closure relies on.+    TrustsTarget+  | -- | @profile add@, which builds it and adds it to a profile.+    AddsToProfile++-- | The words that select a target command.+targetWord :: TargetCommand -> String+targetWord kind = case kind of+  BuildsTarget -> "build"+  DevelopsTarget -> "develop"+  PrintsDevEnv -> "print-dev-env"+  TrustsTarget -> "trust"+  AddsToProfile -> "profile add"++-- | Whether a target command builds what it evaluates, and so takes the+-- launchers @--exec-wrapper@ names.  @develop@ and @print-dev-env@ build+-- a capture whose environment a shell on this host reads, which a+-- launcher for another system cannot serve, so they take none.+buildsTarget :: TargetCommand -> Bool+buildsTarget kind = case kind of+  BuildsTarget -> True+  AddsToProfile -> True+  DevelopsTarget -> False+  PrintsDevEnv -> False+  TrustsTarget -> False++-- | Whether a target command runs builders whose directories+-- @keep-failed@ can keep.  @trust@ builds only with builtins, which keep+-- nothing, so it takes no flag for the setting.+runsBuilders :: TargetCommand -> Bool+runsBuilders kind = case kind of+  BuildsTarget -> True+  AddsToProfile -> True+  DevelopsTarget -> True+  PrintsDevEnv -> True+  TrustsTarget -> False++-- | Arguments to a target command, while the target is still unknown.+data BuildArgs = BuildArgs+  { baTarget :: !(Maybe Target),+    baAttrPath :: !(Maybe T.Text),+    -- | Where @build@ links its output.  Only @build@ takes a flag that+    -- sets it.+    baOutLink :: !OutLink,+    -- | The profile @profile add@ adds to.  Only @profile add@ takes a+    -- flag that sets it.+    baProfile :: !ProfileSelection,+    -- | The priority @profile add@ gives what it adds.  Only+    -- @profile add@ takes a flag that sets it.+    baPriority :: !(Maybe String),+    -- | What @develop@ runs, and its shell's environment.  Only @develop@+    -- takes a flag that sets them.+    baDevelop :: !DevelopArgs,+    -- | What @print-dev-env@ prints.  Only @print-dev-env@ takes a flag+    -- that sets it.+    baFormat :: !DevEnvFormat,+    -- | What @trust@ prints.  Only @trust@ takes a flag that sets it.+    baTrustFormat :: !TrustFormat,+    -- | How @print-dev-env@ and @trust@ lay out their JSON.  Only they+    -- take a flag that sets it.+    baJsonLayout :: !JsonLayout+  }++-- | Target command arguments before any flag is parsed.+emptyBuildArgs :: BuildArgs+emptyBuildArgs = BuildArgs Nothing Nothing defaultOutLink DefaultProfile Nothing emptyDevelopArgs DevEnvScript TrustLines IndentedOnTerminal++-- | Arguments to the push command.+data PushArgs = PushArgs+  { paCacheUrl :: !(Maybe String),+    paKeyFile :: !(Maybe FilePath),+    -- | The file holding the secret key that signs a directory cache's+    -- narinfos.+    paSecretKeyFile :: !(Maybe FilePath),+    paCompressionArg :: !(Maybe String),+    paAll :: !Bool,+    paPaths :: ![String]+  }+  deriving (Eq, Show)++-- | Push arguments before any flag is parsed.+emptyPushArgs :: PushArgs+emptyPushArgs = PushArgs Nothing Nothing Nothing Nothing False []++-- | Parse the command line.  A malformed invocation is an error, never a+-- silent drop: an unknown or misspelled flag fails the parse, so nothing+-- after it (a requested @--substituter@, say) is quietly discarded.+parseArgs :: [String] -> Either String CliOpts+parseArgs = go (CliOpts [] Map.empty False False Nothing Nothing Nothing [] False False False False False False False False Nothing [] CmdUsage)+  where+    go opts [] = Right opts+    go opts (flag : _) | Just answer <- answered flag = Right opts {optCommand = answer}+    go opts ("--nix-path" : val : rest) =+      go (opts {optNixPaths = optNixPaths opts ++ [T.pack val]}) rest+    go opts (flag : features : rest)+      | flag == extraFeaturesFlag = go (withFeatures features opts) rest+    go opts (flag : name : value : rest)+      | Just arg <- autoArg flag value = go (withAutoArg name arg opts) rest+    go opts ("--strict" : rest) =+      go (opts {optStrict = True}) rest+    go opts ("--aterm" : rest) =+      go (opts {optAterm = True}) rest+    go opts ("--store" : dir : rest) =+      go (opts {optStore = Just dir}) rest+    go opts ("--substituter" : url : rest) =+      go (opts {optSubstituter = Just url}) rest+    go opts ("--trusted-key" : key : rest) =+      go (opts {optTrustedKey = Just key}) rest+    go opts ("--exec-wrapper" : spec : rest) =+      go (opts {optExecWrappers = optExecWrappers opts ++ [spec]}) rest+    go opts ("--restrict-eval" : rest) =+      go (opts {optRestrictEval = True}) rest+    go opts ("--pure-eval" : rest) =+      go (opts {optPureEval = True}) rest+    go opts ("--trace-verbose" : rest) =+      go (opts {optTraceVerbose = True}) rest+    go opts ("--no-allow-import-from-derivation" : rest) =+      go (opts {optNoAllowImportFromDerivation = True}) rest+    go opts ("--fallback" : rest) =+      go (opts {optFallback = True}) rest+    go opts (flag : rest)+      | flag `elem` keepFailedFlags = go (opts {optKeepFailed = True}) rest+    go opts ("--read-write-mode" : rest) =+      go (opts {optReadWriteMode = True}) rest+    go opts (flag : rest)+      | Just mode <- sandboxFlag flag = go (opts {optSandbox = Just mode}) rest+    go opts ("eval" : rest) = goEval opts rest+    go opts ("build" : rest) = goTarget BuildsTarget opts emptyBuildArgs rest+    go opts ("develop" : rest) = goTarget DevelopsTarget opts emptyBuildArgs rest+    go opts ("print-dev-env" : rest) = goTarget PrintsDevEnv opts emptyBuildArgs rest+    go opts ("trust" : rest) = goTarget TrustsTarget opts emptyBuildArgs rest+    go opts ("push" : rest) = goPush opts emptyPushArgs rest+    go opts ("store" : rest) = goStore opts rest+    go opts ("profile" : rest) = goProfile opts rest+    go opts ("key" : rest) = goKey opts rest+    go opts ("daemon" : rest) = goDaemon opts DefaultTrust Nothing rest+    go _ [flag]+      | flag `elem` valueFlags = Left (flag ++ " requires a value")+    go _ (flag : _)+      | flag `elem` autoArgFlags = Left (flag ++ autoArgShortfall)+    go _ (arg : _) = Left ("unknown argument: " ++ arg ++ " (run nova-nix --help for usage)")+    -- Sub-parser for eval: handles --strict and --expr interleaved with the file arg.+    goEval opts [] = Right opts+    goEval opts (flag : _) | Just answer <- answered flag = Right opts {optCommand = answer}+    goEval opts ("--strict" : rest) = goEval (opts {optStrict = True}) rest+    goEval opts ("--aterm" : rest) = goEval (opts {optAterm = True}) rest+    goEval opts ("--nix-path" : val : rest) =+      goEval (opts {optNixPaths = optNixPaths opts ++ [T.pack val]}) rest+    goEval opts (flag : features : rest)+      | flag == extraFeaturesFlag = goEval (withFeatures features opts) rest+    goEval opts (flag : name : value : rest)+      | Just arg <- autoArg flag value = goEval (withAutoArg name arg opts) rest+    -- Accepted here as well as at the top level, like build and push:+    -- eval-side reads follow the selected store, so the flag means as+    -- much after the subcommand as before it.+    goEval opts ("--store" : dir : rest) =+      goEval (opts {optStore = Just dir}) rest+    goEval opts ("--restrict-eval" : rest) =+      goEval (opts {optRestrictEval = True}) rest+    goEval opts ("--pure-eval" : rest) =+      goEval (opts {optPureEval = True}) rest+    goEval opts ("--trace-verbose" : rest) =+      goEval (opts {optTraceVerbose = True}) rest+    goEval opts ("--no-allow-import-from-derivation" : rest) =+      goEval (opts {optNoAllowImportFromDerivation = True}) rest+    goEval opts ("--fallback" : rest) =+      goEval (opts {optFallback = True}) rest+    goEval opts (flag : rest)+      | flag `elem` keepFailedFlags = goEval (opts {optKeepFailed = True}) rest+    goEval opts ("--read-write-mode" : rest) =+      goEval (opts {optReadWriteMode = True}) rest+    goEval opts ("--substituter" : url : rest) =+      goEval (opts {optSubstituter = Just url}) rest+    goEval opts ("--trusted-key" : key : rest) =+      goEval (opts {optTrustedKey = Just key}) rest+    goEval opts ("--exec-wrapper" : spec : rest) =+      goEval (opts {optExecWrappers = optExecWrappers opts ++ [spec]}) rest+    goEval opts (flag : rest)+      | Just mode <- sandboxFlag flag = goEval (opts {optSandbox = Just mode}) rest+    goEval opts ("--expr" : expr : rest) =+      go (opts {optCommand = CmdEval (TargetExpr expr)}) rest+    goEval _ [flag]+      | flag `elem` valueFlags = Left (flag ++ " requires a value")+    goEval _ (flag : _)+      | flag `elem` autoArgFlags = Left (flag ++ autoArgShortfall)+    goEval _ (arg@('-' : _) : _) = Left ("unknown eval flag: " ++ arg)+    goEval opts (path : rest) =+      go (opts {optCommand = CmdEval (fileTarget path)}) rest+    -- Sub-parser for the target commands (build, develop, print-dev-env,+    -- trust and profile add): the target, -A, and the shared flags in any+    -- order, and each command's own flags.  The shared flags are+    -- handled here rather than deferred back to 'go' so that one can follow+    -- the file argument, which is where a caller reaches for it, and so+    -- that -A is still recognised after it.+    goTarget kind opts targetArgs [] = finishTarget kind opts targetArgs+    goTarget _ opts _ (flag : _) | Just answer <- answered flag = Right opts {optCommand = answer}+    goTarget kind opts targetArgs ("--store" : dir : rest) =+      goTarget kind (opts {optStore = Just dir}) targetArgs rest+    goTarget kind opts targetArgs ("--substituter" : url : rest) =+      goTarget kind (opts {optSubstituter = Just url}) targetArgs rest+    goTarget kind opts targetArgs ("--trusted-key" : key : rest) =+      goTarget kind (opts {optTrustedKey = Just key}) targetArgs rest+    goTarget kind opts targetArgs ("--nix-path" : val : rest) =+      goTarget kind (opts {optNixPaths = optNixPaths opts ++ [T.pack val]}) targetArgs rest+    goTarget kind opts targetArgs (flag : features : rest)+      | flag == extraFeaturesFlag = goTarget kind (withFeatures features opts) targetArgs rest+    goTarget kind opts targetArgs (flag : name : value : rest)+      | Just arg <- autoArg flag value = goTarget kind (withAutoArg name arg opts) targetArgs rest+    goTarget kind opts targetArgs ("--exec-wrapper" : spec : rest)+      | buildsTarget kind = goTarget kind (opts {optExecWrappers = optExecWrappers opts ++ [spec]}) targetArgs rest+    goTarget kind opts targetArgs ("--restrict-eval" : rest) =+      goTarget kind (opts {optRestrictEval = True}) targetArgs rest+    goTarget kind opts targetArgs ("--pure-eval" : rest) =+      goTarget kind (opts {optPureEval = True}) targetArgs rest+    goTarget kind opts targetArgs ("--trace-verbose" : rest) =+      goTarget kind (opts {optTraceVerbose = True}) targetArgs rest+    goTarget kind opts targetArgs ("--no-allow-import-from-derivation" : rest) =+      goTarget kind (opts {optNoAllowImportFromDerivation = True}) targetArgs rest+    goTarget kind opts targetArgs ("--fallback" : rest) =+      goTarget kind (opts {optFallback = True}) targetArgs rest+    goTarget kind opts targetArgs (flag : rest)+      | flag `elem` keepFailedFlags, runsBuilders kind = goTarget kind (opts {optKeepFailed = True}) targetArgs rest+    goTarget BuildsTarget opts targetArgs ("--check" : rest) =+      goTarget BuildsTarget (opts {optCheck = True}) targetArgs rest+    goTarget kind opts targetArgs (flag : rest)+      | Just mode <- sandboxFlag flag = goTarget kind (opts {optSandbox = Just mode}) targetArgs rest+    goTarget kind opts targetArgs ("--expr" : expr : rest) =+      withTarget kind opts targetArgs (TargetExpr expr) rest+    goTarget kind opts targetArgs (flag : path : rest)+      | flag `elem` attrFlags = case baAttrPath targetArgs of+          Just _ -> Left (targetWord kind ++ " accepts one attribute path")+          Nothing -> goTarget kind opts (targetArgs {baAttrPath = Just (T.pack path)}) rest+    -- Each link flag replaces what the flags before it said, so the+    -- later one wins, as nix-build assigns its outLink as it reads each+    -- (main_nix_build in nix-build.cc).+    goTarget BuildsTarget opts targetArgs (flag : path : rest)+      | flag `elem` outLinkFlags = goTarget BuildsTarget opts (targetArgs {baOutLink = OutLinkAt path}) rest+    goTarget BuildsTarget opts targetArgs (flag : rest)+      | flag `elem` noOutLinkFlags = goTarget BuildsTarget opts (targetArgs {baOutLink = NoOutLink}) rest+    goTarget AddsToProfile opts targetArgs ("--profile" : path : rest) =+      goTarget AddsToProfile opts (targetArgs {baProfile = ProfileAt path}) rest+    goTarget AddsToProfile opts targetArgs ("--priority" : priority : rest) =+      goTarget AddsToProfile opts (targetArgs {baPriority = Just priority}) rest+    -- Every argument after --command is the command's, a flag or --help+    -- included, as upstream's flag of any arity takes them+    -- (Args::processFlag in args.cc), and one is needed (the --command+    -- handler in CmdDevelop's constructor, develop.cc).+    goTarget DevelopsTarget opts targetArgs (flag : rest)+      | flag `elem` commandFlags = case rest of+          [] -> Left "error: --command requires at least one argument"+          first : more -> finishTarget DevelopsTarget opts (developing targetArgs (\args -> args {daCommand = Just (first :| more)}))+    goTarget DevelopsTarget opts targetArgs ("--phase" : phase : rest) =+      goTarget DevelopsTarget opts (developing targetArgs (\args -> args {daPhase = Just phase})) rest+    goTarget DevelopsTarget opts targetArgs (flag : rest)+      | Just phase <- lookup flag phaseFlags = goTarget DevelopsTarget opts (developing targetArgs (\args -> args {daPhase = Just phase})) rest+      | flag `elem` ignoreEnvFlags = goTarget DevelopsTarget opts (developing targetArgs (\args -> args {daEnvironmentBase = EmptyEnvironment})) rest+    -- The refusals upstream's flag handlers make as they read+    -- --unset-env-var and --set-env-var (the MixEnvironment constructor in+    -- command.cc, from 2.34.9), each after error:, as nova-nix reports+    -- upstream's errors.+    goTarget DevelopsTarget opts targetArgs (flag : name : rest)+      | flag `elem` keepFlags = goTarget DevelopsTarget opts (developing targetArgs (\args -> args {daKeep = Set.insert name (daKeep args)})) rest+      | flag `elem` unsetFlags,+        Map.member name (daSet (baDevelop targetArgs)) =+          Left ("error: Cannot unset environment variable '" ++ name ++ "' that is set with '--set-env-var'")+      | flag `elem` unsetFlags = goTarget DevelopsTarget opts (developing targetArgs (\args -> args {daUnset = Set.insert name (daUnset args)})) rest+    goTarget DevelopsTarget opts targetArgs (flag : name : value : rest)+      | flag `elem` setFlags,+        Set.member name (daUnset (baDevelop targetArgs)) =+          Left ("error: Cannot set environment variable '" ++ name ++ "' that is unset with '--unset-env-var'")+      | flag `elem` setFlags,+        Map.member name (daSet (baDevelop targetArgs)) =+          Left ("error: Duplicate definition of environment variable '" ++ name ++ "' with '--set-env-var' is ambiguous")+      | flag `elem` setFlags = goTarget DevelopsTarget opts (developing targetArgs (\args -> args {daSet = Map.insert name value (daSet args)})) rest+    goTarget DevelopsTarget _ _ [flag]+      | flag `elem` developValueFlags = Left (flag ++ " requires a value")+    goTarget DevelopsTarget _ _ (flag : _)+      | flag `elem` setFlags = Left (flag ++ " requires a name and a value")+    goTarget PrintsDevEnv opts targetArgs ("--json" : rest) =+      goTarget PrintsDevEnv opts (targetArgs {baFormat = DevEnvJson}) rest+    goTarget PrintsDevEnv opts targetArgs ("--pretty" : rest) =+      goTarget PrintsDevEnv opts (targetArgs {baJsonLayout = Indented}) rest+    goTarget PrintsDevEnv opts targetArgs ("--no-pretty" : rest) =+      goTarget PrintsDevEnv opts (targetArgs {baJsonLayout = Compact}) rest+    goTarget TrustsTarget opts targetArgs ("--json" : rest) =+      goTarget TrustsTarget opts (targetArgs {baTrustFormat = TrustJson}) rest+    goTarget TrustsTarget opts targetArgs ("--pretty" : rest) =+      goTarget TrustsTarget opts (targetArgs {baJsonLayout = Indented}) rest+    goTarget TrustsTarget opts targetArgs ("--no-pretty" : rest) =+      goTarget TrustsTarget opts (targetArgs {baJsonLayout = Compact}) rest+    goTarget _ _ _ [flag]+      | flag `elem` valueFlags = Left (flag ++ " requires a value")+    goTarget _ _ _ (flag : _)+      | flag `elem` autoArgFlags = Left (flag ++ autoArgShortfall)+    goTarget kind _ _ (arg@('-' : _) : _) = Left ("unknown " ++ targetWord kind ++ " flag: " ++ arg)+    goTarget kind opts targetArgs (path : rest) =+      withTarget kind opts targetArgs (fileTarget path) rest+    -- A target command evaluates one expression, so a second target is a+    -- mistake worth naming rather than a silent last-one-wins.+    withTarget kind opts targetArgs target rest = case baTarget targetArgs of+      Just _ -> Left (targetWord kind ++ " takes one PATH, <NAME> or --expr, not two")+      Nothing -> goTarget kind opts (targetArgs {baTarget = Just target}) rest+    finishTarget kind opts targetArgs = case (baTarget targetArgs, kind) of+      (Nothing, _) -> Left (targetWord kind ++ " requires a PATH, <NAME> or --expr EXPR")+      (Just target, BuildsTarget) -> Right opts {optCommand = CmdBuild target (baAttrPath targetArgs) (baOutLink targetArgs)}+      (Just target, DevelopsTarget) -> Right opts {optCommand = CmdDevelop target (baAttrPath targetArgs) (baDevelop targetArgs)}+      (Just target, PrintsDevEnv) -> Right opts {optCommand = CmdPrintDevEnv target (baAttrPath targetArgs) (baFormat targetArgs) (baJsonLayout targetArgs)}+      (Just target, TrustsTarget) -> Right opts {optCommand = CmdTrust target (baAttrPath targetArgs) (baTrustFormat targetArgs) (baJsonLayout targetArgs)}+      (Just target, AddsToProfile) -> Right opts {optCommand = CmdProfileAdd target (baAttrPath targetArgs) (baProfile targetArgs) (baPriority targetArgs)}+    -- Sub-parser for push: flags and explicit store paths in any order.+    goPush opts pushArgs [] = Right opts {optCommand = CmdPush pushArgs}+    goPush opts _ (flag : _) | Just answer <- answered flag = Right opts {optCommand = answer}+    goPush opts pushArgs ("--store" : dir : rest) =+      goPush (opts {optStore = Just dir}) pushArgs rest+    goPush opts pushArgs ("--cache" : url : rest) =+      goPush opts (pushArgs {paCacheUrl = Just url}) rest+    goPush opts pushArgs ("--key-file" : path : rest) =+      goPush opts (pushArgs {paKeyFile = Just path}) rest+    goPush opts pushArgs ("--secret-key-file" : path : rest) =+      goPush opts (pushArgs {paSecretKeyFile = Just path}) rest+    goPush opts pushArgs ("--compression" : value : rest) =+      goPush opts (pushArgs {paCompressionArg = Just value}) rest+    goPush opts pushArgs ("--all" : rest) =+      goPush opts (pushArgs {paAll = True}) rest+    goPush _ _ [flag]+      | flag `elem` valueFlags = Left (flag ++ " requires a value")+    goPush _ _ (arg@('-' : _) : _) = Left ("unknown push flag: " ++ arg)+    goPush opts pushArgs (path : rest) =+      goPush opts (pushArgs {paPaths = paPaths pushArgs ++ [path]}) rest+    -- Sub-parser for store maintenance verbs.+    goStore _ [] = Left "store: expected a subcommand (delete, gc)"+    goStore opts (flag : _) | Just answer <- answered flag = Right opts {optCommand = answer}+    goStore opts ("delete" : rest) = goStoreDelete opts [] rest+    goStore opts ("gc" : rest) = goStoreGc opts False rest+    goStore _ (sub : _) = Left ("unknown store subcommand: " ++ sub ++ " (expected: delete, gc)")+    goStoreDelete opts paths []+      | null paths = Left "store delete: name at least one store path"+      | otherwise = Right opts {optCommand = CmdStoreDelete paths}+    goStoreDelete opts _ (flag : _) | Just answer <- answered flag = Right opts {optCommand = answer}+    goStoreDelete opts paths ("--store" : dir : rest) =+      goStoreDelete (opts {optStore = Just dir}) paths rest+    goStoreDelete _ _ [flag]+      | flag `elem` valueFlags = Left (flag ++ " requires a value")+    goStoreDelete _ _ (arg@('-' : _) : _) = Left ("unknown store delete flag: " ++ arg)+    goStoreDelete opts paths (path : rest) =+      goStoreDelete opts (paths ++ [path]) rest+    goStoreGc opts printRoots [] = Right opts {optCommand = CmdStoreGc printRoots}+    goStoreGc opts _ (flag : _) | Just answer <- answered flag = Right opts {optCommand = answer}+    goStoreGc opts printRoots ("--store" : dir : rest) =+      goStoreGc (opts {optStore = Just dir}) printRoots rest+    goStoreGc opts _ ("--print-roots" : rest) = goStoreGc opts True rest+    goStoreGc _ _ [flag]+      | flag `elem` valueFlags = Left (flag ++ " requires a value")+    goStoreGc _ _ (arg : _) = Left ("unknown store gc argument: " ++ arg)+    -- Sub-parser for daemon: a later trust flag replaces an earlier one, as+    -- upstream's handlers assign it.+    goDaemon opts trust socketPath [] = Right opts {optCommand = CmdDaemon trust socketPath}+    goDaemon opts _ _ (flag : _) | Just answer <- answered flag = Right opts {optCommand = answer}+    goDaemon opts trust socketPath ("--store" : dir : rest) =+      goDaemon (opts {optStore = Just dir}) trust socketPath rest+    goDaemon opts trust _ ("--socket-path" : path : rest) = goDaemon opts trust (Just path) rest+    goDaemon opts _ socketPath ("--force-trusted" : rest) = goDaemon opts ForceTrusted socketPath rest+    goDaemon opts _ socketPath ("--force-untrusted" : rest) = goDaemon opts ForceUntrusted socketPath rest+    goDaemon opts _ socketPath ("--default-trust" : rest) = goDaemon opts DefaultTrust socketPath rest+    goDaemon _ _ _ [flag]+      | flag `elem` valueFlags = Left (flag ++ " requires a value")+    goDaemon _ _ _ (arg : _) = Left ("unknown daemon argument: " ++ arg)+    -- Sub-parser for profile verbs.+    goProfile _ [] = Left ("profile: expected a subcommand (" ++ profileVerbs ++ ")")+    goProfile opts (flag : _) | Just answer <- answered flag = Right opts {optCommand = answer}+    goProfile opts ("add" : rest) = goTarget AddsToProfile opts emptyBuildArgs rest+    goProfile opts ("remove" : rest) = goProfileRemove opts DefaultProfile [] [] rest+    goProfile opts ("list" : rest) = goProfileList opts DefaultProfile TextOutput IndentedOnTerminal rest+    goProfile opts ("history" : rest) = goProfileHistory opts DefaultProfile rest+    goProfile opts ("rollback" : rest) = goGenerations RollsBack opts DefaultProfile [] MakeChanges rest+    goProfile opts ("wipe-history" : rest) = goGenerations WipesHistory opts DefaultProfile [] MakeChanges rest+    goProfile _ (sub : _) = Left ("unknown profile subcommand: " ++ sub ++ " (expected: " ++ profileVerbs ++ ")")+    profileVerbs = "add, remove, list, history, rollback, wipe-history"+    -- The flags' matchers come before the arguments', each in the order+    -- given, as upstream runs a flag's handler as it reads the flag and+    -- the arguments' once the line is read.+    goProfileRemove opts profile flagged named [] =+      (\selection -> opts {optCommand = CmdProfileRemove profile selection}) <$> removeSelection (flagged ++ map (Selected . RemoveNamed) named)+    goProfileRemove opts _ _ _ (flag : _) | Just answer <- answered flag = Right opts {optCommand = answer}+    goProfileRemove opts profile flagged named ("--store" : dir : rest) =+      goProfileRemove (opts {optStore = Just dir}) profile flagged named rest+    goProfileRemove opts _ flagged named ("--profile" : path : rest) =+      goProfileRemove opts (ProfileAt path) flagged named rest+    goProfileRemove opts profile flagged named ("--regex" : regex : rest) =+      goProfileRemove opts profile (flagged ++ [Selected (RemoveRegex regex)]) named rest+    goProfileRemove opts profile flagged named ("--all" : rest) =+      goProfileRemove opts profile (flagged ++ [SelectedAll]) named rest+    goProfileRemove _ _ _ _ [flag]+      | flag `elem` valueFlags = Left (flag ++ " requires a value")+    goProfileRemove _ _ _ _ (arg@('-' : _) : _) = Left ("unknown profile remove flag: " ++ arg)+    goProfileRemove opts profile flagged named (element : rest) =+      goProfileRemove opts profile flagged (named ++ [element]) rest+    goProfileList opts profile output layout [] = Right opts {optCommand = CmdProfileList profile (listFormat output layout)}+    goProfileList opts _ _ _ (flag : _) | Just answer <- answered flag = Right opts {optCommand = answer}+    goProfileList opts profile output layout ("--store" : dir : rest) =+      goProfileList (opts {optStore = Just dir}) profile output layout rest+    goProfileList opts _ output layout ("--profile" : path : rest) =+      goProfileList opts (ProfileAt path) output layout rest+    goProfileList opts profile _ layout ("--json" : rest) = goProfileList opts profile JsonOutput layout rest+    -- Each sets the layout, the later winning, and has no effect without+    -- --json, as upstream's flags of these names (MixPrintJSON in+    -- common-args.hh, from 2.34.9).+    goProfileList opts profile output _ ("--pretty" : rest) = goProfileList opts profile output Indented rest+    goProfileList opts profile output _ ("--no-pretty" : rest) = goProfileList opts profile output Compact rest+    goProfileList _ _ _ _ [flag]+      | flag `elem` valueFlags = Left (flag ++ " requires a value")+    goProfileList _ _ _ _ (arg : _) = Left ("unknown profile list argument: " ++ arg)+    -- Sub-parser for key verbs.  The last --key-name given is the name,+    -- as upstream's flag handler sets it each time it is read.  --store is+    -- taken and unused, as upstream's key commands take it, a setting+    -- every command accepts.+    goKey _ [] = Left "key: expected a subcommand (generate-secret, convert-secret-to-public)"+    goKey opts (flag : _) | Just answer <- answered flag = Right opts {optCommand = answer}+    goKey opts ("generate-secret" : rest) = goKeyGenerate opts Nothing rest+    goKey opts ("convert-secret-to-public" : rest) = goKeyConvert opts rest+    goKey _ (sub : _) = Left ("unknown key subcommand: " ++ sub ++ " (expected: generate-secret, convert-secret-to-public)")+    goKeyGenerate opts keyName [] = maybe (Left "key generate-secret: required argument '--key-name' is missing") (\name -> Right opts {optCommand = CmdKeyGenerateSecret name}) keyName+    goKeyGenerate opts _ (flag : _) | Just answer <- answered flag = Right opts {optCommand = answer}+    goKeyGenerate opts _ ("--key-name" : name : rest) = goKeyGenerate opts (Just name) rest+    goKeyGenerate opts keyName ("--store" : dir : rest) = goKeyGenerate (opts {optStore = Just dir}) keyName rest+    goKeyGenerate _ _ [flag]+      | flag `elem` valueFlags = Left (flag ++ " requires a value")+    goKeyGenerate _ _ (arg : _) = Left ("unknown key generate-secret argument: " ++ arg)+    goKeyConvert opts [] = Right opts {optCommand = CmdKeyConvertSecretToPublic}+    goKeyConvert opts (flag : _) | Just answer <- answered flag = Right opts {optCommand = answer}+    goKeyConvert opts ("--store" : dir : rest) = goKeyConvert (opts {optStore = Just dir}) rest+    goKeyConvert _ [flag]+      | flag `elem` valueFlags = Left (flag ++ " requires a value")+    goKeyConvert _ (arg : _) = Left ("unknown key convert-secret-to-public argument: " ++ arg)+    listFormat output layout = case output of+      TextOutput -> ListText+      JsonOutput -> ListJson layout+    goProfileHistory opts profile [] = Right opts {optCommand = CmdProfileHistory profile}+    goProfileHistory opts _ (flag : _) | Just answer <- answered flag = Right opts {optCommand = answer}+    goProfileHistory opts profile ("--store" : dir : rest) =+      goProfileHistory (opts {optStore = Just dir}) profile rest+    goProfileHistory opts _ ("--profile" : path : rest) =+      goProfileHistory opts (ProfileAt path) rest+    goProfileHistory _ _ [flag]+      | flag `elem` valueFlags = Left (flag ++ " requires a value")+    goProfileHistory _ _ (arg : _) = Left ("unknown profile history argument: " ++ arg)+    -- The values of the command's flag are kept in order.  Upstream reads+    -- each --to as its handler meets it, so every one must read, and the+    -- last wins; --older-than is kept as a string until the command runs,+    -- so only the last is read.+    goGenerations kind opts profile values changes [] = Right opts {optCommand = generationCommand kind profile values changes}+    goGenerations _ opts _ _ _ (flag : _) | Just answer <- answered flag = Right opts {optCommand = answer}+    goGenerations kind opts profile values changes ("--store" : dir : rest) =+      goGenerations kind (opts {optStore = Just dir}) profile values changes rest+    goGenerations kind opts _ values changes ("--profile" : path : rest) =+      goGenerations kind opts (ProfileAt path) values changes rest+    goGenerations kind opts profile values _ ("--dry-run" : rest) =+      goGenerations kind opts profile values DryRun rest+    goGenerations kind opts profile values changes (flag : given : rest)+      | flag == generationValueFlag kind = goGenerations kind opts profile (values ++ [given]) changes rest+    goGenerations _ _ _ _ _ [flag]+      | flag `elem` valueFlags = Left (flag ++ " requires a value")+    goGenerations kind _ _ _ _ (arg : _) = Left ("unknown " ++ generationWord kind ++ " argument: " ++ arg)+    generationCommand kind profile values = case kind of+      RollsBack -> CmdProfileRollback profile values+      WipesHistory -> CmdProfileWipeHistory profile (listToMaybe (reverse values))+    -- Upstream's two usage errors, in this parser's words.+    removeSelection selected = case selected of+      [] -> Left "profile remove: no packages specified"+      [SelectedAll] -> Right RemoveAll+      _ -> case traverse selectedMatcher selected of+        Just (first : rest) -> Right (RemoveSome (first :| rest))+        _ -> Left "profile remove: --all cannot be used with package names or regular expressions"+    selectedMatcher entry = case entry of+      Selected matcher -> Just matcher+      SelectedAll -> Nothing+    -- What --help and --version answer.  Every parser takes them where a+    -- flag may stand and leaves the rest of the line unparsed: --version+    -- must report the build even when the command after it is one this+    -- build does not have, and a parser that rejected either would make+    -- 'eval --help' a usage error rather than a request.+    answered "--help" = Just CmdHelp+    answered "--version" = Just CmdVersion+    answered _ = Nothing+    -- Upstream's three flags for the @sandbox@ setting+    -- (@BaseSetting<SandboxMode>::convertToArg@ in globals.cc).  Each is+    -- registered under the setting's older names too, and a later+    -- registration of a name replaces an earlier one (@Args::addFlag@ in+    -- args.cc), so upstream's @--build-use-chroot@ and @--build-use-sandbox@+    -- are @--relaxed-sandbox@.  Upstream lists no alias among its flags+    -- (@Args::toJSON@ in args.cc), and the reference lists none.+    sandboxFlag "--sandbox" = Just SandboxEnabled+    sandboxFlag "--no-sandbox" = Just SandboxDisabled+    sandboxFlag "--relaxed-sandbox" = Just SandboxRelaxed+    sandboxFlag "--build-use-chroot" = Just SandboxRelaxed+    sandboxFlag "--build-use-sandbox" = Just SandboxRelaxed+    sandboxFlag _ = Nothing+    -- Flags that consume the following argument as their value.+    valueFlags =+      [extraFeaturesFlag, "--nix-path", "--store", "--substituter", "--trusted-key", "--exec-wrapper", "--expr", "--cache", "--key-file", "--secret-key-file", "--compression", "--profile", "--priority", "--regex", "--to", "--older-than", "--key-name", "--socket-path"]+        ++ attrFlags+        ++ outLinkFlags+    -- Attribute selection, under both of upstream's spellings.+    attrFlags = ["-A", "--attr"]+    -- Upstream's setting flag for experimental features, which adds its+    -- value to the configured ones.+    extraFeaturesFlag = "--extra-experimental-features"+    withFeatures features opts = opts {optExtraExperimentalFeatures = optExtraExperimentalFeatures opts ++ [features]}+    -- The result link, under both of nix-build's spellings.+    outLinkFlags = ["-o", "--out-link"]+    -- No result link, under both of nix-build's spellings.+    noOutLinkFlags = ["--no-out-link", "--no-link"]+    -- Upstream's keep-failed, under nix-build's two spellings; nix build+    -- takes only the long one.+    keepFailedFlags = ["-K", "--keep-failed"]+    -- develop's flags, under each of upstream's spellings: the short one,+    -- the long one and the name 2.24.9 gave it (the MixEnvironment+    -- constructor in command.cc and the CmdDevelop constructor in develop.cc,+    -- from 2.34.9).+    commandFlags = ["-c", "--command"]+    phaseFlags = [("--unpack", "unpack"), ("--configure", "configure"), ("--build", "build"), ("--check", "check"), ("--install", "install"), ("--installcheck", "installCheck")]+    ignoreEnvFlags = ["-i", "--ignore-env", "--ignore-environment"]+    keepFlags = ["-k", "--keep-env-var", "--keep"]+    unsetFlags = ["-u", "--unset-env-var", "--unset"]+    setFlags = ["-s", "--set-env-var"]+    developValueFlags = "--phase" : keepFlags ++ unsetFlags+    developing targetArgs change = targetArgs {baDevelop = change (baDevelop targetArgs)}+    -- The flags that pass a function an argument, each followed by the+    -- argument's name and its value, and what each makes of the value.+    autoArgKinds = [("--arg", AutoArgExpr), ("--argstr", AutoArgString)]+    autoArgFlags = map fst autoArgKinds+    autoArg flag value = ($ value) <$> lookup flag autoArgKinds+    autoArgShortfall = " requires a name and a value"+    withAutoArg name arg opts = opts {optAutoArgs = Map.insert name arg (optAutoArgs opts)}
+ cli/Nix/Cli/Reference.hs view
@@ -0,0 +1,1137 @@+-- | The command line's reference: every command and flag, the nix.conf+-- settings the CLI reads, and the two renderings of them.+--+-- This module is the one place the CLI is documented.  @--help@ prints+-- 'helpLines', and @docs\/cli.json@ holds 'referenceJson', which the+-- project's site renders as its command-line reference; the test suite+-- fails while the committed file differs from it.  "Nix.Cli.Args" is the+-- grammar these entries describe, and the suite checks each flag against+-- it: every command an entry lists accepts the flag, and the parser asks+-- for a value exactly when the entry names an argument.+--+-- The commands and flags are enumerations, and their entries are total+-- functions of them, so a command or flag without documentation fails the+-- warning-clean build.  An example that shows output shows what the test+-- suite gets running it.  A summary or description marks code between+-- backticks, as Markdown does: @--help@ prints it without them, and the+-- site sets it as code.+module Nix.Cli.Reference+  ( -- * Commands+    CommandName (..),+    CommandEntry (..),+    Form (..),+    Example (..),+    codeMark,+    programName,+    commandNames,+    commandWords,+    commandInvocation,+    globalForm,+    command,+    exampleCommandLine,+    shellQuote,++    -- * Flags+    FlagName (..),+    FlagEntry (..),+    FlagScope (..),+    flagNames,+    flag,+    flagSpellings,+    globalFlags,++    -- * Configuration+    Configuration (..),+    Setting (..),+    configuration,++    -- * Hosts+    Host (..),+    currentHost,+    SystemConfDirSource (..),+    systemConfDirSource,+    systemConfDirName,++    -- * Renderings+    helpLines,+    helpWidth,+    wrapWords,+    referenceJson,+    renderIndentedJson,+  )+where++import qualified Data.ByteString as BS+import qualified Data.ByteString.Builder as BB+import qualified Data.ByteString.Char8 as BC+import qualified Data.ByteString.Lazy as BL+import Data.Char (isAsciiLower, isAsciiUpper, isDigit)+import Data.Foldable (toList)+import Data.List (intersperse, sortOn)+import Data.List.NonEmpty (NonEmpty (..))+import qualified Data.Map.Strict as Map+import Data.Ord (Down (..))+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Nix.Config as Config+import Nix.Eval.CallDepth (defaultMaxCallDepth)+import Nix.HostPath (hostPathText)+import Nix.Http (defaultDownloadAttempts)+import Nix.Json (Json (..), renderJson)+import Nix.Push (pushCompressionValues)+import qualified System.FilePath.Posix as Posix+import qualified System.FilePath.Windows as Windows+import qualified System.Info as SI++-- ---------------------------------------------------------------------------+-- Commands+-- ---------------------------------------------------------------------------++-- | The commands, in the order the reference lists them.  The global+-- form, @nova-nix@ with no command, is 'globalForm'.+data CommandName+  = EvalCommand+  | BuildCommand+  | DevelopCommand+  | PrintDevEnvCommand+  | TrustCommand+  | PushCommand+  | StoreDeleteCommand+  | StoreGcCommand+  | ProfileAddCommand+  | ProfileRemoveCommand+  | ProfileListCommand+  | ProfileHistoryCommand+  | ProfileRollbackCommand+  | ProfileWipeHistoryCommand+  | KeyGenerateSecretCommand+  | KeyConvertSecretToPublicCommand+  | DaemonCommand+  deriving (Eq, Ord, Show, Enum, Bounded)++-- | What the reference says about a command, or about the global form.+data CommandEntry = CommandEntry+  { -- | The ways to invoke it, each with what it does in a line.+    commandForms :: !(NonEmpty Form),+    -- | What it does, in a paragraph.+    commandDescription :: !Text,+    -- | Command lines that use it, each with what it is for.+    commandExamples :: !(NonEmpty Example)+  }+  deriving (Eq, Show)++-- | One way to invoke a command.+data Form = Form+  { -- | What follows the command's words: its operands and any flag it+    -- cannot do without.  Empty for a command that takes neither.+    formArguments :: !Text,+    -- | What the form does, in a line.+    formSummary :: !Text+  }+  deriving (Eq, Show)++-- | A command line and what it is for.+data Example = Example+  { -- | What the command line is for, in a sentence.+    exampleDescription :: !Text,+    -- | The arguments after the program's name.+    exampleArguments :: !(NonEmpty Text),+    -- | What it prints on stdout, line by line.  Empty for an example+    -- whose output depends on the machine or the release, or that needs+    -- what the test suite does not have; the suite runs every example+    -- that shows output and compares.+    exampleOutput :: ![Text]+  }+  deriving (Eq, Show)++-- | What opens and closes a code span in the reference's text, as in+-- Markdown.+codeMark :: Char+codeMark = '`'++-- | Text set as code.+codeSpan :: Text -> Text+codeSpan text = T.singleton codeMark <> text <> T.singleton codeMark++-- | The program's name, as every invocation starts.+programName :: Text+programName = "nova-nix"++-- | Every command, in order.+commandNames :: [CommandName]+commandNames = [minBound .. maxBound]++-- | The words that select a command after the program's name.+commandWords :: CommandName -> [Text]+commandWords name = case name of+  EvalCommand -> ["eval"]+  BuildCommand -> ["build"]+  DevelopCommand -> ["develop"]+  PrintDevEnvCommand -> ["print-dev-env"]+  TrustCommand -> ["trust"]+  PushCommand -> ["push"]+  StoreDeleteCommand -> ["store", "delete"]+  StoreGcCommand -> ["store", "gc"]+  ProfileAddCommand -> ["profile", "add"]+  ProfileRemoveCommand -> ["profile", "remove"]+  ProfileListCommand -> ["profile", "list"]+  ProfileHistoryCommand -> ["profile", "history"]+  ProfileRollbackCommand -> ["profile", "rollback"]+  ProfileWipeHistoryCommand -> ["profile", "wipe-history"]+  KeyGenerateSecretCommand -> ["key", "generate-secret"]+  KeyConvertSecretToPublicCommand -> ["key", "convert-secret-to-public"]+  DaemonCommand -> ["daemon"]++-- | A command as it is invoked, @nova-nix store gc@.+commandInvocation :: CommandName -> Text+commandInvocation = T.unwords . (programName :) . commandWords++-- | A form as it is typed after the given words.+formUsage :: [Text] -> Form -> Text+formUsage commandPart form = T.unwords (commandPart ++ filter (not . T.null) [formArguments form])++-- | An example as it is typed at a POSIX shell.+exampleCommandLine :: Example -> Text+exampleCommandLine = T.unwords . (programName :) . map shellQuote . toList . exampleArguments++-- | An argument as a POSIX shell reads it back unchanged: as it is when+-- every character is one no shell treats specially, otherwise in single+-- quotes, each single quote in it closing the quotes, escaped, and opening+-- them again.  A leading @=@ is quoted too, since zsh expands @=name@ to+-- the command's path.+shellQuote :: Text -> Text+shellQuote argument+  | not (T.null argument) && T.all plain argument && not ("=" `T.isPrefixOf` argument) = argument+  | otherwise = "'" <> T.replace "'" "'\\''" argument <> "'"+  where+    plain c = isAsciiLower c || isAsciiUpper c || isDigit c || c `elem` ("_@%+=:,./-" :: String)++-- | @nova-nix@ with no command.+globalForm :: CommandEntry+globalForm =+  CommandEntry+    { commandForms = Form "COMMAND [FLAG...]" "Run one command, with the flags it takes" :| [],+      commandDescription =+        "nova-nix evaluates Nix expressions, builds derivations, starts shells with a derivation's build environment, reports what a derivation's closure relies on, pushes store paths to a binary cache, keeps profiles of packages, maintains its store and serves it to other users' Nix clients, one command per invocation, and reads its settings from `nix.conf` as upstream Nix does. Each command takes the flags listed with it, after the command's name. A command exits with status 0 when it succeeds, and with status 1 when it fails, after saying why on stderr; `build --check` has another status, 104, for an output that differs, and `develop`, once its shell has started, exits with the shell's.",+      commandExamples =+        Example "Print the release this binary was built from." ("--version" :| []) []+          :| [Example "Print the commands, flags and settings." ("--help" :| []) []]+    }++-- | What the reference says about each command.+command :: CommandName -> CommandEntry+command name = case name of+  EvalCommand ->+    CommandEntry+      { commandForms =+          Form "PATH" "Evaluate a .nix file, or a directory's default.nix, print result"+            :| [ Form "'<NAME>'" "Evaluate the file the search path finds for NAME",+                 Form "--expr 'EXPR'" "Evaluate an inline expression"+               ],+        commandDescription =+          "Evaluates the expression in " <> targetSource <> ", and prints its value as `nix-instantiate --eval` prints it. With an argument from `--arg` or `--argstr`, the value is called first, as `nix-instantiate --eval` calls it: " <> callRule <> " Without one it is not called, and a function prints as `<LAMBDA>`; with `--aterm` it is called either way, as `nix-instantiate` calls it before it writes a derivation. A part of the value the evaluation never needed prints as `<CODE>`; with `--strict` the whole value is evaluated first. A relative path resolves against the file's directory, or for `--expr` and an `--arg` expression against the working directory. A `<name>` path, and a `<NAME>` argument, is looked up in the entries `--nix-path` adds, then `NIX_PATH`'s, then the `<nix/*>` expressions nova-nix ships with. An evaluation that writes to the store, as the fetchers do and, with `--read-write-mode`, `builtins.toFile` and `builtins.path` do, stops with an error at its first write to a store directory that upstream Nix's database also manages, such as `/nix/store` where upstream Nix is installed, when the store is opened directly; one that writes nothing is not refused, and a store reached through a daemon is not. With `NOVA_NIX_C_STATS` set to a file, an evaluation that succeeds writes to it a census of the memory its C data layer holds: the objects and bytes of each kind allocated, those its result, the root environment, the import cache and the search path still reach, and what finding them cost. With `NOVA_NIX_REGION_STATS` set to a file, it writes a census of regions: at the end of each force of a thunk, the bytes the force allocated and the bytes of them still reachable, and the most bytes collectors freeing at those points would have held.",+        commandExamples =+          Example "Evaluate an expression." ("eval" :| ["--expr", "1 + 2"]) ["3"]+            :| [ Example+                   "Print an attribute set as far as evaluating it forced it."+                   ("eval" :| ["--expr", "{ a = 1 + 1; }"])+                   ["{ a = <CODE>; }"],+                 Example+                   "Evaluate the whole value before printing it."+                   ("eval" :| ["--strict", "--expr", "{ a = 1 + 1; }"])+                   ["{ a = 2; }"],+                 Example+                   "Print the `.drv` a derivation is written to the store as, to compare it with another evaluator's."+                   ("eval" :| ["--aterm", "--expr", "derivation { name = \"hello\"; system = \"x86_64-linux\"; builder = \"/bin/sh\"; }"])+                   ["Derive([(\"out\",\"/nix/store/pnwh4xsfs4j508bs9iw6bpkyc4zw6ryx-hello\",\"\",\"\")],[],[],\"x86_64-linux\",\"/bin/sh\",[],[(\"builder\",\"/bin/sh\"),(\"name\",\"hello\"),(\"out\",\"/nix/store/pnwh4xsfs4j508bs9iw6bpkyc4zw6ryx-hello\"),(\"system\",\"x86_64-linux\")])"],+                 Example+                   "Call a function with an argument, its default filling the other."+                   ("eval" :| ["--arg", "x", "2", "--expr", "{ x, y ? 3 }: x * y"])+                   ["6"],+                 Example+                   "Call a function with a string argument."+                   ("eval" :| ["--argstr", "name", "world", "--expr", "{ name }: \"hello \" + name"])+                   ["\"hello world\""],+                 Example+                   "Evaluate an expression from a nixpkgs checkout in the working directory."+                   ("eval" :| ["--nix-path", "nixpkgs=./nixpkgs", "--expr", "(import <nixpkgs/lib>).version"])+                   []+               ]+      }+  BuildCommand ->+    CommandEntry+      { commandForms =+          Form "PATH" "Build a derivation from a .nix file, or a directory's default.nix"+            :| [ Form "'<NAME>'" "Build a derivation from the file the search path finds for NAME",+                 Form "--expr 'EXPR'" "Build a derivation from an inline expression"+               ],+        commandDescription =+          "Evaluates " <> targetSource <> ", selects the attribute `-A` names when it is given, realises the output the `outputName` of the derivation that results names, the first of its outputs unless the expression selects another, building that derivation and every derivation it depends on as the output needs, and prints its path, as `nix-build` does; the derivation's other outputs are not asked for. " <> targetCalls <> " A derivation whose outputs a substituter holds is downloaded instead of built, from the substituters `nix.conf` configures and the one `--substituter` adds, and a path is accepted only when a trusted key signed it or its content address makes it, unless `require-sigs` is off. The outputs of a derivation whose `allowSubstitutes` attribute is false are built instead, unless `always-allow-substitutes` is on. A substituter that fails stops the build unless `fallback` is on. With `--check` the derivation is checked as `nix-build --check` checks one: an output of its that is not valid is first downloaded from a substituter that holds it, the derivations it depends on are built or downloaded as ever, and then it is built again beside its outputs, never downloaded, and each output is compared with the one in the store. The rebuild changes nothing in the store and what it wrote is discarded; the downloads and builds before it add to the store as in any build. An output that comes out different fails the command with status 104, so a path a substituter supplied can be held to a build. With `keep-failed` on, a build that fails keeps its directory, under the store's `.nova-nix/builds`, until the derivation is next built, and names the directory its builder worked in on stderr, unless its builder is a builtin; and a check that finds an output different keeps that output's rebuild beside it as `PATH.check`, which nothing registers and the garbage collector removes, and names it in its error. The output is linked from `./result`, or from the path `--out-link` gives, with `-NAME` appended for an output `NAME` other than `out`, as `nix-build` links it, and the link is a root the garbage collector keeps; it replaces a link already there that points into the store, and anything else there fails the command. With `--no-out-link` nothing is linked. Where `sandbox` is on, as it is by default on Linux, a builder runs in a sandbox: it sees its inputs, the paths `sandbox-paths` names and its build directory, which on Linux it sees at `sandbox-build-dir`, and unless its derivation is fixed-output it reaches no network, which on Linux leaves it a loopback of its own; a system that cannot make the sandbox builds without it after a warning, or with `sandbox-fallback` off fails the build. A store directory that upstream Nix's database also manages, such as `/nix/store` where upstream Nix is installed, is refused before anything is evaluated, when the store is opened directly. Through a daemon (see `--store`) the daemon builds the derivation and substitutes its outputs, and an output `--check` finds different fails the command with status 1 in place of 104, as upstream's client reports its daemon's failure; `--exec-wrapper` is refused there.",+        commandExamples =+          Example+            "Build GNU Hello for Windows from the directory a release unpacks to, with the public cache as a substituter."+            ("build" :| ["pkgs/windows/hello.nix", "--substituter", "https://cache.novavero.ai", "--trusted-key", "cache.novavero.ai-1:9gQ7tLWMM+2tdC9H5sKMJltDIPfD7X2GWlZe8Aa8hHQ="])+            []+            :| [ Example+                   "Build an attribute of a file, linking the output from `./result`, a root the garbage collector keeps."+                   ("build" :| ["pkgs/windows/default.nix", "-A", "hello"])+                   [],+                 Example+                   "Build GNU Hello for Windows and print its path with no link, as a script that reads the path does."+                   ("build" :| ["pkgs/windows/hello.nix", "--no-out-link"])+                   [],+                 Example+                   "Build GNU Hello from a nixpkgs checkout in the working directory: nixpkgs is a function, called with its defaults before `hello` is selected from it."+                   ("build" :| ["--nix-path", "nixpkgs=./nixpkgs", "<nixpkgs>", "-A", "hello"])+                   [],+                 Example+                   "Build a derivation written inline, on Linux or macOS."+                   ("build" :| ["--expr", "derivation { name = \"greeting\"; system = builtins.currentSystem; builder = \"/bin/sh\"; args = [ \"-c\" \"echo hello > $out\" ]; }"])+                   [],+                 Example+                   "Check GNU Hello with the public cache as a substituter: Hello and what it is built from are downloaded where the cache holds them and built where it does not, then Hello is built again, and the command fails if its output comes out different."+                   ("build" :| ["pkgs/windows/hello.nix", "--check", "--substituter", "https://cache.novavero.ai", "--trusted-key", "cache.novavero.ai-1:9gQ7tLWMM+2tdC9H5sKMJltDIPfD7X2GWlZe8Aa8hHQ="])+                   []+               ]+      }+  DevelopCommand ->+    CommandEntry+      { commandForms =+          Form "PATH" "Start a shell with the build environment of a derivation in a .nix file, or a directory's default.nix"+            :| [ Form "'<NAME>'" "Start a shell with the build environment of a derivation in the file the search path finds for NAME",+                 Form "--expr 'EXPR'" "Start a shell with the build environment of an inline derivation"+               ],+        commandDescription =+          "Evaluates " <> targetSource <> ", selects the attribute `-A` names when it is given, and starts `bash` with the environment the builder of the derivation that results has once its stdenv's setup has run, as `nix develop` does. " <> targetCalls <> " " <> captureRule <> " The shell sets each variable and function again, but for those that belong to the shell running it, such as `HOME`, `TERM` and the temporary directories, with each output's path replaced by `outputs/NAME` under the working directory. It then puts the caller's `PATH` and `XDG_DATA_DIRS` after the captured ones, points `NIX_BUILD_TOP` and the temporary-directory variables at a fresh directory, and runs `shellHook`. Under structured attributes it reads `.attrs.sh` and `.attrs.json` from a temporary directory, which outlives the shell. An interactive shell reads `~/.bashrc` first and takes its prompt from the `bash-prompt` settings. With `--command` the command runs in place of an interactive shell, and with `--phase`, or a flag naming a phase, the phase runs through the setup's `runPhase`, or through `runHook` where it has none. The shell is `bash` found on the `PATH` of the environment it starts with, `/bin/bash` on macOS unless that `PATH` names another, with `SHELL` set to `bash` and `NIX_GCROOT` to the copy's output, which the garbage collector does not yet keep while the shell runs. That environment is the caller's, changed by `--ignore-env`, `--keep-env-var`, `--unset-env-var` and `--set-env-var`. nova-nix replaces itself with the shell, so the command exits with the shell's status. " <> developRefusals,+        commandExamples =+          Example+            "Start a shell with GNU Hello's build environment, from a nixpkgs checkout in the working directory."+            ("develop" :| ["--nix-path", "nixpkgs=./nixpkgs", "<nixpkgs>", "-A", "hello"])+            []+            :| [ Example+                   "Run Hello's configure phase in its unpacked source, as its builder would."+                   ("develop" :| ["--nix-path", "nixpkgs=./nixpkgs", "<nixpkgs>", "-A", "hello", "--configure"])+                   [],+                 Example+                   "Run a command in Hello's build environment: here, print `$out`, which names `outputs/out` under the working directory."+                   ("develop" :| ["--nix-path", "nixpkgs=./nixpkgs", "<nixpkgs>", "-A", "hello", "--command", "sh", "-c", "echo $out"])+                   []+               ]+      }+  PrintDevEnvCommand ->+    CommandEntry+      { commandForms =+          Form "PATH" "Print the build environment of a derivation in a .nix file, or a directory's default.nix"+            :| [ Form "'<NAME>'" "Print the build environment of a derivation in the file the search path finds for NAME",+                 Form "--expr 'EXPR'" "Print the build environment of an inline derivation"+               ],+        commandDescription =+          "Evaluates " <> targetSource <> ", selects the attribute `-A` names when it is given, and prints the script that `develop`'s shell runs to set the build environment of the derivation that results, which a running `bash` can source, as `nix print-dev-env` does. " <> targetCalls <> " " <> captureRule <> " Under structured attributes the script names `.attrs.sh` and `.attrs.json` in a temporary directory, which is removed when the command exits, as upstream's is. With `--json` it prints the captured environment instead, as one JSON document of the variables, the functions and, under structured attributes, the two files the builder read, laid out over several lines when stdout is a terminal and on one otherwise, unless `--pretty` or `--no-pretty` says which. " <> developRefusals,+        commandExamples =+          Example+            "Print the script that sets GNU Hello's build environment, from a nixpkgs checkout in the working directory."+            ("print-dev-env" :| ["--nix-path", "nixpkgs=./nixpkgs", "<nixpkgs>", "-A", "hello"])+            []+            :| [ Example+                   "Print that environment as JSON."+                   ("print-dev-env" :| ["--nix-path", "nixpkgs=./nixpkgs", "<nixpkgs>", "-A", "hello", "--json"])+                   []+               ]+      }+  TrustCommand ->+    CommandEntry+      { commandForms =+          Form "PATH" "Report what the closure of a derivation in a .nix file, or a directory's default.nix, relies on"+            :| [ Form "'<NAME>'" "Report what the closure of a derivation in the file the search path finds for NAME relies on",+                 Form "--expr 'EXPR'" "Report what an inline derivation's closure relies on"+               ],+        commandDescription =+          "Evaluates " <> targetSource <> ", selects the attribute `-A` names when it is given, and reports what the closure of the derivation that results relies on. " <> targetCalls <> " A closure bottoms out in fixed-output derivations, whose outputs are held to the hash their recipe states when a builtin fetches them or the closure builds them; one downloaded from a substituter is held to the content address its narinfo states, and to the narinfo's NarHash alone when it states none, as upstream holds one. First come those a build runs as builders, where a derivation's builder is inside one's output, or inside the tree a builtin such as `builtin:unpack` makes from it and any others; then those whose files hold prebuilt code, each with the files found; then those not fully read, each with what was not. Each says whether a builtin fetched it or the closure built it, and names any other with the same hash; a file of prebuilt code whose bytes are those of an input a build runs as a builder, such as a copy of a seed in a source archive, is named as that input. Then come how many hold no prebuilt code, the builders the closure does not contain, such as a program on the host, the builders in its input sources, the builtins nova-nix runs itself, and how many input sources its derivations take, store paths none of them builds. A fixed-output derivation whose builder is a builtin and which has no inputs is fetched first, or downloaded from a substituter, so that its bytes can be read; any other is only downloaded, with the paths it references, from a substituter that holds it, since making it would run its builder, and is read only when one does or the store already holds it. A fetch that fails stops the command, and so does a failed download of one that no builtin fetches. The scan finds prebuilt code by its header: a PE image, an ELF or Mach-O file, a COFF object, or an ar archive, whose members it does not read. It looks in a fetched file, in each file of a fetched tree, and in each file of a tar archive, plain or compressed with gzip, bzip2, xz or zstd, that one of those is; it does not open an archive inside another, and it reports a file in another archive format it knows, such as zip, as not read. It reports what the closure relies on, not whether any of it is safe. With `--json` it prints the same report as one JSON document, laid out over several lines when stdout is a terminal and on one otherwise, unless `--pretty` or `--no-pretty` says which: its `version`; `fixedOutputInputs`, keyed by output path, each with its `drvPath`, its `class`, `fetchedBy` or `builtBy`, `sameHash`, the builders inside it or its tree with their counts, `inStore`, and the `prebuiltCode` its scan found, each with its `kind`, `file`, `member`, `sha256` and the run-as-builder inputs it is the bytes of, and the files it did not read; `buildersOutsideClosure`, `buildersInInputSources` and `builtinBuilders`, each builder with how many derivations it builds; and `inputSources`, the paths themselves. When the store is opened directly, in a store directory that upstream Nix's database also manages, such as `/nix/store` where upstream Nix is installed, a closure with a fixed-output input is refused before any is fetched or read, and an evaluation that writes to the store stops at its first write, as `eval`'s does; a closure with no fixed-output input is reported there as anywhere. Through a daemon (see `--store`) the daemon fetches and substitutes the inputs, and what it holds is read from the store's directory; the daemon does not say whether a download failed or no substituter offered the path, so there a failed download of one that no builtin fetches leaves it unread instead of stopping the command.",+        commandExamples =+          Example+            "Report what GNU Hello for Windows relies on, from the directory a release unpacks to, with the public cache as a substituter."+            ("trust" :| ["pkgs/windows/hello.nix", "--substituter", "https://cache.novavero.ai", "--trusted-key", "cache.novavero.ai-1:9gQ7tLWMM+2tdC9H5sKMJltDIPfD7X2GWlZe8Aa8hHQ="])+            []+            :| [ Example+                   "Report the same as one JSON document, on one line."+                   ("trust" :| ["pkgs/windows/hello.nix", "--substituter", "https://cache.novavero.ai", "--trusted-key", "cache.novavero.ai-1:9gQ7tLWMM+2tdC9H5sKMJltDIPfD7X2GWlZe8Aa8hHQ=", "--json", "--no-pretty"])+                   [],+                 Example+                   "Report what a derivation written inline relies on: its builder, `/bin/sh`, is a program on the host."+                   ("trust" :| ["--expr", "derivation { name = \"greeting\"; system = \"x86_64-linux\"; builder = \"/bin/sh\"; args = [ \"-c\" \"echo hello > $out\" ]; }"])+                   [ "Fixed-output inputs run as builders: 0",+                     "Fixed-output inputs holding prebuilt code: 0",+                     "Fixed-output inputs not fully read: 0",+                     "Fixed-output inputs holding no prebuilt code: 0",+                     "Builders outside the closure: 1",+                     "  /bin/sh, for 1 derivation",+                     "Builders in input sources: 0",+                     "Builtin builders: 0",+                     "Input sources: 0",+                     "This reports what the closure relies on, not whether any of it is safe."+                   ]+               ]+      }+  PushCommand ->+    CommandEntry+      { commandForms =+          Form "--cache URL PATH..." "Push store paths (and their closures) to a binary cache"+            :| [Form "--cache URL --all" "Push every valid path except derivations, and their closures"],+        commandDescription =+          "Copies the closure of each `PATH`, or with `--all` every valid path except derivations, to the binary cache at `URL`. A `PATH` is a store path, in full or as its base name; a derivation is refused, since a binary cache serves outputs. Paths the cache already holds are skipped, and every NAR is in place before any narinfo announces it. An `http://` or `https://` `URL` is a nova-cache server, which signs what it receives, and a narinfo is read back to check that the server signed it. A `file://` `URL` names a directory, which gets the layout upstream's `nix copy --to file://` writes, so that any web server can serve it and a substituter can read it through the same `URL`: `nix-cache-info`, a narinfo for each path, signed with the secret key in `--secret-key-file`, and the NARs under `nar/`. The key file is one `key generate-secret` writes, or upstream's `nix key generate-secret` or `nix-store --generate-binary-cache-key`, and a substituter of the cache trusts the public key `key convert-secret-to-public` prints for it. It prints how many paths it pushed and how many the cache already held. Through a daemon (see `--store`) each path's references, NAR hash and deriver are the daemon's, and its files are read from the store's directory, as upstream's client of a daemon on the same machine reads them.",+        commandExamples =+          Example+            "Push every path in the store except derivations, compressed with zstd, to a cache that takes the API key in `cache-api-key`."+            ("push" :| ["--cache", "https://cache.example.org", "--key-file", "cache-api-key", "--compression", "zstd", "--all"])+            []+            :| [ Example+                   "Write the closure of a build's output, here GNU Hello's, to a binary cache in `/srv/cache`, signed with the secret key in `cache-secret-key`; `HASH` stands for the hash in its path."+                   ("push" :| ["--cache", "file:///srv/cache", "--secret-key-file", "cache-secret-key", "/nix/store/HASH-hello"])+                   []+               ]+      }+  StoreDeleteCommand ->+    CommandEntry+      { commandForms = Form "PATH..." "Remove store paths, refused while a root or another valid path keeps them" :| [],+        commandDescription =+          "Deletes each `PATH`'s registration and its tree on disk, in the order given, and prints each one it deleted. A `PATH` is a store path, in full or as its base name, and an entry with only a registration or only a tree is deleted too. A path a root keeps, or that another valid path references, is refused, and the first refusal stops the command, so a path is named before the paths it references. A store directory that upstream Nix's database also manages, such as `/nix/store` where upstream Nix is installed, is refused, and so is a store reached through a daemon (see `--store`).",+        commandExamples =+          Example+            "Delete a build's output, here GNU Hello's, so that the next build makes it again; `HASH` stands for the hash in its path."+            ("store" :| ["delete", "/nix/store/HASH-hello"])+            []+            :| []+      }+  StoreGcCommand ->+    CommandEntry+      { commandForms = Form "" "Remove every store path not reachable from a root" :| [],+        commandDescription =+          "Deletes every store path no root keeps, directly or through the paths that reference it, and prints how many it deleted and the space it freed, as `nix-store --gc` does. The roots are the links `build` made to its outputs and each generation of a profile, while they stay, and the links and files under the store's `.nova-nix/gcroots` directory; a path a running program has open is not a root, and a rooted output does not keep the `.drv` that built it. A collection in a store directory that upstream Nix's database also manages, such as `/nix/store` where upstream Nix is installed, is refused. With `--print-roots` it lists the roots and deletes nothing, in such a store as in any other. A store reached through a daemon (see `--store`) is refused.",+        commandExamples =+          Example "Delete everything no root keeps." ("store" :| ["gc"]) []+            :| [Example "List the roots, each as the link that names it and the path it keeps." ("store" :| ["gc", "--print-roots"]) []]+      }+  ProfileAddCommand ->+    CommandEntry+      { commandForms =+          Form "PATH" "Add a derivation from a .nix file, or the store path a path leads to, to a profile"+            :| [ Form "'<NAME>'" "Add a derivation from the file the search path finds for NAME to a profile",+                 Form "--expr 'EXPR'" "Add a derivation from an inline expression to a profile"+               ],+        commandDescription =+          "Adds a package to a profile and switches the profile to a new generation that holds it, as `nix profile add` does. A `PATH` that is in the store, or a link that leads into it, as the `./result` a build links does, adds the store path it is in, which must be valid. Any other `PATH`, a `<NAME>` or `--expr` is evaluated as `build` evaluates its target, and its derivation built for the outputs it installs: the one the value selects when its `outputSpecified` is true, else those its `meta.outputsToInstall` names, else every output. "+            <> targetCalls+            <> " The package is named after the names of its paths without their versions, with `-1`, `-2` and on appended to a name the profile already holds, and has the priority `--priority` gives, 5 unless it gives another. Where two packages hold a file at one path, the profile links the one with the lower number, and two with one number fail the command, which names both files and the commands that would resolve it. "+            <> profileRules+            <> " A store directory that upstream Nix's database also manages, such as `/nix/store` where upstream Nix is installed, is refused before anything is evaluated, when the store is opened directly.",+        commandExamples =+          Example+            "Build GNU Hello for Windows from the directory a release unpacks to and add it to the default profile, which puts `hello` under `~/.nix-profile/bin`."+            ("profile" :| ["add", "pkgs/windows/hello.nix"])+            []+            :| [ Example+                   "Add what a build linked from `./result` to the default profile."+                   ("profile" :| ["add", "./result"])+                   [],+                 Example+                   "Add a package whose files the profile links in place of those of one at the default priority."+                   ("profile" :| ["add", "--priority", "4", "./result"])+                   []+               ]+      }+  ProfileRemoveCommand ->+    CommandEntry+      { commandForms =+          Form "NAME..." "Take packages off a profile, by name or by a store path they hold"+            :| [ Form "--regex PATTERN" "Take off a profile the packages whose names a regular expression matches",+                 Form "--all" "Take every package off a profile"+               ],+        commandDescription =+          "Takes packages off a profile and switches the profile to a new generation without them, as `nix profile remove` does. A `NAME` selects the package of that name, and a store path every package that holds it; `--regex` selects every package whose identifier a POSIX extended regular expression matches whole, ignoring case, where a package a flake added is identified by its flake reference and attribute and any other by the names of the store paths it holds without their versions, each once, in order and joined by `, `; and `--all`, which takes nothing beside it, every package. Each package taken off is named, and then how many were taken off and kept; a selector that selects nothing is warned of, and when nothing is selected the profile is left as it is. A number is refused, as upstream refuses one in place of a name, and so is a line that selects nothing, or `--all` beside another selector. "+            <> profileRules+            <> " A store directory that upstream Nix's database also manages, such as `/nix/store` where upstream Nix is installed, is refused, when the store is opened directly.",+        commandExamples =+          Example "Take GNU Hello off the default profile." ("profile" :| ["remove", "hello"]) []+            :| [Example "Take every package off a profile other than the default." ("profile" :| ["remove", "--all", "--profile", "./my-profile"]) []]+      }+  ProfileListCommand ->+    CommandEntry+      { commandForms =+          Form "" "Print the packages in a profile"+            :| [Form "--json" "Print a profile's manifest as JSON"],+        commandDescription =+          "Prints each package in a profile, as `nix profile list` does: its name, in bold when stdout takes colour, and its store paths, with a blank line between packages, and for a package a flake added its flake attribute and its original and locked flake references. "+            <> stylingRule+            <> " With `--json` it prints the profile's `manifest.json` instead, indented when stdout is a terminal unless `--pretty` or `--no-pretty` says otherwise, the later of them winning. A profile with no manifest holds no packages. The default profile and its link are made when they are missing, and a profile whose current generation is outside the store is refused, as for every profile command.",+        commandExamples =+          Example "List the packages in the default profile." ("profile" :| ["list"]) []+            :| [Example "Print the default profile's manifest, indented." ("profile" :| ["list", "--json", "--pretty"]) []]+      }+  ProfileHistoryCommand ->+    CommandEntry+      { commandForms = Form "" "Print each generation of a profile and what changed in it" :| [],+        commandDescription =+          "Prints each generation of a profile in order of number, as `nix profile history` does: `Version N (DATE):`, and `Version N (DATE) <- M:` after the first, where `DATE` is the day in UTC the generation was made and `M` the generation listed before it, with `N` in green for the current generation and in bold for the others when stdout takes colour; then a line for each package that differs from generation `M`'s, `NAME: OLD -> NEW`, with the empty-set sign for the versions of a package one of the two lacks, or `No changes.`, and a blank line before the next generation. `NAME` is what `profile remove --regex` matches, and a package's versions are those in its store paths' names, each once and joined by `, `, an epsilon standing for an empty one. "+            <> stylingRule+            <> " A generation whose store path is gone holds no packages. A generation was made when its link was. The default profile and its link are made when they are missing, and a profile whose current generation is outside the store is refused, as for every profile command.",+        commandExamples =+          Example "Show what changed in each generation of the default profile." ("profile" :| ["history"]) []+            :| [Example "Show the generations of a profile other than the default." ("profile" :| ["history", "--profile", "./my-profile"]) []]+      }+  ProfileRollbackCommand ->+    CommandEntry+      { commandForms =+          Form "" "Switch a profile to the generation before the current one"+            :| [Form "--to N" "Switch a profile to generation N"],+        commandDescription =+          "Switches a profile to the newest generation older than its current one, or with `--to N` to generation `N`, as `nix profile rollback` does, and says `switching profile from version CURRENT to N`, `CURRENT` being 0 when the profile has no current generation, and so none older. A generation holds the packages the profile held when it was made, so a rollback brings back what a later change took off, and a change after a rollback makes a generation numbered after the newest. `N` may end in `K`, `M`, `G` or `T`, which multiply it by 1024 once to four times, as upstream reads a number. With `--dry-run` it says where it would switch and switches nothing. "+            <> generationRules,+        commandExamples =+          Example "Switch the default profile back to the generation before the current one." ("profile" :| ["rollback"]) []+            :| [Example "Switch the default profile to generation 2." ("profile" :| ["rollback", "--to", "2"]) []]+      }+  ProfileWipeHistoryCommand ->+    CommandEntry+      { commandForms =+          Form "" "Delete every generation of a profile but the current one"+            :| [Form "--older-than AGE" "Delete the generations of a profile made more than AGE ago, but the newest of them"],+        commandDescription =+          "Deletes every generation of a profile but its current one, as `nix profile wipe-history` does, saying `removing profile version N` for each, so that none can be rolled back to; the next `store gc` drops their roots and deletes what only they kept. With `--older-than Nd`, `N` a whole number of days from 1, it deletes only the generations made more than `N` days ago, but the newest of them, which the profile held then, and never the current one; one made since then that is numbered below the newest of them is kept, with a warning. A generation was made when its link was. With `--dry-run` it says `would remove profile version N` for each and deletes nothing. A profile with no current generation keeps none for being current. "+            <> generationRules,+        commandExamples =+          Example "Delete every generation of the default profile but the current one." ("profile" :| ["wipe-history"]) []+            :| [ Example "Delete the generations made more than 30 days ago, keeping the newest of them." ("profile" :| ["wipe-history", "--older-than", "30d"]) [],+                 Example "Say which generations would be deleted, and delete none." ("profile" :| ["wipe-history", "--dry-run"]) []+               ]+      }+  KeyGenerateSecretCommand ->+    CommandEntry+      { commandForms = Form "--key-name NAME" "Print a new secret key for signing store paths" :| [],+        commandDescription =+          "Generates an Ed25519 secret key named `NAME` and prints it on stdout with no line feed after it, as `nix key generate-secret` does: `NAME`, a colon, and the base64 of the key's 64 bytes, the seed it was made from and then that seed's public key. `push --secret-key-file` signs a `file://` cache with such a key, and `key convert-secret-to-public` prints the public key a substituter of the cache trusts. Any `NAME` is taken; the cache's host and the key's number, as in `cache.example.org-1`, is the convention, and a substituter finds the key that checks a signature by the name the signature carries.",+        commandExamples =+          Example "Print a new secret key for a cache at cache.example.org." ("key" :| ["generate-secret", "--key-name", "cache.example.org-1"]) [] :| []+      }+  KeyConvertSecretToPublicCommand ->+    CommandEntry+      { commandForms = Form "" "Print the public key of the secret key read from stdin" :| [],+        commandDescription =+          "Reads a secret key from stdin, all of it as it is, and prints its public key with no line feed after it, as `nix key convert-secret-to-public` does: the key's name, a colon, and the base64 of the key's last 32 bytes. The base64 is read as upstream reads it, up to its first `=` and skipping line feeds, so what follows the padding of a 64-byte key, such as a line feed, is not read; any other character outside base64 before it, a carriage return or a space among them, a key with no name or no bytes, and a key that is not 64 bytes are refused in upstream's words.",+        commandExamples =+          Example "Print the public key of a secret key piped to stdin." ("key" :| ["convert-secret-to-public"]) [] :| []+      }+  DaemonCommand ->+    CommandEntry+      { commandForms = Form "" "Serve the store to other users' Nix clients over a Unix socket, or a named pipe on Windows, until stopped" :| [],+        commandDescription =+          "Serves the store, as `nix daemon` does, to clients that speak upstream Nix's worker protocol, such as upstream's `nix` given `--store daemon`, on a Unix socket at `$NIX_DAEMON_SOCKET_PATH`, else `daemon-socket/socket` in `$NIX_STATE_DIR`, else `/nix/var/nix/daemon-socket/socket`, or where `--socket-path` puts it. The socket is writable by every user, so the directory it is in decides who reaches it. On Windows it listens on the named pipe `\\\\.\\pipe\\nova-nix-daemon`, or the `\\\\.\\pipe\\NAME` that `$NIX_DAEMON_SOCKET_PATH` or `--socket-path` names, and refuses to start where another process has the pipe; the pipe refuses clients on other machines and lets Users read and write but not create an instance of it. A client is trusted when `trusted-users` names it, may connect when it is trusted or `allowed-users` names it, and may not when its group is `build-users-group`; each names users, groups as `@GROUP`, or everyone as `*`. On Windows a client is its account, which the daemon reads from the client's token as the client connects, before it has sent anything: an entry names an account of this machine as `NAME`, any other as `DOMAIN\\NAME`, `NAME@DOMAIN`, `BUILTIN\\Administrators` or `NT AUTHORITY\\SYSTEM`, or any account by its SID, which an account whose name holds a space needs, and a group the token grants by after `@`. A client is refused for `build-users-group` by the groups Windows holds for its account, whatever its token shows. Paths go to clients under `/nix/store`, wherever the store's files are. A client the daemon does not trust may not repair, has its settings limited as upstream's daemon limits them, and is shown roots without what holds them. The daemon holds the store open while it runs, so a collection waits for it to stop, and serves each connection on its own. It answers queries of the store: which paths are valid, their info, referrers and derivers, a derivation's outputs, the roots, and a path's NAR, and it keeps temporary and indirect roots. It builds and substitutes the paths a client asks it to realise; it adds the derivations, sources and paths that clients of protocol 1.25 or later send, holding a path a client it does not trust copies in to the signatures of the trusted keys unless its content address makes it or `require-sigs` is off; a client asking it to add signatures or collect garbage is told it does not yet. A command of nova-nix's own reaches the store directly, or through a daemon, nova-nix's or upstream's, as `--store` chooses: by default through the daemon when it cannot write the store and the daemon's socket is there, and failing as upstream's client does when it cannot connect, as it does when the store is first used. The daemon opens its own store directly, and reads only `--store`. A store directory that upstream Nix's database also manages, such as `/nix/store` where upstream Nix is installed, is refused.",+        commandExamples =+          Example "Serve the platform store, as root, to every user's clients." ("daemon" :| []) []+            :| [Example "Serve a store under `/srv`, on a socket beside it, trusting no client." ("daemon" :| ["--store", "/srv/nix/store", "--socket-path", "/srv/nix/daemon-socket/socket", "--force-untrusted"]) []]+      }++-- | What a profile is and where it is, as the descriptions of the+-- commands that change one say.+profileRules :: Text+profileRules = "A profile is a link to one of its generations, `PROFILE-1-link`, `PROFILE-2-link` and on beside it, each a store path holding the packages' files linked into one tree and a `manifest.json` that lists the packages, and each a root the garbage collector keeps. The default profile is `profiles/profile` in the state directory, which is `$NIX_STATE_HOME`, else `$XDG_STATE_HOME/nix`, else `~/.local/state/nix`, or on Windows `nix\\state` in the Local AppData folder; `~/.nix-profile`, or with `use-xdg-base-directories` on `profile` in the state directory, links to it, and both are made when they are missing, whichever profile `--profile` names. A profile whose current generation is outside the store, as one upstream Nix keeps in `/nix/store` is while nova-nix uses another store, is refused. A change that finds the profile changed by another command since it began starts again. On Windows each link is a symlink, which needs Developer Mode or an elevated shell."++-- | Where a profile's generations are and which profile a command that+-- switches or deletes them refuses, as their descriptions say.+generationRules :: Text+generationRules = "A profile's generations are `PROFILE-1-link`, `PROFILE-2-link` and on beside it, and its current one is the one its link names by that bare name, as a switch writes it; a link naming anything else, an absolute path included, names no current generation. The default profile and its link are made when they are missing, and a profile whose current generation is outside the store is refused, as for every profile command. On Windows each link is a symlink, which needs Developer Mode or an elevated shell."++-- | When upstream styles what it prints on stdout, as the descriptions of+-- the commands that style a line say.+stylingRule :: Text+stylingRule = "Stdout takes colour when it is a terminal and `TERM` is set to something other than `dumb`, or whatever it is when `CLICOLOR_FORCE` or `FORCE_COLOR` is set, and never while `NO_COLOR` or `NOCOLOR` is set, whatever their values."++-- | What a command that takes a target evaluates, as its description+-- names it.+targetSource :: Text+targetSource = "the file `PATH` names, or its `default.nix` when `PATH` is a directory, the file the search path finds for `<NAME>`, or the expression `--expr` gives"++-- | How @develop@ and @print-dev-env@ capture a build environment, as+-- upstream's @nix develop@ does.+captureRule :: Text+captureRule = "The derivation's builder must be `bash`. A copy of it, named with `-env` after its name and with no checks on what its outputs refer to, is built in its place, with upstream's `get-env.sh` as its builder's script: it sources `$stdenv/setup` when `stdenv` is set, then writes the variables and functions bash holds to the copy's output, so the copy's path is the one `nix develop` builds. It reads the variables from the declare commands `declare -p` prints, which macOS's `/bin/bash`, bash 3.2, does not print, so a builder that is that bash captures none. What the derivation depends on is built or downloaded first, as `build` does, and a copy already built is not built again."++-- | What @develop@ and @print-dev-env@ refuse before evaluating anything.+developRefusals :: Text+developRefusals = "A store directory that upstream Nix's database also manages, such as `/nix/store` where upstream Nix is installed, is refused before anything is evaluated, when the store is opened directly. On Windows the command is refused."++-- | How a value is called with the arguments @--arg@ and @--argstr@+-- give, upstream's @autoCallFunction@.+callRule :: Text+callRule = "a set with `__functor` stands for what its functor returns given the set, which is called in turn; a function with a set pattern is called with every argument when it takes `...` and otherwise with those its formals name, its defaults filling the rest, and a formal with neither an argument nor a default fails the command; any other value is left as it is."++-- | When the commands that take a target call a function, as @nix-build@+-- does.+targetCalls :: Text+targetCalls = "Before each component of the `-A` path is selected from it, and once the path has selected it, the value is called as `nix-build` calls it, with the arguments from `--arg` and `--argstr` or with none: " <> callRule++-- ---------------------------------------------------------------------------+-- Flags+-- ---------------------------------------------------------------------------++-- | The flags, in the order the JSON and each command's list give them;+-- @--help@ groups them by the commands they apply to.+data FlagName+  = ExprFlag+  | AttrFlag+  | OutLinkFlag+  | NoOutLinkFlag+  | StrictFlag+  | AtermFlag+  | ReadWriteModeFlag+  | NixPathFlag+  | ArgFlag+  | ArgStrFlag+  | RestrictEvalFlag+  | PureEvalFlag+  | TraceVerboseFlag+  | NoAllowImportFromDerivationFlag+  | ExtraExperimentalFeaturesFlag+  | SubstituterFlag+  | TrustedKeyFlag+  | FallbackFlag+  | KeepFailedFlag+  | CheckFlag+  | ShellCommandFlag+  | PhaseFlag+  | UnpackFlag+  | ConfigureFlag+  | BuildPhaseFlag+  | CheckPhaseFlag+  | InstallFlag+  | InstallCheckFlag+  | IgnoreEnvFlag+  | KeepEnvVarFlag+  | UnsetEnvVarFlag+  | SetEnvVarFlag+  | SandboxFlag+  | NoSandboxFlag+  | RelaxedSandboxFlag+  | ExecWrapperFlag+  | CacheFlag+  | AllFlag+  | KeyFileFlag+  | SecretKeyFileFlag+  | CompressionFlag+  | PrintRootsFlag+  | KeyNameFlag+  | ProfileFlag+  | PriorityFlag+  | RegexFlag+  | ToFlag+  | OlderThanFlag+  | DryRunFlag+  | JsonFlag+  | PrettyFlag+  | NoPrettyFlag+  | ForceTrustedFlag+  | ForceUntrustedFlag+  | DefaultTrustFlag+  | SocketPathFlag+  | StoreFlag+  | HelpFlag+  | VersionFlag+  deriving (Eq, Ord, Show, Enum, Bounded)++-- | What the reference says about a flag.+data FlagEntry = FlagEntry+  { -- | The long spelling, without its leading @--@.+    flagLong :: !Text,+    -- | The one-letter spelling, without its leading @-@, where there is+    -- one.+    flagShort :: !(Maybe Char),+    -- | A second long spelling, without its leading @--@, where upstream+    -- accepts one.+    flagAlias :: !(Maybe Text),+    -- | The name of the value it takes, where it takes one.+    flagArgument :: !(Maybe Text),+    -- | What it does, in a line.+    flagDescription :: !Text,+    -- | Where it applies.+    flagScope :: !FlagScope+  }+  deriving (Eq, Show)++-- | Where a flag applies.+data FlagScope+  = -- | To the global form, which runs no command.+    GlobalFlag+  | -- | To each of these commands.+    CommandFlag !(NonEmpty CommandName)+  deriving (Eq, Show)++-- | Every flag, in order.+flagNames :: [FlagName]+flagNames = [minBound .. maxBound]++-- | A flag's spellings: the one-letter one first, where there is one,+-- then the long one and its alias.+flagSpellings :: FlagEntry -> NonEmpty Text+flagSpellings entry = case flagShort entry of+  Just letter -> T.pack ['-', letter] :| (longSpelling entry : alias)+  Nothing -> longSpelling entry :| alias+  where+    alias = map ("--" <>) (toList (flagAlias entry))++-- | A flag's long spelling, which names it.+longSpelling :: FlagEntry -> Text+longSpelling entry = "--" <> flagLong entry++-- | The flags of the global form, in order.+globalFlags :: [FlagName]+globalFlags = filter ((== GlobalFlag) . flagScope . flag) flagNames++-- | What the reference says about each flag.+flag :: FlagName -> FlagEntry+flag name = case name of+  ExprFlag ->+    long "expr" (Just "EXPR") "Evaluate `EXPR` in place of a file; a relative path in it resolves against the working directory" evaluating+  AttrFlag ->+    short 'A' "attr" (Just "ATTRPATH") "Select a dotted attribute path (`a.b.c`)" selecting+  OutLinkFlag ->+    short 'o' "out-link" (Just "PATH") "Link the output from `PATH` in place of `./result`" buildOnly+  NoOutLinkFlag ->+    aliased "no-out-link" "no-link" Nothing "Create no link to the output, and no GC root" buildOnly+  StrictFlag ->+    long "strict" Nothing "Deep-force all thunks before printing (warning: OOM on large results)" evalOnly+  AtermFlag ->+    long "aterm" Nothing "Print the `.drv` ATerm of the derivation the target evaluates to, in place of its value" evalOnly+  ReadWriteModeFlag ->+    long "read-write-mode" Nothing "Write what evaluation makes (`builtins.toFile`, `builtins.path` and the like) to the store and register it, and build or substitute what a path's context names, as `build` does; without it `eval` computes those paths, writes only what a fetcher fetches, and of the outputs a path's context names builds only those of a derivation whose `allowSubstitutes` is false while `always-allow-substitutes` is off, refusing to substitute any other" evalOnly+  NixPathFlag ->+    long "nix-path" (Just "NAME=PATH") "Add search path (repeatable, merged with `NIX_PATH`)" evaluating+  ArgFlag ->+    long "arg" (Just "NAME EXPR") "Pass the value of `EXPR` as the argument `NAME` to a function the target evaluates to" evaluating+  ArgStrFlag ->+    long "argstr" (Just "NAME STRING") "Pass `STRING`, as a string, as the argument `NAME` to a function the target evaluates to" evaluating+  RestrictEvalFlag ->+    long "restrict-eval" Nothing "Confine reads to the search path roots and what the evaluation itself writes; fetch only `allowed-uris`" evaluating+  PureEvalFlag ->+    long "pure-eval" Nothing "Confine reads as `--restrict-eval` does, with no search path but the bundled `<nix/*>`, no `currentTime`, `currentSystem` or `storePath`, and pinned fetches only (`allowed-uris` applies only under `--restrict-eval`)" evaluating+  TraceVerboseFlag ->+    long "trace-verbose" Nothing "Make `builtins.traceVerbose` behave as `builtins.trace`; without it, the first argument is never forced" evaluating+  NoAllowImportFromDerivationFlag ->+    long "no-allow-import-from-derivation" Nothing "Refuse to build or substitute what a path's context names when `import` or another builtin reads the path, even an output already valid" evaluating+  ExtraExperimentalFeaturesFlag ->+    long "extra-experimental-features" (Just "FEATURES") "Turn on the experimental features `FEATURES` names, upstream's names separated by spaces, beside those `experimental-features` turns on: `flakes` lets `builtins.parseFlakeRef` and `builtins.flakeRefToString` read a GitHub, GitLab, sourcehut, path or registry reference" evaluating+  SubstituterFlag ->+    long "substituter" (Just "URL") "Try this binary cache before building" evaluating+  TrustedKeyFlag ->+    long "trusted-key" (Just "KEY") "Trust signatures by this public key (`NAME:BASE64`) from any substituter" evaluating+  FallbackFlag ->+    long "fallback" Nothing "Build from source if substitution fails" evaluating+  KeepFailedFlag ->+    short 'K' "keep-failed" Nothing "Keep the directory of a build that fails, and the rebuild of an output `--check` finds different as `PATH.check`" building+  CheckFlag ->+    long "check" Nothing "Build the derivation again beside its valid outputs, and fail with status 104 if an output comes out different" buildOnly+  ShellCommandFlag ->+    short 'c' "command" (Just "CMD [ARG...]") "Run `CMD` with every argument after it, flags included, in place of an interactive shell" developOnly+  PhaseFlag ->+    long "phase" (Just "NAME") "Run the phase `NAME`, such as `build`, in place of an interactive shell; the last phase flag given wins" developOnly+  UnpackFlag ->+    long "unpack" Nothing "Run the `unpack` phase" developOnly+  ConfigureFlag ->+    long "configure" Nothing "Run the `configure` phase" developOnly+  BuildPhaseFlag ->+    long "build" Nothing "Run the `build` phase" developOnly+  CheckPhaseFlag ->+    long "check" Nothing "Run the `check` phase" developOnly+  InstallFlag ->+    long "install" Nothing "Run the `install` phase" developOnly+  InstallCheckFlag ->+    long "installcheck" Nothing "Run the `installCheck` phase" developOnly+  IgnoreEnvFlag ->+    shortAliased 'i' "ignore-env" "ignore-environment" Nothing "Start the shell with only the variables `--keep-env-var` names and those `--set-env-var` sets" developOnly+  KeepEnvVarFlag ->+    shortAliased 'k' "keep-env-var" "keep" (Just "NAME") "Keep the variable `NAME` under `--ignore-env` (repeatable)" developOnly+  UnsetEnvVarFlag ->+    shortAliased 'u' "unset-env-var" "unset" (Just "NAME") "Unset the variable `NAME` (repeatable)" developOnly+  SetEnvVarFlag ->+    short 's' "set-env-var" (Just "NAME VALUE") "Set the variable `NAME` to `VALUE` (repeatable)" developOnly+  SandboxFlag ->+    long "sandbox" Nothing "Enable sandboxing" evaluating+  NoSandboxFlag ->+    long "no-sandbox" Nothing "Disable sandboxing" evaluating+  RelaxedSandboxFlag ->+    long "relaxed-sandbox" Nothing "Enable sandboxing, but allow builds to disable it" evaluating+  ExecWrapperFlag ->+    long "exec-wrapper" (Just "S=PATH") "Run system `S`'s derivations through `PATH` (repeatable), e.g. `x86_64-windows=/usr/bin/wine`; refused where the store is reached through a daemon" (CommandFlag (EvalCommand :| [BuildCommand, ProfileAddCommand]))+  CacheFlag ->+    long "cache" (Just "URL") "The cache to push to: a nova-cache server's `http://` or `https://` URL, or a directory's `file://` URL (required)" pushOnly+  AllFlag ->+    long "all" Nothing "Select every valid path except derivations, in place of `PATH...`; for `profile remove`, every package" (CommandFlag (PushCommand :| [ProfileRemoveCommand]))+  KeyFileFlag ->+    long "key-file" (Just "PATH") "File holding a nova-cache server's API key" pushOnly+  SecretKeyFileFlag ->+    long "secret-key-file" (Just "PATH") "File holding the secret key that signs a `file://` cache's narinfos (required there)" pushOnly+  CompressionFlag ->+    long "compression" (Just "KIND") ("Artifact packaging (" <> pushCompressionValues <> "; default none)") pushOnly+  PrintRootsFlag ->+    long "print-roots" Nothing "List the roots as `LINK -> PATH` and delete nothing" (CommandFlag (StoreGcCommand :| []))+  KeyNameFlag ->+    long "key-name" (Just "NAME") "The name of the new key, such as `cache.example.org-1` (required)" (CommandFlag (KeyGenerateSecretCommand :| []))+  ProfileFlag ->+    long "profile" (Just "PATH") "Work on the profile at `PATH` in place of the default profile" (CommandFlag (ProfileAddCommand :| [ProfileRemoveCommand, ProfileListCommand, ProfileHistoryCommand, ProfileRollbackCommand, ProfileWipeHistoryCommand]))+  PriorityFlag ->+    long "priority" (Just "N") "Give the package priority `N` (default 5): of two files at one path, the profile links the one with the lower number" (CommandFlag (ProfileAddCommand :| []))+  RegexFlag ->+    long "regex" (Just "PATTERN") "Select the packages whose identifier a POSIX extended regular expression matches whole, ignoring case: for a package a flake added, its flake reference and attribute, and for any other the names of the store paths it holds, without their versions" (CommandFlag (ProfileRemoveCommand :| []))+  ToFlag ->+    long "to" (Just "N") "Switch to generation `N` in place of the one before the current" (CommandFlag (ProfileRollbackCommand :| []))+  OlderThanFlag ->+    long "older-than" (Just "AGE") "Delete only the generations older than `AGE`, `N` days written `Nd`, keeping the newest of them" (CommandFlag (ProfileWipeHistoryCommand :| []))+  DryRunFlag ->+    long "dry-run" Nothing "Say what the command would change, and change nothing" (CommandFlag (ProfileRollbackCommand :| [ProfileWipeHistoryCommand]))+  JsonFlag ->+    long "json" Nothing "Print JSON: the environment in place of the script, the profile's `manifest.json` in place of its packages' lines, or the report in place of its lines" jsonCommands+  PrettyFlag ->+    long "pretty" Nothing "With `--json`, indent the JSON, as when stdout is a terminal" jsonCommands+  NoPrettyFlag ->+    long "no-pretty" Nothing "With `--json`, print the JSON on one line, as when stdout is not a terminal" jsonCommands+  ForceTrustedFlag ->+    long "force-trusted" Nothing "Trust every client, without asking who it is" daemonOnly+  ForceUntrustedFlag ->+    long "force-untrusted" Nothing "Trust no client, without asking who it is" daemonOnly+  DefaultTrustFlag ->+    long "default-trust" Nothing "Admit and trust each client as `trusted-users` and `allowed-users` say (the default)" daemonOnly+  SocketPathFlag ->+    long "socket-path" (Just "PATH") "Listen on the socket at `PATH`, or on Windows the named pipe `PATH`, in place of `$NIX_DAEMON_SOCKET_PATH` and the default" daemonOnly+  StoreFlag ->+    long "store" (Just "STORE") "Use `STORE`: `auto`, the default, which opens the store directly when its `.nova-nix` directory can be read and written and otherwise goes through the daemon when its socket, or on Windows its pipe, is there; `daemon`, the daemon at its default address; `unix://PATH`, the daemon at that socket, or on Windows `unix://\\\\.\\pipe\\NAME`, that pipe; `local`, the platform store, opened directly; or a store directory, a path with a path separator in it (`./store` for one in the working directory, since a word on its own is refused, as upstream refuses it), which is the store itself, opened directly. Overrides the `store` setting and `NIX_REMOTE`. `daemon` serves a store it opens itself, so it reads this flag alone, and takes `auto` or `local` for the platform store or a store directory. A store that holds paths, none of them under the directory it is opened at, is refused" (CommandFlag (EvalCommand :| [BuildCommand, DevelopCommand, PrintDevEnvCommand, TrustCommand, PushCommand, StoreDeleteCommand, StoreGcCommand, ProfileAddCommand, ProfileRemoveCommand, ProfileListCommand, ProfileHistoryCommand, ProfileRollbackCommand, ProfileWipeHistoryCommand, KeyGenerateSecretCommand, KeyConvertSecretToPublicCommand, DaemonCommand]))+  HelpFlag ->+    long "help" Nothing "Print the commands, flags and settings, and exit" GlobalFlag+  VersionFlag ->+    long "version" Nothing "Print the version and exit" GlobalFlag+  where+    long longName = FlagEntry longName Nothing Nothing+    short letter longName = FlagEntry longName (Just letter) Nothing+    aliased longName aliasName = FlagEntry longName Nothing (Just aliasName)+    shortAliased letter longName aliasName = FlagEntry longName (Just letter) (Just aliasName)+    evalOnly = CommandFlag (EvalCommand :| [])+    buildOnly = CommandFlag (BuildCommand :| [])+    pushOnly = CommandFlag (PushCommand :| [])+    developOnly = CommandFlag (DevelopCommand :| [])+    daemonOnly = CommandFlag (DaemonCommand :| [])+    -- The commands that print JSON with --json.+    jsonCommands = CommandFlag (PrintDevEnvCommand :| [TrustCommand, ProfileListCommand])+    -- The commands that select an attribute of what they evaluate, and+    -- those that evaluate.+    selecting = CommandFlag (BuildCommand :| [DevelopCommand, PrintDevEnvCommand, TrustCommand, ProfileAddCommand])+    evaluating = CommandFlag (EvalCommand :| [BuildCommand, DevelopCommand, PrintDevEnvCommand, TrustCommand, ProfileAddCommand])+    -- The commands whose builds keep-failed can keep: trust builds only+    -- with builtins, which keep nothing.+    building = CommandFlag (EvalCommand :| [BuildCommand, DevelopCommand, PrintDevEnvCommand, ProfileAddCommand])++-- ---------------------------------------------------------------------------+-- Configuration+-- ---------------------------------------------------------------------------++-- | The nix.conf settings the CLI reads, and where it reads them.+data Configuration = Configuration+  { configSettings :: !(NonEmpty Setting),+    -- | Where the settings come from, in a paragraph.+    configDescription :: !Text+  }+  deriving (Eq, Show)++-- | A nix.conf setting.+data Setting = Setting+  { -- | Its name in @nix.conf@.+    settingName :: !Text,+    -- | What it does, in a line.+    settingDescription :: !Text,+    -- | The flag that adds to it on one invocation, where there is one: an+    -- entry to a list, or a Boolean moved from its default; for @sandbox@+    -- and @store@, the value the flag names, in place of the configured+    -- one.+    settingFlag :: !(Maybe FlagName)+  }+  deriving (Eq, Show)++-- | The settings, and where they are read.+configuration :: Configuration+configuration =+  Configuration+    { configSettings =+        Setting "substituters" "Binary caches a build substitutes from, each the `http://` or `https://` URL of one a server serves or the `file://` URL of a directory, such as one `push` writes (`file:///D:/cache` on Windows), which is asked at the `Priority` its `nix-cache-info` states, `0` when it states none" (Just SubstituterFlag)+          :| [ Setting "trusted-public-keys" "Public keys, one of which must have signed a substituted path, unless its content address makes the path or `require-sigs` is off" (Just TrustedKeyFlag),+               Setting "secret-key-files" "Files of secret keys, as `key generate-secret` writes them, whose public keys are trusted beside `trusted-public-keys`; a file that cannot be read is passed over" Nothing,+               Setting "require-sigs" "Whether a path that is not content-addressed must be signed by a trusted key to be substituted, or added through the daemon with its signatures checked (default `true`)" Nothing,+               Setting "store" "The store commands use, spelled as `--store` spells it (default: `$NIX_REMOTE`, else `auto`)" (Just StoreFlag),+               Setting "fallback" "Build from source when a substitute fails" (Just FallbackFlag),+               Setting "keep-failed" "Keep the directory of a build that fails, and the rebuild of an output `--check` finds different as `PATH.check` (default `false`)" (Just KeepFailedFlag),+               Setting "always-allow-substitutes" "Substitute a derivation whose `allowSubstitutes` attribute is false" Nothing,+               Setting "cores" "The `NIX_BUILD_CORES` a builder is given, `0` giving the default count: the CPU limit of the process's cgroup on Linux, otherwise the hardware threads (default `0`)" Nothing,+               Setting "max-call-depth" ("How many function calls may be active around a new one before evaluation refuses it (default " <> T.pack (show defaultMaxCallDepth) <> ")") Nothing,+               Setting "filetransfer-retry-attempts" ("How many times a download or upload is tried, a failure a retry could outlive being tried again; also named `download-attempts` (default " <> T.pack (show defaultDownloadAttempts) <> ")") Nothing,+               Setting "restrict-eval" "Turn on restricted evaluation" (Just RestrictEvalFlag),+               Setting "pure-eval" "Turn on pure evaluation" (Just PureEvalFlag),+               Setting "allowed-uris" "URI prefixes a fetch may reach under `restrict-eval`" Nothing,+               Setting "trace-verbose" "Make `builtins.traceVerbose` trace" (Just TraceVerboseFlag),+               Setting "allow-import-from-derivation" "Let a builtin that reads a path build or substitute what the path's context names (default: true)" (Just NoAllowImportFromDerivationFlag),+               Setting "trace-import-from-derivation" "Warn, naming the first output, when a builtin that reads a path realises what its context names" Nothing,+               Setting "experimental-features" "Experimental features to turn on, by upstream's names (default: none); a name upstream does not know is dropped with a warning" (Just ExtraExperimentalFeaturesFlag),+               Setting "sandbox" "Whether a build runs in a sandbox: `true`, `relaxed` (a build that is fixed-output or sets `__noChroot` does not) or `false` (default: `true` on Linux, `false` elsewhere)" (Just SandboxFlag),+               Setting "sandbox-fallback" "Build unsandboxed, after a warning, where a Linux system cannot make the sandbox; on macOS such a build fails (default `true`)" Nothing,+               Setting "sandbox-paths" "Host paths a sandboxed build sees, each `TARGET=SOURCE` or a path naming itself, with `?` after one that may be missing (default: on Linux `/bin/sh` as a release archive's bundled shell; on macOS `/System/Library/Frameworks`, `/System/Library/PrivateFrameworks`, `/bin/sh`, `/bin/bash` and `/usr/lib`)" Nothing,+               Setting "sandbox-build-dir" "Where a sandboxed build on Linux sees its build directory (default `/build`)" Nothing,+               Setting "sandbox-dev-shm-size" "The size of a sandboxed build's `/dev/shm`, as `tmpfs` takes it (default `50%`)" Nothing,+               Setting "allowed-impure-host-deps" "Host paths at or beneath which a derivation's `__impureHostDeps` may name one for a sandboxed build on macOS (default on macOS: `/System/Library`, `/usr/lib`, `/dev` and `/bin/sh`)" Nothing,+               Setting "darwin-log-sandbox-violations" "Send what a sandboxed build's profile refuses on macOS to the system log" Nothing,+               Setting "require-drop-supplementary-groups" "Fail a sandboxed build when the user's supplementary groups cannot be dropped (default: on for root)" Nothing,+               Setting "build-users-group" "The group whose members builds run as, one build to a member at a time, when nova-nix runs as root on Linux or macOS, and whose members may not connect to the daemon; with it empty a build runs as the user nova-nix runs as (default: `nixbld` for root, empty otherwise)" Nothing,+               Setting "use-xdg-base-directories" "Link the default profile from `profile` in the state directory in place of `~/.nix-profile` (default `false`)" Nothing,+               Setting "ssl-cert-file" "The CA bundle a sandboxed fixed-output build sees (default: `$NIX_SSL_CERT_FILE`, `$SSL_CERT_FILE`, or the first that exists of `/etc/ssl/certs/ca-certificates.crt` and `etc/ssl/certs/ca-bundle.crt` under `/nix/var/nix/profiles/default`)" Nothing,+               Setting "bash-prompt" "The prompt (`PS1`) of an interactive `develop` shell, in place of the user's" Nothing,+               Setting "bash-prompt-prefix" "Text put before the prompt of an interactive `develop` shell" Nothing,+               Setting "bash-prompt-suffix" "Text put after the prompt of an interactive `develop` shell" Nothing,+               Setting "trusted-users" "The users the daemon trusts, each a name, `@GROUP` for a group's members, or `*` for everyone; on Windows an account's name, `NAME` for one of this machine, `DOMAIN\\NAME` or `NAME@DOMAIN` for another, or its SID (default `root`, and on Windows `@S-1-5-32-544`, the machine's administrators)" Nothing,+               Setting "allowed-users" "The users who may connect to the daemon, named as `trusted-users` names them; a trusted user always may (default `*`)" Nothing,+               Setting "trusted-substituters" "Substituters a client the daemon does not trust may ask it for, besides those it uses" Nothing+             ],+      configDescription =+        "`nix.conf` is read in upstream's order: `$NIX_CONF_DIR/nix.conf`, where `NIX_CONF_DIR` defaults to "+          <> codeSpan (systemConfDirName PosixHost)+          <> ", or "+          <> codeSpan (systemConfDirName WindowsHost)+          <> " on Windows; the XDG `nix/nix.conf` files, the config home's in `$NIX_CONFIG_HOME` when that is set, or `$NIX_USER_CONF_FILES`; then `$NIX_CONFIG`. A later source replaces an earlier one's value, an `extra-` prefix on a list setting adds to it instead, and a flag adds to whatever they configure: an entry to a list, or a Boolean moved from its default, which a flag cannot move back."+    }++-- ---------------------------------------------------------------------------+-- Hosts+-- ---------------------------------------------------------------------------++-- | The two families of host whose conventions differ in what the CLI+-- reads.+data Host = PosixHost | WindowsHost+  deriving (Eq, Show)++-- | The host this binary was built for.+currentHost :: Host+currentHost = case SI.os of+  "mingw32" -> WindowsHost+  _ -> PosixHost++-- | Where a host's machine-wide config directory comes from, with @nix@+-- beneath it either way: a fixed path (upstream's @sysconfdir@ on Unix) or+-- an environment variable naming it (@%ProgramData%@ on Windows).  One+-- value serves both the lookup and the reference's text, so the two+-- cannot disagree.+data SystemConfDirSource = FixedConfDir !FilePath | EnvConfDir !BS.ByteString+  deriving (Eq, Show)++-- | A host's machine-wide config directory.+systemConfDirSource :: Host -> SystemConfDirSource+systemConfDirSource host = case host of+  PosixHost -> FixedConfDir posixSysconfDir+  WindowsHost -> EnvConfDir programDataVar++-- | Upstream's @sysconfdir@ on Unix, which libstore's meson.build forces+-- absolute, so @\/etc\/nix@ is the compiled-in system directory.+posixSysconfDir :: FilePath+posixSysconfDir = "/etc"++-- | Windows' all-users application data directory, the machine-wide+-- config directory there.+programDataVar :: BS.ByteString+programDataVar = "ProgramData"++-- | The system config directory as the reference names it: the path on+-- POSIX, the variable on Windows, each joined with that host's separator+-- whichever host renders it.+systemConfDirName :: Host -> Text+systemConfDirName host = T.pack (base `joined` T.unpack (hostPathText Config.nixConfDirName))+  where+    base = case systemConfDirSource host of+      FixedConfDir dir -> dir+      EnvConfDir var -> "%" <> BC.unpack var <> "%"+    joined = case host of+      PosixHost -> (Posix.</>)+      WindowsHost -> (Windows.</>)++-- ---------------------------------------------------------------------------+-- Help+-- ---------------------------------------------------------------------------++-- | The width @--help@ wraps its text to.+helpWidth :: Int+helpWidth = 80++-- | How far an entry is indented.+helpIndent :: Int+helpIndent = 2++-- | The least space between an entry and its description.+helpGap :: Int+helpGap = 2++-- | What @--help@ prints: the usage line, each command's forms, the flags+-- grouped by the commands they apply to, each group's title wrapped as its+-- text is, the settings and where they are read, then the global form's+-- flags.+helpLines :: [Text]+helpLines =+  usageLines+    ++ section "Commands:" commandRows+    ++ concatMap (uncurry section) flagGroups+    ++ section "Settings read from nix.conf:" settingRows+    ++ [""]+    ++ map (indentBy helpIndent) (wrapWords (helpWidth - helpIndent) (unmarked (configDescription configuration)))+    ++ [""]+    ++ concatMap (row . flagRow) globalFlags+  where+    usagePrefix = "Usage: "+    usageLines = case fmap (formUsage [programName]) (commandForms globalForm) of+      first :| rest -> (usagePrefix <> first) : map (indentBy (T.length usagePrefix)) rest+    section header rows = "" : wrapWords helpWidth header ++ concatMap row rows+    commandRows =+      [ (formUsage (commandWords name) form, unmarked (formSummary form))+      | name <- commandNames,+        form <- toList (commandForms (command name))+      ]+    flagGroups =+      [ ("Flags for " <> describeCommands names <> ":", map flagRow members)+      | (names, members) <- sortOn groupOrder (Map.toList (Map.fromListWith (flip (++)) grouped))+      ]+    grouped = [(Set.fromList (toList names), [name]) | name <- flagNames, CommandFlag names <- [flagScope (flag name)]]+    groupOrder (names, _) = (Set.lookupMin names, Down (Set.size names))+    settingRows =+      [ (settingName setting, unmarked (settingDescription setting) <> maybe "" (\name -> " (" <> longSpelling (flag name) <> ")") (settingFlag setting))+      | setting <- toList (configSettings configuration)+      ]+    entries = map fst (commandRows ++ concatMap snd flagGroups ++ settingRows ++ map flagRow globalFlags)+    column = helpIndent + foldl' max 0 (map T.length entries) + helpGap+    row (entry, description) = case wrapWords (helpWidth - column) description of+      [] -> [indentBy helpIndent entry]+      first : rest ->+        (indentBy helpIndent (T.justifyLeft (column - helpIndent) ' ' entry) <> first)+          : map (indentBy column) rest++-- | A flag's entry in @--help@: its spellings and its argument, and its+-- description.+flagRow :: FlagName -> (Text, Text)+flagRow name =+  (T.intercalate ", " (toList (flagSpellings entry)) <> maybe "" (" " <>) (flagArgument entry), unmarked (flagDescription entry))+  where+    entry = flag name++-- | Marked text as @--help@ prints it, without its code marks.+unmarked :: Text -> Text+unmarked = T.filter (/= codeMark)++-- | Commands named in a sentence: each by its words, @every command@ for+-- all of them.+describeCommands :: Set.Set CommandName -> Text+describeCommands names+  | names == Set.fromList commandNames = "every command"+  | otherwise = joinWithAnd (map (T.unwords . commandWords) (Set.toAscList names))++-- | Items in a sentence: @a@, @a and b@, @a, b and c@.+joinWithAnd :: [Text] -> Text+joinWithAnd items = case reverse items of+  [] -> ""+  [only] -> only+  final : before -> T.intercalate ", " (reverse before) <> " and " <> final++-- | Text after @width@ spaces.+indentBy :: Int -> Text -> Text+indentBy width = (T.replicate width " " <>)++-- | Text broken into lines of at most @width@ characters, at spaces, each+-- line as full as it can be.  A word longer than the width is a line of+-- its own.+wrapWords :: Int -> Text -> [Text]+wrapWords width text = case T.words text of+  [] -> []+  first : rest -> go first rest+  where+    go line [] = [line]+    go line (word : more)+      | T.length line + 1 + T.length word <= width = go (line <> " " <> word) more+      | otherwise = line : go word more++-- ---------------------------------------------------------------------------+-- JSON+-- ---------------------------------------------------------------------------++-- | The reference as JSON, the bytes of @docs\/cli.json@: the global form,+-- the commands, the flags and the configuration, each command and flag in+-- order, and a command named as it is invoked.+referenceJson :: BS.ByteString+referenceJson =+  renderIndentedJson $+    object+      [ ("program", JsonString programName),+        ("global", commandJson programName [programName] globalForm),+        ("commands", JsonArray [commandJson (commandInvocation name) (programName : commandWords name) (command name) | name <- commandNames]),+        ("flags", JsonArray (map flagJson flagNames)),+        ("configuration", configurationJson)+      ]+  where+    commandJson invocation commandPart entry =+      object+        [ ("name", JsonString invocation),+          ("synopsis", JsonArray [object [("usage", JsonString (formUsage commandPart form)), ("summary", JsonString (formSummary form))] | form <- toList (commandForms entry)]),+          ("description", JsonString (commandDescription entry)),+          ("examples", JsonArray (map exampleJson (toList (commandExamples entry))))+        ]+    exampleJson example =+      object+        [ ("description", JsonString (exampleDescription example)),+          ("arguments", strings (toList (exampleArguments example))),+          ("command", JsonString (exampleCommandLine example)),+          ("output", strings (exampleOutput example))+        ]+    flagJson name =+      let entry = flag name+       in object+            [ ("name", JsonString (longSpelling entry)),+              ("spellings", strings (toList (flagSpellings entry))),+              ("argument", maybe JsonNull JsonString (flagArgument entry)),+              ("description", JsonString (flagDescription entry)),+              ("commands", strings (scopeInvocations (flagScope entry)))+            ]+    scopeInvocations GlobalFlag = [programName]+    scopeInvocations (CommandFlag names) = map commandInvocation (toList names)+    configurationJson =+      object+        [ ("description", JsonString (configDescription configuration)),+          ( "settings",+            JsonArray+              [ object+                  [ ("name", JsonString (settingName setting)),+                    ("description", JsonString (settingDescription setting)),+                    ("flag", maybe JsonNull (JsonString . longSpelling . flag) (settingFlag setting))+                  ]+              | setting <- toList (configSettings configuration)+              ]+          )+        ]+    object = JsonObject . Map.fromList+    strings = JsonArray . map JsonString++-- | JSON laid out one member or element per line, indented two spaces a+-- level, with a final newline: the layout of JavaScript's+-- @JSON.stringify(value, null, 2)@, so a change to one entry is a change+-- to its lines alone.  Each value is written as 'renderJson' writes it.+renderIndentedJson :: Json -> BS.ByteString+renderIndentedJson value = BL.toStrict (BB.toLazyByteString (layout 0 value <> BB.char7 '\n'))+  where+    layout :: Int -> Json -> BB.Builder+    layout depth json = case json of+      JsonArray items@(_ : _) -> nested depth '[' ']' (map (layout (depth + 1)) items)+      JsonObject members+        | not (Map.null members) ->+            nested depth '{' '}' [BB.byteString (renderJson (JsonString key)) <> ": " <> layout (depth + 1) member | (key, member) <- Map.toAscList members]+      leaf -> BB.byteString (renderJson leaf)+    nested depth open close items =+      BB.char7 open+        <> mconcat (intersperse (BB.char7 ',') (map (\item -> newline (depth + 1) <> item) items))+        <> newline depth+        <> BB.char7 close+    newline depth = BB.char7 '\n' <> BB.byteString (BC.replicate (2 * depth) ' ')
+ data/develop/COPYING view
@@ -0,0 +1,501 @@+                  GNU LESSER GENERAL PUBLIC LICENSE+                       Version 2.1, February 1999++ Copyright (C) 1991, 1999 Free Software Foundation, Inc.+ <https://fsf.org/>+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++[This is the first released version of the Lesser GPL.  It also counts+ as the successor of the GNU Library Public License, version 2, hence+ the version number 2.1.]++                            Preamble++  The licenses for most software are designed to take away your+freedom to share and change it.  By contrast, the GNU General Public+Licenses are intended to guarantee your freedom to share and change+free software--to make sure the software is free for all its users.++  This license, the Lesser General Public License, applies to some+specially designated software packages--typically libraries--of the+Free Software Foundation and other authors who decide to use it.  You+can use it too, but we suggest you first think carefully about whether+this license or the ordinary General Public License is the better+strategy to use in any particular case, based on the explanations below.++  When we speak of free software, we are referring to freedom of use,+not price.  Our General Public Licenses are designed to make sure that+you have the freedom to distribute copies of free software (and charge+for this service if you wish); that you receive source code or can get+it if you want it; that you can change the software and use pieces of+it in new free programs; and that you are informed that you can do+these things.++  To protect your rights, we need to make restrictions that forbid+distributors to deny you these rights or to ask you to surrender these+rights.  These restrictions translate to certain responsibilities for+you if you distribute copies of the library or if you modify it.++  For example, if you distribute copies of the library, whether gratis+or for a fee, you must give the recipients all the rights that we gave+you.  You must make sure that they, too, receive or can get the source+code.  If you link other code with the library, you must provide+complete object files to the recipients, so that they can relink them+with the library after making changes to the library and recompiling+it.  And you must show them these terms so they know their rights.++  We protect your rights with a two-step method: (1) we copyright the+library, and (2) we offer you this license, which gives you legal+permission to copy, distribute and/or modify the library.++  To protect each distributor, we want to make it very clear that+there is no warranty for the free library.  Also, if the library is+modified by someone else and passed on, the recipients should know+that what they have is not the original version, so that the original+author's reputation will not be affected by problems that might be+introduced by others.++  Finally, software patents pose a constant threat to the existence of+any free program.  We wish to make sure that a company cannot+effectively restrict the users of a free program by obtaining a+restrictive license from a patent holder.  Therefore, we insist that+any patent license obtained for a version of the library must be+consistent with the full freedom of use specified in this license.++  Most GNU software, including some libraries, is covered by the+ordinary GNU General Public License.  This license, the GNU Lesser+General Public License, applies to certain designated libraries, and+is quite different from the ordinary General Public License.  We use+this license for certain libraries in order to permit linking those+libraries into non-free programs.++  When a program is linked with a library, whether statically or using+a shared library, the combination of the two is legally speaking a+combined work, a derivative of the original library.  The ordinary+General Public License therefore permits such linking only if the+entire combination fits its criteria of freedom.  The Lesser General+Public License permits more lax criteria for linking other code with+the library.++  We call this license the "Lesser" General Public License because it+does Less to protect the user's freedom than the ordinary General+Public License.  It also provides other free software developers Less+of an advantage over competing non-free programs.  These disadvantages+are the reason we use the ordinary General Public License for many+libraries.  However, the Lesser license provides advantages in certain+special circumstances.++  For example, on rare occasions, there may be a special need to+encourage the widest possible use of a certain library, so that it becomes+a de-facto standard.  To achieve this, non-free programs must be+allowed to use the library.  A more frequent case is that a free+library does the same job as widely used non-free libraries.  In this+case, there is little to gain by limiting the free library to free+software only, so we use the Lesser General Public License.++  In other cases, permission to use a particular library in non-free+programs enables a greater number of people to use a large body of+free software.  For example, permission to use the GNU C Library in+non-free programs enables many more people to use the whole GNU+operating system, as well as its variant, the GNU/Linux operating+system.++  Although the Lesser General Public License is Less protective of the+users' freedom, it does ensure that the user of a program that is+linked with the Library has the freedom and the wherewithal to run+that program using a modified version of the Library.++  The precise terms and conditions for copying, distribution and+modification follow.  Pay close attention to the difference between a+"work based on the library" and a "work that uses the library".  The+former contains code derived from the library, whereas the latter must+be combined with the library in order to run.++                  GNU LESSER GENERAL PUBLIC LICENSE+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION++  0. This License Agreement applies to any software library or other+program which contains a notice placed by the copyright holder or+other authorized party saying it may be distributed under the terms of+this Lesser General Public License (also called "this License").+Each licensee is addressed as "you".++  A "library" means a collection of software functions and/or data+prepared so as to be conveniently linked with application programs+(which use some of those functions and data) to form executables.++  The "Library", below, refers to any such software library or work+which has been distributed under these terms.  A "work based on the+Library" means either the Library or any derivative work under+copyright law: that is to say, a work containing the Library or a+portion of it, either verbatim or with modifications and/or translated+straightforwardly into another language.  (Hereinafter, translation is+included without limitation in the term "modification".)++  "Source code" for a work means the preferred form of the work for+making modifications to it.  For a library, complete source code means+all the source code for all modules it contains, plus any associated+interface definition files, plus the scripts used to control compilation+and installation of the library.++  Activities other than copying, distribution and modification are not+covered by this License; they are outside its scope.  The act of+running a program using the Library is not restricted, and output from+such a program is covered only if its contents constitute a work based+on the Library (independent of the use of the Library in a tool for+writing it).  Whether that is true depends on what the Library does+and what the program that uses the Library does.++  1. You may copy and distribute verbatim copies of the Library's+complete source code as you receive it, in any medium, provided that+you conspicuously and appropriately publish on each copy an+appropriate copyright notice and disclaimer of warranty; keep intact+all the notices that refer to this License and to the absence of any+warranty; and distribute a copy of this License along with the+Library.++  You may charge a fee for the physical act of transferring a copy,+and you may at your option offer warranty protection in exchange for a+fee.++  2. You may modify your copy or copies of the Library or any portion+of it, thus forming a work based on the Library, and copy and+distribute such modifications or work under the terms of Section 1+above, provided that you also meet all of these conditions:++    a) The modified work must itself be a software library.++    b) You must cause the files modified to carry prominent notices+    stating that you changed the files and the date of any change.++    c) You must cause the whole of the work to be licensed at no+    charge to all third parties under the terms of this License.++    d) If a facility in the modified Library refers to a function or a+    table of data to be supplied by an application program that uses+    the facility, other than as an argument passed when the facility+    is invoked, then you must make a good faith effort to ensure that,+    in the event an application does not supply such function or+    table, the facility still operates, and performs whatever part of+    its purpose remains meaningful.++    (For example, a function in a library to compute square roots has+    a purpose that is entirely well-defined independent of the+    application.  Therefore, Subsection 2d requires that any+    application-supplied function or table used by this function must+    be optional: if the application does not supply it, the square+    root function must still compute square roots.)++These requirements apply to the modified work as a whole.  If+identifiable sections of that work are not derived from the Library,+and can be reasonably considered independent and separate works in+themselves, then this License, and its terms, do not apply to those+sections when you distribute them as separate works.  But when you+distribute the same sections as part of a whole which is a work based+on the Library, the distribution of the whole must be on the terms of+this License, whose permissions for other licensees extend to the+entire whole, and thus to each and every part regardless of who wrote+it.++Thus, it is not the intent of this section to claim rights or contest+your rights to work written entirely by you; rather, the intent is to+exercise the right to control the distribution of derivative or+collective works based on the Library.++In addition, mere aggregation of another work not based on the Library+with the Library (or with a work based on the Library) on a volume of+a storage or distribution medium does not bring the other work under+the scope of this License.++  3. You may opt to apply the terms of the ordinary GNU General Public+License instead of this License to a given copy of the Library.  To do+this, you must alter all the notices that refer to this License, so+that they refer to the ordinary GNU General Public License, version 2,+instead of to this License.  (If a newer version than version 2 of the+ordinary GNU General Public License has appeared, then you can specify+that version instead if you wish.)  Do not make any other change in+these notices.++  Once this change is made in a given copy, it is irreversible for+that copy, so the ordinary GNU General Public License applies to all+subsequent copies and derivative works made from that copy.++  This option is useful when you wish to copy part of the code of+the Library into a program that is not a library.++  4. You may copy and distribute the Library (or a portion or+derivative of it, under Section 2) in object code or executable form+under the terms of Sections 1 and 2 above provided that you accompany+it with the complete corresponding machine-readable source code, which+must be distributed under the terms of Sections 1 and 2 above on a+medium customarily used for software interchange.++  If distribution of object code is made by offering access to copy+from a designated place, then offering equivalent access to copy the+source code from the same place satisfies the requirement to+distribute the source code, even though third parties are not+compelled to copy the source along with the object code.++  5. A program that contains no derivative of any portion of the+Library, but is designed to work with the Library by being compiled or+linked with it, is called a "work that uses the Library".  Such a+work, in isolation, is not a derivative work of the Library, and+therefore falls outside the scope of this License.++  However, linking a "work that uses the Library" with the Library+creates an executable that is a derivative of the Library (because it+contains portions of the Library), rather than a "work that uses the+library".  The executable is therefore covered by this License.+Section 6 states terms for distribution of such executables.++  When a "work that uses the Library" uses material from a header file+that is part of the Library, the object code for the work may be a+derivative work of the Library even though the source code is not.+Whether this is true is especially significant if the work can be+linked without the Library, or if the work is itself a library.  The+threshold for this to be true is not precisely defined by law.++  If such an object file uses only numerical parameters, data+structure layouts and accessors, and small macros and small inline+functions (ten lines or less in length), then the use of the object+file is unrestricted, regardless of whether it is legally a derivative+work.  (Executables containing this object code plus portions of the+Library will still fall under Section 6.)++  Otherwise, if the work is a derivative of the Library, you may+distribute the object code for the work under the terms of Section 6.+Any executables containing that work also fall under Section 6,+whether or not they are linked directly with the Library itself.++  6. As an exception to the Sections above, you may also combine or+link a "work that uses the Library" with the Library to produce a+work containing portions of the Library, and distribute that work+under terms of your choice, provided that the terms permit+modification of the work for the customer's own use and reverse+engineering for debugging such modifications.++  You must give prominent notice with each copy of the work that the+Library is used in it and that the Library and its use are covered by+this License.  You must supply a copy of this License.  If the work+during execution displays copyright notices, you must include the+copyright notice for the Library among them, as well as a reference+directing the user to the copy of this License.  Also, you must do one+of these things:++    a) Accompany the work with the complete corresponding+    machine-readable source code for the Library including whatever+    changes were used in the work (which must be distributed under+    Sections 1 and 2 above); and, if the work is an executable linked+    with the Library, with the complete machine-readable "work that+    uses the Library", as object code and/or source code, so that the+    user can modify the Library and then relink to produce a modified+    executable containing the modified Library.  (It is understood+    that the user who changes the contents of definitions files in the+    Library will not necessarily be able to recompile the application+    to use the modified definitions.)++    b) Use a suitable shared library mechanism for linking with the+    Library.  A suitable mechanism is one that (1) uses at run time a+    copy of the library already present on the user's computer system,+    rather than copying library functions into the executable, and (2)+    will operate properly with a modified version of the library, if+    the user installs one, as long as the modified version is+    interface-compatible with the version that the work was made with.++    c) Accompany the work with a written offer, valid for at+    least three years, to give the same user the materials+    specified in Subsection 6a, above, for a charge no more+    than the cost of performing this distribution.++    d) If distribution of the work is made by offering access to copy+    from a designated place, offer equivalent access to copy the above+    specified materials from the same place.++    e) Verify that the user has already received a copy of these+    materials or that you have already sent this user a copy.++  For an executable, the required form of the "work that uses the+Library" must include any data and utility programs needed for+reproducing the executable from it.  However, as a special exception,+the materials to be distributed need not include anything that is+normally distributed (in either source or binary form) with the major+components (compiler, kernel, and so on) of the operating system on+which the executable runs, unless that component itself accompanies+the executable.++  It may happen that this requirement contradicts the license+restrictions of other proprietary libraries that do not normally+accompany the operating system.  Such a contradiction means you cannot+use both them and the Library together in an executable that you+distribute.++  7. You may place library facilities that are a work based on the+Library side-by-side in a single library together with other library+facilities not covered by this License, and distribute such a combined+library, provided that the separate distribution of the work based on+the Library and of the other library facilities is otherwise+permitted, and provided that you do these two things:++    a) Accompany the combined library with a copy of the same work+    based on the Library, uncombined with any other library+    facilities.  This must be distributed under the terms of the+    Sections above.++    b) Give prominent notice with the combined library of the fact+    that part of it is a work based on the Library, and explaining+    where to find the accompanying uncombined form of the same work.++  8. You may not copy, modify, sublicense, link with, or distribute+the Library except as expressly provided under this License.  Any+attempt otherwise to copy, modify, sublicense, link with, or+distribute the Library is void, and will automatically terminate your+rights under this License.  However, parties who have received copies,+or rights, from you under this License will not have their licenses+terminated so long as such parties remain in full compliance.++  9. You are not required to accept this License, since you have not+signed it.  However, nothing else grants you permission to modify or+distribute the Library or its derivative works.  These actions are+prohibited by law if you do not accept this License.  Therefore, by+modifying or distributing the Library (or any work based on the+Library), you indicate your acceptance of this License to do so, and+all its terms and conditions for copying, distributing or modifying+the Library or works based on it.++  10. Each time you redistribute the Library (or any work based on the+Library), the recipient automatically receives a license from the+original licensor to copy, distribute, link with or modify the Library+subject to these terms and conditions.  You may not impose any further+restrictions on the recipients' exercise of the rights granted herein.+You are not responsible for enforcing compliance by third parties with+this License.++  11. If, as a consequence of a court judgment or allegation of patent+infringement or for any other reason (not limited to patent issues),+conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License.  If you cannot+distribute so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you+may not distribute the Library at all.  For example, if a patent+license would not permit royalty-free redistribution of the Library by+all those who receive copies directly or indirectly through you, then+the only way you could satisfy both it and this License would be to+refrain entirely from distribution of the Library.++If any portion of this section is held invalid or unenforceable under any+particular circumstance, the balance of the section is intended to apply,+and the section as a whole is intended to apply in other circumstances.++It is not the purpose of this section to induce you to infringe any+patents or other property right claims or to contest validity of any+such claims; this section has the sole purpose of protecting the+integrity of the free software distribution system which is+implemented by public license practices.  Many people have made+generous contributions to the wide range of software distributed+through that system in reliance on consistent application of that+system; it is up to the author/donor to decide if he or she is willing+to distribute software through any other system and a licensee cannot+impose that choice.++This section is intended to make thoroughly clear what is believed to+be a consequence of the rest of this License.++  12. If the distribution and/or use of the Library is restricted in+certain countries either by patents or by copyrighted interfaces, the+original copyright holder who places the Library under this License may add+an explicit geographical distribution limitation excluding those countries,+so that distribution is permitted only in or among countries not thus+excluded.  In such case, this License incorporates the limitation as if+written in the body of this License.++  13. The Free Software Foundation may publish revised and/or new+versions of the Lesser General Public License from time to time.+Such new versions will be similar in spirit to the present version,+but may differ in detail to address new problems or concerns.++Each version is given a distinguishing version number.  If the Library+specifies a version number of this License which applies to it and+"any later version", you have the option of following the terms and+conditions either of that version or of any later version published by+the Free Software Foundation.  If the Library does not specify a+license version number, you may choose any version ever published by+the Free Software Foundation.++  14. If you wish to incorporate parts of the Library into other free+programs whose distribution conditions are incompatible with these,+write to the author to ask for permission.  For software which is+copyrighted by the Free Software Foundation, write to the Free+Software Foundation; we sometimes make exceptions for this.  Our+decision will be guided by the two goals of preserving the free status+of all derivatives of our free software and of promoting the sharing+and reuse of software generally.++                            NO WARRANTY++  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE+LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH+DAMAGES.++                     END OF TERMS AND CONDITIONS++           How to Apply These Terms to Your New Libraries++  If you develop a new library, and you want it to be of the greatest+possible use to the public, we recommend making it free software that+everyone can redistribute and change.  You can do so by permitting+redistribution under these terms (or, alternatively, under the terms of the+ordinary General Public License).++  To apply these terms, attach the following notices to the library.  It is+safest to attach them to the start of each source file to most effectively+convey the exclusion of warranty; and each file should have at least the+"copyright" line and a pointer to where the full notice is found.++    <one line to give the library's name and a brief idea of what it does.>+    Copyright (C) <year>  <name of author>++    This library is free software; you can redistribute it and/or+    modify it under the terms of the GNU Lesser General Public+    License as published by the Free Software Foundation; either+    version 2.1 of the License, or (at your option) any later version.++    This library is distributed in the hope that it will be useful,+    but WITHOUT ANY WARRANTY; without even the implied warranty of+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU+    Lesser General Public License for more details.++    You should have received a copy of the GNU Lesser General Public+    License along with this library; if not, see <https://www.gnu.org/licenses/>.++Also add information on how to contact you by electronic and paper mail.++You should also get your employer (if you work as a programmer) or your+school, if any, to sign a "copyright disclaimer" for the library, if+necessary.  Here is a sample; alter the names:++  Yoyodyne, Inc., hereby disclaims all copyright interest in the+  library `Frob' (a library for tweaking knobs) written by James Random Hacker.++  <signature of Moe Ghoul>, 1 April 1990+  Moe Ghoul, President of Vice++That's all there is to it!
+ data/develop/get-env.sh view
@@ -0,0 +1,158 @@+# shellcheck shell=bash+set -e+# shellcheck disable=SC1090  # Dynamic sourcing is intentional+if [ -e "$NIX_ATTRS_SH_FILE" ]; then source "$NIX_ATTRS_SH_FILE"; fi++export IN_NIX_SHELL=impure+export dontAddDisableDepTrack=1++if [[ -n $stdenv ]]; then+    # shellcheck disable=SC1091  # setup file is in nix store+    source "$stdenv"/setup+fi++# Better to use compgen, but stdenv bash doesn't have it.+__vars="$(declare -p)"+__functions="$(declare -F)"++__dumpEnv() {+    printf '{\n'++    printf '  "bashFunctions": {\n'+    local __first=1+    while read -r __line; do+        if ! [[ $__line =~ ^declare\ -f\ (.*) ]]; then continue; fi+        __fun_name="${BASH_REMATCH[1]}"+        __fun_body="$(type "$__fun_name")"+        if [[ $__fun_body =~ \{(.*)\} ]]; then+            if [[ -z $__first ]]; then printf ',\n'; else __first=; fi+            __fun_body="${BASH_REMATCH[1]}"+            printf "    "+            __escapeString "$__fun_name"+            printf ':'+            __escapeString "$__fun_body"+        else+            printf "Cannot parse definition of function '%s'.\n" "$__fun_name" >&2+            return 1+        fi+    done < <(printf "%s\n" "$__functions")+    printf '\n  },\n'++    printf '  "variables": {\n'+    local __first=1+    while read -r __line; do+        if ! [[ $__line =~ ^declare\ (-[^ ])\ ([^=]*) ]]; then continue; fi+        local type="${BASH_REMATCH[1]}"+        local __var_name="${BASH_REMATCH[2]}"++        if [[ $__var_name =~ ^BASH_ || \+              $__var_name =~ ^COMP_ || \+              $__var_name = _ || \+              $__var_name = DIRSTACK || \+              $__var_name = EUID || \+              $__var_name = FUNCNAME || \+              $__var_name = HISTCMD || \+              $__var_name = HOSTNAME || \+              $__var_name = GROUPS || \+              $__var_name = PIPESTATUS || \+              $__var_name = PWD || \+              $__var_name = RANDOM || \+              $__var_name = SHLVL || \+              $__var_name = SECONDS || \+              $__var_name = EPOCHREALTIME || \+              $__var_name = EPOCHSECONDS \+            ]]; then continue; fi++        if [[ -z $__first ]]; then printf ',\n'; else __first=; fi++        printf "    "+        __escapeString "$__var_name"+        printf ': {'++        # FIXME: handle -i, -r, -n.+        if [[ $type == -x ]]; then+            printf '"type": "exported", "value": '+            __escapeString "${!__var_name}"+        elif [[ $type == -- ]]; then+            printf '"type": "var", "value": '+            __escapeString "${!__var_name}"+        elif [[ $type == -a ]]; then+            printf '"type": "array", "value": ['+            local __first2=1+            # shellcheck disable=SC1087  # Complex array manipulation, syntax is correct+            __var_name="$__var_name[@]"+            # shellcheck disable=SC1087  # Complex array manipulation, syntax is correct+            for __i in "${!__var_name}"; do+                if [[ -z $__first2 ]]; then printf ', '; else __first2=; fi+                __escapeString "$__i"+                printf ' '+            done+            printf ']'+        elif [[ $type == -A ]]; then+            printf '"type": "associative", "value": {\n'+            local __first2=1+            declare -n __var_name2="$__var_name"+            for __i in "${!__var_name2[@]}"; do+                if [[ -z $__first2 ]]; then printf ',\n'; else __first2=; fi+                printf "      "+                __escapeString "$__i"+                printf ": "+                __escapeString "${__var_name2[$__i]}"+            done+            printf '\n    }'+        else+            printf '"type": "unknown"'+        fi++        printf "}"+    done < <(printf "%s\n" "$__vars")+    printf '\n  }'++    if [ -e "$NIX_ATTRS_SH_FILE" ]; then+        printf ',\n  "structuredAttrs": {\n    '+        __escapeString ".attrs.sh"+        printf ': '+        __escapeString "$(<"$NIX_ATTRS_SH_FILE")"+        printf ',\n    '+        __escapeString ".attrs.json"+        printf ': '+        __escapeString "$(<"$NIX_ATTRS_JSON_FILE")"+        printf '\n  }'+    fi++    printf '\n}'+}++__escapeString() {+    local __s="$1"+    __s="${__s//\\/\\\\}"+    __s="${__s//\"/\\\"}"+    __s="${__s//$'\n'/\\n}"+    __s="${__s//$'\r'/\\r}"+    __s="${__s//$'\t'/\\t}"+    printf '"%s"' "$__s"+}++__dumpEnvToOutput() {+    local __output="$1"+    if [[ -z ${__done-} ]]; then+        __dumpEnv > "$__output"+        __done=1+    else+        echo -n >> "$__output"+    fi+}++# In case of `__structuredAttrs = true;` the list of outputs is an associative+# array with a format like `outname => /nix/store/hash-drvname-outname`.+# Otherwise it is a space-separated list of output variable names.+if [ -e "$NIX_ATTRS_SH_FILE" ]; then+    # shellcheck disable=SC2154  # outputs is set by sourced file+    for __output in "${outputs[@]}"; do+        __dumpEnvToOutput "$__output"+    done+else+    for __outname in $outputs; do+        __dumpEnvToOutput "${!__outname}"+    done+fi
data/nix/fetchurl.nix view
@@ -53,9 +53,9 @@     # (see Nix.Builder.runBuiltinFetchurl).     builder = "builtin:fetchurl"; -    # An unpacked or executable output is a tree, so its fixed-output-    # hash must be taken over the NAR serialisation rather than the-    # flat file bytes.+    # An unpacked output is a tree, and an executable one a file whose+    # mode only a NAR records, so the fixed-output hash of either is+    # taken over the NAR serialisation rather than the flat file bytes.     outputHashMode = if unpack || executable then "recursive" else "flat";      inherit
nova-nix.cabal view
@@ -1,6 +1,6 @@ cabal-version:      3.0 name:               nova-nix-version:            0.10.0.0+version:            0.11.0.0 synopsis:           Windows-native Nix implementation in Haskell and C99 description:   An implementation of Nix for Windows, written in Haskell with a C99@@ -11,13 +11,13 @@    On the derivations its CI checks, over pinned pairs of Nix and nixpkgs,   the derivation paths it computes match upstream's.  On Windows it builds-  packages from source through a stage-1 stdenv over prebuilt MinGW-w64-  and MSYS2 packages pinned by SHA-256, and builds GNU Mes from a-  1,623-byte seed.  The project is experimental; see the README for what-  is not implemented.+  a toolchain from a 1,623-byte seed, through GNU Mes, TinyCC and GCC+  4.6.4, 10 and 16, to the native x86_64 GCC its stdenv wraps, and builds+  packages from source with it.  The project is experimental; see the+  README for what is not implemented. -  Evaluation needs the C data layer, so library code must run it between-  @Nix.Eval.Arena.arenaInit@ and @Nix.Eval.Arena.arenaDestroy@.+  Evaluation runs in a session (@Nix.Eval.IO.withEvalSession@), which sets+  up the C data layer it needs and tears it down as the session ends.    Built on @nova-cache@ for NAR serialization, narinfo handling, and   Ed25519-signed binary substitution.@@ -43,7 +43,10 @@ -- fails with "nn_*.h: No such file or directory". extra-source-files:     cbits/*.h+    sandbox/*.h data-files:+    develop/COPYING+    develop/get-env.sh     nix/fetchurl.nix data-dir: data @@ -68,65 +71,130 @@     Nix.Eval.Types     Nix.Eval.IO     Nix.Eval.Policy+    Nix.Eval.RealiseContext     Nix.Eval.Operator     Nix.Eval.Print     Nix.Eval.SourceError     Nix.Eval.SourcePos+    Nix.Eval.StartupSymbols     Nix.Eval.StringInterp     Nix.Eval.Symbol+    Nix.Eval.AllocSite+    Nix.Eval.Builtin     Nix.Eval.CAttrSet     Nix.Eval.CThunk     Nix.Eval.CEnv     Nix.Eval.CLambda+    Nix.Eval.CPrimop+    Nix.Eval.CRegion+    Nix.Eval.CRoots     Nix.Eval.CList     Nix.Eval.CCtxStr+    Nix.Eval.CStr     Nix.Eval.CBytecode+    Nix.Eval.CStats     Nix.Eval.Compile     Nix.Eval.EvalFormals-    Nix.Eval.Arena     Nix.Eval.AttrPath+    Nix.Eval.AutoCall     Nix.Eval.CStatus+    Nix.Eval.CData     Nix.Store+    Nix.Store.Access     Nix.Store.Path     Nix.Store.Path.Internal     Nix.Store.DB     Nix.Store.GC     Nix.Store.Handle+    Nix.Store.Import     Nix.Store.Lock     Nix.Store.Symlink     Nix.Store.CaseSensitive     Nix.Store.EntryName     Nix.Store.ExecBit+    Nix.Store.Metadata+    Nix.Store.Ops+    Nix.Store.Upstream     Nix.DependencyGraph     Nix.Derivation     Nix.Derivation.StructuredAttrs+    Nix.DrvName+    Nix.Develop.Capture+    Nix.Develop.Environment+    Nix.Develop.Shell     Nix.Builder+    Nix.Builder.BuildDir+    Nix.Builder.BuildUser+    Nix.Builder.Buildenv+    Nix.Builder.Cores     Nix.Builder.Log+    Nix.Builder.Sandbox+    Nix.Builder.Sandbox.Spawn+    Nix.Builder.Settings     Nix.Builder.Unpack+    Nix.CacheDirectory     Nix.Compression+    Nix.Compression.Stream     Nix.Config+    Nix.Daemon.Auth+    Nix.Daemon.Client+    Nix.Daemon.ClientStore+    Nix.Daemon.Connection+    Nix.Daemon.Dial+    Nix.Daemon.Listen+    Nix.Daemon.LocalStore+    Nix.Daemon.Ops+    Nix.Daemon.Protocol+    Nix.Daemon.StoreChoice+    Nix.Daemon.Wire     Nix.Environment+    Nix.ExperimentalFeature+    Nix.Fetch.Archive+    Nix.Fetch.Attrs+    Nix.Fetch.Download+    Nix.Fetch.Input+    Nix.Fetch.Tar+    Nix.Fetch.Tree+    Nix.Fetch.Url+    Nix.Flake.Ref     Nix.HostPath+    Nix.Profile.Generation+    Nix.Profile.Manifest+    Nix.Profile.Tree     Nix.Push+    Nix.Push.Directory+    Nix.Push.Source     Nix.Realise     Nix.Substituter+    Nix.Trust+    Nix.Trust.Fetch+    Nix.Trust.Scan     Nix.Builtins     Nix.Hash     Nix.Http     Nix.Json+    Nix.Key+    Nix.Logger+    Nix.Signals    autogen-modules:  Paths_nova_nix   other-modules:+    Nix.Builder.Job+    Nix.Eval.Arena     Nix.Store.Exclusive     Paths_nova_nix    build-depends:       base                >= 4.22 && < 5     , array               >= 0.5 && < 0.6+    , binary              >= 0.8 && < 0.9     , bytestring          >= 0.11 && < 0.13-    , containers          >= 0.6 && < 0.9+    , containers          >= 0.6.0.1 && < 0.9     , crypton             >= 1.1 && < 2-    , directory           >= 1.3.8 && < 1.4+    -- 1.3.9 is the first whose removePathForcibly works relative to each+    -- directory's descriptor and never follows a link, which removing a+    -- sandbox's chroot relies on.+    , directory           >= 1.3.9 && < 1.4     , filepath            >= 1.4.100 && < 1.6     , http-client         >= 0.7 && < 0.8     , http-client-tls     >= 0.3 && < 0.5@@ -134,11 +202,21 @@     , ram                 >= 0.20 && < 1     , filelock            >= 0.1.1 && < 0.2     , mtl                 >= 2.2 && < 2.4-    , nova-cache:{nova-cache, xz, zstandard, bzip2} >= 0.11.1.1 && < 0.13-    , process             >= 1.6 && < 1.7+    , network             >= 3.2 && < 3.3+    , nova-cache:{nova-cache, xz, zstandard, bzip2} >= 0.14 && < 0.15+    -- 1.6.8 is the first whose OpenExtHandle holds the process and its+    -- job alone, the job a Windows builder's limit is set on+    -- (Nix.Builder.Job).+    , process             >= 1.6.8 && < 1.7     , random              >= 1.2 && < 1.4     , regex-tdfa          >= 1.3 && < 1.4-    , sqlite-simple       >= 0.4 && < 0.5+    -- Nix.Store.DB wraps a read-only direct-sqlite handle in Connection,+    -- whose two fields 0.4.19 introduced (0.4.18 has one) in a minor+    -- release, so the bound holds to the release whose shape is known.+    , sqlite-simple       >= 0.4.19 && < 0.4.20+    -- 2.3.28 is the first whose open2 opens a database read-only, which a+    -- store's queries for a read-only evaluation do.+    , direct-sqlite       >= 2.3.28 && < 2.4     , tar                 >= 0.7.1 && < 0.8     , text                >= 2.0 && < 2.2     , time                >= 1.9 && < 1.17@@ -150,19 +228,37 @@   -- Platform calls base cannot express: the exclusive create behind NAR   -- unpacking (Nix.Store.Exclusive), reading the environment as bytes on   -- POSIX (Nix.Environment; getenv, as upstream reads it), where Windows-  -- reads it through base's UTF-16 API, and marking a builder's log pipe-  -- close-on-exec on POSIX (Nix.Builder.Log).  Win32 2.9 is the first-  -- whose hANDLEToHandle serves the native Windows I/O manager; unix 2.8-  -- is the first whose openFd takes creat and cloexec in its flags.+  -- reads it through base's UTF-16 API, marking a builder's log pipe+  -- close-on-exec on POSIX (Nix.Builder.Log), creating a store or build+  -- directory with its mode on POSIX, and on Windows raising a failure to+  -- create one as the IOError base raises (Nix.Store.Access), a+  -- registered path's modes, times and owner (Nix.Store.Metadata), on+  -- POSIX a develop shell's temporary files, environment and exec+  -- (Nix.Develop.Shell), a build user's lookup, lock file and files+  -- (Nix.Builder.BuildUser), and on Windows the daemon's named pipe and+  -- the accounts its clients are named by (Nix.Daemon.Pipe).+  -- Win32 2.12 is the first whose setFileTime leaves a time it is not+  -- given as it is; unix 2.8 is the first whose openFd takes creat and+  -- cloexec in its flags.  advapi32 holds the token, account and+  -- security-descriptor calls cbits/nn_winfs.c makes, and authz the+  -- groups it computes for an account.   if os(windows)     build-depends:-        Win32             >= 2.9 && < 2.15+        Win32             >= 2.12 && < 2.15+    exposed-modules:+        Nix.Daemon.Pipe+    other-modules:+        Nix.Store.Win32Path+    extra-libraries:+        advapi32+        authz   else     build-depends:         unix              >= 2.8 && < 2.9    c-sources:     cbits/nn_symbol.c+    cbits/nn_str.c     cbits/nn_attrset.c     cbits/nn_thunk.c     cbits/nn_env.c@@ -171,8 +267,17 @@     cbits/nn_arena.c     cbits/nn_bytecode.c     cbits/nn_lambda.c+    cbits/nn_primop.c+    cbits/nn_roots.c+    cbits/nn_region.c+    cbits/nn_graph.c+    cbits/nn_stats.c+    cbits/nn_tracker.c     cbits/nn_winfs.c     cbits/nn_darwinfs.c+    cbits/nn_cpus.c+    cbits/nn_buildusers.c+    cbits/nn_hangup.c   include-dirs:     cbits   -- -Werror deliberately NOT baked in: a future gcc/clang adding a new   -- -Wall diagnostic must not retroactively break installing published@@ -193,8 +298,41 @@     -- parse the replacement.  The old spelling stays, warning muted,     -- until hlint learns it (then: pattern -> data, drop these flags).     -Wno-pattern-namespace-specifier+    -- The evaluator in Nix.Eval is written over any MonadEval.  These two+    -- let the SPECIALIZE pragmas in Nix.Eval.IO compile all of it for+    -- EvalIO: each function's code is visible to the modules importing+    -- it, and an overloaded function is specialised to the monad its+    -- caller knows, not only one marked INLINABLE.  profiling/stress.nix,+    -- fib 30 and two million selects or elemAts run 1.7 to 2.4 times as+    -- fast, allocating 40 to 50% less, for a library build about 13%+    -- longer.+    -fspecialise-aggressively+    -fexpose-all-unfoldings  -- ---------------------------------------------------------------------------+-- CLI library: the command line's grammar and reference, which the+-- executable runs and the test suite checks.  A sublibrary is private, so+-- none of it is the package's published API.+-- ---------------------------------------------------------------------------+library cli+  exposed-modules:+    Nix.Cli.Args+    Nix.Cli.Reference+  hs-source-dirs:   cli+  default-language:  Haskell2010+  default-extensions:+    OverloadedStrings+  ghc-options:      -Wall -Wcompat++  build-depends:+      base                >= 4.22 && < 5+    , bytestring          >= 0.11 && < 0.13+    , containers          >= 0.6 && < 0.9+    , filepath            >= 1.4.100 && < 1.6+    , nova-nix+    , text                >= 2.0 && < 2.2++-- --------------------------------------------------------------------------- -- CLI executable -- --------------------------------------------------------------------------- executable nova-nix@@ -207,9 +345,10 @@     OverloadedStrings   ghc-options:      -Wall -Wcompat -threaded -rtsopts -  -- file-io reads a config file by the bytes of its path.  0.1.1 is the-  -- first whose read does not create a missing file on Windows, which-  -- would turn a missing include into an empty one.+  -- file-io reads a config file, and on Linux /proc/mounts,+  -- /proc/self/cgroup and a cgroup's cpu.max, by the bytes of its path.  0.1.1 is the first whose read does not create a+  -- missing file on Windows, which would turn a missing include into an+  -- empty one.   build-depends:       base                >= 4.22 && < 5     , bytestring          >= 0.11 && < 0.13@@ -217,17 +356,85 @@     , directory           >= 1.3.8 && < 1.4     , file-io             >= 0.1.1 && < 0.2     , filepath            >= 1.4.100 && < 1.6+    , mtl                 >= 2.2 && < 2.4+    , nova-cache          >= 0.14 && < 0.15     , nova-nix+    , nova-nix:cli     , text                >= 2.0 && < 2.2  -- ---------------------------------------------------------------------------+-- Sandbox helper: the program every sandboxed build runs through.  Its+-- core, sandbox/nova-nix-sandbox.c, reads the plan and reports a failed+-- step as every OS does, and links the backend for the OS it is built+-- for (sandbox/backend.h), which makes the sandbox: on Linux,+-- sandbox/linux.c, namespaces and a chroot, set up between their creation+-- and the builder's exec, where nova-nix itself can run nothing; on+-- macOS, sandbox/darwin.c, a profile applied in the builder's process+-- before its exec; both share sandbox/posix.c.  On Windows,+-- sandbox/windows.c starts the builder as a build slot's account, on the+-- window station of the slot's logon, in a job, and ends the slot's+-- processes before and after the build, which takes advapi32's token+-- calls.  The runtime it links is never started.  nova-nix finds it+-- beside itself.+-- ---------------------------------------------------------------------------++executable nova-nix-sandbox+  main-is:          nova-nix-sandbox.c+  hs-source-dirs:   sandbox+  c-sources:        sandbox/plan.c+  default-language:  Haskell2010+  cc-options:       -std=c99 -Wall -Wextra -pedantic+  build-depends:+      base                >= 4.22 && < 5+  if os(linux)+    c-sources:      sandbox/linux.c sandbox/mountinfo.c sandbox/posix.c+  elif os(darwin)+    c-sources:      sandbox/darwin.c sandbox/posix.c+  elif os(windows)+    c-sources:      sandbox/windows.c+    extra-libraries:+        advapi32+  else+    buildable: False++-- --------------------------------------------------------------------------- -- Tests -- --------------------------------------------------------------------------- test-suite nova-nix-test   type:             exitcode-stdio-1.0   main-is:          Main.hs   hs-source-dirs:   test-  other-modules:    HttpFixture+  other-modules:+    CacheFixture+    DaemonLink+    DirDacl+    HttpFixture+    NodeStatus+    Test.Archive+    Test.Builder+    Test.BuildUser+    Test.CData+    Test.Cli+    Test.Daemon+    Test.DaemonClient+    Test.DaemonPipe+    Test.DaemonStore+    Test.Derivation+    Test.Eval+    Test.Exceptions+    Test.Fetch+    Test.Harness+    Test.Key+    Test.Parser+    Test.Pkgs+    Test.Push+    Test.Realise+    Test.Store+    Test.StoreChoice+    Test.Substituter+    Test.Trust+    Test.WindowsSandbox+    UserResources   default-language: Haskell2010   default-extensions:     OverloadedStrings@@ -235,6 +442,17 @@   -- one thread while another waits on it, which needs real concurrency   -- under blocking foreign calls.   ghc-options:      -Wall -Wcompat -Wno-pattern-namespace-specifier -threaded+  -- The sandbox helper's parsers, which the suite holds to the plans the+  -- library renders and the mount tables it reads, the key the Linux+  -- sandbox tests plant, the wait for a process the build user tests+  -- expect killed, and the Windows calls the Windows sandbox tests make,+  -- which build elsewhere as stubs.  No -std or -pedantic: GHC+  -- compiles the C it generates for the executable's link with these+  -- options too, and the RTS headers it includes are not strict C99; the+  -- C99-strict CI job compiles these sources that way.+  c-sources:        sandbox/plan.c sandbox/mountinfo.c test/cbits/sandbox_check.c test/cbits/keyring.c test/cbits/process_wait.c test/cbits/nn_test_sandbox_windows.c+  include-dirs:     sandbox+  cc-options:       -Wall -Wextra    build-depends:       base                >= 4.22 && < 5@@ -243,19 +461,67 @@     , containers          >= 0.6 && < 0.9     , mtl                 >= 2.2 && < 2.4     , directory           >= 1.3 && < 1.4+    , filelock            >= 0.1.1 && < 0.2     , filepath            >= 1.4.100 && < 1.6     , http-client         >= 0.7 && < 0.8     , http-types          >= 0.12 && < 0.13     , network             >= 3.2 && < 3.3-    , nova-cache:{nova-cache, zstandard} >= 0.11.1.1 && < 0.13+    , nova-cache:{nova-cache, zstandard} >= 0.14 && < 0.15     , nova-nix+    , nova-nix:cli     , process             >= 1.6.12 && < 1.7     , QuickCheck          >= 2.12.5 && < 2.19     , sqlite-simple       >= 0.4 && < 0.5     , tar                 >= 0.7.1 && < 0.8     , text                >= 2.0 && < 2.2+    , time                >= 1.9 && < 1.17     , zlib                >= 0.7 && < 0.8     , zstd                >= 0.1 && < 0.2++  -- On Windows the store access tests read a directory's DACL back+  -- through advapi32 (DirDacl), the daemon's pipe tests make tokens and+  -- pipes with the owners they name through advapi32 (Test.DaemonPipe),+  -- and the sandbox tests make build accounts through netapi32 and+  -- advapi32, their passwords through bcrypt, and a test service through+  -- advapi32, and read and open window stations through user32;+  -- elsewhere the store metadata tests read lstat (NodeStatus): a node's+  -- group and other bits, and a symlink's own time.+  if os(windows)+    c-sources:+        test/cbits/nn_test_dacl.c+        test/cbits/nn_test_pipe_owner.c+    cc-options:       -std=c99 -Wall -Wextra -pedantic+    extra-libraries:+        advapi32+        bcrypt+        netapi32+        user32+  else+    build-depends:+        unix              >= 2.8 && < 2.9++-- ---------------------------------------------------------------------------+-- Benchmarks+-- ---------------------------------------------------------------------------++-- What an attribute set costs held in C and held in GHC's heap, for+-- profiling/bench.sh's memory suite, which says how to run it.+benchmark attrset-memory+  type:             exitcode-stdio-1.0+  main-is:          AttrSetMemory.hs+  hs-source-dirs:   profiling+  c-sources:        profiling/heap-in-use.c+  default-language: Haskell2010+  -- -threaded: the non-moving collector marks beside the program there,+  -- as it would beside the evaluator.  -T: the figures are the RTS's.+  ghc-options:      -Wall -Wcompat -threaded -rtsopts "-with-rtsopts=-T"++  build-depends:+      base                >= 4.22 && < 5+    , bytestring          >= 0.11 && < 0.13+    , nova-nix+    , primitive           >= 0.9 && < 0.10+    , text                >= 2.0 && < 2.2  source-repository head   type:     git
+ profiling/AttrSetMemory.hs view
@@ -0,0 +1,234 @@+{-# LANGUAGE OverloadedStrings #-}++-- | The attrset-memory benchmark: what a population of attribute sets+-- costs held in C, as nova-nix holds them (@cbits\/nn_attrset.c@), and+-- held in GHC's heap as flat arrays, in bytes per entry and in the time a+-- major collection takes while the population is live.+--+-- @attrset-memory c|flat SIZES@ builds one set for each set the file+-- @SIZES@ lists, a line of an entry count and how many sets have it (the+-- census's reached sets, which bench.sh's memory suite passes it), and+-- prints its figures as lines of a name and a value.  The collector is the+-- RTS's: the default copying one, or the non-moving one under+-- @+RTS -xn@.  Each timed collection is a full major one: under the+-- non-moving collector it marks inside the pause, where a running program+-- marks beside the mutator and pauses only to synchronise, so its pause+-- here is the collector's whole work.  A set's bytes in GHC's heap are+-- the copying collector's live bytes: the non-moving collector reports+-- for its heap the estimate its previous mark left (genLiveUncopiedWords,+-- rts/sm/Storage.c at GHC 9.14.1), so under it they are not measured.+--+-- A C set is built through "Nix.Eval.CAttrSet" as the evaluator builds a+-- set literal's, with room for its entries and no more.  The evaluator's+-- sets from @removeAttrs@, and from @\/\/@ when it merges, have room for+-- every entry of their inputs, so a C set of the same size there costs at+-- least what it does here, while one @\/\/@ layers holds the right+-- operand's entries alone; bench.sh's memory report gives the census's+-- own figure beside.+-- A flat set holds the same keys and positions in one 'PrimArray', the+-- keys first as the C set's shared block holds them, and its values in a+-- 'SmallArray'.  Every value is one shared closure, so that the figures+-- are the sets' own and not their values': a value slot costs a pointer+-- in both, as it does in the evaluator.+module Main (main) where++import Control.Exception (evaluate)+import Control.Monad (forM_, replicateM_)+import qualified Data.ByteString.Char8 as BS8+import Data.Primitive.Array (Array, newArray, sizeofArray, unsafeFreezeArray, writeArray)+import Data.Primitive.PrimArray (PrimArray, newPrimArray, primArrayFromListN, sizeofPrimArray, unsafeFreezePrimArray, writePrimArray)+import Data.Primitive.SmallArray (SmallArray, newSmallArray, runSmallArray)+import Data.Text (Text)+import Data.Word (Word32, Word64)+import GHC.Stats (GCDetails (..), RTSStats (..), getRTSStats)+import Nix.Builder (BuildStop (..))+import Nix.Eval.AllocSite (SetSite (SetLiteral))+import Nix.Eval.CAttrSet (CAttrSet, cattrsetFreeze, cattrsetInsert, cattrsetNew)+import Nix.Eval.CRegion (Regions (RegionsOff))+import Nix.Eval.CThunk (cthunkNull)+import Nix.Eval.IO (SessionSettings (..), SessionStore (ReadOnlySession), withEvalSession)+import Nix.Eval.Policy (unrestrictedPolicy)+import Nix.Eval.SourcePos (PosIdx (..))+import Nix.Eval.Symbol (Symbol (..))+import Nix.Logger (EscapeFilter (DropEscapes), handleLogger)+import Nix.Store.Ops (EvalWrites (..), StoreOps (..), StoreQueries (..))+import Nix.Store.Path (defaultStoreDir)+import System.Environment (getArgs)+import System.Exit (ExitCode (..), exitWith)+import System.IO (hPutStrLn, stderr)+import System.Mem (performBlockingMajorGC)++foreign import ccall unsafe "heap_in_use"+  c_heap_in_use :: IO Word64++-- | @HEAP_IN_USE_UNKNOWN@ in heap-in-use.c.+heapInUseUnknown :: Word64+heapInUseUnknown = maxBound++-- | Major collections timed with the population live, after the one that+-- settles it.+timedCollections :: Int+timedCollections = 5++-- | Apart from each other, so that a set's keys look like interned+-- symbols rather than a run of consecutive numbers.+keyStride :: Word32+keyStride = 7++nanosPerSecond :: Double+nanosPerSecond = 1e9++-- | Where the population lives.+data Representation = InC | InGhcHeap++-- | Which collector the RTS runs, as its statistics show it: only the+-- non-moving one spends time marking its own heap.+data Collector = Copying | NonMoving++-- | A set held in GHC's heap: its keys, then its positions, and its+-- values.+data FlatAttrs = FlatAttrs !(PrimArray Word32) !(SmallArray ())++main :: IO ()+main = do+  args <- getArgs+  case args of+    [representation, sizesPath] -> do+      sizes <- parseSizes <$> BS8.readFile sizesPath+      case (representation, sizes) of+        (_, Left problem) -> usage problem+        ("c", Right counted) -> inSession (measure InC counted (buildC counted) sizeofPrimArray)+        ("flat", Right counted) -> measure InGhcHeap counted (buildFlat counted) sizeofArray+        _ -> usage ("no representation " <> representation)+    _ -> usage "expected a representation and a sizes file"++-- | Run the C population's measure in an evaluation session, the only+-- place the C data layer makes a set.  The session runs no regions, so+-- the C allocator's growth is the sets' alone and none of the+-- collector's bookkeeping, and it opens its arena before the measure+-- takes its first figure.  Nothing is evaluated, so its store holds+-- nothing and refuses every operation.+inSession :: IO a -> IO a+inSession action = withEvalSession settings (const action)+  where+    settings = SessionSettings unrestrictedPolicy (pure []) defaultStoreDir "/" RegionsOff (ReadOnlySession queries ops) (handleLogger DropEscapes stderr)+    queries = StoreQueries {sqValidPaths = const (pure mempty), sqReferences = const (pure (Right mempty))}+    ops =+      StoreOps+        { soQueries = queries,+          soAddEvalObjects = const (pure (Left refusal)),+          soAddSourceTree = \_ _ _ -> pure (Left refusal),+          soBuild = const (pure (Left (BuildStop refusal 1))),+          soCheck = const (pure (Left (BuildStop refusal 1))),+          soAddOutLinkRoot = \_ _ -> pure (Left refusal),+          soEvalWrites = WrittenInDirectory+        }+    refusal :: Text+    refusal = "the attrset-memory benchmark evaluates nothing"++usage :: String -> IO a+usage problem = do+  hPutStrLn stderr ("attrset-memory: " <> problem)+  hPutStrLn stderr "usage: attrset-memory c|flat SIZES [+RTS -xn]"+  exitWith (ExitFailure 2)++-- | Each line's entry count and how many sets have it.+parseSizes :: BS8.ByteString -> Either String [(Int, Int)]+parseSizes = traverse line . filter (not . BS8.null) . BS8.lines+  where+    line text = case map BS8.readInt (BS8.words text) of+      [Just (size, rest), Just (count, more)]+        | BS8.null rest && BS8.null more && size >= 0 && count >= 0 -> Right (size, count)+      _ -> Left ("not an entry count and a number of sets: " <> BS8.unpack text)++-- | Build the population, settle it with a major collection and time+-- more with it live, then print the figures.  The population is used+-- after the timed collections, which keeps it live through them.  Its+-- bytes are GHC's live bytes for sets in GHC's heap, and the C+-- allocator's growth across the build for C sets, which a C library+-- heap-in-use.c has no figure for leaves unknown.+measure :: Representation -> [(Int, Int)] -> IO population -> (population -> Int) -> IO ()+measure representation sizes construct count = do+  before <- settle+  cBefore <- c_heap_in_use+  population <- construct+  built <- settle+  cBuilt <- c_heap_in_use+  replicateM_ timedCollections performBlockingMajorGC+  timed <- getRTSStats+  held <- evaluate (count population)+  let entries = sum [size * sets | (size, sets) <- sizes]+      collector = if nonmoving_gc_elapsed_ns timed > 0 then NonMoving else Copying+      ghcBytes = gcdetails_live_bytes (gc built) - gcdetails_live_bytes (gc before)+      bytes = case (representation, collector) of+        (InGhcHeap, Copying) -> Just ghcBytes+        (InGhcHeap, NonMoving) -> Nothing+        (InC, _)+          | cBefore == heapInUseUnknown -> Nothing+          | otherwise -> Just (cBuilt - cBefore)+      collections = fromIntegral (major_gcs timed - major_gcs built) :: Double+      perCollection field = fromIntegral (field timed - field built) / collections / nanosPerSecond+  mapM_+    (\(name, value) -> putStrLn (name <> " " <> value))+    [ ("collector", case collector of Copying -> "copying"; NonMoving -> "non-moving"),+      ("sets", show held),+      ("entries", show entries),+      ("bytes", maybe "unknown" show bytes),+      ("bytes-per-entry", maybe "unknown" (\b -> show (fromIntegral b / fromIntegral (max 1 entries) :: Double)) bytes),+      ("major-gcs", show (major_gcs timed - major_gcs built)),+      ("gc-pause-seconds", show (perCollection gc_elapsed_ns)),+      ("gc-cpu-seconds", show (perCollection gc_cpu_ns)),+      ("mark-seconds", show (perCollection nonmoving_gc_elapsed_ns))+    ]++-- | A major collection, and the statistics after it.  While the+-- non-moving collector's concurrent mark runs, GHC downgrades a forced+-- major collection to a minor one (GarbageCollect, rts/sm/GC.c at+-- 9.14.1), and nothing in base waits for that mark, so the collection is+-- repeated until one is major.  It is a non-concurrent one, as every+-- 'performBlockingMajorGC' is, so no mark runs once it returns and every+-- later one is major too.+settle :: IO RTSStats+settle = do+  start <- getRTSStats+  performBlockingMajorGC+  after <- getRTSStats+  if major_gcs after > major_gcs start then pure after else settle++-- | One size per set, in the file's order.+perSet :: [(Int, Int)] -> [Int]+perSet sizes = concat [replicate count size | (size, count) <- sizes]++-- | A set's keys: distinct and ascending, as a frozen C set's are.+keysOf :: Int -> [Word32]+keysOf size = [fromIntegral i * keyStride + 1 | i <- [0 .. size - 1]]++buildC :: [(Int, Int)] -> IO (PrimArray CAttrSet)+buildC sizes = do+  let each = perSet sizes+  slots <- newPrimArray (length each)+  -- The benchmark never counts by site, so the site is a placeholder.+  forM_ (zip [0 ..] each) $ \(i, size) -> do+    set <- cattrsetNew SetLiteral size+    forM_ (zip (keysOf size) [0 ..]) $ \(key, pos) ->+      cattrsetInsert set (Symbol key) (PosIdx pos) cthunkNull+    cattrsetFreeze set+    writePrimArray slots i set+  unsafeFreezePrimArray slots++buildFlat :: [(Int, Int)] -> IO (Array FlatAttrs)+buildFlat sizes = do+  let each = perSet sizes+  slots <- newArray (length each) (FlatAttrs mempty (flatValues 0))+  forM_ (zip [0 ..] each) $ \(i, size) ->+    writeArray slots i =<< evaluate (flatAttrs size)+  unsafeFreezeArray slots++flatAttrs :: Int -> FlatAttrs+flatAttrs size =+  FlatAttrs+    (primArrayFromListN (2 * size) (keysOf size ++ map fromIntegral [0 .. size - 1]))+    (flatValues size)++flatValues :: Int -> SmallArray ()+flatValues size = runSmallArray (newSmallArray size ())
+ profiling/heap-in-use.c view
@@ -0,0 +1,37 @@+/*+ * heap-in-use.c - The bytes the C allocator has handed out and not taken+ * back, for the attrset-memory benchmark, chunk headers and alignment+ * included: glibc's mallinfo2 over every arena and the chunks it maps+ * directly, or macOS's default malloc zone.  Elsewhere the answer is+ * HEAP_IN_USE_UNKNOWN.+ */++#include <stdint.h>+#include <stdlib.h>++#if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 33))+#include <malloc.h>+#define HEAP_IN_USE_GLIBC 1+#elif defined(__APPLE__)+#include <malloc/malloc.h>+#define HEAP_IN_USE_DARWIN 1+#endif++/* The answer where the C library has no figure to give. */+#define HEAP_IN_USE_UNKNOWN UINT64_MAX++uint64_t heap_in_use(void);++uint64_t heap_in_use(void)+{+#if defined(HEAP_IN_USE_GLIBC)+    struct mallinfo2 info = mallinfo2();+    return (uint64_t)info.uordblks + (uint64_t)info.hblkhd;+#elif defined(HEAP_IN_USE_DARWIN)+    malloc_statistics_t stats;+    malloc_zone_statistics(NULL, &stats);+    return (uint64_t)stats.size_in_use;+#else+    return HEAP_IN_USE_UNKNOWN;+#endif+}
+ sandbox/backend.h view
@@ -0,0 +1,89 @@+/*+ * What nova-nix-sandbox's core and its backend give each other.+ *+ * The core (nova-nix-sandbox.c) is the program as every OS runs it: the+ * command line, the plan read from standard input, and the record a step+ * that fails writes on the status channel.  A backend is the sandbox of+ * one OS (linux.c, darwin.c, windows.c): it starts the builder there as+ * the plan says, waits for it, ends it when the lifeline closes, and has+ * the helper end as the builder ended, or fail where it cannot see the+ * build out (backend_run).  The executable links the core with the one+ * backend for the OS it is built for.  The core reads and writes its+ * channels through the backend, since each OS has its own calls for them;+ * the POSIX backends share theirs (posix.h).+ */++#ifndef NOVA_NIX_SANDBOX_BACKEND_H+#define NOVA_NIX_SANDBOX_BACKEND_H++#include <stddef.h>++#include "plan.h"++/* ------------------------------------------------------------------------+ * The core, for a backend+ * ------------------------------------------------------------------------ */++/* The index a record carries when the failure is of no plan entry. */+#define NO_INDEX (-1L)++/* Marks a function that never returns, for compilers that take the GNU+ * attribute, so that each file calling status_fail knows the step after+ * a failure is not reached.  C99 has no keyword for it. */+#if defined(__GNUC__)+#define NO_RETURN __attribute__((noreturn))+#else+#define NO_RETURN+#endif++/* Write the one record a failure reports, "STAGE ERROR INDEX\n", on the+ * status channel: the step, the errno it failed with or 0, and the plan+ * entry or process it concerns.  The Windows backend's steps report the+ * Win32 error code of the call that failed in place of an errno. */+void status_report(const char *stage, int error, long index);++/* Report a failure and end the process that saw it. */+void status_fail(const char *stage, int error, long index) NO_RETURN;++/* ------------------------------------------------------------------------+ * A backend, for the core+ * ------------------------------------------------------------------------ */++/* The backend a plan must be for; the core refuses a plan for another. */+extern const enum plan_backend backend_plan;++/* Ready this process to run a builder, before the core reads the plan.+ * Once it answers 0 the status channel takes records, and nothing the+ * builder writes reaches it.  Answers -1 when there is no status channel,+ * so that nothing can be reported; a step that fails once there is one+ * reports and ends the process. */+int backend_prepare_run(void);++/* Read exactly LENGTH bytes from standard input, taking nothing past them,+ * since what follows the plan is the lifeline.  Answers 0, or an errno+ * value; EPIPE for input that ends early. */+int backend_read_input(char *bytes, size_t length);++/* Write the LENGTH bytes at BYTES on the status channel, as far as it+ * takes them: standard output, unless backend_prepare_run moved it. */+void backend_write_status(const char *bytes, size_t length);++/* Run ARGV[0] with the arguments ARGV and the plan's environment, in the+ * sandbox PLAN describes; on Windows, run the command line the helper was+ * given past its verb, which ARGV holds as the C runtime decoded it.+ * Standard input, past the plan, is the lifeline: when it closes, the+ * builder is killed.  A step that fails before the builder starts reports+ * and ends the process.  Otherwise the helper ends as the builder ended:+ * this answers the builder's exit status, or a failure when how it ended+ * cannot be known or, on macOS and Windows, when the build's processes+ * cannot all be ended or, on macOS, when its output does not end, or does+ * not return when the backend ends the helper by the signal that ended+ * the builder or, on macOS, reports a failure to watch the build log. */+int backend_run(const struct plan *plan, char **argv);++/* Check that this system can make the sandbox.  Answers NULL when it can,+ * or the stage of the check that failed, with the errno it failed with,+ * or 0, in *ERROR. */+const char *backend_probe(int *error);++#endif
+ sandbox/darwin.c view
@@ -0,0 +1,1249 @@+/*+ * nova-nix-sandbox's macOS backend (backend.h): runs the builder under the+ * sandbox profile its plan carries, which macOS's sandbox then holds the+ * builder and every process it starts to.+ *+ * The profile is applied with sandbox_init_with_parameters in a child of+ * the helper, just before that child executes the builder, as upstream+ * applies its profile in the child it forks for the builder+ * (DarwinDerivationBuilder::setUser in darwin-derivation-builder.cc at Nix+ * 2.36.0, called from UnixDerivationBuilderImpl::runChild in+ * unix-derivation-builder.cc).  nova-nix renders the profile+ * (Nix.Builder.Sandbox); the plan carries its text and the values of the+ * parameters it reads, to which the helper adds the build's mark.+ *+ * The helper stays the builder's parent: it waits for the builder, kills+ * the builder's process group when the lifeline closes or a terminating+ * signal arrives, and ends as the builder ended, unless it cannot learn+ * how the builder ended, finish the sweep below, see the build's output+ * end or watch the log, each of which fails the build.  The builder leads+ * a session of its own, and once it has ended, or the build is to end,+ * every process still in its group is killed before the builder is+ * reaped, as upstream kills the group before it waits.+ *+ * macOS has no PID namespace, and a process of the build can leave the+ * group by a session of its own.  A builder runs as the invoking user,+ * whose other processes must live, or, when the plan names one, as a build+ * user, whose every process nova-nix kills once the build ends, as+ * upstream kills its build user's.  Either way, before it ends the helper+ * stops and then kills every process of the builder's user that carries+ * the build's mark (sweep_build): a Mach service name, random and made by+ * the helper for this build alone, that the build's profile allows, beside+ * a second that it refuses.  It does so whichever way the build ends: the+ * builder's own end, the lifeline's, or any terminating signal the helper+ * can catch; only SIGKILL, which no process can catch, ends the helper+ * before it has.+ *+ * The builder writes its output to a pipe the helper holds the reading+ * end of and copies to its own standard error, the build log.  Upstream+ * reads the builder's pipe itself until it ends, which killing the build+ * user's processes makes sure of; here a process the sweep could not end+ * may still hold the builder's pipe, and nova-nix's log ends when the+ * helper does all the same.  The helper never blocks on the log: what the+ * log does not take at once is held, and the helper reads no more of the+ * builder's pipe until it has, waiting for the log through the queue that+ * also brings it signals and the lifeline's end.  Once the build's+ * processes have ended it copies at most LOG_DRAIN_BYTES_MAX more, and it+ * waits for the log to take the rest only while the build is not to end:+ * a reader that has gone away closes the log, which fails the write.+ *+ * The probe applies a profile that allows everything to the probe process+ * itself, which shows that this system's sandbox takes a profile from this+ * process; a process already in a sandbox, for one, is refused another.+ */++#include <errno.h>+#include <fcntl.h>+#include <grp.h>+#include <libproc.h>+#include <signal.h>+#include <stdarg.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/event.h>+#include <sys/proc.h>+#include <sys/resource.h>+#include <sys/sysctl.h>+#include <sys/types.h>+#include <sys/wait.h>+#include <time.h>+#include <unistd.h>++#include "backend.h"+#include "plan.h"+#include "posix.h"++/* libSystem's entry point that applies a profile with parameters to the+ * calling process.  It is exported but declared in no SDK header, whose+ * sandbox.h declares only the deprecated sandbox_init; upstream declares it+ * the same way (in darwin-derivation-builder.cc).  Answers 0, or -1 with+ * *ERRORBUF naming what the profile's interpreter refused.  FLAGS 0 takes+ * PROFILE as a profile's text, and PARAMETERS is each name followed by its+ * value, the whole NULL-terminated. */+int sandbox_init_with_parameters(const char *profile, uint64_t flags, const char *const parameters[],+                                 char **errorbuf);++/* libSystem's check of what a process's sandbox allows, exported but+ * declared in no SDK header.  Asked of an operation on a Mach service's+ * name, it answers 0 when the process may look the name up, as a process+ * in no sandbox may any, and 1 when its sandbox refuses it, as it also+ * answers for a zombie and for a PID no process has; any other answer is+ * an error.  SANDBOX_CHECK_NO_REPORT keeps a refusal out of the system+ * log. */+int sandbox_check(pid_t pid, const char *operation, int type, ...);+extern const int SANDBOX_CHECK_NO_REPORT;++/* sandbox_check's filter type for a Mach service's global name. */+#define SANDBOX_FILTER_GLOBAL_NAME 2++/* The parameters through which the profile reads the build's mark: the+ * name it allows (the token) and the name it refuses (the decoy). */+#define TOKEN_PARAMETER "_NOVA_NIX_BUILD_TOKEN"+#define DECOY_PARAMETER "_NOVA_NIX_BUILD_DECOY"+#define MARK_PARAMETER_COUNT 2++/* A mark's name: this prefix, then random bytes in hex. */+#define MARK_PREFIX "org.nova-nix.build."+#define MARK_RANDOM_BYTES 16+#define MARK_LENGTH (sizeof MARK_PREFIX - 1 + 2 * MARK_RANDOM_BYTES)++/* How many listings of the user's processes the sweep takes in all, how+ * many times one listing is tried while processes start faster than it+ * can be sized, and how long the sweep waits, each time it kills the+ * processes it stopped, for them to end. */+#define SWEEP_PASSES_MAX 64+#define LISTING_ATTEMPTS_MAX 8+#define SWEEP_EXIT_SECONDS 10++/* How many bytes of the builder's output the helper holds at once, and+ * how many it copies, at most, once the build's processes have ended. */+#define LOG_CHUNK_BYTES 65536+#define LOG_DRAIN_BYTES_MAX (64 * 1024 * 1024)++/* How long a message of the helper's to the build log may be. */+#define LOG_MESSAGE_BYTES 512++/* The most the builder's report of a failed setup step holds: one status+ * record, with room to spare. */+#define REPORT_BYTES_MAX 256++/* The backend this file is. */+const enum plan_backend backend_plan = PLAN_DARWIN;++/* The open descriptors of the process reading it. */+static const char descriptor_listing[] = "/dev/fd";++/* What the probe applies: a profile that allows everything. */+static const char probe_profile[] = "(version 1)\n(allow default)\n";++/* The signals the helper answers by ending the build, every one a process+ * can catch whose default action ends it, so that none sent to the helper+ * ends it while the build runs; and SIGCHLD, which says the builder may+ * have ended. */+static const int handled_signals[] = {SIGHUP,  SIGINT,  SIGQUIT, SIGILL,  SIGTRAP,   SIGABRT, SIGEMT,+                                      SIGFPE,  SIGBUS,  SIGSEGV, SIGSYS,  SIGPIPE,   SIGALRM, SIGTERM,+                                      SIGXCPU, SIGXFSZ, SIGVTALRM, SIGPROF, SIGUSR1, SIGUSR2, SIGCHLD};++#define HANDLED_SIGNAL_COUNT (sizeof handled_signals / sizeof handled_signals[0])++/* The lifeline's read, which only needs to see it end. */+#define LIFELINE_READ_BYTES 64++/* The names that mark one build's processes. */+struct build_mark {+    char token[MARK_LENGTH + 1];+    char decoy[MARK_LENGTH + 1];+};++/* ------------------------------------------------------------------------+ * Time+ * ------------------------------------------------------------------------ */++/* SECONDS from now on the monotonic clock, in *DEADLINE.  Answers 0, or -1+ * with errno set when the clock cannot be read. */+static int deadline_in(int seconds, struct timespec *deadline)+{+    if (clock_gettime(CLOCK_MONOTONIC, deadline) < 0)+        return -1;+    deadline->tv_sec += seconds;+    return 0;+}++/* The time left until DEADLINE on the monotonic clock in *LEFT.  Answers+ * 1 while some is left, 0 once none is, and -1 with errno set when the+ * clock cannot be read. */+static int time_left(const struct timespec *deadline, struct timespec *left)+{+    struct timespec now;+    if (clock_gettime(CLOCK_MONOTONIC, &now) < 0)+        return -1;+    if (now.tv_sec > deadline->tv_sec || (now.tv_sec == deadline->tv_sec && now.tv_nsec >= deadline->tv_nsec))+        return 0;+    left->tv_sec = deadline->tv_sec - now.tv_sec;+    left->tv_nsec = deadline->tv_nsec - now.tv_nsec;+    if (left->tv_nsec < 0) {+        left->tv_sec -= 1;+        left->tv_nsec += 1000000000L;+    }+    return 1;+}++/* ------------------------------------------------------------------------+ * The build log+ * ------------------------------------------------------------------------ */++/* What the helper watches while the build runs and after it: the queue,+ * the lifeline, and whether the build is to end, which a terminating+ * signal or the lifeline's end says. */+struct watch {+    int queue;+    /* The lifeline, or -1 once it has ended. */+    int lifeline_fd;+    int ending;+};++/* The builder's output on its way to the build log, the helper's standard+ * error, which the helper never waits to write to while the build runs. */+struct log_copy {+    /* The reading end of the builder's pipe, or -1 once it has ended. */+    int from;+    /* What was read from it and the log has not taken yet. */+    char held[LOG_CHUNK_BYTES];+    size_t start;+    size_t end;+    /* Whether the log refused a write, as when nova-nix stopped reading+     * it: whatever is read after that is dropped. */+    int gone;+    /* The errno value of a failure to watch the log, or 0. */+    int unwatched;+    /* The errno value of a failure that would leave the builder's pipe+     * unread, or the helper woken without end, which ends the build, or+     * 0. */+    int stalled;+};++/* Write what is held to the log, as far as it takes it without waiting.+ * Answers 1 once nothing is held, and 0 while some is. */+static int log_flush(struct log_copy *copy)+{+    while (copy->start < copy->end) {+        ssize_t wrote = write(STDERR_FILENO, copy->held + copy->start, copy->end - copy->start);+        if (wrote > 0) {+            copy->start += (size_t)wrote;+        } else if (wrote < 0 && errno == EINTR) {+            continue;+        } else if (wrote < 0 && errno == EAGAIN) {+            return 0;+        } else {+            copy->gone = 1;+            copy->start = copy->end;+        }+    }+    copy->start = copy->end = 0;+    return 1;+}++/* Read once from the builder's pipe into what is held, which is empty,+ * dropping it when the log has gone.  Answers how many bytes were read;+ * the pipe's end, or a failed read, closes it. */+static size_t log_fill(struct log_copy *copy)+{+    ssize_t got;+    if (copy->from < 0)+        return 0;+    got = read(copy->from, copy->held, sizeof copy->held);+    if (got > 0) {+        copy->start = 0;+        copy->end = copy->gone ? 0 : (size_t)got;+        return (size_t)got;+    }+    if (got < 0 && (errno == EINTR || errno == EAGAIN))+        return 0;+    close(copy->from);+    copy->from = -1;+    return 0;+}++/* Apply one change to QUEUE, on its own, so that its failure is known.+ * Answers 0, or an errno value. */+static int queue_change(int queue, int fd, int16_t filter, uint16_t flags)+{+    struct kevent change;+    EV_SET(&change, (uintptr_t)fd, filter, flags, 0, 0, NULL);+    return kevent(queue, &change, 1, NULL, 0, NULL) < 0 ? errno : 0;+}++/* Switch the queue between reading the builder's pipe and waiting for the+ * log to take what is held, by whether anything is held, one change at a+ * time.  Waiting on the log is switched on before reading the pipe is+ * switched off, so a failure of either leaves the pipe read: the log is+ * then given up as gone, and what is held dropped.  The pipe left unread,+ * or the wait on the log left on, which would wake the helper without+ * end, stalls the build instead, which ends it. */+static void log_watch(int queue, struct log_copy *copy)+{+    int error;+    if (copy->start < copy->end) {+        error = queue_change(queue, STDERR_FILENO, EVFILT_WRITE, EV_ENABLE);+        if (error == 0 && copy->from >= 0) {+            error = queue_change(queue, copy->from, EVFILT_READ, EV_DISABLE);+            if (error != 0 && queue_change(queue, STDERR_FILENO, EVFILT_WRITE, EV_DISABLE) != 0)+                copy->stalled = error;+        }+        if (error != 0) {+            copy->unwatched = error;+            copy->gone = 1;+            copy->start = copy->end = 0;+        }+        return;+    }+    if (copy->from >= 0 && (error = queue_change(queue, copy->from, EVFILT_READ, EV_ENABLE)) != 0)+        copy->unwatched = copy->stalled = error;+    if ((error = queue_change(queue, STDERR_FILENO, EVFILT_WRITE, EV_DISABLE)) != 0)+        copy->unwatched = copy->stalled = error;+}++/* Note what a signal or the lifeline says in EVENT: a terminating signal,+ * or the lifeline's end, ends the build. */+static void watch_note(struct watch *watch, const struct kevent *event)+{+    if (event->filter == EVFILT_READ && watch->lifeline_fd >= 0 && (int)event->ident == watch->lifeline_fd) {+        char discard[LIFELINE_READ_BYTES];+        ssize_t read_now = read(watch->lifeline_fd, discard, sizeof discard);+        if (read_now <= 0 && !(read_now < 0 && errno == EINTR)) {+            /* Closing it takes it off the queue. */+            close(watch->lifeline_fd);+            watch->lifeline_fd = -1;+            watch->ending = 1;+        }+    } else if (event->filter == EVFILT_SIGNAL && (int)event->ident != SIGCHLD) {+        watch->ending = 1;+    }+}++/* Wait for the log to take more of what is held, for as long as the build+ * is not to end: a nova-nix that stops reading closes the log on its way+ * out, which fails the write, or ends the helper, so the wait lasts no+ * longer than the reader does.  Answers 1 once the log may take more, and+ * 0 once the build is to end or the log cannot be watched. */+static int log_wait(struct watch *watch, struct log_copy *copy)+{+    log_watch(watch->queue, copy);+    while (!watch->ending && !copy->gone && copy->stalled == 0) {+        struct kevent event;+        int got = kevent(watch->queue, NULL, 0, &event, 1, NULL);+        if (got < 0 && errno == EINTR)+            continue;+        if (got < 0) {+            copy->unwatched = errno;+            return 0;+        }+        if (got > 0 && event.filter == EVFILT_WRITE && (int)event.ident == STDERR_FILENO)+            return 1;+        if (got > 0)+            watch_note(watch, &event);+    }+    return 0;+}++/* How copying the rest of the builder's output ended. */+enum drain_outcome {+    /* The pipe ended, or holds nothing more, or the log has gone. */+    DRAIN_DONE,+    /* LOG_DRAIN_BYTES_MAX were copied and the pipe still held more. */+    DRAIN_ENDLESS,+    /* The build was to end, or the log could not be watched, before the+     * log took what was left. */+    DRAIN_CUT+};++/* Copy what is held, and what is left in the builder's pipe, into the log,+ * without waiting for a writer, which a process the sweep could not end+ * may be; then close the pipe.  Waits for the log to take it for as long+ * as the build is not to end, and copies at most LOG_DRAIN_BYTES_MAX, so+ * a leftover writer that never stops cannot keep the helper. */+static enum drain_outcome log_drain(struct watch *watch, struct log_copy *copy)+{+    enum drain_outcome outcome = DRAIN_DONE;+    size_t copied = 0;+    for (;;) {+        size_t got;+        if (!log_flush(copy)) {+            if (log_wait(watch, copy))+                continue;+            if (!copy->gone)+                outcome = DRAIN_CUT;+            copy->start = copy->end = 0;+            break;+        }+        if (copy->from < 0)+            break;+        if (copied >= LOG_DRAIN_BYTES_MAX) {+            outcome = DRAIN_ENDLESS;+            break;+        }+        got = log_fill(copy);+        if (got == 0 && copy->from >= 0)+            break;+        copied += got;+    }+    if (copy->from >= 0) {+        close(copy->from);+        copy->from = -1;+    }+    return outcome;+}++/* Write a message of the helper's to the log, in printf's terms, waiting+ * for the log to take it as log_drain does, and dropping it if the log has+ * gone or the build is to end. */+static void log_message(struct watch *watch, struct log_copy *copy, const char *format, ...)+{+    char message[LOG_MESSAGE_BYTES];+    int length;+    va_list arguments;+    va_start(arguments, format);+    length = vsnprintf(message, sizeof message, format, arguments);+    va_end(arguments);+    if (length < 0 || copy->gone)+        return;+    if ((size_t)length >= sizeof message)+        length = (int)sizeof message - 1;+    memcpy(copy->held, message, (size_t)length);+    copy->start = 0;+    copy->end = (size_t)length;+    for (;;) {+        if (log_flush(copy) || !log_wait(watch, copy))+            break;+    }+    copy->start = copy->end = 0;+}++/* ------------------------------------------------------------------------+ * The builder's process+ * ------------------------------------------------------------------------ */++/* Apply the plan's profile to this process with PARAMETERS.  On a refusal+ * the interpreter's words go to the build log, in upstream's line+ * (DarwinDerivationBuilder::setUser), since a status record holds no+ * text; the process ends right after, which releases them. */+static void apply_profile(const struct plan *plan, const char *const *parameters)+{+    char *refusal = NULL;+    if (sandbox_init_with_parameters(plan->profile, 0, parameters, &refusal) != 0) {+        fprintf(stderr, "failed to configure sandbox: %s\n", refusal != NULL ? refusal : "(null)");+        status_fail("sandbox", 0, NO_INDEX);+    }+}++/* The child the helper forks, which becomes the builder: upstream's+ * runChild for a build that is not a builtin.  LOG_FD is the writing end+ * of the pipe the helper copies into the build log, and REPORT_FD that of+ * the pipe the child reports a failed setup step on, which its exec+ * closes, and which the helper relays to the status channel. */+static void child_main(const struct plan *plan, const char *const *parameters, int log_fd, int report_fd, char **argv,+                       const sigset_t *original_mask)+{+    struct rlimit core;++    posix_report_to(report_fd);++    /* No controlling terminal, and no terminal signals; the builder leads+     * the process group the helper kills (commonChildInit). */+    if (setsid() < 0)+        status_fail("setsid", errno, NO_INDEX);++    if (chdir(plan->build_dir) < 0)+        status_fail("chdir", errno, NO_INDEX);++    if (dup2(log_fd, STDOUT_FILENO) < 0 || dup2(log_fd, STDERR_FILENO) < 0)+        status_fail("output", errno, NO_INDEX);++    /* Every descriptor but the report pipe, which closes when the builder+     * starts (runChild's closeExtraFDs). */+    posix_close_descriptors(descriptor_listing, posix_status_fd());++    /* No core dumps (runChild).  Upstream also raises the hard limit to+     * infinity, which an unprivileged process may not; the hard limit is+     * left as it is. */+    if (getrlimit(RLIMIT_CORE, &core) == 0) {+        core.rlim_cur = 0;+        setrlimit(RLIMIT_CORE, &core);+    }++    /* The build user's ids, with no supplementary group, before the+     * profile, as upstream's setUser drops to the build user before it+     * applies one; upstream gives a macOS build user no supplementary+     * groups. */+    if (plan->as_build_user) {+        if (setgroups(0, NULL) < 0)+            status_fail("setgroups", errno, NO_INDEX);+        if (setgid((gid_t)plan->build_gid) < 0 || getgid() != (gid_t)plan->build_gid+            || getegid() != (gid_t)plan->build_gid)+            status_fail("setgid", errno, NO_INDEX);+        if (setuid((uid_t)plan->build_uid) < 0 || getuid() != (uid_t)plan->build_uid+            || geteuid() != (uid_t)plan->build_uid)+            status_fail("setuid", errno, NO_INDEX);+    }++    /* Last before the exec, as upstream's runChild calls setUser. */+    apply_profile(plan, parameters);++    sigprocmask(SIG_SETMASK, original_mask, NULL);+    execve(argv[0], argv, plan->environment);+    status_fail("exec", errno, NO_INDEX);+}++/* ------------------------------------------------------------------------+ * The build's mark+ * ------------------------------------------------------------------------ */++/* Write a new mark's name into NAME, which holds MARK_LENGTH bytes and its+ * terminator. */+static void make_mark_name(char *name)+{+    static const char hex[] = "0123456789abcdef";+    const size_t prefix = sizeof MARK_PREFIX - 1;+    unsigned char bytes[MARK_RANDOM_BYTES];+    size_t i;+    arc4random_buf(bytes, sizeof bytes);+    memcpy(name, MARK_PREFIX, prefix);+    for (i = 0; i < MARK_RANDOM_BYTES; i++) {+        name[prefix + 2 * i] = hex[bytes[i] >> 4];+        name[prefix + 2 * i + 1] = hex[bytes[i] & 0xf];+    }+    name[MARK_LENGTH] = '\0';+}++/* The plan's parameters followed by the mark's, NULL-terminated, in a+ * buffer for the caller to free, or NULL. */+static const char **profile_parameters(const struct plan *plan, const struct build_mark *mark)+{+    size_t from_plan = 2 * plan->parameter_count;+    const char **parameters = calloc(from_plan + 2 * MARK_PARAMETER_COUNT + 1, sizeof *parameters);+    if (parameters == NULL)+        return NULL;+    if (from_plan > 0)+        memcpy(parameters, plan->parameters, from_plan * sizeof *parameters);+    parameters[from_plan] = TOKEN_PARAMETER;+    parameters[from_plan + 1] = mark->token;+    parameters[from_plan + 2] = DECOY_PARAMETER;+    parameters[from_plan + 3] = mark->decoy;+    return parameters;+}++/* ------------------------------------------------------------------------+ * The sweep+ * ------------------------------------------------------------------------ */++/* PIDs, in a buffer that grows. */+struct pid_set {+    pid_t *pids;+    size_t count;+    size_t capacity;+};++static int pid_set_has(const struct pid_set *set, pid_t pid)+{+    size_t i;+    for (i = 0; i < set->count; i++)+        if (set->pids[i] == pid)+            return 1;+    return 0;+}++/* Make room in SET for COUNT PIDs in all.  Answers 0, or ENOMEM. */+static int pid_set_reserve(struct pid_set *set, size_t count)+{+    pid_t *grown;+    if (count <= set->capacity)+        return 0;+    grown = realloc(set->pids, count * sizeof *grown);+    if (grown == NULL)+        return ENOMEM;+    set->pids = grown;+    set->capacity = count;+    return 0;+}++/* Add PID to SET, which has room for it. */+static void pid_set_put(struct pid_set *set, pid_t pid)+{+    set->pids[set->count++] = pid;+}++/* One of the user's processes as a listing found it: whether it was still+ * running then, rather than a zombie, which starts no other process. */+struct listed_process {+    pid_t pid;+    int running;+};++/* How listing the user's processes ended. */+enum listing_outcome {+    LISTED,+    /* A call failed, with errno set. */+    LISTING_FAILED,+    /* Processes started faster than a listing could be sized for them,+     * LISTING_ATTEMPTS_MAX times running. */+    LISTING_OUTRUN+};++/* The processes whose effective user is USER, in *LISTED, a buffer for the+ * caller to free, and their count in *COUNT. */+static enum listing_outcome user_processes(uid_t user, struct listed_process **listed, size_t *count)+{+    int request[4] = {CTL_KERN, KERN_PROC, KERN_PROC_UID, 0};+    int attempt;+    request[3] = (int)user;+    for (attempt = 0; attempt < LISTING_ATTEMPTS_MAX; attempt++) {+        size_t bytes = 0;+        size_t found;+        size_t i;+        struct kinfo_proc *processes;+        struct listed_process *each;+        if (sysctl(request, 4, NULL, &bytes, NULL, 0) < 0)+            return LISTING_FAILED;+        processes = malloc(bytes > 0 ? bytes : sizeof *processes);+        if (processes == NULL)+            return LISTING_FAILED;+        if (sysctl(request, 4, processes, &bytes, NULL, 0) < 0) {+            int error = errno;+            free(processes);+            /* More processes than when it was sized: size it again. */+            if (error == ENOMEM)+                continue;+            errno = error;+            return LISTING_FAILED;+        }+        found = bytes / sizeof *processes;+        each = malloc((found > 0 ? found : 1) * sizeof *each);+        if (each == NULL) {+            free(processes);+            return LISTING_FAILED;+        }+        for (i = 0; i < found; i++) {+            each[i].pid = processes[i].kp_proc.p_pid;+            each[i].running = processes[i].kp_proc.p_stat != SZOMB;+        }+        free(processes);+        *listed = each;+        *count = found;+        return LISTED;+    }+    return LISTING_OUTRUN;+}++/* Whether PID is a process that has not ended. */+static int still_running(pid_t pid)+{+    struct proc_bsdinfo info;+    return proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, sizeof info) == (int)sizeof info+        && info.pbi_status != SZOMB;+}++/* What sandbox_check says of a listed process and the build's mark. */+enum mark_answer {+    /* Not a process of this build. */+    MARK_ABSENT,+    /* A process of this build. */+    MARK_PRESENT,+    /* Not known: a process that was running when listed and has ended+     * since, which may have been this build's and may have started+     * another first, or one sandbox_check answered with an error. */+    MARK_UNKNOWN+};++/* Whether a listed process is one of this build's: its sandbox refuses+ * the decoy and lets it look up the token.  Under sandbox = true only+ * this build's profile allows the token, which this helper made, and ends+ * by refusing the decoy, after which nothing changes either answer; a+ * process in no sandbox, or in one that allows every name, may look up+ * the decoy; and a zombie, or a PID no process has, is refused both.+ *+ * The decoy is asked first.  A refusal shows the process is in a sandbox,+ * which can no longer change (a process in one is refused another), so+ * the token's answer comes from the same profile.  Asked the other way+ * round, a process that applies a sandbox of its own between the two,+ * as many of the user's applications and services do early in their+ * lives, would be allowed the token while it had none and refused the+ * decoy once it had one, and be taken for the build's. */+static enum mark_answer process_mark(const struct listed_process *process, const struct build_mark *mark)+{+    int name_check = SANDBOX_FILTER_GLOBAL_NAME | SANDBOX_CHECK_NO_REPORT;+    int decoy = sandbox_check(process->pid, "mach-lookup", name_check, mark->decoy);+    int token;+    if (decoy == 0)+        return MARK_ABSENT;+    if (decoy != 1)+        return MARK_UNKNOWN;+    token = sandbox_check(process->pid, "mach-lookup", name_check, mark->token);+    if (token == 0)+        return MARK_PRESENT;+    if (token != 1)+        return MARK_UNKNOWN;+    return process->running && !still_running(process->pid) ? MARK_UNKNOWN : MARK_ABSENT;+}++/* How killing a set of processes ended. */+enum ending {+    /* Every one is known to have ended. */+    ENDING_DONE,+    /* The end of one could not be watched for. */+    ENDING_UNWATCHED,+    /* One had not ended in time. */+    ENDING_LINGERING+};++/* Kill every process in SET and wait for each to end, for up to+ * SWEEP_EXIT_SECONDS.  Each is watched before it is killed, so its end+ * cannot be missed, and one that has already ended cannot be watched,+ * which says so.  Every one is killed, whatever the answer; *ERROR+ * receives the errno value behind ENDING_UNWATCHED. */+static enum ending end_processes(const struct pid_set *set, int *error)+{+    int queue = kqueue();+    enum ending ending = ENDING_DONE;+    size_t pending = 0;+    size_t i;+    struct timespec deadline;+    if (queue < 0) {+        *error = errno;+        ending = ENDING_UNWATCHED;+    }+    for (i = 0; i < set->count; i++) {+        struct kevent change;+        EV_SET(&change, (uintptr_t)set->pids[i], EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);+        if (queue >= 0 && kevent(queue, &change, 1, NULL, 0, NULL) == 0) {+            pending++;+        } else if (queue >= 0 && errno != ESRCH) {+            *error = errno;+            ending = ENDING_UNWATCHED;+        }+        kill(set->pids[i], SIGKILL);+    }+    if (pending > 0 && deadline_in(SWEEP_EXIT_SECONDS, &deadline) < 0) {+        *error = errno;+        ending = ENDING_UNWATCHED;+        pending = 0;+    }+    while (pending > 0) {+        struct kevent event;+        struct timespec left;+        int got;+        int some_left = time_left(&deadline, &left);+        if (some_left < 0) {+            *error = errno;+            ending = ENDING_UNWATCHED;+            break;+        }+        if (some_left == 0) {+            if (ending == ENDING_DONE)+                ending = ENDING_LINGERING;+            break;+        }+        got = kevent(queue, NULL, 0, &event, 1, &left);+        if (got < 0 && errno == EINTR)+            continue;+        if (got < 0) {+            *error = errno;+            ending = ENDING_UNWATCHED;+            break;+        }+        if (got > 0 && event.filter == EVFILT_PROC && (event.fflags & NOTE_EXIT) != 0)+            pending--;+    }+    if (queue >= 0)+        close(queue);+    return ending;+}++/* How a sweep ended. */+enum sweep_outcome {+    /* A listing, taken once every process of the build found before had+     * ended, found none. */+    SWEEP_DONE,+    /* The user's processes could not be listed, or the sets of the+     * build's could not grow. */+    SWEEP_UNLISTED,+    /* The user's processes started faster than a listing could be sized,+     * LISTING_ATTEMPTS_MAX times running. */+    SWEEP_OUTRUN,+    /* The listings ran out while the build's processes were still found. */+    SWEEP_UNSETTLED,+    /* The end of a process the sweep killed could not be watched for. */+    SWEEP_UNWATCHED,+    /* A process the sweep killed had not ended in time. */+    SWEEP_LINGERING+};++/* Kill every process in STOPPED that is still one of the build's, and+ * wait for each to end.  Only a process sandbox_check finds to be the+ * build's is killed, which never kills a PID another process has taken+ * since; one it cannot answer for (MARK_UNKNOWN) is left as it is,+ * stopped if it was the build's, neither killed nor continued, as+ * continuing it could free a process of the build.  With no room to+ * gather them, each is asked and killed in turn without waiting for its+ * end. */+static void end_still_marked(const struct pid_set *stopped, const struct build_mark *mark)+{+    struct pid_set still = {NULL, 0, 0};+    size_t i;+    int ignored;+    if (pid_set_reserve(&still, stopped->count) != 0) {+        for (i = 0; i < stopped->count; i++) {+            struct listed_process process;+            process.pid = stopped->pids[i];+            process.running = 1;+            if (process_mark(&process, mark) == MARK_PRESENT)+                kill(process.pid, SIGKILL);+        }+        return;+    }+    for (i = 0; i < stopped->count; i++) {+        struct listed_process process;+        process.pid = stopped->pids[i];+        process.running = 1;+        if (process_mark(&process, mark) == MARK_PRESENT)+            pid_set_put(&still, process.pid);+    }+    end_processes(&still, &ignored);+    free(still.pids);+}++/* End every process of the build, whose processes are USER's.  Each+ * listing stops every process of the+ * build it finds, those it has stopped before included, since one of them+ * may continue another (SIGCONT, which the profile lets a build send its+ * own processes), and a process stopped while it forks still starts its+ * child.  Room to record every process a listing holds is made before any+ * is stopped, and each is recorded before it is stopped, so none is+ * stopped and then forgotten.  Once a listing finds none it has not+ * stopped, and no process that ended before it could be asked, the+ * processes of the build that listing found are killed and waited for,+ * and the listing starts over.  A PID stopped before and absent from that+ * listing is not killed: the listing holds every process whose effective+ * user is USER, so that PID now names none of the user's, the process+ * having ended, or another having taken its PID; a process of the build+ * cannot become another user, as macOS refuses a process in a sandbox the+ * exec of a setuid program.  The sweep is done only when a listing, taken+ * once every process of the build found before has ended, finds none of+ * the build's and none it could not tell.  A process can start another+ * only while it runs, and every process running when that listing was+ * taken was asked, so none of the build's is left, short of one that ended+ * after that listing and whose PID another process was given before it+ * was asked.  The listings are bounded; whatever the outcome, every process+ * stopped that is still the build's is killed (end_still_marked, which+ * says which few it leaves).  *ERROR receives the errno value behind+ * SWEEP_UNLISTED or SWEEP_UNWATCHED. */+static enum sweep_outcome sweep_build(const struct build_mark *mark, uid_t user, int *error)+{+    struct pid_set stopped = {NULL, 0, 0};+    struct pid_set present = {NULL, 0, 0};+    pid_t self = getpid();+    enum sweep_outcome outcome = SWEEP_UNSETTLED;+    size_t pass;+    for (pass = 0; pass < SWEEP_PASSES_MAX && outcome == SWEEP_UNSETTLED; pass++) {+        size_t count = 0;+        size_t fresh = 0;+        size_t unknown = 0;+        size_t i;+        struct listed_process *listed = NULL;+        switch (user_processes(user, &listed, &count)) {+        case LISTED:+            break;+        case LISTING_FAILED:+            *error = errno;+            outcome = SWEEP_UNLISTED;+            break;+        case LISTING_OUTRUN:+            outcome = SWEEP_OUTRUN;+            break;+        }+        if (outcome != SWEEP_UNSETTLED)+            break;+        present.count = 0;+        if (pid_set_reserve(&present, count) != 0 || pid_set_reserve(&stopped, stopped.count + count) != 0) {+            free(listed);+            *error = ENOMEM;+            outcome = SWEEP_UNLISTED;+            break;+        }+        for (i = 0; i < count; i++) {+            pid_t pid = listed[i].pid;+            if (pid <= 0 || pid == self)+                continue;+            switch (process_mark(&listed[i], mark)) {+            case MARK_ABSENT:+                break;+            case MARK_UNKNOWN:+                unknown++;+                break;+            case MARK_PRESENT:+                pid_set_put(&present, pid);+                if (!pid_set_has(&stopped, pid)) {+                    pid_set_put(&stopped, pid);+                    fresh++;+                }+                kill(pid, SIGSTOP);+                break;+            }+        }+        free(listed);+        if (fresh > 0 || unknown > 0)+            continue;+        if (present.count == 0) {+            outcome = SWEEP_DONE;+            break;+        }+        switch (end_processes(&present, error)) {+        case ENDING_DONE:+            break;+        case ENDING_UNWATCHED:+            outcome = SWEEP_UNWATCHED;+            break;+        case ENDING_LINGERING:+            outcome = SWEEP_LINGERING;+            break;+        }+        present.count = 0;+        stopped.count = 0;+    }+    if (stopped.count > 0)+        end_still_marked(&stopped, mark);+    free(present.pids);+    free(stopped.pids);+    return outcome;+}++/* ------------------------------------------------------------------------+ * The helper+ * ------------------------------------------------------------------------ */++/* The handled signals the helper watches, written into WATCHED, which+ * holds HANDLED_SIGNAL_COUNT; answers how many.  A signal this process+ * started out ignoring is left out, as one started under nohup ignores+ * SIGHUP, and the builder inherits it ignored: the helper runs in+ * nova-nix's process group, and a signal sent to that group, which+ * nova-nix ignores and carries on through, must not end the build, as it+ * never reaches upstream's builder in a session of its own. */+static size_t watched_signals(int *watched)+{+    size_t count = 0;+    size_t i;+    for (i = 0; i < HANDLED_SIGNAL_COUNT; i++) {+        struct sigaction current;+        if (handled_signals[i] != SIGCHLD && sigaction(handled_signals[i], NULL, &current) == 0+            && current.sa_handler == SIG_IGN)+            continue;+        watched[count++] = handled_signals[i];+    }+    return count;+}++/* A queue that wakes on each of the COUNT signals in WATCHED, on the+ * lifeline, and on the builder's pipe, made before the builder exists.+ * Answers the queue, or -1 with errno set. */+static int watch_queue(int lifeline_fd, int log_fd, const int *watched, size_t count)+{+    struct kevent changes[HANDLED_SIGNAL_COUNT + 2];+    size_t i;+    int queue = kqueue();+    if (queue < 0)+        return -1;+    for (i = 0; i < count; i++)+        EV_SET(&changes[i], (uintptr_t)watched[i], EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);+    EV_SET(&changes[count], (uintptr_t)lifeline_fd, EVFILT_READ, EV_ADD, 0, 0, NULL);+    EV_SET(&changes[count + 1], (uintptr_t)log_fd, EVFILT_READ, EV_ADD, 0, 0, NULL);+    if (kevent(queue, changes, (int)(count + 2), NULL, 0, NULL) < 0) {+        int error = errno;+        close(queue);+        errno = error;+        return -1;+    }+    return queue;+}++/* Add the log taking more to QUEUE, not yet watched for.  Standard error+ * has to be something kqueue can watch for writing, as the pipe runHelper+ * passes is and /dev/null is not (EINVAL).  Answers 0, or -1 with errno+ * set. */+static int watch_log(int queue)+{+    struct kevent change;+    EV_SET(&change, (uintptr_t)STDERR_FILENO, EVFILT_WRITE, EV_ADD | EV_DISABLE, 0, 0, NULL);+    return kevent(queue, &change, 1, NULL, 0, NULL);+}++/* Kill every process of the build that is still in the builder's group,+ * and the builder itself, which may not yet lead the group it makes. */+static void kill_build(pid_t child)+{+    kill(-child, SIGKILL);+    kill(child, SIGKILL);+}++/* Whether the builder has ended, leaving it to be reaped. */+static int builder_ended(pid_t child)+{+    siginfo_t info;+    memset(&info, 0, sizeof info);+    return waitid(P_PID, (id_t)child, &info, WEXITED | WNOHANG | WNOWAIT) == 0 && info.si_pid == child;+}++/* Wait for the builder, copying its output into the build log as the log+ * takes it, killing the build on a terminating signal or when the+ * lifeline closes, and the rest of its group once it has ended.  Answers+ * 0 with how it ended in *WAIT_STATUS, or the errno of a wait that+ * failed, which ends the build: the builder is killed, and how it ended+ * cannot be known. */+static int wait_for_builder(pid_t child, struct watch *watch, struct log_copy *copy, int *wait_status)+{+    int queue = watch->queue;+    for (;;) {+        struct kevent event;+        int got;+        if (builder_ended(child)) {+            kill(-child, SIGKILL);+            return posix_reap(child, wait_status);+        }+        got = kevent(queue, NULL, 0, &event, 1, NULL);+        if (got < 0) {+            if (errno == EINTR)+                continue;+            /* With nothing left to watch, the build is ended and reaped. */+            kill_build(child);+            return posix_reap(child, wait_status);+        }+        if (got == 0)+            continue;+        if (event.filter == EVFILT_READ && copy->from >= 0 && (int)event.ident == copy->from) {+            /* A read the queue reported before it stopped watching the+             * pipe waits until what is held has gone. */+            if (copy->start == copy->end)+                log_fill(copy);+            log_flush(copy);+            log_watch(queue, copy);+            if (copy->stalled != 0 && !watch->ending) {+                watch->ending = 1;+                kill_build(child);+            }+        } else if (event.filter == EVFILT_WRITE && (int)event.ident == STDERR_FILENO) {+            log_flush(copy);+            log_watch(queue, copy);+            if (copy->stalled != 0 && !watch->ending) {+                watch->ending = 1;+                kill_build(child);+            }+        } else {+            watch_note(watch, &event);+            if (watch->ending)+                kill_build(child);+        }+    }+}++/* Relay to the status channel what the child reported on its pipe, read+ * from FD once the child has ended or executed the builder, either of+ * which closes its end.  Answers 1 when it reported a failed step, and 0+ * when it reported nothing; a read that fails ends the helper with its+ * own record. */+static int relay_report(int fd)+{+    char report[REPORT_BYTES_MAX];+    size_t got = 0;+    for (;;) {+        ssize_t read_now = read(fd, report + got, sizeof report - got);+        if (read_now < 0 && errno == EINTR)+            continue;+        if (read_now < 0)+            status_fail("relay", errno, NO_INDEX);+        if (read_now == 0 || (got += (size_t)read_now) == sizeof report)+            break;+    }+    close(fd);+    if (got == 0)+        return 0;+    backend_write_status(report, got);+    return 1;+}++/* Set O_NONBLOCK on FD.  Answers 0, or -1 with errno set. */+static int set_nonblocking(int fd)+{+    int flags = fcntl(fd, F_GETFL);+    return flags < 0 ? -1 : fcntl(fd, F_SETFL, flags | O_NONBLOCK);+}++int backend_run(const struct plan *plan, char **argv)+{+    int null_fd;+    int log_pipe[2];+    int report_pipe[2];+    int reported;+    int error;+    int sweep_error = 0;+    size_t i;+    size_t watched_count;+    int watched[HANDLED_SIGNAL_COUNT];+    pid_t child;+    sigset_t handled;+    sigset_t original_mask;+    int wait_status = 0;+    struct build_mark mark;+    const char **parameters;+    enum sweep_outcome sweep;+    enum drain_outcome drain;+    struct watch watch;+    struct log_copy copy;++    /* Standard input, past the plan, is the lifeline; the builder reads+     * /dev/null (commonChildInit). */+    watch.lifeline_fd = fcntl(STDIN_FILENO, F_DUPFD_CLOEXEC, 3);+    watch.ending = 0;+    null_fd = open("/dev/null", O_RDWR | O_CLOEXEC);+    if (watch.lifeline_fd < 0 || null_fd < 0 || dup2(null_fd, STDIN_FILENO) < 0)+        status_fail("stdin", errno, NO_INDEX);+    close(null_fd);++    /* The builder's pipe, both ends closed on exec: the builder takes the+     * writing end as its standard output and error, and the helper reads+     * it without waiting. */+    if (pipe(log_pipe) < 0 || fcntl(log_pipe[0], F_SETFD, FD_CLOEXEC) < 0+        || fcntl(log_pipe[1], F_SETFD, FD_CLOEXEC) < 0 || set_nonblocking(log_pipe[0]) < 0)+        status_fail("log", errno, NO_INDEX);+    /* The helper writes the log without waiting either. */+    if (set_nonblocking(STDERR_FILENO) < 0)+        status_fail("logmode", errno, NO_INDEX);+    /* The child's report of a failed setup step, both ends closed on+     * exec, so that the helper alone writes the status channel once the+     * child exists and writes at most one record. */+    if (pipe(report_pipe) < 0 || fcntl(report_pipe[0], F_SETFD, FD_CLOEXEC) < 0+        || fcntl(report_pipe[1], F_SETFD, FD_CLOEXEC) < 0)+        status_fail("report", errno, NO_INDEX);+    copy.from = log_pipe[0];+    copy.start = copy.end = 0;+    copy.gone = 0;+    copy.unwatched = 0;+    copy.stalled = 0;++    make_mark_name(mark.token);+    make_mark_name(mark.decoy);+    parameters = profile_parameters(plan, &mark);+    if (parameters == NULL)+        status_fail("sweep", errno, NO_INDEX);++    /* The signals the helper answers are read through the queue, which+     * records each one sent once it watches for it, blocked or not, but+     * not one already pending when it starts to watch.  So the queue+     * watches first and the signals are blocked after: one sent before the+     * block ends the helper, before any builder exists, and none sent+     * after it is lost.  The builder unblocks them before it executes. */+    watched_count = watched_signals(watched);+    watch.queue = watch_queue(watch.lifeline_fd, log_pipe[0], watched, watched_count);+    if (watch.queue < 0)+        status_fail("signals", errno, NO_INDEX);+    if (watch_log(watch.queue) < 0)+        status_fail("logwatch", errno, NO_INDEX);+    sigemptyset(&handled);+    for (i = 0; i < watched_count; i++)+        sigaddset(&handled, watched[i]);+    if (sigprocmask(SIG_BLOCK, &handled, &original_mask) < 0)+        status_fail("signals", errno, NO_INDEX);++    child = fork();+    if (child < 0)+        status_fail("fork", errno, NO_INDEX);+    if (child == 0) {+        close(report_pipe[0]);+        child_main(plan, parameters, log_pipe[1], report_pipe[1], argv, &original_mask);+        _exit(EXIT_FAILURE);+    }+    /* The child reports a failed setup step on its pipe, which its exec+     * closes, and the helper relays it.  The helper keeps the status+     * channel for that and for the one failure the build log cannot carry,+     * one to watch the log itself, which it reports only when the child+     * reported nothing, so the channel never holds two records. */+    close(log_pipe[1]);+    close(report_pipe[1]);+    free(parameters);++    /* The queue stays open past the builder's end, so the drain and the+     * last messages wait on the log only while the build is not to end. */+    error = wait_for_builder(child, &watch, &copy, &wait_status);+    reported = relay_report(report_pipe[0]);+    sweep = sweep_build(&mark, plan->as_build_user ? (uid_t)plan->build_uid : getuid(), &sweep_error);+    drain = log_drain(&watch, &copy);+    if (copy.unwatched != 0 && !reported)+        status_fail("logwatch", copy.unwatched, NO_INDEX);+    /* Every other reason goes to the build log. */+    if (error != 0) {+        /* Upstream's words for a wait that fails (Pid::wait in+         * processes.cc). */+        log_message(&watch, &copy, "nova-nix-sandbox: cannot get exit status of PID %ld: %s\n", (long)child,+                    strerror(error));+        return EXIT_FAILURE;+    }+    /* A process of the build may be left in each of these, so the build+     * fails. */+    switch (sweep) {+    case SWEEP_DONE:+        break;+    case SWEEP_UNLISTED:+        log_message(&watch, &copy, "nova-nix-sandbox: cannot list the build's processes: %s\n",+                    strerror(sweep_error));+        return EXIT_FAILURE;+    case SWEEP_OUTRUN:+        log_message(&watch, &copy,+                    "nova-nix-sandbox: processes started faster than they could be listed, %d times running\n",+                    LISTING_ATTEMPTS_MAX);+        return EXIT_FAILURE;+    case SWEEP_UNSETTLED:+        log_message(&watch, &copy, "nova-nix-sandbox: the build's processes were still running after %d listings\n",+                    SWEEP_PASSES_MAX);+        return EXIT_FAILURE;+    case SWEEP_UNWATCHED:+        log_message(&watch, &copy, "nova-nix-sandbox: cannot watch the build's processes end: %s\n",+                    strerror(sweep_error));+        return EXIT_FAILURE;+    case SWEEP_LINGERING:+        log_message(&watch, &copy,+                    "nova-nix-sandbox: a process of the build had not ended %d seconds after it was killed\n",+                    SWEEP_EXIT_SECONDS);+        return EXIT_FAILURE;+    }+    switch (drain) {+    case DRAIN_DONE:+        break;+    case DRAIN_ENDLESS:+        log_message(&watch, &copy, "nova-nix-sandbox: the build's output went on past %d bytes after it ended\n",+                    LOG_DRAIN_BYTES_MAX);+        return EXIT_FAILURE;+    case DRAIN_CUT:+        /* The build was to end before the log took all its output, at+         * nova-nix's word, which no longer reads it: the end the builder+         * came to is relayed all the same, as for a build that ended with+         * nothing left to copy. */+        break;+    }+    return posix_relay(wait_status);+}++/* ------------------------------------------------------------------------+ * The probe+ * ------------------------------------------------------------------------ */++const char *backend_probe(int *error)+{+    static const char *const no_parameters[] = {NULL};+    char *refusal = NULL;+    *error = 0;+    if (sandbox_init_with_parameters(probe_profile, 0, no_parameters, &refusal) != 0) {+        if (refusal != NULL)+            fprintf(stderr, "nova-nix-sandbox: %s\n", refusal);+        return "sandbox";+    }+    return NULL;+}
+ sandbox/linux.c view
@@ -0,0 +1,1110 @@+/*+ * nova-nix-sandbox's Linux backend (backend.h): runs the builder in fresh+ * user, mount, PID, IPC and UTS namespaces, and a network namespace unless+ * the build may reach the host's network, with a chroot that holds the+ * build's inputs.+ *+ * The setup runs here, in C between the namespaces' creation and the+ * builder's exec, because nova-nix itself can run nothing there: the+ * process library it spawns builders with gives no hook between fork and+ * exec, and a child forked from the threaded GHC runtime may make only+ * async-signal-safe calls before it execs.+ *+ * The status channel is the pipe the helper gets as standard output.  It+ * moves to a close-on-exec descriptor and standard output becomes the+ * log, so a builder that starts closes it, and the reader sees end of+ * file with nothing written.  The builder is PID 1 of its PID namespace,+ * which ends with it.+ *+ * The probe checks that this system lets an unprivileged process make the+ * namespaces, as upstream's userNamespacesSupported and+ * mountAndPidNamespacesSupported do (namespaces.cc at Nix 2.24.9,+ * linux-namespaces.cc at 2.36.0).+ *+ * The steps follow upstream's LocalDerivationGoal::startBuilder and+ * runChild (local-derivation-goal.cc at 2.24.9, which this file calls LDG;+ * chroot-derivation-builder.cc and linux-derivation-builder.cc at 2.36.0).+ */++#define _GNU_SOURCE++#include <errno.h>+#include <fcntl.h>+#include <grp.h>+#include <limits.h>+#include <linux/keyctl.h>+#include <net/if.h>+#include <netinet/in.h>+#include <poll.h>+#include <sched.h>+#include <signal.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/ioctl.h>+#include <sys/mount.h>+#include <sys/prctl.h>+#include <sys/resource.h>+#include <sys/signalfd.h>+#include <sys/socket.h>+#include <sys/stat.h>+#include <sys/statvfs.h>+#include <sys/syscall.h>+#include <sys/types.h>+#include <sys/wait.h>+#include <unistd.h>++#include "backend.h"+#include "mountinfo.h"+#include "plan.h"+#include "posix.h"++/* mount_setattr and what it takes, from the kernel's UAPI at Linux 5.12+ * (include/uapi/linux/mount.h, include/uapi/linux/fcntl.h and the syscall+ * tables).  They are spelled out here because a C library before glibc+ * 2.36 declares none of them, and <linux/mount.h> conflicts with+ * <sys/mount.h> there.  The number is 442 in the asm-generic table and+ * x86's; an architecture this file does not know uses the mountinfo walk+ * alone. */+#if defined(SYS_mount_setattr)+#define MOUNT_SETATTR_SYSCALL SYS_mount_setattr+#elif defined(__x86_64__) || defined(__i386__) || defined(__aarch64__) || defined(__arm__) || defined(__riscv)+#define MOUNT_SETATTR_SYSCALL 442+#endif+#define MOUNT_SETATTR_READ_ONLY ((uint64_t)0x00000001)+#define MOUNT_SETATTR_RECURSIVE 0x8000++struct mount_setattr_attributes {+    uint64_t attr_set;+    uint64_t attr_clr;+    uint64_t propagation;+    uint64_t userns_fd;+};++/* The byte the helper sends the child once its ids are mapped. */+#define RELEASE_BYTE '1'++/* Exit statuses of the probe's mount check, read back by the probe. */+#define PROBE_PRIVATE_FAILED 1+#define PROBE_PROC_FAILED 2++/* The hostname and domain name a build sees (runChild in LDG).  Upstream+ * passes sizeof, so the kernel holds the terminating NUL too. */+static const char sandbox_hostname[] = "localhost";+static const char sandbox_domainname[] = "(none)";++/* What a devpts instance of the sandbox's own is mounted with (runChild in+ * LDG). */+static const char devpts_options[] = "newinstance,mode=0620";++/* The mount table of the process reading it. */+static const char mountinfo_path[] = "/proc/self/mountinfo";++/* The open descriptors of the process reading it. */+static const char descriptor_listing[] = "/proc/self/fd";++/* What the read of a file with no size, such as one in /proc, starts with. */+#define PROC_READ_START_BYTES ((size_t)16 * 1024)++/* What the cloned child needs: the plan, the program, the sync pipe and+ * the signal mask to restore before it execs. */+struct child_context {+    const struct plan *plan;+    char **argv;+    int sync_read;+    int sync_write;+    sigset_t original_mask;+};++/* The backend this file is. */+const enum plan_backend backend_plan = PLAN_LINUX;++/* ------------------------------------------------------------------------+ * Paths+ * ------------------------------------------------------------------------ */++/* PREFIX followed by PATH, or NULL with errno set. */+static char *joined(const char *prefix, const char *path)+{+    size_t prefix_length = strlen(prefix);+    size_t path_length = strlen(path);+    char *result = malloc(prefix_length + path_length + 1);+    if (result == NULL) {+        errno = ENOMEM;+        return NULL;+    }+    memcpy(result, prefix, prefix_length);+    memcpy(result + prefix_length, path, path_length + 1);+    return result;+}++static int path_exists(const char *path)+{+    struct stat st;+    return lstat(path, &st) == 0;+}++/* Create PATH and every missing directory above it, as upstream's+ * createDirs does.  Answers 0, or -1 with errno set. */+static int create_dirs(const char *path)+{+    char *copy = joined("", path);+    char *slash;+    if (copy == NULL)+        return -1;+    for (slash = strchr(copy + 1, '/'); ; slash = strchr(slash + 1, '/')) {+        if (slash != NULL)+            *slash = '\0';+        if (mkdir(copy, 0777) < 0 && errno != EEXIST) {+            int error = errno;+            free(copy);+            errno = error;+            return -1;+        }+        if (slash == NULL)+            break;+        *slash = '/';+    }+    free(copy);+    return 0;+}++/* ------------------------------------------------------------------------+ * Mounts+ * ------------------------------------------------------------------------ */++/* The flags a read-only remount of a bind must keep: in a user namespace+ * the kernel refuses to clear those the source mount locked. */+static unsigned long locked_flags(const char *path, int *error)+{+    struct statvfs fs;+    unsigned long flags = 0;+    if (statvfs(path, &fs) < 0) {+        *error = errno;+        return 0;+    }+    if (fs.f_flag & ST_NOSUID) flags |= MS_NOSUID;+    if (fs.f_flag & ST_NODEV) flags |= MS_NODEV;+    if (fs.f_flag & ST_NOEXEC) flags |= MS_NOEXEC;+    if (fs.f_flag & ST_NOATIME) flags |= MS_NOATIME;+    if (fs.f_flag & ST_NODIRATIME) flags |= MS_NODIRATIME;+    if (fs.f_flag & ST_RELATIME) flags |= MS_RELATIME;+    *error = 0;+    return flags;+}++/* Read the whole of a file that reports no size, such as one in /proc,+ * into a buffer of its own.  Answers the buffer, or NULL with errno set. */+static char *read_whole(const char *path, size_t *length)+{+    size_t capacity = PROC_READ_START_BYTES;+    size_t used = 0;+    char *bytes = malloc(capacity);+    int fd = open(path, O_RDONLY | O_CLOEXEC);+    int error = 0;+    if (bytes == NULL || fd < 0) {+        error = bytes == NULL ? ENOMEM : errno;+        goto failed;+    }+    for (;;) {+        ssize_t got;+        if (used == capacity) {+            char *larger = realloc(bytes, capacity * 2);+            if (larger == NULL) {+                error = ENOMEM;+                goto failed;+            }+            bytes = larger;+            capacity *= 2;+        }+        got = read(fd, bytes + used, capacity - used);+        if (got < 0) {+            if (errno == EINTR)+                continue;+            error = errno;+            goto failed;+        }+        if (got == 0)+            break;+        used += (size_t)got;+    }+    close(fd);+    *length = used;+    return bytes;++failed:+    if (fd >= 0)+        close(fd);+    free(bytes);+    errno = error;+    return NULL;+}++/* The /proc entry for a descriptor, through which a path-taking call acts+ * on what the descriptor opened. */+static void descriptor_path(char *path, size_t capacity, int fd)+{+    snprintf(path, capacity, "/proc/self/fd/%d", fd);+}++/* Open what is at RELATIVE beneath the directory or mount TOP names, one+ * component at a time without following a link, so the walk stays beneath+ * TOP whatever another user does to a path meanwhile; each step crosses+ * into a mount on the component it reaches.  Answers a descriptor, or -1+ * with errno set. */+static int open_beneath(int top, char *relative)+{+    char *cursor = relative;+    int at = fcntl(top, F_DUPFD_CLOEXEC, 0);+    while (at >= 0) {+        char *slash;+        int next;+        int error;+        while (*cursor == '/')+            cursor++;+        if (*cursor == '\0')+            break;+        slash = strchr(cursor, '/');+        if (slash != NULL)+            *slash = '\0';+        next = openat(at, cursor, O_PATH | O_NOFOLLOW | O_CLOEXEC);+        error = errno;+        close(at);+        errno = error;+        at = next;+        if (slash == NULL)+            break;+        cursor = slash + 1;+    }+    return at;+}++/* Remount the mount a descriptor names read-only, keeping the flags it+ * locked.  Answers 0, or an errno value. */+static int remount_read_only_at(int mounted)+{+    char path[64];+    int error = 0;+    unsigned long keep;+    descriptor_path(path, sizeof path, mounted);+    keep = locked_flags(path, &error);+    if (error != 0)+        return error;+    return mount(NULL, path, NULL, MS_BIND | MS_REMOUNT | MS_RDONLY | keep, NULL) < 0 ? errno : 0;+}++/* Remount the mount MOUNTED names read-only, and each mount beneath it,+ * as the process's mountinfo lists them, each reached from MOUNTED by+ * open_beneath, not by its path.  The mount namespace is the child's own+ * and private, and nothing else mounts in it, so the list does not+ * change under the walk.  Answers 0, or an errno value. */+static int remount_tree_read_only(int mounted)+{+    char link[64];+    char top[PATH_MAX];+    char point[PATH_MAX];+    size_t point_length = 0;+    size_t length = 0;+    struct mountinfo_cursor cursor;+    enum mountinfo_read found;+    int error = 0;+    ssize_t top_length;+    char *mountinfo;+    descriptor_path(link, sizeof link, mounted);+    top_length = readlink(link, top, sizeof top - 1);+    if (top_length < 0)+        return errno;+    top[top_length] = '\0';+    mountinfo = read_whole(mountinfo_path, &length);+    if (mountinfo == NULL)+        return errno;+    cursor.next = mountinfo;+    cursor.end = mountinfo + length;+    while ((found = mountinfo_next_within(&cursor, top, (size_t)top_length, point, sizeof point - 1, &point_length))+           == MOUNTINFO_FOUND) {+        int beneath;+        point[point_length] = '\0';+        if (strlen(point) != point_length) {+            error = EINVAL;+            break;+        }+        beneath = open_beneath(mounted, point + top_length);+        if (beneath < 0) {+            error = errno;+            break;+        }+        error = remount_read_only_at(beneath);+        close(beneath);+        if (error != 0)+            break;+    }+    if (error == 0 && found == MOUNTINFO_TOO_LONG)+        error = ENAMETOOLONG;+    free(mountinfo);+    return error;+}++/* Make the mount a descriptor names read-only, and every mount beneath+ * it, which a recursive bind brought along, so no part of a host path a+ * build sees stays writable.  mount_setattr does it in one step, setting+ * the flag without touching the others, so a locked one stays as it is.+ * A kernel before Linux 5.12 has no mount_setattr; there each mount is+ * remounted read-only in turn.  Answers 0, or an errno value. */+static int make_read_only(int mounted)+{+#if defined(MOUNT_SETATTR_SYSCALL)+    struct mount_setattr_attributes attributes;+    memset(&attributes, 0, sizeof attributes);+    attributes.attr_set = MOUNT_SETATTR_READ_ONLY;+    if (syscall(MOUNT_SETATTR_SYSCALL, mounted, "", AT_EMPTY_PATH | MOUNT_SETATTR_RECURSIVE, &attributes,+                sizeof attributes)+        == 0)+        return 0;+    if (errno != ENOSYS)+        return errno;+#endif+    return remount_tree_read_only(mounted);+}++/* What make_point answers for a symlink source, copied rather than+ * bound. */+#define TARGET_IS_COPIED_LINK (-2)++/* How a directory on the way to a target is opened: as a path alone,+ * which takes search on it and not read, as a directory a bind may have+ * brought in at 0711 allows, and serves to open, make and link beneath+ * it and to mount on. */+#define WALK_FLAGS (O_PATH | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)++/* Open the directory NAME in PARENT, making it where it is missing, without+ * following a link.  Answers a descriptor, or -1 with errno set, ELOOP for+ * a link. */+static int enter_directory(int parent, const char *name)+{+    struct stat st;+    int below = openat(parent, name, WALK_FLAGS);+    if (below < 0 && errno == ENOENT) {+        if (mkdirat(parent, name, 0777) < 0 && errno != EEXIST)+            return -1;+        below = openat(parent, name, WALK_FLAGS);+    }+    /* A link opened with O_DIRECTORY fails as no directory first. */+    if (below < 0 && errno == ENOTDIR && fstatat(parent, name, &st, AT_SYMLINK_NOFOLLOW) == 0 && S_ISLNK(st.st_mode))+        errno = ELOOP;+    return below;+}++/* Open the directory that holds TARGET beneath the chroot's ROOT, making+ * each directory on the way where it is missing.  Each component is opened+ * without following a link, so a target whose path crosses one, such as+ * the skeleton's /dev/fd or a link an earlier entry copied in, fails with+ * ELOOP where joining it to the root and following what is there would+ * lead out of the chroot; upstream joins and follows (doBind in LDG).+ * Answers the directory's descriptor and points *NAME at the target's last+ * component, in *COMPONENTS, which the caller frees, or at nothing when+ * TARGET is the root itself; or -1 with errno set. */+static int walk_to_parent(const char *root, const char *target, char **components, const char **name)+{+    char *cursor;+    int directory;+    *name = NULL;+    *components = joined("", target);+    if (*components == NULL)+        return -1;+    directory = open(root, WALK_FLAGS);+    cursor = *components;+    while (directory >= 0) {+        char *slash;+        while (*cursor == '/')+            cursor++;+        if (*cursor == '\0')+            break;+        slash = strchr(cursor, '/');+        if (slash != NULL)+            *slash = '\0';+        if (*name != NULL) {+            int below = enter_directory(directory, *name);+            int error = errno;+            close(directory);+            errno = error;+            directory = below;+            if (directory < 0)+                break;+        }+        *name = cursor;+        if (slash == NULL)+            break;+        cursor = slash + 1;+    }+    if (directory < 0) {+        int error = errno;+        free(*components);+        *components = NULL;+        errno = error;+    }+    return directory;+}++/* Make, in PARENT at NAME, the place for a bind of SOURCE, whose lstat is+ * ST: a directory or an empty file to mount on, opened without following+ * a link, or for a symlink source a copy of the link, which cannot be+ * bound (doBind in LDG).  NAME is nothing for the root itself, which only a+ * directory binds.  Answers a descriptor of what to mount on,+ * TARGET_IS_COPIED_LINK, or -1 with errno set. */+static int make_point(int parent, const char *name, const struct stat *st, const char *source)+{+    if (S_ISLNK(st->st_mode)) {+        char contents[PATH_MAX];+        ssize_t length = readlink(source, contents, sizeof contents - 1);+        if (length < 0)+            return -1;+        if (name == NULL) {+            errno = EEXIST;+            return -1;+        }+        contents[length] = '\0';+        return symlinkat(contents, parent, name) < 0 ? -1 : TARGET_IS_COPIED_LINK;+    }+    if (name == NULL) {+        if (S_ISDIR(st->st_mode))+            return fcntl(parent, F_DUPFD_CLOEXEC, 0);+        errno = EISDIR;+        return -1;+    }+    if (S_ISDIR(st->st_mode))+        return enter_directory(parent, name);+    return openat(parent, name, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW | O_CLOEXEC, 0666);+}++/* Open the bind just made at NAME in PARENT, or on the root ROOT itself,+ * reached through the directory the walk found, not by a path joined+ * again; the lookup crosses into the new mount.  Answers a descriptor, or+ * -1 with errno set. */+static int open_bind(const char *root, int parent, const char *name)+{+    if (name == NULL)+        return open(root, WALK_FLAGS);+    return openat(parent, name, O_PATH | O_NOFOLLOW | O_CLOEXEC);+}++/* Bind SOURCE onto the mount point a descriptor names, through the+ * descriptor's /proc entry, so the path the walk found is the one bound+ * onto.  Answers 0, or an errno value. */+static int bind_onto(const char *source, int mount_point)+{+    char path[64];+    snprintf(path, sizeof path, "/proc/self/fd/%d", mount_point);+    return mount(source, path, "", MS_BIND | MS_REC, NULL) < 0 ? errno : 0;+}++/* Bind one plan entry into the chroot, as upstream's doBind (in LDG),+ * and make it read-only when the plan says so.  Fails the process. */+static void bind_entry(const struct plan *plan, size_t index)+{+    const struct bind *bind = &plan->binds[index];+    const char *source = bind->source;+    char *resolved = NULL;+    char *components;+    const char *name;+    struct stat st;+    long at = (long)index;+    int parent;+    int mount_point;+    int error;++    if (bind->canonical) {+        resolved = realpath(source, NULL);+        if (resolved == NULL) {+            if (bind->optional && errno == ENOENT)+                return;+            status_fail("bind-source", errno, at);+        }+        source = resolved;+    }+    /* Upstream leaves /proc to the procfs it mounts (runChild in LDG). */+    if (strcmp(source, "/proc") == 0) {+        free(resolved);+        return;+    }+    if (lstat(source, &st) < 0) {+        if (bind->optional && errno == ENOENT) {+            free(resolved);+            return;+        }+        status_fail("bind-source", errno, at);+    }+    parent = walk_to_parent(plan->root, bind->target, &components, &name);+    if (parent < 0)+        status_fail("bind-target", errno, at);+    mount_point = make_point(parent, name, &st, source);+    if (mount_point == -1)+        status_fail("bind-target", errno, at);+    if (mount_point != TARGET_IS_COPIED_LINK) {+        error = bind_onto(source, mount_point);+        close(mount_point);+        if (error != 0)+            status_fail("bind", error, at);+        if (bind->read_only) {+            int mounted = open_bind(plan->root, parent, name);+            error = mounted < 0 ? errno : make_read_only(mounted);+            if (mounted >= 0)+                close(mounted);+            if (error != 0)+                status_fail("remount", error, at);+        }+    }+    close(parent);+    free(components);+    free(resolved);+}++/* Whether the plan binds anything at TARGET in the chroot. */+static int plan_binds(const struct plan *plan, const char *target)+{+    size_t i;+    for (i = 0; i < plan->bind_count; i++)+        if (strcmp(plan->binds[i].target, target) == 0)+            return 1;+    return 0;+}++/* Bind a host device directory or node the devpts fallback needs, as+ * upstream binds it: writable, as the sandbox binds only these and the+ * build directory, since a terminal is written through it, and only where+ * the kernel will not mount a devpts of the sandbox's own. */+static void bind_host(const struct plan *plan, const char *source, const char *stage)+{+    struct stat st;+    char *components;+    const char *name;+    int parent;+    int mount_point;+    int error = 0;+    if (lstat(source, &st) < 0)+        status_fail(stage, errno, NO_INDEX);+    parent = walk_to_parent(plan->root, source, &components, &name);+    if (parent < 0)+        status_fail(stage, errno, NO_INDEX);+    mount_point = make_point(parent, name, &st, source);+    if (mount_point == -1)+        status_fail(stage, errno, NO_INDEX);+    /* A host node that is a link is copied, as upstream's doBind copies+     * one (in LDG), and nothing is left to bind. */+    if (mount_point != TARGET_IS_COPIED_LINK) {+        error = bind_onto(source, mount_point);+        close(mount_point);+    }+    close(parent);+    free(components);+    if (error != 0)+        status_fail(stage, error, NO_INDEX);+}++/* /proc, /dev/shm and /dev/pts of the sandbox's own (runChild in LDG). */+static void mount_filesystems(const struct plan *plan)+{+    char *proc = joined(plan->root, "/proc");+    char *shm = joined(plan->root, "/dev/shm");+    char *pts = joined(plan->root, "/dev/pts");+    char *ptmx = joined(plan->root, "/dev/ptmx");+    char *pts_ptmx = joined(plan->root, "/dev/pts/ptmx");+    if (proc == NULL || shm == NULL || pts == NULL || ptmx == NULL || pts_ptmx == NULL)+        status_fail("proc", ENOMEM, NO_INDEX);++    if (create_dirs(proc) < 0 || mount("none", proc, "proc", 0, NULL) < 0)+        status_fail("proc", errno, NO_INDEX);++    if (path_exists("/dev/shm")) {+        char *options = joined("size=", plan->dev_shm_size);+        if (options == NULL || mount("none", shm, "tmpfs", 0, options) < 0)+            status_fail("dev-shm", errno, NO_INDEX);+        free(options);+    }++    if (path_exists("/dev/pts/ptmx") && !path_exists(ptmx) && !plan_binds(plan, "/dev/pts")) {+        if (mount("none", pts, "devpts", 0, devpts_options) == 0) {+            if (symlink("/dev/pts/ptmx", ptmx) < 0)+                status_fail("devpts", errno, NO_INDEX);+            /* With some kernels ptmx is created with mode 0 (runChild in+             * LDG). */+            if (chmod(pts_ptmx, 0666) < 0)+                status_fail("devpts", errno, NO_INDEX);+        } else {+            if (errno != EINVAL)+                status_fail("devpts", errno, NO_INDEX);+            bind_host(plan, "/dev/pts", "devpts");+            bind_host(plan, "/dev/ptmx", "devpts");+        }+    }+    free(proc);+    free(shm);+    free(pts);+    free(ptmx);+    free(pts_ptmx);+}++/* ------------------------------------------------------------------------+ * The child: PID 1 of the new namespaces+ * ------------------------------------------------------------------------ */++/* Bring the private network's loopback interface up (runChild in LDG). */+static void loopback_up(void)+{+    struct ifreq request;+    int fd = socket(PF_INET, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_IP);+    if (fd < 0)+        status_fail("loopback-socket", errno, NO_INDEX);+    memset(&request, 0, sizeof request);+    memcpy(request.ifr_name, "lo", sizeof "lo");+    request.ifr_flags = IFF_UP | IFF_LOOPBACK | IFF_RUNNING;+    if (ioctl(fd, SIOCSIFFLAGS, &request) < 0)+        status_fail("loopback", errno, NO_INDEX);+    close(fd);+}++/* Die with the helper, as upstream's child dies with its parent+ * (startProcess in processes.cc).  A credential change can clear the+ * setting, so it is made again once the ids are final. */+static void die_with_helper(void)+{+    if (prctl(PR_SET_PDEATHSIG, SIGKILL) < 0)+        status_fail("pdeathsig", errno, NO_INDEX);+}++/* clone(2) as fork makes a child, with no stack of its own: without+ * CLONE_VM the child runs on its copy of this process's stack.  Upstream+ * clones onto a stack it maps (startProcess in processes.cc), a switch the+ * address sanitizer cannot follow (google/sanitizers issue 189), so its+ * reports from such a child may be false; on its copy of a stack the+ * sanitizer knows, the child's are true.  The raw system call, as+ * bubblewrap makes it, since glibc's clone takes a stack; the arguments+ * after the stack are read only for flags this file does not pass.  The+ * child gets 0, and runs single-threaded, as this process does. */+static pid_t raw_clone(int flags)+{+#if defined(__s390__) || defined(__CRIS__)+    return (pid_t)syscall(SYS_clone, (void *)NULL, (unsigned long)flags);+#else+    return (pid_t)syscall(SYS_clone, (unsigned long)flags, (void *)NULL);+#endif+}++static int child_main(const struct child_context *context)+{+    const struct plan *plan = context->plan;+    char release = '\0';+    ssize_t got;+    size_t i;+    char *etc;+    struct rlimit core;++    /* Before the release, so a helper that has already died is seen as the+     * end of the sync pipe, and one that dies later kills this process. */+    die_with_helper();++    /* Wait until the helper has mapped this namespace's ids; end of file+     * means it failed and has reported why (runChild in LDG). */+    close(context->sync_write);+    do {+        got = read(context->sync_read, &release, 1);+    } while (got < 0 && errno == EINTR);+    if (got != 1 || release != RELEASE_BYTE)+        _exit(EXIT_FAILURE);+    close(context->sync_read);++    /* No controlling terminal, and no terminal signals (commonChildInit in+     * child.cc). */+    if (setsid() < 0)+        status_fail("setsid", errno, NO_INDEX);++    if (plan->private_network)+        loopback_up();++    if (sethostname(sandbox_hostname, sizeof sandbox_hostname) < 0)+        status_fail("hostname", errno, NO_INDEX);+    if (setdomainname(sandbox_domainname, sizeof sandbox_domainname) < 0)+        status_fail("domainname", errno, NO_INDEX);++    /* Mounts made below must not propagate out (runChild in LDG). */+    if (mount(NULL, "/", NULL, MS_PRIVATE | MS_REC, NULL) < 0)+        status_fail("private", errno, NO_INDEX);++    /* pivot_root needs the new root to be a mount of its own (runChild in+     * LDG). */+    if (mount(plan->root, plan->root, NULL, MS_BIND, NULL) < 0)+        status_fail("bind-root", errno, NO_INDEX);++    for (i = 0; i < plan->bind_count; i++)+        bind_entry(plan, i);++    mount_filesystems(plan);++    /* Upstream's mode for /etc once its files are in place (runChild in LDG).+     * /etc belongs to the user who made the chroot.  That is root for a+     * build as a build user, as upstream's /etc is; for a build as the+     * invoking user it is that user, as whom the builder runs, so the+     * builder can make it writable again.  It is the build's own copy,+     * removed with the chroot, and its host files are read-only binds. */+    etc = joined(plan->root, "/etc");+    if (etc == NULL || chmod(etc, 0555) < 0)+        status_fail("etc", errno, NO_INDEX);+    free(etc);++    /* Make the chroot the root and detach the old one (runChild in LDG). */+    if (chdir(plan->root) < 0)+        status_fail("chdir-root", errno, NO_INDEX);+    if (mkdir("real-root", 0) < 0)+        status_fail("real-root", errno, NO_INDEX);+    if (syscall(SYS_pivot_root, ".", "real-root") < 0)+        status_fail("pivot", errno, NO_INDEX);+    if (chroot(".") < 0)+        status_fail("chroot", errno, NO_INDEX);+    if (umount2("real-root", MNT_DETACH) < 0)+        status_fail("umount", errno, NO_INDEX);+    if (rmdir("real-root") < 0)+        status_fail("rmdir", errno, NO_INDEX);++    /* The sandbox's ids, which map to the plan's host ids (runChild in+     * LDG). */+    if (setgid((gid_t)plan->sandbox_gid) < 0)+        status_fail("setgid", errno, NO_INDEX);+    if (setuid((uid_t)plan->sandbox_uid) < 0)+        status_fail("setuid", errno, NO_INDEX);+    die_with_helper();++    if (chdir(plan->build_dir) < 0)+        status_fail("chdir", errno, NO_INDEX);++    /* Every descriptor but the status pipe, which closes when the builder+     * starts (runChild's closeExtraFDs). */+    posix_close_descriptors(descriptor_listing, posix_status_fd());++    /* A session keyring of the builder's own, anonymous and empty, which+     * upstream does not make: its builder runs as a build user, with no+     * keys of the invoking user's.  A builder run as the invoking user+     * would otherwise inherit the user's session keyring through the+     * namespaces, and with it possession of every key linked from it, and+     * one run as a build user loses nothing by the join.  The join stops+     * that inheritance and nothing more (security/keys at+     * Linux 6.8): /proc/keys lists the keys of every uid the namespace+     * maps, the builder's own among them (key_serial_next in proc.c); the+     * user keyring gives its owner's uid every permission+     * (look_up_user_keyrings in process_keys.c); and a key's owner gets those+     * permissions whatever namespace asks (key_task_permission in+     * permission.c).  So the builder can link the user keyring into its own+     * (keyctl_keyring_link in keyctl.c), possess it, and read what it holds.+     * Only a filter refusing keyctl, add_key and request_key closes that.  A+     * kernel without keyrings has none to inherit, and a filter that refuses+     * the join refuses the builder's keyctl too. */+    if (syscall(SYS_keyctl, KEYCTL_JOIN_SESSION_KEYRING, (char *)NULL) < 0 && errno != ENOSYS && errno != EPERM)+        status_fail("keyring", errno, NO_INDEX);++    /* No privileges gained through the exec, from a setuid program or file+     * capabilities a sandbox-paths entry makes reachable, as upstream's+     * builder gains none unless allow-new-privileges is set+     * (allowNewPrivileges in globals.hh and setupSeccomp in+     * local-derivation-goal.cc at 2.24.9, local-settings.hh and+     * linux-derivation-builder.cc at 2.36.0). */+    if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0)+        status_fail("no-new-privs", errno, NO_INDEX);++    /* No core dumps (runChild in LDG).  Upstream also raises the hard limit+     * to infinity, which an unprivileged process may not; the hard limit is+     * left as it is. */+    if (getrlimit(RLIMIT_CORE, &core) == 0) {+        core.rlim_cur = 0;+        setrlimit(RLIMIT_CORE, &core);+    }++    sigprocmask(SIG_SETMASK, &context->original_mask, NULL);+    execve(context->argv[0], context->argv, plan->environment);+    status_fail("exec", errno, NO_INDEX);+    return EXIT_FAILURE;+}++/* ------------------------------------------------------------------------+ * The helper: outside the new namespaces+ * ------------------------------------------------------------------------ */++/* Write a namespace's id map from outside it (startBuilder in LDG).  Answers+ * 0, or an errno value. */+static int write_proc_file(pid_t pid, const char *name, const char *contents)+{+    char path[64];+    int fd;+    size_t length = strlen(contents);+    ssize_t written;+    snprintf(path, sizeof path, "/proc/%ld/%s", (long)pid, name);+    fd = open(path, O_WRONLY | O_CLOEXEC);+    if (fd < 0)+        return errno;+    written = write(fd, contents, length);+    if (written < 0 || (size_t)written != length) {+        int error = written < 0 ? errno : EIO;+        close(fd);+        return error;+    }+    close(fd);+    return 0;+}++/* Report a failure of the helper's own, after the child is made.  The+ * child's PID namespace ends with it. */+static void fail_after_clone(pid_t child, const char *stage, int error)+{+    int wait_status;+    kill(child, SIGKILL);+    while (waitpid(child, &wait_status, 0) < 0 && errno == EINTR)+        ;+    status_fail(stage, error, (long)child);+}++/* Wait for the builder, killing it on a terminating signal or when the+ * lifeline closes.  Answers 0 with how it ended in *WAIT_STATUS, or the+ * errno of a wait that failed, which ends the build: the builder is+ * killed, and how it ended cannot be known.  The kernel ends the builder's+ * PID namespace with the builder, PID 1 there, so once it is reaped no+ * process of the build is left. */+static int wait_for_builder(pid_t child, int signals_fd, int lifeline_fd, int *wait_status)+{+    for (;;) {+        struct pollfd watched[2];+        pid_t reaped;+        watched[0].fd = signals_fd;+        watched[0].events = POLLIN;+        watched[0].revents = 0;+        watched[1].fd = lifeline_fd;+        watched[1].events = POLLIN;+        watched[1].revents = 0;+        if (poll(watched, 2, -1) < 0) {+            if (errno == EINTR)+                continue;+            /* With nothing left to watch, the builder is ended and reaped. */+            kill(child, SIGKILL);+            return posix_reap(child, wait_status);+        }+        if (watched[1].revents != 0) {+            char discard[64];+            ssize_t got = read(lifeline_fd, discard, sizeof discard);+            if (got <= 0 && !(got < 0 && errno == EINTR)) {+                kill(child, SIGKILL);+                close(lifeline_fd);+                lifeline_fd = -1;+            }+        }+        if (watched[0].revents & POLLIN) {+            struct signalfd_siginfo info;+            ssize_t got = read(signals_fd, &info, sizeof info);+            if (got == (ssize_t)sizeof info && info.ssi_signo != SIGCHLD)+                kill(child, SIGKILL);+        }+        reaped = waitpid(child, wait_status, WNOHANG);+        if (reaped == child)+            return 0;+        if (reaped < 0 && errno != EINTR) {+            int error = errno;+            kill(child, SIGKILL);+            return error;+        }+    }+}++int backend_run(const struct plan *plan, char **argv)+{+    struct child_context context;+    int lifeline_fd;+    int signals_fd;+    int null_fd;+    int sync_pipe[2];+    int error;+    int flags;+    pid_t child;+    char map[64];+    sigset_t handled;+    int wait_status = 0;++    /* Standard input, past the plan, is the lifeline; the builder reads+     * /dev/null (commonChildInit in child.cc). */+    lifeline_fd = fcntl(STDIN_FILENO, F_DUPFD_CLOEXEC, 3);+    null_fd = open("/dev/null", O_RDWR | O_CLOEXEC);+    if (lifeline_fd < 0 || null_fd < 0 || dup2(null_fd, STDIN_FILENO) < 0)+        status_fail("stdin", errno, NO_INDEX);+    close(null_fd);++    /* Supplementary groups cannot be dropped inside the new user namespace+     * (startBuilder in LDG). */+    if (setgroups(0, NULL) < 0) {+        if (errno != EPERM || plan->require_drop_groups)+            status_fail("setgroups", errno, NO_INDEX);+    }++    if (pipe2(sync_pipe, O_CLOEXEC) < 0)+        status_fail("sync", errno, NO_INDEX);++    /* The signals the helper answers are blocked from before the builder+     * exists, and read through a descriptor once it does, so none is lost+     * and none interrupts the setup; the builder unblocks them before it+     * execs. */+    sigemptyset(&handled);+    sigaddset(&handled, SIGTERM);+    sigaddset(&handled, SIGINT);+    sigaddset(&handled, SIGHUP);+    sigaddset(&handled, SIGCHLD);+    if (sigprocmask(SIG_BLOCK, &handled, &context.original_mask) < 0)+        status_fail("signals", errno, NO_INDEX);++    context.plan = plan;+    context.argv = argv;+    context.sync_read = sync_pipe[0];+    context.sync_write = sync_pipe[1];++    /* No CLONE_PARENT, so the builder stays this process's child and its+     * exit is this process's to relay (startProcess in processes.cc, and+     * LocalDerivationGoal::startBuilder in local-derivation-goal.cc at+     * 2.24.9, ChrootLinuxDerivationBuilder::startChild in+     * linux-derivation-builder.cc at 2.36.0). */+    flags = CLONE_NEWUSER | CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWIPC | CLONE_NEWUTS | SIGCHLD;+    if (plan->private_network)+        flags |= CLONE_NEWNET;+    child = raw_clone(flags);+    if (child < 0)+        status_fail("clone", errno, NO_INDEX);+    if (child == 0)+        _exit(child_main(&context));+    close(sync_pipe[0]);++    signals_fd = signalfd(-1, &handled, SFD_CLOEXEC);+    if (signals_fd < 0)+        fail_after_clone(child, "signals", errno);++    /* The sandbox's ids map to the host ids the plan names: a build user's,+     * which only root may map to, or the invoking user's (startBuilder in+     * LDG). */+    snprintf(map, sizeof map, "%lu %lu 1", plan->sandbox_uid, plan->host_uid);+    if ((error = write_proc_file(child, "uid_map", map)) != 0)+        fail_after_clone(child, "uid-map", error);+    if ((error = write_proc_file(child, "setgroups", "deny")) != 0)+        fail_after_clone(child, "setgroups-deny", error);+    snprintf(map, sizeof map, "%lu %lu 1", plan->sandbox_gid, plan->host_gid);+    if ((error = write_proc_file(child, "gid_map", map)) != 0)+        fail_after_clone(child, "gid-map", error);++    {+        char release = RELEASE_BYTE;+        ssize_t written;+        do {+            written = write(sync_pipe[1], &release, 1);+        } while (written < 0 && errno == EINTR);+        if (written != 1)+            fail_after_clone(child, "release", written < 0 ? errno : EIO);+    }+    close(sync_pipe[1]);+    posix_close_status();++    error = wait_for_builder(child, signals_fd, lifeline_fd, &wait_status);+    close(signals_fd);+    if (error != 0) {+        /* The status pipe is closed, so the reason goes to the build log,+         * in upstream's words for a wait that fails (Pid::wait in+         * processes.cc). */+        fprintf(stderr, "nova-nix-sandbox: cannot get exit status of PID %ld: %s\n", (long)child, strerror(error));+        return EXIT_FAILURE;+    }+    return posix_relay(wait_status);+}++/* ------------------------------------------------------------------------+ * The probe+ * ------------------------------------------------------------------------ */++/* Compare a sysctl's contents, its trailing newlines and spaces trimmed as+ * upstream trims them (userNamespacesSupported in namespaces.cc at 2.24.9,+ * linux-namespaces.cc at 2.36.0), with EXPECTED: 1 when they match, 0 when+ * they do not, and -1 when the file cannot be read. */+static int sysctl_is(const char *path, const char *expected)+{+    char contents[32];+    ssize_t length;+    int fd = open(path, O_RDONLY | O_CLOEXEC);+    if (fd < 0)+        return -1;+    length = read(fd, contents, sizeof contents - 1);+    close(fd);+    if (length < 0)+        return -1;+    while (length > 0 && (contents[length - 1] == '\n' || contents[length - 1] == ' '))+        length--;+    contents[length] = '\0';+    return strcmp(contents, expected) == 0;+}++static int probe_exit(void)+{+    return EXIT_SUCCESS;+}++static int probe_mounts(void)+{+    /* So the remount below does not touch the parent's /proc. */+    if (mount(NULL, "/", NULL, MS_PRIVATE | MS_REC, NULL) < 0)+        return PROBE_PRIVATE_FAILED;+    if (mount("none", "/proc", "proc", 0, NULL) < 0)+        return PROBE_PROC_FAILED;+    return EXIT_SUCCESS;+}++/* Clone a child into the namespaces and wait for it.  Answers the child's+ * exit status, or -1 with errno set when it could not be made. */+static int probe_child(int (*entry)(void), int flags)+{+    int wait_status;+    pid_t child = raw_clone(flags | SIGCHLD);+    if (child < 0)+        return -1;+    if (child == 0)+        _exit(entry());+    while (waitpid(child, &wait_status, 0) < 0)+        if (errno != EINTR)+            return -1;+    return WIFEXITED(wait_status) ? WEXITSTATUS(wait_status) : EXIT_FAILURE;+}++/* The namespace checks.  Answers the stage of the check that failed and+ * its errno, or NULL when none did. */+static const char *probe_namespaces(int *error)+{+    int outcome = probe_child(probe_exit, CLONE_NEWUSER);+    *error = 0;+    if (outcome != 0) {+        *error = outcome < 0 ? errno : 0;+        return "userns";+    }+    outcome = probe_child(probe_mounts, CLONE_NEWNS | CLONE_NEWPID | CLONE_NEWUSER);+    if (outcome < 0) {+        *error = errno;+        return "mountns";+    }+    if (outcome != 0) {+        /* Ubuntu's AppArmor lets an unprivileged process make a user+         * namespace but denies it capabilities there, so the mounts fail;+         * naming the restriction says what to change. */+        if (sysctl_is("/proc/sys/kernel/apparmor_restrict_unprivileged_userns", "1") == 1)+            return "apparmor";+        return outcome == PROBE_PROC_FAILED ? "proc-remount" : "mountns";+    }+    return NULL;+}++const char *backend_probe(int *error)+{+    if ((*error = posix_reset_sigchld()) != 0)+        return "sigchld";+    if (!path_exists("/proc/self/ns/user"))+        return "userns-missing";+    if (sysctl_is("/proc/sys/user/max_user_namespaces", "0") != 0)+        return "userns-max";+    if (sysctl_is("/proc/sys/kernel/unprivileged_userns_clone", "0") == 1)+        return "userns-clone";+    return probe_namespaces(error);+}
+ sandbox/mountinfo.c view
@@ -0,0 +1,93 @@+/*+ * The mountinfo reader: mountinfo.h says what it reads.+ */++#include "mountinfo.h"++#include <string.h>++/* The field a line's mount point is, counting from one. */+#define MOUNT_POINT_FIELD 5++/* The digits of one of the kernel's octal escapes. */+#define ESCAPE_DIGITS 3++static int is_octal(char byte)+{+    return byte >= '0' && byte <= '7';+}++/* Undo the escapes in the LENGTH bytes at FIELD, writing the first+ * CAPACITY bytes of the result to OUT.  Answers the length of the whole+ * result.  A backslash that does not begin an escape stays as it is, and+ * an escape past 0377 keeps its low eight bits, as the kernel writes+ * none. */+static size_t unescape(const char *field, size_t length, char *out, size_t capacity)+{+    size_t read = 0;+    size_t produced = 0;+    while (read < length) {+        char byte = field[read];+        if (byte == '\\' && length - read > ESCAPE_DIGITS && is_octal(field[read + 1]) && is_octal(field[read + 2])+            && is_octal(field[read + 3])) {+            int value = (field[read + 1] - '0') * 64 + (field[read + 2] - '0') * 8 + (field[read + 3] - '0');+            byte = (char)(unsigned char)(value & 0xff);+            read += ESCAPE_DIGITS + 1;+        } else {+            read++;+        }+        if (produced < capacity)+            out[produced] = byte;+        produced++;+    }+    return produced;+}++/* Whether the LENGTH bytes at POINT are DIR or a path beneath it. */+static int within(const char *point, size_t length, const char *dir, size_t dir_length)+{+    if (length < dir_length || memcmp(point, dir, dir_length) != 0)+        return 0;+    return length == dir_length || point[dir_length] == '/';+}++enum mountinfo_read mountinfo_next_within(struct mountinfo_cursor *cursor, const char *dir, size_t dir_length,+                                          char *point, size_t capacity, size_t *point_length)+{+    while (cursor->next < cursor->end) {+        const char *line = cursor->next;+        const char *line_end = memchr(line, '\n', (size_t)(cursor->end - line));+        const char *field = line;+        const char *field_end;+        int number;+        size_t length;++        if (line_end == NULL)+            line_end = cursor->end;+        cursor->next = line_end < cursor->end ? line_end + 1 : cursor->end;++        for (number = 1; number < MOUNT_POINT_FIELD && field != NULL; number++) {+            const char *space = memchr(field, ' ', (size_t)(line_end - field));+            field = space == NULL ? NULL : space + 1;+        }+        if (field == NULL)+            continue;+        field_end = memchr(field, ' ', (size_t)(line_end - field));+        if (field_end == NULL)+            field_end = line_end;++        length = unescape(field, (size_t)(field_end - field), point, capacity);+        if (length > capacity) {+            /* Too long to hold, which matters only for a point beneath+             * DIR, or one whose first bytes cannot say. */+            if (capacity <= dir_length || within(point, capacity, dir, dir_length))+                return MOUNTINFO_TOO_LONG;+            continue;+        }+        if (within(point, length, dir, dir_length)) {+            *point_length = length;+            return MOUNTINFO_FOUND;+        }+    }+    return MOUNTINFO_END;+}
+ sandbox/mountinfo.h view
@@ -0,0 +1,37 @@+/*+ * The mount points at or beneath a directory, read from the text of+ * /proc/self/mountinfo without IO: the fifth field of each line, its+ * fields split at single spaces, with the kernel's three-digit octal+ * escapes undone (a space, a tab, a newline and a backslash in a path).+ * Nix.Builder.Sandbox.Spawn's mountPointsWithin reads the text the same+ * way, which the test suite checks.  Portable C, so the test suite links+ * it too.+ */++#ifndef NOVA_NIX_SANDBOX_MOUNTINFO_H+#define NOVA_NIX_SANDBOX_MOUNTINFO_H++#include <stddef.h>++struct mountinfo_cursor {+    const char *next;+    const char *end;+};++/* What looking for the next mount point came to. */+enum mountinfo_read {+    MOUNTINFO_FOUND,+    MOUNTINFO_END,+    /* A mount point at DIR or beneath it, or one whose first bytes cannot+     * say, longer than the space given for it. */+    MOUNTINFO_TOO_LONG+};++/* Find the next mount point at DIR or beneath it, DIR being DIR_LENGTH+ * bytes, and write it, unescaped, to the CAPACITY bytes at POINT, with its+ * length in *POINT_LENGTH.  The point is bytes, not a C string: an escape+ * can make a NUL. */+enum mountinfo_read mountinfo_next_within(struct mountinfo_cursor *cursor, const char *dir, size_t dir_length,+                                          char *point, size_t capacity, size_t *point_length);++#endif
+ sandbox/nova-nix-sandbox.c view
@@ -0,0 +1,178 @@+/*+ * nova-nix-sandbox: runs one nova-nix builder in the sandbox its plan+ * describes.  This file is the program as every OS runs it; the backend+ * for the OS it is built for (backend.h) makes the sandbox.  nova-nix+ * runs every sandboxed build through this program, spawning it as it+ * spawns a builder, with an empty environment, so the dynamic loader+ * reads no variable the derivation set.+ *+ *   nova-nix-sandbox run PROGRAM [ARG...]+ *     Reads the plan from standard input, sets the sandbox up and runs+ *     PROGRAM there with ARGs and the environment the plan holds.+ *     Standard output is the status channel and standard error the build+ *     log.  On Linux and Windows the builder writes its standard output+ *     and standard error to the log itself; on macOS it writes both to a+ *     pipe of the helper's, which the helper copies into the log+ *     (darwin.c).  A step that fails writes one record,+ *     "STAGE ERRNO INDEX\n", on the status channel, its ERRNO a Win32+ *     error code for a Windows step (backend.h), and the process exits.+ *     A builder that starts leaves the channel empty, but on macOS for a+ *     failure to watch the build log, and the process exits as the+ *     builder did, or fails with the reason in the build log where it+ *     cannot see the build out (backend_run in backend.h).+ *     Standard input stays open after the plan as a lifeline: when+ *     nova-nix closes it, by ending or dying, the builder is killed.+ *+ *   nova-nix-sandbox probe+ *     Checks that this system lets the backend make the sandbox.  Exits 0+ *     when it does, or writes one record naming the check that failed and+ *     exits 1.+ *+ * The plan is a version line, a line holding the length of the rest, then+ * the tokens plan.h describes, which plan.c parses; a plan for another+ * backend than the one linked is refused as one that cannot be read.  Its+ * format and the stage names are shared with Nix.Builder.Sandbox, which+ * writes the one and reads the other.+ */++#include <errno.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#include "backend.h"+#include "plan.h"++/* The largest plan read, so a runaway writer cannot exhaust memory. */+#define PLAN_MAX_BYTES ((size_t)64 * 1024 * 1024)++/* The longest line of the plan's header, its length line included. */+#define PLAN_HEADER_LINE_MAX 64++/* ------------------------------------------------------------------------+ * Records+ * ------------------------------------------------------------------------ */++void status_report(const char *stage, int error, long index)+{+    char record[128];+    int length = snprintf(record, sizeof record, "%s %d %ld\n", stage, error, index);+    if (length > 0 && (size_t)length < sizeof record)+        backend_write_status(record, (size_t)length);+}++void status_fail(const char *stage, int error, long index)+{+    status_report(stage, error, index);+    _Exit(EXIT_FAILURE);+}++/* ------------------------------------------------------------------------+ * The plan+ * ------------------------------------------------------------------------ */++/* Read one header line, a byte at a time so nothing past it is taken from+ * the pipe.  Answers 0, or an errno value. */+static int read_header_line(char *line, size_t capacity)+{+    size_t length = 0;+    for (;;) {+        char byte;+        int error = backend_read_input(&byte, 1);+        if (error != 0)+            return error;+        if (length + 1 >= capacity)+            return EINVAL;+        line[length++] = byte;+        if (byte == '\n') {+            line[length] = '\0';+            return 0;+        }+    }+}++/* Read the plan: the version line, the length line, then that many bytes+ * of tokens, leaving the pipe open after them.  Answers 0, or an errno+ * value. */+static int read_plan_bytes(char **bytes_out, size_t *length_out)+{+    char line[PLAN_HEADER_LINE_MAX];+    char *rest = NULL;+    unsigned long long length;+    char *bytes;+    int error = read_header_line(line, sizeof line);+    if (error != 0)+        return error;+    if (strcmp(line, PLAN_VERSION_LINE) != 0)+        return EINVAL;+    error = read_header_line(line, sizeof line);+    if (error != 0)+        return error;+    if (line[0] < '0' || line[0] > '9')+        return EINVAL;+    errno = 0;+    length = strtoull(line, &rest, 10);+    if (errno != 0 || rest == NULL || strcmp(rest, "\n") != 0)+        return EINVAL;+    if (length > PLAN_MAX_BYTES)+        return E2BIG;+    bytes = malloc(length > 0 ? (size_t)length : 1);+    if (bytes == NULL)+        return ENOMEM;+    error = backend_read_input(bytes, (size_t)length);+    if (error != 0) {+        free(bytes);+        return error;+    }+    *bytes_out = bytes;+    *length_out = (size_t)length;+    return 0;+}++/* ------------------------------------------------------------------------+ * The commands+ * ------------------------------------------------------------------------ */++static int run(char **argv)+{+    struct plan plan;+    char *plan_bytes = NULL;+    size_t plan_length = 0;+    int error;+    int status;++    if (backend_prepare_run() != 0)+        return EXIT_FAILURE;+    error = read_plan_bytes(&plan_bytes, &plan_length);+    if (error == 0)+        error = plan_parse(plan_bytes, plan_length, &plan);+    if (error == 0 && plan.backend != backend_plan)+        error = EINVAL;+    if (error != 0)+        status_fail("plan", error, NO_INDEX);+    status = backend_run(&plan, argv);+    plan_release(&plan);+    free(plan_bytes);+    return status;+}++static int probe(void)+{+    int error = 0;+    const char *failed = backend_probe(&error);+    if (failed != NULL) {+        status_report(failed, error, NO_INDEX);+        return EXIT_FAILURE;+    }+    return EXIT_SUCCESS;+}++int main(int argc, char **argv)+{+    if (argc >= 3 && strcmp(argv[1], "run") == 0)+        return run(argv + 2);+    if (argc == 2 && strcmp(argv[1], "probe") == 0)+        return probe();+    fprintf(stderr, "usage: %s run PROGRAM [ARG...] | %s probe\n", argv[0], argv[0]);+    return EXIT_FAILURE;+}
+ sandbox/plan.c view
@@ -0,0 +1,398 @@+/*+ * The sandbox helper's plan parser: plan.h says what a plan holds.+ */++#include "plan.h"++#include <errno.h>+#include <limits.h>+#include <stdlib.h>+#include <string.h>++/* A cursor over a plan's tokens. */+struct tokens {+    char *next;+    char *end;+};++/* What reading a token came to. */+enum token_read {+    TOKEN_FOUND,+    TOKEN_END,+    TOKEN_MALFORMED+};++/* Read the next token: its decimal length, with no leading zero, a colon,+ * that many bytes holding no NUL, then a NUL. */+static enum token_read read_token(struct tokens *cursor, char **token)+{+    char *at = cursor->next;+    size_t remaining = (size_t)(cursor->end - at);+    size_t length = 0;+    size_t digits = 0;+    char *bytes;++    if (at >= cursor->end)+        return TOKEN_END;+    while (at < cursor->end && *at >= '0' && *at <= '9') {+        size_t digit = (size_t)(*at - '0');+        if (length > remaining / 10)+            return TOKEN_MALFORMED;+        length = length * 10 + digit;+        if (length > remaining)+            return TOKEN_MALFORMED;+        digits++;+        at++;+    }+    if (digits == 0 || (digits > 1 && cursor->next[0] == '0'))+        return TOKEN_MALFORMED;+    if (at >= cursor->end || *at != ':')+        return TOKEN_MALFORMED;+    bytes = at + 1;+    if ((size_t)(cursor->end - bytes) <= length || bytes[length] != '\0')+        return TOKEN_MALFORMED;+    if (memchr(bytes, '\0', length) != NULL)+        return TOKEN_MALFORMED;+    cursor->next = bytes + length + 1;+    *token = bytes;+    return TOKEN_FOUND;+}++/* Read KEY's token, then its value's. */+static int read_value(struct tokens *cursor, const char *key, char **value)+{+    char *found;+    return read_token(cursor, &found) == TOKEN_FOUND && strcmp(found, key) == 0+        && read_token(cursor, value) == TOKEN_FOUND;+}++/* Pass over COUNT tokens. */+static int skip_tokens(struct tokens *cursor, size_t count)+{+    char *token;+    size_t i;+    for (i = 0; i < count; i++)+        if (read_token(cursor, &token) != TOKEN_FOUND)+            return 0;+    return 1;+}++/* A decimal that fits an int: a uid_t or gid_t, or the value of a handle+ * a process inherits, whose significant bits on Windows are its low 32+ * and which a process's handle table keeps small. */+static int parse_id(const char *text, unsigned long *out)+{+    char *rest = NULL;+    unsigned long value;+    if (*text < '0' || *text > '9')+        return 0;+    errno = 0;+    value = strtoul(text, &rest, 10);+    if (errno != 0 || rest == NULL || *rest != '\0' || value > (unsigned long)INT_MAX)+        return 0;+    *out = value;+    return 1;+}++/* A decimal size in bytes. */+static int parse_size(const char *text, unsigned long long *out)+{+    char *rest = NULL;+    unsigned long long value;+    if (*text < '0' || *text > '9')+        return 0;+    errno = 0;+    value = strtoull(text, &rest, 10);+    if (errno != 0 || rest == NULL || *rest != '\0')+        return 0;+    *out = value;+    return 1;+}++/* Whether TEXT is an absolute Windows path: a drive letter, a colon and a+ * separator, or two backslashes, which start a UNC path or a device's. */+static int windows_absolute(const char *text)+{+    int letter = (text[0] >= 'A' && text[0] <= 'Z') || (text[0] >= 'a' && text[0] <= 'z');+    if (letter && text[1] == ':' && (text[2] == '\\' || text[2] == '/'))+        return 1;+    return text[0] == '\\' && text[1] == '\\';+}++/* A bind's flags: "-" for none, else letters r (read-only), o (optional)+ * and c (resolve the source's symlinks first). */+static int parse_bind_flags(const char *text, struct bind *bind)+{+    const char *letter;+    if (strcmp(text, "-") == 0)+        return 1;+    if (*text == '\0')+        return 0;+    for (letter = text; *letter != '\0'; letter++) {+        switch (*letter) {+        case 'r': bind->read_only = 1; break;+        case 'o': bind->optional = 1; break;+        case 'c': bind->canonical = 1; break;+        default: return 0;+        }+    }+    return 1;+}++/* Choose between two words a value may be: 1 for YES, 0 for NO. */+static int parse_choice(const char *value, const char *yes, const char *no, int *out)+{+    if (strcmp(value, yes) == 0)+        *out = 1;+    else if (strcmp(value, no) == 0)+        *out = 0;+    else+        return 0;+    return 1;+}++static int parse_linux_singletons(struct tokens *cursor, struct plan *plan)+{+    char *value;+    if (!read_value(cursor, "root", &value) || value[0] != '/')+        return 0;+    plan->root = value;+    if (!read_value(cursor, "build-dir", &value) || value[0] != '/')+        return 0;+    plan->build_dir = value;+    if (!read_value(cursor, "dev-shm-size", &value))+        return 0;+    plan->dev_shm_size = value;+    if (!read_value(cursor, "sandbox-uid", &value) || !parse_id(value, &plan->sandbox_uid))+        return 0;+    if (!read_value(cursor, "sandbox-gid", &value) || !parse_id(value, &plan->sandbox_gid))+        return 0;+    if (!read_value(cursor, "host-uid", &value) || !parse_id(value, &plan->host_uid))+        return 0;+    if (!read_value(cursor, "host-gid", &value) || !parse_id(value, &plan->host_gid))+        return 0;+    if (!read_value(cursor, "network", &value) || !parse_choice(value, "private", "host", &plan->private_network))+        return 0;+    return read_value(cursor, "drop-groups", &value) && parse_choice(value, "require", "tolerate", &plan->require_drop_groups);+}++/* What a Darwin plan gives for each build user id when the builder runs+ * as the invoking user. */+#define NO_BUILD_USER "-"++static int parse_darwin_singletons(struct tokens *cursor, struct plan *plan)+{+    char *value;+    char *uid;+    char *gid;+    if (!read_value(cursor, "build-dir", &value) || value[0] != '/')+        return 0;+    plan->build_dir = value;+    if (!read_value(cursor, "profile", &value))+        return 0;+    plan->profile = value;+    if (!read_value(cursor, "build-uid", &uid) || !read_value(cursor, "build-gid", &gid))+        return 0;+    if (strcmp(uid, NO_BUILD_USER) == 0 && strcmp(gid, NO_BUILD_USER) == 0)+        return 1;+    plan->as_build_user = 1;+    return parse_id(uid, &plan->build_uid) && parse_id(gid, &plan->build_gid);+}++/* A SID's string form, which starts S-1-, as the helper takes it: never+ * one of the two-letter aliases a security descriptor's text may use. */+#define SID_PREFIX "S-1-"++static int parse_windows_singletons(struct tokens *cursor, struct plan *plan)+{+    char *value;+    if (!read_value(cursor, "build-dir", &value) || !windows_absolute(value))+        return 0;+    plan->build_dir = value;+    if (!read_value(cursor, "token", &value) || !parse_id(value, &plan->token_handle) || plan->token_handle == 0)+        return 0;+    if (!read_value(cursor, "slot-sid", &value) || strncmp(value, SID_PREFIX, sizeof SID_PREFIX - 1) != 0)+        return 0;+    plan->slot_sid = value;+    return read_value(cursor, "memory-cap", &value) && parse_size(value, &plan->memory_cap) && plan->memory_cap > 0;+}++static int parse_singletons(struct tokens *cursor, struct plan *plan)+{+    char *value;+    if (!read_value(cursor, "backend", &value))+        return 0;+    if (strcmp(value, "linux") == 0) {+        plan->backend = PLAN_LINUX;+        return parse_linux_singletons(cursor, plan);+    }+    if (strcmp(value, "darwin") == 0) {+        plan->backend = PLAN_DARWIN;+        return parse_darwin_singletons(cursor, plan);+    }+    if (strcmp(value, "windows") == 0) {+        plan->backend = PLAN_WINDOWS;+        return parse_windows_singletons(cursor, plan);+    }+    return 0;+}++/* The entries a backend's plan repeats before the environment: binds on+ * Linux, each three tokens after its key, and params on Darwin, each two.+ * A Windows plan repeats none, which a NULL key says. */+struct section {+    const char *key;+    size_t width;+};++static struct section backend_section(enum plan_backend backend)+{+    struct section section;+    section.key = NULL;+    section.width = 0;+    switch (backend) {+    case PLAN_LINUX:+        section.key = "bind";+        section.width = 3;+        break;+    case PLAN_DARWIN:+        section.key = "param";+        section.width = 2;+        break;+    case PLAN_WINDOWS:+        break;+    }+    return section;+}++/* Count the backend's entries and the environment's after the singletons,+ * checking that nothing but those follows. */+static int count_sections(struct tokens cursor, struct section section, size_t *repeated, size_t *entries)+{+    char *key = NULL;+    enum token_read read = read_token(&cursor, &key);+    *repeated = 0;+    *entries = 0;+    while (read == TOKEN_FOUND && section.key != NULL && strcmp(key, section.key) == 0) {+        if (!skip_tokens(&cursor, section.width))+            return 0;+        (*repeated)++;+        read = read_token(&cursor, &key);+    }+    while (read == TOKEN_FOUND && strcmp(key, "env") == 0) {+        if (!skip_tokens(&cursor, 1))+            return 0;+        (*entries)++;+        read = read_token(&cursor, &key);+    }+    return read == TOKEN_END;+}++static int parse_bind(struct tokens *cursor, struct bind *bind)+{+    char *target;+    char *source;+    char *flags;+    if (!read_value(cursor, "bind", &target) || read_token(cursor, &source) != TOKEN_FOUND+        || read_token(cursor, &flags) != TOKEN_FOUND)+        return 0;+    if (target[0] != '/' || source[0] != '/')+        return 0;+    bind->target = target;+    bind->source = source;+    return parse_bind_flags(flags, bind);+}++/* A param's name, which is not empty, and its value. */+static int parse_parameter(struct tokens *cursor, const char **name, const char **value)+{+    char *read_name;+    char *read_value_token;+    if (!read_value(cursor, "param", &read_name) || read_token(cursor, &read_value_token) != TOKEN_FOUND+        || read_name[0] == '\0')+        return 0;+    *name = read_name;+    *value = read_value_token;+    return 1;+}++/* Allocate what the counted entries are parsed into. */+static int allocate_sections(struct plan *plan, size_t repeated, size_t entries)+{+    if (plan->backend == PLAN_LINUX && repeated > 0) {+        plan->binds = calloc(repeated, sizeof *plan->binds);+        if (plan->binds == NULL)+            return 0;+    }+    if (plan->backend == PLAN_DARWIN) {+        plan->parameters = calloc(2 * repeated + 1, sizeof *plan->parameters);+        if (plan->parameters == NULL)+            return 0;+    }+    plan->environment = calloc(entries + 1, sizeof *plan->environment);+    return plan->environment != NULL;+}++/* Parse the REPEATED entries count_sections found, which a Windows plan+ * has none of. */+static int parse_repeated(struct tokens *cursor, struct plan *plan, size_t repeated)+{+    size_t i;+    for (i = 0; i < repeated; i++) {+        if (plan->backend == PLAN_LINUX) {+            if (!parse_bind(cursor, &plan->binds[i]))+                return 0;+            plan->bind_count++;+        } else {+            if (!parse_parameter(cursor, &plan->parameters[2 * i], &plan->parameters[2 * i + 1]))+                return 0;+            plan->parameter_count++;+        }+    }+    return 1;+}++int plan_parse(char *bytes, size_t length, struct plan *plan)+{+    struct tokens cursor;+    size_t repeated;+    size_t entries;+    size_t i;++    memset(plan, 0, sizeof *plan);+    cursor.next = bytes;+    cursor.end = bytes + length;+    if (!parse_singletons(&cursor, plan) || !count_sections(cursor, backend_section(plan->backend), &repeated, &entries))+        return EINVAL;++    if (!allocate_sections(plan, repeated, entries)) {+        plan_release(plan);+        return ENOMEM;+    }+    if (!parse_repeated(&cursor, plan, repeated)) {+        plan_release(plan);+        return EINVAL;+    }+    for (i = 0; i < entries; i++) {+        char *entry;+        if (!read_value(&cursor, "env", &entry)) {+            plan_release(plan);+            return EINVAL;+        }+        plan->environment[plan->environment_count++] = entry;+    }+    return 0;+}++void plan_release(struct plan *plan)+{+    free(plan->binds);+    free(plan->parameters);+    free(plan->environment);+    plan->binds = NULL;+    plan->bind_count = 0;+    plan->parameters = NULL;+    plan->parameter_count = 0;+    plan->environment = NULL;+    plan->environment_count = 0;+}
+ sandbox/plan.h view
@@ -0,0 +1,101 @@+/*+ * The plan nova-nix-sandbox carries out, as Nix.Builder.Sandbox renders it,+ * parsed without IO.  It is portable C, so the test suite links it too and+ * checks it against the plans the renderer writes.+ *+ * After the header the plan holds tokens, each its length in decimal, a+ * colon, that many bytes and a NUL, so a token's bytes cannot end it early+ * or start another.  The tokens are keys and their values in one fixed+ * shape.  The first is backend, naming the backend the plan is for; the+ * rest are that backend's:+ *+ *   linux: root, build-dir, dev-shm-size, sandbox-uid, sandbox-gid,+ *   host-uid, host-gid, network and drop-groups, each once and in that+ *   order, then any number of binds;+ *+ *   darwin: build-dir, profile, build-uid and build-gid, each once and in+ *   that order, then any number of params, each a name and its value;+ *+ *   windows: build-dir, token, slot-sid and memory-cap, each once and in+ *   that order;+ *+ * then, for any of them, any number of environment entries.+ */++#ifndef NOVA_NIX_SANDBOX_PLAN_H+#define NOVA_NIX_SANDBOX_PLAN_H++#include <stddef.h>++/* The first line of every plan; a plan of another version is refused. */+#define PLAN_VERSION_LINE "nova-nix-sandbox-plan 5\n"++/* The backend a plan is for, named as the OS that backend runs on. */+enum plan_backend {+    PLAN_LINUX,+    PLAN_DARWIN,+    PLAN_WINDOWS+};++struct bind {+    const char *target;+    const char *source;+    int read_only;+    int optional;+    int canonical;+};++struct plan {+    enum plan_backend backend;+    const char *build_dir;++    /* Linux's.  The builder runs as SANDBOX_UID and SANDBOX_GID in its+     * user namespace, which map to HOST_UID and HOST_GID outside it: a+     * build user's ids, or the invoking user's. */+    const char *root;+    const char *dev_shm_size;+    unsigned long sandbox_uid;+    unsigned long sandbox_gid;+    unsigned long host_uid;+    unsigned long host_gid;+    int private_network;+    int require_drop_groups;+    struct bind *binds;+    size_t bind_count;++    /* Darwin's: the profile's text; the build user the builder runs as,+     * when AS_BUILD_USER is set, which a plan gives as "-" for both ids+     * otherwise; and the profile's parameters as+     * sandbox_init_with_parameters takes them, each name followed by its+     * value, the whole NULL-terminated. */+    const char *profile;+    int as_build_user;+    unsigned long build_uid;+    unsigned long build_gid;+    const char **parameters;+    size_t parameter_count;++    /* Windows's: the value of the inherited handle to the primary token+     * of the build slot's account, that account's SID in its S-1-...+     * form, and the most memory, in bytes, each process of the build may+     * commit. */+    unsigned long token_handle;+    const char *slot_sid;+    unsigned long long memory_cap;++    /* NAME=VALUE entries, NULL-terminated, for the builder's execve, or+     * on Windows its environment block. */+    char **environment;+    size_t environment_count;+};++/* Parse the LENGTH bytes of tokens at BYTES into PLAN, whose strings point+ * into BYTES.  Answers 0, ENOMEM, or EINVAL for tokens of any other shape,+ * a token holding a NUL among them, since each is used as a C string.  On+ * failure nothing is left to release. */+int plan_parse(char *bytes, size_t length, struct plan *plan);++/* Release what a parsed plan holds, apart from the bytes it points into. */+void plan_release(struct plan *plan);++#endif
+ sandbox/posix.c view
@@ -0,0 +1,187 @@+/*+ * The channels, start and end of a run that nova-nix-sandbox's POSIX+ * backends share (posix.h).+ */++#define _POSIX_C_SOURCE 200809L++#include <dirent.h>+#include <errno.h>+#include <fcntl.h>+#include <limits.h>+#include <signal.h>+#include <stdlib.h>+#include <string.h>+#include <sys/resource.h>+#include <sys/types.h>+#include <sys/wait.h>+#include <unistd.h>++#include "backend.h"+#include "posix.h"++/* The most descriptors one pass over a descriptor listing closes; a+ * listing that names more is read again, since closing changes it. */+#define CLOSE_BATCH 1024++/* How far up descriptors are closed where neither a listing nor a finite+ * limit says where they end. */+#define CLOSE_FALLBACK_TOP 1024++/* The status channel's descriptor, or the descriptor posix_report_to+ * names in its place.  It is the process's, so it lives at file scope:+ * every failure of the setup is reported on it, a child's before its exec+ * included. */+static int status_fd = STDOUT_FILENO;++int posix_status_fd(void)+{+    return status_fd;+}++void posix_close_status(void)+{+    close(status_fd);+    status_fd = -1;+}++void posix_report_to(int fd)+{+    status_fd = fd;+}++void backend_write_status(const char *bytes, size_t length)+{+    while (length > 0) {+        ssize_t written = write(status_fd, bytes, length);+        if (written < 0) {+            if (errno == EINTR)+                continue;+            return;+        }+        bytes += written;+        length -= (size_t)written;+    }+}++int backend_read_input(char *bytes, size_t length)+{+    size_t got = 0;+    while (got < length) {+        ssize_t read_now = read(STDIN_FILENO, bytes + got, length - got);+        if (read_now < 0) {+            if (errno == EINTR)+                continue;+            return errno;+        }+        if (read_now == 0)+            return EPIPE;+        got += (size_t)read_now;+    }+    return 0;+}++int backend_prepare_run(void)+{+    int error;+    /* The status pipe moves to a descriptor the builder's exec closes, and+     * standard output becomes the log, as upstream's child gets standard+     * error on both (commonChildInit in child.cc). */+    int moved = fcntl(STDOUT_FILENO, F_DUPFD_CLOEXEC, 3);+    if (moved < 0)+        return -1;+    status_fd = moved;+    if (dup2(STDERR_FILENO, STDOUT_FILENO) < 0)+        status_fail("stdout", errno, NO_INDEX);++    if ((error = posix_reset_sigchld()) != 0)+        status_fail("sigchld", error, NO_INDEX);+    return 0;+}++int posix_reset_sigchld(void)+{+    struct sigaction action;+    memset(&action, 0, sizeof action);+    sigemptyset(&action.sa_mask);+    action.sa_handler = SIG_DFL;+    return sigaction(SIGCHLD, &action, NULL) < 0 ? errno : 0;+}++int posix_reap(pid_t child, int *wait_status)+{+    for (;;) {+        if (waitpid(child, wait_status, 0) == child)+            return 0;+        if (errno != EINTR)+            return errno;+    }+}++int posix_relay(int wait_status)+{+    if (WIFEXITED(wait_status))+        return WEXITSTATUS(wait_status);+    if (WIFSIGNALED(wait_status)) {+        int signal_number = WTERMSIG(wait_status);+        sigset_t just_this;+        struct rlimit core;+        if (getrlimit(RLIMIT_CORE, &core) == 0) {+            core.rlim_cur = 0;+            setrlimit(RLIMIT_CORE, &core);+        }+        signal(signal_number, SIG_DFL);+        sigemptyset(&just_this);+        sigaddset(&just_this, signal_number);+        sigprocmask(SIG_UNBLOCK, &just_this, NULL);+        raise(signal_number);+        return 128 + signal_number;+    }+    return EXIT_FAILURE;+}++void posix_close_descriptors(const char *listing, int keep)+{+    DIR *dir = opendir(listing);+    if (dir != NULL) {+        int own = dirfd(dir);+        int fds[CLOSE_BATCH];+        size_t count = 0;+        size_t i;+        struct dirent *entry;+        int more = 1;+        while (more) {+            count = 0;+            more = 0;+            rewinddir(dir);+            while ((entry = readdir(dir)) != NULL) {+                long fd;+                char *rest = NULL;+                if (entry->d_name[0] < '0' || entry->d_name[0] > '9')+                    continue;+                fd = strtol(entry->d_name, &rest, 10);+                if (rest == NULL || *rest != '\0' || fd < 3 || fd == own || fd == keep)+                    continue;+                if (count == sizeof fds / sizeof fds[0]) {+                    more = 1;+                    break;+                }+                fds[count++] = (int)fd;+            }+            for (i = 0; i < count; i++)+                close(fds[i]);+        }+        closedir(dir);+        return;+    }+    {+        struct rlimit limit;+        int fd;+        int top = CLOSE_FALLBACK_TOP;+        if (getrlimit(RLIMIT_NOFILE, &limit) == 0 && limit.rlim_cur != RLIM_INFINITY && limit.rlim_cur < (rlim_t)INT_MAX)+            top = (int)limit.rlim_cur;+        for (fd = 3; fd < top; fd++)+            if (fd != keep)+                close(fd);+    }+}
+ sandbox/posix.h view
@@ -0,0 +1,50 @@+/*+ * What nova-nix-sandbox's POSIX backends (linux.c, darwin.c) share.  This+ * file's C gives backend.h's channels as a POSIX system has them: the plan+ * on standard input, and the status channel on the pipe the helper gets+ * as standard output, which a run moves to a descriptor the builder's+ * exec closes.  It also starts a run and ends one: it reaps the builder,+ * and ends the helper as the builder ended.+ */++#ifndef NOVA_NIX_SANDBOX_POSIX_H+#define NOVA_NIX_SANDBOX_POSIX_H++#include <sys/types.h>++/* The status channel's descriptor: standard output until+ * backend_prepare_run moves it, the descriptor posix_report_to names once+ * it has been called, and -1 once posix_close_status has closed it. */+int posix_status_fd(void);++/* Close the status channel, once the builder is released and nothing is+ * left to report on it. */+void posix_close_status(void);++/* Report on FD from now on, in place of the status channel: a child that+ * reports its failures to the process that made it, which relays them. */+void posix_report_to(int fd);++/* Put SIGCHLD back to its default, as upstream's initNix does (in+ * shared.cc at 2.24.9): a SIGCHLD ignored where this program was+ * started would have the kernel reap the builder unasked, leaving nothing+ * to wait for.  Answers 0, or an errno value. */+int posix_reset_sigchld(void);++/* Reap CHILD, blocking.  Answers 0, or the errno of a wait that failed. */+int posix_reap(pid_t child, int *wait_status);++/* End this process as the builder ended: by the signal that killed it,+ * with no core dump of this process's own, or by answering the status+ * this process is to exit with: the builder's exit status, 128 plus the+ * signal should raising it return, or EXIT_FAILURE for any other end. */+int posix_relay(int wait_status);++/* Close every descriptor from 3 up but KEEP, as upstream's child closes+ * them before it executes the builder.  LISTING is a directory naming each+ * open descriptor; where it cannot be read, every descriptor below the+ * process's limit is closed, or below CLOSE_FALLBACK_TOP where getrlimit+ * gives no finite limit an int holds. */+void posix_close_descriptors(const char *listing, int keep);++#endif
+ sandbox/windows.c view
@@ -0,0 +1,870 @@+/*+ * nova-nix-sandbox's Windows backend (backend.h): runs the builder as the+ * build slot's account whose primary token the helper is given, on the+ * window station Windows makes for that token's logon, attached to a+ * pseudoconsole the helper owns, in a job that caps each process's memory+ * and lets none of them break away, and ends every process running as the+ * slot's account before the builder starts and after the build.+ *+ * The helper runs as the service that logs each slot on, which hands it+ * the slot's token as a handle it inherits and names in the plan, with the+ * slot's SID.  The token must be a primary token whose user is that SID;+ * the helper keeps it from every process it starts but the builder, which+ * runs as it.  Starting a process under another logon's token takes+ * SeAssignPrimaryTokenPrivilege and SeIncreaseQuotaPrivilege, which the+ * helper enables in its own token first, and which the probe checks it can+ * enable.+ *+ * The builder starts with an empty window station and desktop name, which+ * puts it on the window station Windows makes for its token's logon+ * session and that station's default desktop: a station of that logon+ * alone.  The helper makes none, since a service running as a virtual+ * account may not name a window station, and the service's own is not the+ * slot's to open.+ *+ * CreateProcessAsUserW opens the builder's image with the access of the+ * thread that calls it, not of the token it starts the builder with.  So+ * the helper calls it impersonating the slot, and reverts after, so that+ * a derivation cannot have the slot run an image only the service may+ * read.  The impersonation takes no privilege, as the slot's token comes+ * from a logon the service made with the slot's password, in the logon+ * session the helper runs in.+ *+ * A process started with a console of its own, as libiberty starts gcc's+ * subprograms when gcc has none, fails to start under a build account's+ * token, where one sharing a console its parent owns starts.  So the+ * builder is attached to a pseudoconsole the helper owns, which what it+ * starts shares.  The pseudoconsole's output is the console's screen as+ * terminal sequences, not the build log, so a thread of the helper's+ * reads it and drops it, which also keeps the console from waiting on a+ * full pipe.  The build log is the builder's standard output and+ * standard error, the helper's own standard error, as on Linux, and its+ * standard input is NUL; those two handles are all it inherits.+ *+ * The builder starts suspended, is assigned to the build's job and is+ * then resumed, so no process it starts runs outside the job.  The job+ * kills its processes when its last handle closes, the helper's, so the+ * build ends with the helper however the helper ends.  It caps the memory+ * each process may commit, ends a process at an unhandled exception at+ * once, and grants no breakaway, so no process in it can break away from+ * it.  It nests in any job the helper is in, the process library's among+ * them.  The helper waits until the job holds no process, as nova-nix+ * waits for an unsandboxed build's job, and exits with the builder's exit+ * code.  Standard input, past the plan, is the lifeline: a thread of the+ * helper's reads it, and when it ends terminates the job.+ *+ * A build can still have a process started for it outside the job, as+ * WMI's Win32_Process.Create starts one, which then outlives the build,+ * holding what it copied from the build, the build log among them.  So,+ * as upstream ends every process of its build user before a build and+ * after it, the helper ends every process running as the slot's account+ * before the builder starts and once the job holds no process.  A listing+ * of the processes misses one started after it, so the helper lists them+ * again until a listing finds none of the slot's still running.  It can+ * end a process whose DACL grants it, as the DACL of every process the+ * slot starts does that keeps the default DACL the service gives the+ * slot's token; a process given a security descriptor that grants it+ * nothing is beyond the reach of any account without+ * SeDebugPrivilege, the helper's included.  A sweep that fails before the+ * build is reported on the status channel; one that fails after it is+ * said in the build log and fails the build, as a process of the build+ * may be left running.+ *+ * The status channel is the helper's standard output, which no process+ * of the build inherits, so a builder that starts leaves it empty.  A+ * record's error is the Win32 error code of the call that failed, but+ * for the plan's, which the core reports with errno values; a failure+ * once the builder runs goes to the build log.+ *+ * The plan's text is UTF-8, which the helper turns to UTF-16.  The+ * builder's command line is the helper's own past its program's name and+ * the run verb, as the process that started the helper wrote it, and+ * names the program as CreateProcess reads a command line: the C+ * runtime's argv holds the command line in the system's code page, which+ * loses what that cannot hold, and rebuilding a command line from it+ * could quote it differently.+ */++/* Windows 10 1809, the first with pseudoconsoles, which the headers+ * declare from that version on. */+#define _WIN32_WINNT 0x0A00+#define NTDDI_VERSION 0x0A000006++#include <errno.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <wchar.h>++#include <windows.h>+#include <sddl.h>+#include <tlhelp32.h>++#include "backend.h"+#include "plan.h"++/* The exit code the build's processes are ended with when the lifeline+ * ends or the helper cannot watch them: the process library's, which+ * ends an unsandboxed build's job with it. */+#define ENDED_BUILD_EXIT_CODE 1++/* The pseudoconsole's size, and the room its output pipe has. */+#define CONSOLE_COLUMNS 80+#define CONSOLE_ROWS 25+#define CONSOLE_PIPE_BYTES 65536++/* How much of the pseudoconsole's output, and of the lifeline, one read+ * takes. */+#define DRAIN_READ_BYTES 4096++/* The attributes the builder starts with: its handle list and its+ * pseudoconsole. */+#define START_ATTRIBUTE_COUNT 2++/* How long a sweep of the slot's processes may take, in all, to end those+ * it finds and come to a listing that finds none still running. */+#define SWEEP_WAIT_SECONDS 10++/* The Win32 error a sweep that outlasts its wait is reported with. */+#define SWEEP_TIMEOUT_ERROR ERROR_TIMEOUT++/* The memory cap is a SIZE_T in the job's limits; on every Windows this+ * backend builds for, a SIZE_T holds any cap a plan names. */+typedef char memory_cap_fits_size[sizeof(SIZE_T) >= sizeof(unsigned long long) ? 1 : -1];++/* The backend this file is. */+const enum plan_backend backend_plan = PLAN_WINDOWS;++/* The privileges a process needs to start a process under another+ * logon's token (CreateProcessAsUserW).  winnt.h spells their names+ * narrow without UNICODE, so they are spelled here. */+static const WCHAR *const start_privileges[] = {L"SeAssignPrimaryTokenPrivilege", L"SeIncreaseQuotaPrivilege"};++/* A token's user: a TOKEN_USER and the SID it points at, which follows it+ * in the buffer and is at most SECURITY_MAX_SID_SIZE bytes, so one call+ * fills it.  The union aligns the buffer for the structure. */+union token_user {+    TOKEN_USER user;+    BYTE bytes[sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE];+};++/* The pseudoconsole and its pipes: the write end of its input, the read+ * end of its output, and the thread that reads that output and drops+ * it. */+struct console {+    HPCON console;+    HANDLE input;+    HANDLE output;+    HANDLE drain;+};++/* How a sweep of the slot's processes ended. */+enum sweep_outcome {+    /* A listing found none of the slot's processes still running. */+    SWEEP_DONE,+    /* The processes could not be listed. */+    SWEEP_UNLISTED,+    /* A process running as the slot's account could not be ended. */+    SWEEP_UNENDED,+    /* Listings still found the slot's processes running+     * SWEEP_WAIT_SECONDS after the sweep began. */+    SWEEP_LINGERING+};++/* What a sweep came to: how it ended, the Win32 error behind+ * SWEEP_UNLISTED or SWEEP_UNENDED, and the process the latter concerns,+ * its ID and its program's name. */+struct sweep {+    enum sweep_outcome outcome;+    DWORD error;+    DWORD pid;+    WCHAR program[MAX_PATH];+};++/* The window station and desktop name the builder starts with: an empty+ * one, which starts it on the window station of its token's logon, on that+ * station's default desktop.  CreateProcessAsUserW takes the name as a+ * string it may write to. */+static WCHAR logon_desktop[] = L"";+/* ------------------------------------------------------------------------+ * The channels+ * ------------------------------------------------------------------------ */++void backend_write_status(const char *bytes, size_t length)+{+    HANDLE status = GetStdHandle(STD_OUTPUT_HANDLE);+    while (length > 0) {+        DWORD written = 0;+        DWORD chunk = length > MAXDWORD ? MAXDWORD : (DWORD)length;+        if (!WriteFile(status, bytes, chunk, &written, NULL) || written == 0)+            return;+        bytes += written;+        length -= written;+    }+}++int backend_read_input(char *bytes, size_t length)+{+    HANDLE input = GetStdHandle(STD_INPUT_HANDLE);+    size_t got = 0;+    while (got < length) {+        DWORD read_now = 0;+        DWORD want = length - got > MAXDWORD ? MAXDWORD : (DWORD)(length - got);+        if (!ReadFile(input, bytes + got, want, &read_now, NULL))+            return GetLastError() == ERROR_BROKEN_PIPE ? EPIPE : EIO;+        if (read_now == 0)+            return EPIPE;+        got += read_now;+    }+    return 0;+}++/* The status channel is standard output as the helper was given it: the+ * builder inherits only the handles its start lists, so nothing it+ * writes reaches the channel, and nothing needs moving first. */+int backend_prepare_run(void)+{+    HANDLE status = GetStdHandle(STD_OUTPUT_HANDLE);+    return status == NULL || status == INVALID_HANDLE_VALUE ? -1 : 0;+}++/* ------------------------------------------------------------------------+ * Text+ * ------------------------------------------------------------------------ */++/* TEXT, UTF-8, as UTF-16 in a buffer of its own.  A failure fails the+ * process at STAGE, for INDEX. */+static WCHAR *widened(const char *text, const char *stage, long index)+{+    int length = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, text, -1, NULL, 0);+    WCHAR *wide;+    if (length <= 0)+        status_fail(stage, (int)GetLastError(), index);+    wide = malloc((size_t)length * sizeof *wide);+    if (wide == NULL)+        status_fail(stage, ERROR_NOT_ENOUGH_MEMORY, index);+    if (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, text, -1, wide, length) != length)+        status_fail(stage, (int)GetLastError(), index);+    return wide;+}++/* The plan's environment as the block CreateProcessAsUserW takes with+ * CREATE_UNICODE_ENVIRONMENT: each entry in UTF-16 and NUL-terminated, in+ * the plan's order, then a NUL that ends the block, which with no entry+ * is two NULs.  An empty entry would end the block early, so it fails, as+ * one that is not UTF-8 does. */+static WCHAR *environment_block(const struct plan *plan)+{+    size_t total = 0;+    size_t i;+    WCHAR *block;+    WCHAR *at;+    for (i = 0; i < plan->environment_count; i++) {+        int length;+        if (plan->environment[i][0] == '\0')+            status_fail("environment", ERROR_INVALID_PARAMETER, (long)i);+        length = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, plan->environment[i], -1, NULL, 0);+        if (length <= 0)+            status_fail("environment", (int)GetLastError(), (long)i);+        total += (size_t)length;+    }+    /* Zeroed, so the NULs that end the block are there already. */+    block = calloc(total + 2, sizeof *block);+    if (block == NULL)+        status_fail("environment", ERROR_NOT_ENOUGH_MEMORY, NO_INDEX);+    at = block;+    for (i = 0; i < plan->environment_count; i++) {+        int length = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, plan->environment[i], -1, at,+                                         (int)(total - (size_t)(at - block)));+        if (length <= 0)+            status_fail("environment", (int)GetLastError(), (long)i);+        at += length;+    }+    return block;+}++/* Pass over one argument of a command line, and the spaces and tabs after+ * it, as the C runtime reads a program's name: each quote opens or closes+ * a quoted part, and a space or tab outside one ends the argument.  The+ * run verb, which the core read as "run", holds no backslash, so it ends+ * where this says too. */+static const WCHAR *past_argument(const WCHAR *at)+{+    int quoted = 0;+    while (*at != L'\0' && (quoted || (*at != L' ' && *at != L'\t'))) {+        if (*at == L'"')+            quoted = !quoted;+        at++;+    }+    while (*at == L' ' || *at == L'\t')+        at++;+    return at;+}++/* The builder's command line, in a buffer of its own, which+ * CreateProcessAsUserW may write to: the helper's own past its program's+ * name and the run verb, as given. */+static WCHAR *builder_command_line(void)+{+    const WCHAR *tail = past_argument(past_argument(GetCommandLineW()));+    size_t length = wcslen(tail) + 1;+    WCHAR *copy = malloc(length * sizeof *copy);+    if (copy == NULL)+        status_fail("command-line", ERROR_NOT_ENOUGH_MEMORY, NO_INDEX);+    memcpy(copy, tail, length * sizeof *copy);+    return copy;+}++/* ------------------------------------------------------------------------+ * The tokens+ * ------------------------------------------------------------------------ */++/* Enable each of the start privileges in TOKEN.  Answers 0, or the+ * Win32 error of the step that failed: ERROR_NOT_ALL_ASSIGNED for a+ * privilege the token does not hold. */+static DWORD enable_privileges(HANDLE token)+{+    size_t i;+    for (i = 0; i < sizeof start_privileges / sizeof start_privileges[0]; i++) {+        TOKEN_PRIVILEGES wanted;+        DWORD outcome;+        wanted.PrivilegeCount = 1;+        wanted.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;+        if (!LookupPrivilegeValueW(NULL, start_privileges[i], &wanted.Privileges[0].Luid))+            return GetLastError();+        if (!AdjustTokenPrivileges(token, FALSE, &wanted, 0, NULL, NULL))+            return GetLastError();+        /* The call succeeds for a privilege the token does not hold, and+         * says so in the thread's last error alone. */+        outcome = GetLastError();+        if (outcome != ERROR_SUCCESS)+            return outcome;+    }+    return 0;+}++/* Enable each of the start privileges in this process's own token, the+ * service's.  Answers as enable_privileges does. */+static DWORD enable_own_privileges(void)+{+    HANDLE own = NULL;+    DWORD error;+    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &own))+        return GetLastError();+    error = enable_privileges(own);+    CloseHandle(own);+    return error;+}++/* The slot's token the plan names, kept from every process this one+ * starts but the builder, once it is known to be a primary token whose+ * user is the plan's slot, whose SID goes in *SLOT for the caller to+ * release with LocalFree. */+static HANDLE slot_token(const struct plan *plan, PSID *slot)+{+    HANDLE token = (HANDLE)(ULONG_PTR)plan->token_handle;+    union token_user user;+    TOKEN_TYPE type;+    DWORD size = 0;+    WCHAR *slot_text;+    if (!SetHandleInformation(token, HANDLE_FLAG_INHERIT, 0))+        status_fail("token", (int)GetLastError(), NO_INDEX);+    if (!GetTokenInformation(token, TokenType, &type, sizeof type, &size))+        status_fail("token", (int)GetLastError(), NO_INDEX);+    if (type != TokenPrimary)+        status_fail("token", ERROR_BAD_TOKEN_TYPE, NO_INDEX);+    if (!GetTokenInformation(token, TokenUser, &user, sizeof user, &size))+        status_fail("token", (int)GetLastError(), NO_INDEX);+    slot_text = widened(plan->slot_sid, "slot-sid", NO_INDEX);+    if (!ConvertStringSidToSidW(slot_text, slot))+        status_fail("slot-sid", (int)GetLastError(), NO_INDEX);+    free(slot_text);+    if (!EqualSid(user.user.User.Sid, *slot))+        status_fail("token-user", 0, NO_INDEX);+    return token;+}++/* ------------------------------------------------------------------------+ * The slot's processes+ * ------------------------------------------------------------------------ */++/* Whether PROCESS, open to query, runs as SLOT.  A process whose token+ * this one may not query counts as another account's: it is not one this+ * process could end. */+static int runs_as(HANDLE process, PSID slot)+{+    HANDLE token = NULL;+    union token_user user;+    DWORD size = 0;+    int same;+    if (!OpenProcessToken(process, TOKEN_QUERY, &token))+        return 0;+    same = GetTokenInformation(token, TokenUser, &user, sizeof user, &size) && EqualSid(user.user.User.Sid, slot);+    CloseHandle(token);+    return same;+}++/* Whether the process PROCESS, open to query, has not ended.  One whose+ * exit code cannot be read counts as running, and so does one that ended+ * with STILL_ACTIVE's value as its code, which the sweep cannot tell from+ * one running: it ends the build that left it a failure. */+static int still_running(HANDLE process)+{+    DWORD code = 0;+    return !GetExitCodeProcess(process, &code) || code == STILL_ACTIVE;+}++/* Record in *SWEEP that the process ENTRY names, which runs as the slot's+ * account, could not be ended, for the Win32 error ERROR. */+static void unended(struct sweep *sweep, const PROCESSENTRY32W *entry, DWORD error)+{+    sweep->outcome = SWEEP_UNENDED;+    sweep->error = error;+    sweep->pid = entry->th32ProcessID;+    memcpy(sweep->program, entry->szExeFile, sizeof sweep->program);+}++/* End the process ENTRY names, which runs as the slot's account and which+ * QUERY, the caller's handle to it, keeps from giving its ID to another,+ * and wait until DEADLINE for it to end where this process may wait on it.+ * Answers 1 when it was running, 0 when it had already ended, or -1 with+ * *SWEEP saying why it could not be ended or did not end in time.  The+ * rights to end a process and to wait on it are asked for apart, as a+ * process's DACL can grant the one and not the other; one this process+ * may end but not wait on is counted running, for the next listing to+ * find ended. */+static int end_process(HANDLE query, const PROCESSENTRY32W *entry, ULONGLONG deadline, struct sweep *sweep)+{+    HANDLE ending;+    HANDLE waitable;+    if (!still_running(query))+        return 0;+    ending = OpenProcess(PROCESS_TERMINATE, FALSE, entry->th32ProcessID);+    if (ending == NULL) {+        unended(sweep, entry, GetLastError());+        return -1;+    }+    /* With a handle that may end the process, TerminateProcess refuses+     * only one that has ended or is ending. */+    if (!TerminateProcess(ending, ENDED_BUILD_EXIT_CODE) && GetLastError() != ERROR_ACCESS_DENIED) {+        unended(sweep, entry, GetLastError());+        CloseHandle(ending);+        return -1;+    }+    CloseHandle(ending);+    waitable = OpenProcess(SYNCHRONIZE, FALSE, entry->th32ProcessID);+    if (waitable != NULL) {+        ULONGLONG now = GetTickCount64();+        DWORD waited = WaitForSingleObject(waitable, now < deadline ? (DWORD)(deadline - now) : 0);+        DWORD error = GetLastError();+        CloseHandle(waitable);+        if (waited == WAIT_TIMEOUT) {+            sweep->outcome = SWEEP_LINGERING;+            return -1;+        }+        if (waited != WAIT_OBJECT_0) {+            unended(sweep, entry, error);+            return -1;+        }+    }+    return 1;+}++/* List the processes and end each that runs as SLOT, waiting until+ * DEADLINE for each to end.  Answers how many were running, or -1 with+ * *SWEEP saying why the pass failed. */+static long sweep_pass(PSID slot, ULONGLONG deadline, struct sweep *sweep)+{+    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);+    PROCESSENTRY32W entry;+    long running = 0;+    BOOL listed;+    if (snapshot == INVALID_HANDLE_VALUE) {+        sweep->outcome = SWEEP_UNLISTED;+        sweep->error = GetLastError();+        return -1;+    }+    entry.dwSize = sizeof entry;+    for (listed = Process32FirstW(snapshot, &entry); listed; listed = Process32NextW(snapshot, &entry)) {+        HANDLE process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, entry.th32ProcessID);+        int ended;+        if (process == NULL)+            continue;+        ended = runs_as(process, slot) ? end_process(process, &entry, deadline, sweep) : 0;+        CloseHandle(process);+        if (ended < 0) {+            CloseHandle(snapshot);+            return -1;+        }+        running += ended;+    }+    if (GetLastError() != ERROR_NO_MORE_FILES) {+        sweep->outcome = SWEEP_UNLISTED;+        sweep->error = GetLastError();+        CloseHandle(snapshot);+        return -1;+    }+    CloseHandle(snapshot);+    return running;+}++/* End every process running as SLOT: list them and end each, until a+ * listing finds none still running, for up to SWEEP_WAIT_SECONDS. */+static struct sweep sweep_slot(PSID slot)+{+    struct sweep sweep;+    ULONGLONG deadline = GetTickCount64() + SWEEP_WAIT_SECONDS * 1000ULL;+    memset(&sweep, 0, sizeof sweep);+    sweep.outcome = SWEEP_DONE;+    for (;;) {+        long running = sweep_pass(slot, deadline, &sweep);+        if (running <= 0)+            return sweep;+        if (GetTickCount64() >= deadline) {+            sweep.outcome = SWEEP_LINGERING;+            return sweep;+        }+    }+}++/* End every process running as SLOT before the builder starts, reporting+ * a sweep that fails on the status channel. */+static void sweep_before_build(PSID slot)+{+    struct sweep sweep = sweep_slot(slot);+    if (sweep.outcome == SWEEP_UNLISTED)+        status_fail("sweep", (int)sweep.error, NO_INDEX);+    if (sweep.outcome == SWEEP_UNENDED)+        status_fail("sweep", (int)sweep.error, (long)sweep.pid);+    if (sweep.outcome == SWEEP_LINGERING)+        status_fail("sweep", SWEEP_TIMEOUT_ERROR, NO_INDEX);+}++/* End every process running as SLOT once the build has ended.  Answers+ * whether none is left, saying in the build log why one may be. */+static int sweep_after_build(PSID slot)+{+    struct sweep sweep = sweep_slot(slot);+    switch (sweep.outcome) {+    case SWEEP_DONE:+        return 1;+    case SWEEP_UNLISTED:+        fprintf(stderr, "nova-nix-sandbox: cannot list the processes running as the build's account: Win32 error %lu\n",+                (unsigned long)sweep.error);+        return 0;+    case SWEEP_UNENDED:+        fprintf(stderr,+                "nova-nix-sandbox: cannot end process %lu (%ls), which runs as the build's account: Win32 error %lu\n",+                (unsigned long)sweep.pid, sweep.program, (unsigned long)sweep.error);+        return 0;+    case SWEEP_LINGERING:+        fprintf(stderr, "nova-nix-sandbox: processes were still running as the build's account %d seconds after it ended\n",+                SWEEP_WAIT_SECONDS);+        return 0;+    }+    return 0;+}++/* ------------------------------------------------------------------------+ * The pseudoconsole+ * ------------------------------------------------------------------------ */++/* Read the pseudoconsole's output, whose read end PARAMETER is, and drop+ * it, until the pseudoconsole closes its end, which fails the read: a+ * pipe's read answers no bytes, and succeeds, for a write of none. */+static DWORD WINAPI drain_console(LPVOID parameter)+{+    char discard[DRAIN_READ_BYTES];+    DWORD got = 0;+    while (ReadFile(parameter, discard, sizeof discard, &got, NULL))+        ;+    return 0;+}++/* The Win32 error an HRESULT carries, or ERROR_GEN_FAILURE for one that+ * carries none. */+static int hresult_error(HRESULT result)+{+    return HRESULT_FACILITY(result) == FACILITY_WIN32 ? HRESULT_CODE(result) : ERROR_GEN_FAILURE;+}++/* Make the pseudoconsole and start the thread that drains it.  Its pipes'+ * ends here are not inheritable, so no process of the build holds one. */+static void make_console(struct console *made)+{+    HANDLE input_read = NULL;+    HANDLE output_write = NULL;+    COORD size;+    HRESULT result;+    if (!CreatePipe(&input_read, &made->input, NULL, 0)+        || !CreatePipe(&made->output, &output_write, NULL, CONSOLE_PIPE_BYTES))+        status_fail("console", (int)GetLastError(), NO_INDEX);+    size.X = CONSOLE_COLUMNS;+    size.Y = CONSOLE_ROWS;+    result = CreatePseudoConsole(size, input_read, output_write, 0, &made->console);+    /* The pseudoconsole holds copies of the ends it was given. */+    CloseHandle(input_read);+    CloseHandle(output_write);+    if (FAILED(result))+        status_fail("console", hresult_error(result), NO_INDEX);+    made->drain = CreateThread(NULL, 0, drain_console, made->output, 0, NULL);+    if (made->drain == NULL)+        status_fail("console", (int)GetLastError(), NO_INDEX);+}++/* Close the pseudoconsole once the build has ended.  Before Windows 11+ * 24H2, ClosePseudoConsole waits until its last output has been read,+ * which the drain goes on reading, until the pseudoconsole closes its end+ * of the pipe.  The read end closes only then: closing a handle another+ * thread is reading would not end that read. */+static void close_console(struct console *made)+{+    CloseHandle(made->input);+    ClosePseudoConsole(made->console);+    WaitForSingleObject(made->drain, INFINITE);+    CloseHandle(made->drain);+    CloseHandle(made->output);+}++/* ------------------------------------------------------------------------+ * The job+ * ------------------------------------------------------------------------ */++/* Make the build's job and the completion port it reports on. */+static void make_job(const struct plan *plan, HANDLE *job, HANDLE *port)+{+    JOBOBJECT_ASSOCIATE_COMPLETION_PORT association;+    JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits;+    *job = CreateJobObjectW(NULL, NULL);+    if (*job == NULL)+        status_fail("job", (int)GetLastError(), NO_INDEX);+    *port = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);+    if (*port == NULL)+        status_fail("job", (int)GetLastError(), NO_INDEX);+    memset(&association, 0, sizeof association);+    association.CompletionKey = *job;+    association.CompletionPort = *port;+    memset(&limits, 0, sizeof limits);+    limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE+                                              | JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION+                                              | JOB_OBJECT_LIMIT_PROCESS_MEMORY;+    limits.ProcessMemoryLimit = (SIZE_T)plan->memory_cap;+    if (!SetInformationJobObject(*job, JobObjectAssociateCompletionPortInformation, &association, sizeof association)+        || !SetInformationJobObject(*job, JobObjectExtendedLimitInformation, &limits, sizeof limits))+        status_fail("job", (int)GetLastError(), NO_INDEX);+}++/* Read the lifeline, standard input past the plan, until it ends, then+ * end the build, whose job PARAMETER is.  A read that answers no bytes is+ * its end, as at the end of a file.  The job's handle stays open until+ * this process ends, since this thread may end the job until then. */+static DWORD WINAPI watch_lifeline(LPVOID parameter)+{+    HANDLE input = GetStdHandle(STD_INPUT_HANDLE);+    char discard[DRAIN_READ_BYTES];+    DWORD got = 0;+    while (ReadFile(input, discard, sizeof discard, &got, NULL) && got > 0)+        ;+    TerminateJobObject(parameter, ENDED_BUILD_EXIT_CODE);+    return 0;+}++/* Wait until the job holds no process, saying in the build log of each+ * process the memory cap stopped that it did.  The port's messages wake+ * the wait, ACTIVE_PROCESS_ZERO among them, but the job's own count of+ * its processes says whether the build is over: a job a process of the+ * build makes nests in the build's, and its messages can reach the+ * build's port too.  Answers 0, or the Win32 error of a wait that+ * failed. */+static DWORD wait_for_build(HANDLE job, HANDLE port, const struct plan *plan)+{+    for (;;) {+        JOBOBJECT_BASIC_ACCOUNTING_INFORMATION accounting;+        DWORD message = 0;+        ULONG_PTR key = 0;+        LPOVERLAPPED detail = NULL;+        if (!GetQueuedCompletionStatus(port, &message, &key, &detail, INFINITE))+            return GetLastError();+        /* The message's detail is the process's ID. */+        if (key == (ULONG_PTR)job && message == JOB_OBJECT_MSG_PROCESS_MEMORY_LIMIT)+            fprintf(stderr, "nova-nix-sandbox: process %lu of the build reached its memory limit of %llu bytes\n",+                    (unsigned long)(ULONG_PTR)detail, plan->memory_cap);+        if (!QueryInformationJobObject(job, JobObjectBasicAccountingInformation, &accounting, sizeof accounting, NULL))+            return GetLastError();+        if (accounting.ActiveProcesses == 0)+            return 0;+    }+}++/* ------------------------------------------------------------------------+ * The run+ * ------------------------------------------------------------------------ */++/* The attributes the builder starts with: the handles it inherits, which+ * must stay where they are until the list is deleted, and the+ * pseudoconsole it attaches to. */+static LPPROC_THREAD_ATTRIBUTE_LIST start_attributes(HANDLE *inherited, size_t count, HPCON console)+{+    SIZE_T size = 0;+    LPPROC_THREAD_ATTRIBUTE_LIST list;+    /* Asked of no list, the call fails, answering the size a list takes. */+    InitializeProcThreadAttributeList(NULL, START_ATTRIBUTE_COUNT, 0, &size);+    list = malloc(size);+    if (list == NULL)+        status_fail("attributes", ERROR_NOT_ENOUGH_MEMORY, NO_INDEX);+    if (!InitializeProcThreadAttributeList(list, START_ATTRIBUTE_COUNT, 0, &size))+        status_fail("attributes", (int)GetLastError(), NO_INDEX);+    if (!UpdateProcThreadAttribute(list, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, inherited, count * sizeof *inherited,+                                   NULL, NULL)+        || !UpdateProcThreadAttribute(list, 0, PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, console, sizeof console, NULL,+                                      NULL))+        status_fail("attributes", (int)GetLastError(), NO_INDEX);+    return list;+}++/* An inheritable handle to NUL, the builder's standard input, and an+ * inheritable copy of the build log, this process's standard error, for+ * its standard output and error. */+static void builder_handles(HANDLE *nul, HANDLE *log)+{+    SECURITY_ATTRIBUTES inheritable;+    inheritable.nLength = sizeof inheritable;+    inheritable.lpSecurityDescriptor = NULL;+    inheritable.bInheritHandle = TRUE;+    *nul = CreateFileW(L"NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, &inheritable, OPEN_EXISTING, 0, NULL);+    if (*nul == INVALID_HANDLE_VALUE)+        status_fail("stdin", (int)GetLastError(), NO_INDEX);+    if (!DuplicateHandle(GetCurrentProcess(), GetStdHandle(STD_ERROR_HANDLE), GetCurrentProcess(), log, 0, TRUE,+                         DUPLICATE_SAME_ACCESS))+        status_fail("log", (int)GetLastError(), NO_INDEX);+}++/* Start the builder suspended, as SLOT's TOKEN, impersonating the slot+ * for the call so that the builder's image is opened with the slot's+ * access, and revert after it, on every path.  A start that fails, or a+ * revert that does, fails this process. */+static PROCESS_INFORMATION start_builder(HANDLE token, WCHAR *command, WCHAR *environment, const WCHAR *build_dir,+                                         STARTUPINFOEXW *startup)+{+    PROCESS_INFORMATION process;+    BOOL started;+    DWORD error;+    memset(&process, 0, sizeof process);+    if (!ImpersonateLoggedOnUser(token))+        status_fail("impersonate", (int)GetLastError(), NO_INDEX);+    started = CreateProcessAsUserW(token, NULL, command, NULL, NULL, TRUE,+                                   CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT | EXTENDED_STARTUPINFO_PRESENT,+                                   environment, build_dir, &startup->StartupInfo, &process);+    error = started ? 0 : GetLastError();+    if (!RevertToSelf()) {+        DWORD revert_error = GetLastError();+        if (started)+            TerminateProcess(process.hProcess, ENDED_BUILD_EXIT_CODE);+        status_fail("revert", (int)revert_error, NO_INDEX);+    }+    if (!started)+        status_fail("exec", (int)error, NO_INDEX);+    return process;+}++int backend_run(const struct plan *plan, char **argv)+{+    PSID slot = NULL;+    HANDLE token;+    struct console console;+    HANDLE job = NULL;+    HANDLE port = NULL;+    HANDLE inherited[2];+    WCHAR *environment;+    WCHAR *build_dir;+    WCHAR *command;+    LPPROC_THREAD_ATTRIBUTE_LIST attributes;+    STARTUPINFOEXW startup;+    PROCESS_INFORMATION process;+    HANDLE watcher;+    DWORD error;+    DWORD code = 0;+    int status;++    /* The builder's command line is read from this process's own, which+     * argv holds in the system's code page. */+    (void)argv;++    if ((error = enable_own_privileges()) != 0)+        status_fail("privileges", (int)error, NO_INDEX);+    token = slot_token(plan, &slot);+    sweep_before_build(slot);+    make_console(&console);+    make_job(plan, &job, &port);+    builder_handles(&inherited[0], &inherited[1]);+    environment = environment_block(plan);+    build_dir = widened(plan->build_dir, "build-dir", NO_INDEX);+    command = builder_command_line();+    attributes = start_attributes(inherited, sizeof inherited / sizeof inherited[0], console.console);++    memset(&startup, 0, sizeof startup);+    startup.StartupInfo.cb = sizeof startup;+    startup.StartupInfo.lpDesktop = logon_desktop;+    startup.StartupInfo.dwFlags = STARTF_USESTDHANDLES;+    startup.StartupInfo.hStdInput = inherited[0];+    startup.StartupInfo.hStdOutput = inherited[1];+    startup.StartupInfo.hStdError = inherited[1];+    startup.lpAttributeList = attributes;+    process = start_builder(token, command, environment, build_dir, &startup);+    if (!AssignProcessToJobObject(job, process.hProcess)) {+        error = GetLastError();+        TerminateProcess(process.hProcess, ENDED_BUILD_EXIT_CODE);+        status_fail("assign", (int)error, NO_INDEX);+    }+    /* From here a failure that ends this process ends the job's last+     * handle with it, and so the builder. */+    watcher = CreateThread(NULL, 0, watch_lifeline, job, 0, NULL);+    if (watcher == NULL)+        status_fail("lifeline", (int)GetLastError(), NO_INDEX);+    CloseHandle(watcher);+    if (ResumeThread(process.hThread) == (DWORD)-1)+        status_fail("resume", (int)GetLastError(), NO_INDEX);++    CloseHandle(process.hThread);+    CloseHandle(inherited[0]);+    CloseHandle(inherited[1]);+    CloseHandle(token);+    DeleteProcThreadAttributeList(attributes);+    free(attributes);+    free(command);+    free(build_dir);+    free(environment);++    error = wait_for_build(job, port, plan);+    CloseHandle(port);+    if (error != 0) {+        TerminateJobObject(job, ENDED_BUILD_EXIT_CODE);+        fprintf(stderr, "nova-nix-sandbox: cannot wait for the build's processes: Win32 error %lu\n",+                (unsigned long)error);+        status = EXIT_FAILURE;+    } else if (!GetExitCodeProcess(process.hProcess, &code)) {+        fprintf(stderr, "nova-nix-sandbox: cannot get exit status of process %lu: Win32 error %lu\n",+                (unsigned long)process.dwProcessId, (unsigned long)GetLastError());+        status = EXIT_FAILURE;+    } else {+        /* main's status reaches ExitProcess as these same 32 bits. */+        status = (int)code;+    }+    CloseHandle(process.hProcess);+    if (!sweep_after_build(slot))+        status = EXIT_FAILURE;+    close_console(&console);+    LocalFree(slot);+    return status;+}++/* ------------------------------------------------------------------------+ * The probe+ * ------------------------------------------------------------------------ */++const char *backend_probe(int *error)+{+    DWORD failed = enable_own_privileges();+    *error = (int)failed;+    return failed != 0 ? "privileges" : NULL;+}
src/Nix/Builder.hs view
@@ -1,1737 +1,3114 @@-{-# LANGUAGE ScopedTypeVariables #-}---- | Derivation builder - executes build recipes.------ == The build process------ When Nix needs to build a derivation (cache miss), it:------ 1. Creates a temp directory for the build--- 2. Sets up the environment: only store paths from @inputDrvs@ and---    @inputSrcs@ are visible.  PATH contains only the builder and---    specified dependencies.  No internet access (in sandboxed mode).--- 3. Runs the builder (usually @bash -e \/nix\/store\/...-stdenv\/setup@)--- 4. The @setup@ script sources the derivation's environment variables,---    then runs @genericBuild@ which calls @unpackPhase@, @patchPhase@,---    @configurePhase@, @buildPhase@, @installPhase@, @fixupPhase@, etc.--- 5. Builder writes output to @$out@ (the output store path)--- 6. Nix scans the output for references to other store paths--- 7. Output is moved to the store and registered------ == On Windows------ The key difference is process creation.  Upstream on Linux uses--- @fork\/exec@ with namespace isolation.  nova-nix spawns builders through--- "System.Process", which reaches @CreateProcess@ on Windows with no POSIX--- layer, and runs them without filesystem or network isolation.------ The builder's process tree runs inside a Win32 job object with--- kill-on-job-close ('Proc.use_process_jobs'), so an interrupt or a--- builder exit reaps grandchildren instead of orphaning them.  Filesystem--- and privilege isolation are still future work: a restricted token with a--- store-granting ACL (the security boundary), then AppContainer for more.------ We ship @bash.exe@ (from MSYS2) as the default builder on Windows.--- Same approach as Git for Windows.-module Nix.Builder-  ( -- * Build execution-    BuildResult (..),-    buildDerivation,-    buildWithDeps,-    substitutePaths,--    -- * Build configuration-    BuildConfig (..),-    defaultBuildConfig,--    -- * Pure pieces (exported for tests)-    AttrsDelivery (..),-    attrsDelivery,-    BuilderSpawn (..),-    buildPath,-    closureUnder,-    execWrapperConfig,-    execWrapperFor,-    spawnFor,-    ReferenceCycle (..),-    orderByReferences,-    rewriteEnv,-    rewritePlaceholders,-    scrubAmbient,-    unionEnvs,-    verifyFetchHash,-    fetchUrlsFromEnv,-    tryFetchUrlsWith,-  )-where--import Control.Exception (IOException, bracket, catch, catches, displayException, finally, onException, try)-import Control.Monad (filterM, foldM, unless, when)-import Control.Monad.Except (ExceptT (..), liftEither, runExceptT, throwError)-import Control.Monad.IO.Class (liftIO)-import Data.Bifunctor (first)-import qualified Data.ByteString as BS-import Data.Char (isAscii, isSpace, toLower, toUpper)-import Data.Foldable (for_)-import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef, writeIORef)-import Data.List (sort)-import Data.List.NonEmpty (NonEmpty (..))-import qualified Data.List.NonEmpty as NE-import Data.Map.Strict (Map)-import qualified Data.Map.Strict as Map-import Data.Maybe (catMaybes, fromMaybe, isJust, mapMaybe, maybeToList)-import Data.Set (Set)-import qualified Data.Set as Set-import Data.Text (Text)-import qualified Data.Text as T-import qualified Data.Text.Encoding as TE-import Data.Text.Encoding.Error (lenientDecode)-import qualified Data.Text.IO as TIO-import qualified Network.HTTP.Client as HTTP-import qualified Network.HTTP.Client.TLS as HTTPS-import qualified Network.HTTP.Types.Status as HTTP-import Nix.Builder.Log (openLogPipe, streamBuildLog)-import Nix.Builder.Unpack (UnpackLimits, builtinUnpackBuilder, defaultUnpackLimits, runBuiltinUnpack)-import Nix.DependencyGraph (TopoResult (..), buildDepGraph, topoSort)-import Nix.Derivation (Derivation (..), DerivationOutput (..), Platform, currentPlatform, extraPlatforms, fromATerm, platformToText)-import Nix.Derivation.StructuredAttrs (decodeStructuredAttrs, renderAttrsJson, renderAttrsShell, stringsAttr, structuredAttrsKey, withOutputPlaceholders)-import Nix.Hash (IncrementalHash, bytesToHexText, hashFinalizeBytes, hashInitWithAlgo, hashPlaceholder, hashUpdateChunk, hexToBytes, makeStorePath, rawHashWithAlgo, sha256Digest)-import Nix.Http (AttemptFailure (..), FetchRetryPolicy, attemptFailureMessage, catchSync, defaultFetchRetryPolicy, fetchStatusFailure, ioRetryEffects, retryTransient, transferFailureHandlers, withTransfer, withUserAgent)-import Nix.Realise (Fallback (..), FetchOutcome (..), RealiseEffects (..), Realised (..), SubstEffects (..), realise, realiseFailureMessage)-import Nix.Store (PathLock, PathRegistration, Store (..), acquirePathLock, isValid, placeInStore, queryReferences, registerPaths, releasePathLock, rewriteBytes, rewriteStoreHashes, scanReferences, volumeCaseHack)-import qualified Nix.Store.ExecBit as ExecBit-import Nix.Store.Path (BadStorePath, StoreDir (..), StorePath (spHash, spName), defaultStoreDir, defaultStoreDirText, parseStorePath, storePathToFilePath, storePathToText, unStoreDir)-import Nix.Substituter (CacheConfig, SubstResult (..), queryReferencesWith, trySubstituteWith)-import qualified NovaCache.Base32 as Nix32-import qualified NovaCache.NAR as NAR-import System.Directory (createDirectoryIfMissing, doesDirectoryExist, doesPathExist, removeDirectoryRecursive, removePathForcibly)-import qualified System.Environment-import System.Exit (ExitCode (..))-import System.FilePath (takeDirectory, takeFileName, (</>))-import qualified System.IO-import qualified System.Info-import qualified System.Process as Proc---- ------------------------------------------------------------------------------ Named constants--- ------------------------------------------------------------------------------- | Environment variable for the build top directory.-envNixBuildTop :: Text-envNixBuildTop = "NIX_BUILD_TOP"---- | The four temp-directory names, every one pointed at the build--- directory, matching upstream's single assignment of all four.  Tools--- disagree about which one they read (POSIX tools take @TMPDIR@, msys--- reads @TMPDIR@ and @TMP@, native Windows tools take @TMP@ then--- @TEMP@), and a scrubbed environment that repoints only one leaves--- the others to fall back to a directory the build cannot own - on--- Windows, GetTempPath bottoms out at the Windows directory itself.-envTmpDir, envTempDir, envTmp, envTemp :: Text-envTmpDir = "TMPDIR"-envTempDir = "TEMPDIR"-envTmp = "TMP"-envTemp = "TEMP"---- | Environment variable for the Nix store path.-envNixStore :: Text-envNixStore = "NIX_STORE"---- | Ambient variables a Windows builder may inherit, by uppercase-folded--- name.  SystemRoot is a hard execution requirement - the CLR's crypto--- provider fails to load without it (verified live on a clean Windows 11--- box), while plain Win32 binaries merely tolerate its absence - and--- SystemDrive and windir are the aliases some tools consult instead of it.-windowsAmbientAllowlist :: [Text]-windowsAmbientAllowlist = [systemRootKey, "SYSTEMDRIVE", "WINDIR"]---- | The folded name 'scrubAmbient' derives COMSPEC from.-systemRootKey :: Text-systemRootKey = "SYSTEMROOT"---- | The command interpreter variable, synthesized from SystemRoot rather--- than inherited: programs shelling out through the C runtime's--- @system()@ read it from the block.-envComspec :: Text-envComspec = "COMSPEC"---- | Executable-extension resolution, pinned instead of inherited so name--- resolution does not drift with host configuration.  cmd.exe's own--- built-in default when the variable is absent adds @.VBS;.JS;.WS;.MSC@;--- a build has no business resolving those implicitly.-envPathext, pathextValue :: Text-envPathext = "PATHEXT"-pathextValue = ".COM;.EXE;.BAT;.CMD"---- | Environment variable for PATH.-envPath :: Text-envPath = "PATH"---- | The magic builder string for the built-in URL fetcher.  A derivation with--- this builder is not executed as a process - the Builder downloads its @url@--- and verifies it against @outputHash@ (see 'runBuiltinFetchurl').--- Bytes, matching the 'drvBuilder' field it is compared against.-builtinFetchurlBuilder :: BS.ByteString-builtinFetchurlBuilder = "builtin:fetchurl"---- | Derivation environment keys read by @builtin:fetchurl@.-envUrl, envUrls, envOut :: Text-envUrl = "url"-envUrls = "urls"-envOut = "out"---- | HTTP success status code.-httpStatusOk :: Int-httpStatusOk = 200---- | Environment variable for the reproducible-builds.org build timestamp.-envSourceDateEpoch :: Text-envSourceDateEpoch = "SOURCE_DATE_EPOCH"---- | The derivation attribute naming ambient variables a fixed-output--- build may read, upstream's carve-out for fetchers that need proxies.-envImpureEnvVars :: Text-envImpureEnvVars = "impureEnvVars"---- | The variables naming a structured derivation's two attribute files.-envNixAttrsJsonFile, envNixAttrsShFile :: Text-envNixAttrsJsonFile = "NIX_ATTRS_JSON_FILE"-envNixAttrsShFile = "NIX_ATTRS_SH_FILE"---- | Where in the build directory a structured derivation's attributes--- land, under upstream's names.-attrsJsonFileName, attrsShellFileName :: FilePath-attrsJsonFileName = ".attrs.json"-attrsShellFileName = ".attrs.sh"---- | The attribute listing the attributes a derivation passes as files.-envPassAsFile :: Text-envPassAsFile = "passAsFile"---- | What upstream adds to an attribute's name to name the variable holding--- the path of its file, and what it puts before the hash of that name to--- name the file.-passedFileVarSuffix, passedFilePrefix :: Text-passedFileVarSuffix = "Path"-passedFilePrefix = ".attr-"---- | The bytes upstream's @tokenizeString@ splits a list attribute at by--- default (@src\/libutil\/util.hh@ at 2.24.9).  Not 'isSpace': a form feed,--- a vertical tab or a non-ASCII space does not separate there.-tokenSeparators :: BS.ByteString-tokenSeparators = " \t\n\r"---- | The fixed build timestamp handed to every builder: 1980-01-01 UTC.--- Determinism-aware tools (binutils @ld@ writes it into the PE header--- instead of the wall clock; gcc uses it for @__DATE__@\/@__TIME__@)--- produce identical output across builds.  1980 rather than 0 because--- zip timestamps cannot represent dates before 1980 - the same value--- nixpkgs' stdenv uses.  A derivation env may override it.-sourceDateEpochValue :: Text-sourceDateEpochValue = "315532800"---- ------------------------------------------------------------------------------ Configuration--- ------------------------------------------------------------------------------- | Configuration for the build environment.-data BuildConfig = BuildConfig-  { -- | Store directory (where outputs go).-    bcStoreDir :: !StoreDir,-    -- | Temp directory for builds (cleaned after each build).-    bcTmpDir :: !FilePath,-    -- | Binary caches to try before building (checked in priority order).-    bcCaches :: ![CacheConfig],-    -- | What a failed substitute leads to: upstream's @fallback@.-    bcFallback :: !Fallback,-    -- | Extraction budget for @builtin:unpack@ builds.-    bcUnpackLimits :: !UnpackLimits,-    -- | How a download is retried: each URL of a @builtin:fetchurl@-    -- before the next is tried, and each narinfo and NAR the substituter-    -- requests, as upstream's one @download-attempts@ setting governs-    -- every transfer.-    bcFetchRetry :: !FetchRetryPolicy,-    -- | Launchers for derivations whose @system@ this machine cannot execute-    -- directly, keyed by that system string exactly as-    -- 'Nix.Derivation.platformToText' spells it (@x86_64-windows@ -> a wine-    -- binary). Prepended to the builder at the spawn boundary only, so the-    -- derivation itself - and its store paths - stay identical to a native-    -- build's. A foreign system with no entry here is refused rather than-    -- spawned natively; see 'execWrapperFor'.-    bcExecWrappers :: !(Map Text FilePath),-    -- | Where a builder's output goes, a line at a time as each line-    -- completes ("Nix.Builder.Log").  Upstream's default logger prints-    -- every build-log line to standard error, which is where-    -- 'defaultBuildConfig' points this.-    bcBuildLog :: !System.IO.Handle-  }-  deriving (Eq, Show)---- | Default build configuration.-defaultBuildConfig :: StoreDir -> BuildConfig-defaultBuildConfig dir =-  BuildConfig-    { bcStoreDir = dir,-      bcTmpDir =-        if isWindows-          then "C:\\Temp\\nova-nix-build"-          else "/tmp/nova-nix-build",-      bcCaches = [],-      bcFallback = NoFallback,-      bcExecWrappers = Map.empty,-      bcUnpackLimits = defaultUnpackLimits,-      bcFetchRetry = defaultFetchRetryPolicy,-      bcBuildLog = System.IO.stderr-    }---- | Result of a build attempt.-data BuildResult-  = -- | Build succeeded. Output registered at this store path.-    BuildSuccess !StorePath-  | -- | Build failed with an error message and exit code.-    BuildFailure !Text !Int-  deriving (Eq, Show)---- ------------------------------------------------------------------------------ Build loop--- ------------------------------------------------------------------------------- | Build a derivation, given its @.drv@ path, which names it in a failure--- as upstream's do: run its builder and capture output.------ 1. Validate all inputs exist in the store--- 2. Create temp build directory--- 3. Set up environment from derivation + standard vars--- 4. Run the builder process, which writes each output at its store path--- 5. On success: scan the outputs for references and register them,---    failing on a reference cycle between them ('registerOutputs')--- 6. On failure: clean up and report error--- 7. Exception safety: synchronous exceptions convert to BuildFailure;---    asynchronous exceptions propagate ('catchSync') - an interrupt---    must abort the build, never be reported as a build failure.-buildDerivation :: BuildConfig -> Store -> Derivation -> StorePath -> IO BuildResult-buildDerivation config store drv drvPath =-  buildDerivationInner config store drv drvPath-    `catchSync` \err -> pure (BuildFailure ("build exception: " <> T.pack (show err)) 1)---- | Build under the outputs' path locks.  A derivation another process--- finished while we waited for them is adopted rather than redone:--- rebuilding would delete a registered path out from under whoever is--- already using it, which is why substitution adopts a finished path too.-buildDerivationInner :: BuildConfig -> Store -> Derivation -> StorePath -> IO BuildResult-buildDerivationInner config store drv drvPath =-  withOutputLocks config store drv (maybe (buildUnderLock config store drv drvPath) (pure . BuildSuccess))---- | Hold every output's path lock for the whole build, and report--- whether the derivation was already finished by the time they were--- granted.------ #119 and #121 made delete, materialize and register one critical--- section under @\<store-path\>.lock@.  The build path never joined it,--- so two concurrent builds of one derivation shared a build directory--- ('computeBuildDir' is deterministic), interleaved their writes into a--- single tree, and each registered it as valid.  Nothing failed; the--- registered output was simply not what either build produced.------ Outputs are locked in 'lockOrder', so two processes racing the same--- multi-output derivation request them in the same sequence and neither--- can hold a lock the other needs while waiting on one it holds.  A--- build holds locks for its own outputs only - dependencies are--- resolved before 'buildDerivation' is called, never underneath it - so--- that sequence is the only one there is to agree on.------ The validity re-check happens under the locks, not before them:--- checked earlier it would answer about a moment that has already--- passed by the time the build starts.-withOutputLocks :: BuildConfig -> Store -> Derivation -> (Maybe StorePath -> IO a) -> IO a-withOutputLocks config store drv act = do-  heldLocks <- newIORef []-  let takeLock sp = do-        lock <- acquirePathLock (bcStoreDir config) sp-        atomicModifyIORef' heldLocks (\locks -> (lock : locks, ()))-  ( do-      mapM_ takeLock (lockOrder (map doPath (drvOutputs drv)))-      finishedElsewhere <- allOutputsValid store drv-      act finishedElsewhere-    )-    `finally` (readIORef heldLocks >>= mapM_ releasePathLock)---- | The order a process takes more than one path lock in.  Substitution--- holds each lock until its batch registers, and a build until it finishes,--- so both have to use this order: the blocking lock has no timeout, and two--- processes taking the same paths in different orders would wait forever.-lockOrder :: [StorePath] -> [StorePath]-lockOrder = sort---- | The derivation's first output path when EVERY output is already--- registered, otherwise 'Nothing'.------ Every output, never just the first: a partially valid multi-output--- derivation still has to build, and treating it as finished would leave--- the missing outputs missing.  Both the lock-held re-check and the gate--- in 'realiseEffects' ask this one question, so the two cannot disagree.-allOutputsValid :: Store -> Derivation -> IO (Maybe StorePath)-allOutputsValid store drv = case map doPath (drvOutputs drv) of-  [] -> pure Nothing-  outputPaths@(firstOutput : _) -> do-    validity <- mapM (isValid store) outputPaths-    pure (if and validity then Just firstOutput else Nothing)---- | The build itself, with every output's lock already held.-buildUnderLock :: BuildConfig -> Store -> Derivation -> StorePath -> IO BuildResult-buildUnderLock config store drv drvPath = do-  -- 1. Validate inputs (sources + input-derivation outputs) exist, and-  --    take their closure: what an output may reference besides the-  --    derivation's own outputs.-  inputs <- validateInputs config store drv >>= either (pure . Left) (inputClosure store)-  case inputs of-    Left errMsg -> pure (BuildFailure errMsg 1)-    Right inputPaths -> do-      -- 2. Create temp build directory.  The location is deterministic-      --    (computeBuildDir), so a crashed earlier run may have left stale-      --    contents that builtin:unpack would misread as an archive-      --    collision - always start from an empty directory, and always-      --    remove it on the way out (finally), builder exceptions included.-      let buildDir = computeBuildDir config drv-      removePathForcibly buildDir-      createDirectoryIfMissing True buildDir-      (`finally` cleanupBuildDir buildDir) $ do-        -- 3. Compute output paths (but do NOT pre-create them - the builder-        --    is responsible for creating $out, $dev, etc.).-        ---        --    $out is the FINAL store path now, as upstream's is: a temp-        --    path recorded by the build (a compiler driver, a libtool-        --    archive) would otherwise outlive the temp dir it named.-        outputValidity <- mapM (isValid store . doPath) (drvOutputs drv)-        case traverse outputPlan (zip (drvOutputs drv) outputValidity) of-          Left nameErr -> pure (BuildFailure ("output name is not a store path name: " <> T.pack (show nameErr)) 1)-          Right plans -> runPlannedBuild config store drv drvPath inputPaths buildDir plans---- | Where the builder writes each output, and where that has to end up.------ The two coincide for an output being built: writing into the final store--- path is what this whole arrangement is for.  They differ for an output--- that is already valid, which the builder is still handed (a package with--- a @dev@ output has one builder writing both) but which must not be--- touched: it is registered, its @NarHash@ describes its current bytes,--- and 'placeInStore' has already sealed it read-only.-data OutputPlan = OutputPlan-  { -- | The derivation output's name, as it reaches the environment.-    opName :: !Text,-    -- | Where the output has to be when the build is done.-    opFinal :: !StorePath,-    -- | Where the builder is told to write.-    opScratch :: !StorePath,-    -- | Whether 'opFinal' is already registered, and so must survive.-    opValid :: !Bool-  }---- | Plan one output, given whether its final path is already valid.-outputPlan :: (DerivationOutput, Bool) -> Either BadStorePath OutputPlan-outputPlan (out, valid)-  | not valid = Right (OutputPlan (doName out) (doPath out) (doPath out) False)-  | otherwise = do-      fallback <- fallbackOutputPath (doPath out)-      pure (OutputPlan (doName out) (doPath out) fallback True)---- | A scratch store path for an output that must not be written to, built--- so it cannot collide with any real store path.------ Upstream's @makeFallbackPath@ (the @StorePath@ overload, in--- @src/libstore/unix/build/local-derivation-goal.cc@ at 2.24.9) with the--- same shape: a bogus @rewrite:@ path type and an all-zeroes inner hash,--- keyed on the output path it stands in for.--- Upstream's type string also names the @.drv@ path--- (@rewrite:\<drv\>:\<path\>@), so the scratch path a builder sees differs--- from upstream's.  The output path already names one output of one--- derivation, so the result is just as unique.-fallbackOutputPath :: StorePath -> Either BadStorePath StorePath-fallbackOutputPath sp =-  makeStorePath-    defaultStoreDir-    ("rewrite:" <> spHash sp <> "-" <> spName sp)-    (BS.replicate 32 0)-    (spName sp)---- | Parse @--exec-wrapper SYSTEM=PATH@ specs into the map 'bcExecWrappers'--- wants.------ @SYSTEM@ is a derivation's own @system@ string, spelled as--- 'Nix.Derivation.platformToText' spells it, because 'execWrapperFor'--- matches it by equality and nothing else.------ A system named twice is an error rather than last-one-wins: two specs for--- one system is a mistake in the invocation either way, and silently--- picking one of them means a build runs through a launcher the operator--- did not think they had asked for.-execWrapperConfig :: [String] -> Either Text (Map Text FilePath)-execWrapperConfig = foldl' step (Right Map.empty)-  where-    step acc spec = do-      wrappers <- acc-      (system, path) <- one spec-      if Map.member system wrappers-        then Left ("--exec-wrapper names " <> system <> " twice")-        else Right (Map.insert system path wrappers)-    one spec = case break (== '=') spec of-      (system, '=' : path)-        | not (null system), not (null path) -> Right (T.pack system, path)-      _ -> Left ("--exec-wrapper expects SYSTEM=PATH, got: " <> T.pack spec)---- | How this machine can spawn a derivation's builder.-data BuilderSpawn-  = -- | The derivation targets this machine's platform; spawn it directly.-    SpawnNative-  | -- | Spawn through this launcher, named for the derivation's system.-    SpawnThrough !FilePath-  | -- | Nothing here can execute this derivation's builder; the payload is-    -- the system string that has no launcher.-    SpawnUnsupported !Text-  deriving (Eq, Show)---- | How to spawn this derivation's builder on this machine.------ \"This is my platform\" and \"I have no launcher for this platform\" are--- different answers: collapsing them to \"spawn directly\" runs a foreign--- builder natively and reports whatever the loader says, after the whole--- closure has already been realized. A system this machine cannot execute--- and has not been told how to is refused instead.-execWrapperFor :: BuildConfig -> Derivation -> BuilderSpawn-execWrapperFor = spawnFor currentPlatform---- | 'execWrapperFor' with the host named, so the rule can be checked for--- every host on whichever one runs the suite.  A derivation for the host's--- own system, or for one the host executes through its compatibility layer--- ('extraPlatforms'), spawns directly whatever launchers are configured:--- upstream runs its extra platforms natively and has no launcher notion.-spawnFor :: Platform -> BuildConfig -> Derivation -> BuilderSpawn-spawnFor host config drv-  | platform == host || platform `elem` extraPlatforms host = SpawnNative-  | otherwise = case Map.lookup system (bcExecWrappers config) of-      Just launcher -> SpawnThrough launcher-      Nothing -> SpawnUnsupported system-  where-    platform = drvPlatform drv-    system = platformToText platform---- | The build, once every output knows where it is written and where it--- belongs, and the closure of the inputs is known.-runPlannedBuild :: BuildConfig -> Store -> Derivation -> StorePath -> Set StorePath -> FilePath -> [OutputPlan] -> IO BuildResult-runPlannedBuild config store drv drvPath inputPaths buildDir plans = do-  let scratchDir p = storePathToFilePath (bcStoreDir config) (opScratch p)-      outputDirs = [(opName p, scratchDir p) | p <- plans]-      -- Every scratch path is the build's to use: the ones that are final-      -- paths may hold a tree an interrupted run left behind, and the-      -- fallbacks may hold one an interrupted run failed to discard.-      clearScratch = for_ plans (removePathForcibly . scratchDir)-  clearScratch-  createDirectoryIfMissing True (unStoreDir (bcStoreDir config))-  -- The cleanup contract: the build directory is not where outputs live-  -- any more, so an interrupt or a throw between the builder starting and-  -- registration committing would otherwise strand an unregistered tree at-  -- a real store path.  Once the registrations are committed there is-  -- nothing left to take back, and the flag says so.-  committed <- newIORef False-  let cleanupUnlessCommitted = do-        done <- readIORef committed-        unless done clearScratch-  ( do-      -- 4. Decode builder/args/env for the spawn boundary.  Derivation-      --    strings are BYTES (identity); spawning a process needs real-      --    text, so invalid UTF-8 in any of them is a clean build-      --    failure, never a mojibake spawn.  An attribute that reaches-      --    the builder as a file stays bytes ('attrsDelivery').  The-      --    builtin builders skip this - they read the byte fields-      --    directly.-      exitResult <- case drvBuilder drv of-        b-          | b == builtinFetchurlBuilder -> first (uncurry BuilderRefused) <$> runBuiltinFetchurl (bcFetchRetry config) drv outputDirs-          | b == builtinUnpackBuilder -> first (uncurry BuilderRefused) <$> runBuiltinUnpack (bcStoreDir config) (bcUnpackLimits config) drv outputDirs-        _ -> case (execWrapperFor config drv, decodeBuilderStrings drv) of-          (SpawnUnsupported system, _) ->-            pure-              ( Left-                  ( BuilderRefused-                      1-                      ( "no way to run a "-                          <> system-                          <> " builder on this machine; pass --exec-wrapper "-                          <> system-                          <> "=PATH to name a launcher for it"-                      )-                  )-              )-          (_, Left errMsg) -> pure (Left (BuilderRefused 1 errMsg))-          (spawn, Right (builderText, argTexts)) ->-            let builderPath = T.unpack (onStore config builderText)-                builderArgs = map (T.unpack . buildRewrite config outputDirs) argTexts-                -- Env still names the real builder - a launcher only-                -- changes what's spawned, not what the derivation says.-                (spawnPath, spawnArgs) = case spawn of-                  SpawnThrough launcher -> (launcher, builderPath : builderArgs)-                  _ -> (builderPath, builderArgs)-                -- Only a fixed-output derivation's impureEnvVars reach-                -- the spawn: upstream gates the carve-out on the-                -- derivation type being non-sandboxed, which for us is-                -- exactly the fixed-output case.-                carriesHash out = not (T.null (doHashAlgo out))-                impureVars delivery-                  | any carriesHash (drvOutputs drv) = adImpureEnvVars delivery-                  | otherwise = Right []-             in case attrsDelivery config drv buildDir outputDirs of-                  Left err -> pure (Left (BuilderRefused 1 err))-                  Right delivery -> case impureVars delivery of-                    Left err -> pure (Left (BuilderRefused 1 err))-                    Right passed -> do-                      for_ (adFiles delivery) (uncurry BS.writeFile)-                      -- 5. Run the builder-                      runBuilder (bcBuildLog config) spawnPath spawnArgs (buildEnvironment config (adEnv delivery) builderPath buildDir) passed buildDir-      case exitResult of-        Left failure -> do-          -- Whatever the builder wrote is in the store now, so failure has-          -- to take it back out: an unregistered tree there is invisible to-          -- the database and would only confuse the next run.-          clearScratch-          pure (builderFailureResult failure)-        Right () -> do-          -- 6. Success: validate that the builder created all expected-          --    outputs.  Outputs may be files or directories - both are-          --    valid (real Nix allows $out to be a single file, a-          --    directory tree, or a symlink).-          missing <- filterM (fmap not . doesPathExist . snd) outputDirs-          case missing of-            _ : _ -> do-              let names = T.intercalate ", " (map fst missing)-              -- The builder may have produced some outputs before omitting-              -- another.  None were registered, so take those orphaned-              -- trees back out of the store.-              clearScratch-              pure (BuildFailure ("builder succeeded but outputs missing: " <> names) 1)-            [] -> do-              result <- registerOutputs config store drv drvPath inputPaths plans-              case result of-                BuildSuccess _ -> do-                  writeIORef committed True-                  -- Upstream discards a valid output's redirected copy-                  -- rather than reading it; only the fallbacks go, the-                  -- registered trees stay.-                  for_ [p | p <- plans, opValid p] (removePathForcibly . scratchDir)-                _ -> clearScratch-              pure result-    )-    `onException` cleanupUnlessCommitted---- | Why the builder step of a build failed, with the exit code the--- build reports.-data BuilderFailure-  = -- | The builder ran and exited unsuccessfully.  What it wrote is-    -- already in the build log, which upstream's default logger does not-    -- repeat in the failure: it shows the log's last lines there only-    -- when it has not been printing them (@log-lines@, derivation-goal.cc-    -- at 2.24.9).-    BuilderExited !Int-  | -- | The builder did not run, or a builtin builder refused, for the-    -- reason given.-    BuilderRefused !Int !Text---- | The build result a failed builder step reports.-builderFailureResult :: BuilderFailure -> BuildResult-builderFailureResult failure = case failure of-  BuilderExited code -> BuildFailure "builder failed" code-  BuilderRefused code reason -> BuildFailure ("builder failed: " <> reason) code---- | Decode a derivation's builder path and arguments from their identity--- bytes to the 'Text' the process-spawn boundary needs.  @Left@ names the--- offending field.  The environment is decoded where 'attrsDelivery'--- decides what of it reaches the builder as variables.-decodeBuilderStrings :: Derivation -> Either Text (Text, [Text])-decodeBuilderStrings drv = do-  builderText <- decodeSpawnField "the builder path" (drvBuilder drv)-  argTexts <- traverse (decodeSpawnField "a builder argument") (drvArgs drv)-  pure (builderText, argTexts)---- | Decode one derivation string for the spawn, @what@ naming it in the--- failure.-decodeSpawnField :: Text -> BS.ByteString -> Either Text Text-decodeSpawnField what bytes = case TE.decodeUtf8' bytes of-  Right t -> Right t-  Left _ -> Left ("cannot spawn builder: " <> what <> " contains invalid UTF-8")---- | 'decodeSpawnField' for an environment variable.-decodeVariable :: Text -> BS.ByteString -> Either Text Text-decodeVariable name = decodeSpawnField ("environment variable '" <> name <> "'")---- ------------------------------------------------------------------------------ Input validation--- ------------------------------------------------------------------------------- | Rewrite a derivation string's store paths from their identity (the--- canonical @\/nix\/store@ spelling) to where this machine actually keeps--- them, at the spawn boundary. A no-op when the two coincide.-onStore :: BuildConfig -> Text -> Text-onStore config = maybe id (uncurry T.replace) (storeRewrite config)---- | The replacement 'onStore' makes, when the two spellings differ.-storeRewrite :: BuildConfig -> Maybe (Text, Text)-storeRewrite config-  | storeDirText == defaultStoreDirText = Nothing-  | otherwise = Just (defaultStoreDirText <> "/", storeDirText <> "/")-  where-    storeDirText = T.pack (unStoreDir (bcStoreDir config))---- | Check that all inputs needed to build a derivation are present in the--- store, and return them: the input sources, then the input derivations'--- requested outputs.------ Input sources must be valid.  For input derivations, the artifacts a build--- actually reads are their realized OUTPUT paths, not the @.drv@ recipe files,--- so we resolve each requested output (by reading the input @.drv@ the build--- driver materialized) and validate those outputs.  "Nix.Realise" realizes a--- derivation's inputs before it builds, so their outputs are present by the--- time it is validated.-validateInputs :: BuildConfig -> Store -> Derivation -> IO (Either Text [StorePath])-validateInputs config store drv = do-  -- Check input sources-  srcResults <- mapM (isValid store) (drvInputSrcs drv)-  let missingSrcs = [sp | (sp, valid) <- zip (drvInputSrcs drv) srcResults, not valid]-  if not (null missingSrcs)-    then pure (Left ("missing input sources: " <> T.intercalate ", " (map formatSP missingSrcs)))-    else do-      resolved <- resolveInputOutputs config drv-      case resolved of-        Left err -> pure (Left err)-        Right requiredOutputs -> do-          outResults <- mapM (isValid store) requiredOutputs-          let missingOutputs = [sp | (sp, valid) <- zip requiredOutputs outResults, not valid]-          if not (null missingOutputs)-            then pure (Left ("missing input derivation outputs: " <> T.intercalate ", " (map formatSP missingOutputs)))-            else pure (Right (drvInputSrcs drv ++ requiredOutputs))---- | Resolve each input derivation's requested output names to their store--- paths by reading the input @.drv@ from the store.  @Left@ if an input @.drv@--- cannot be read or names an output the derivation does not define.-resolveInputOutputs :: BuildConfig -> Derivation -> IO (Either Text [StorePath])-resolveInputOutputs config drv =-  runExceptT (concat <$> traverse resolveOne (Map.toList (drvInputDrvs drv)))-  where-    resolveOne (inputDrvPath, wantedOutputs) = do-      inputDrv <- ExceptT (readDrvFromStore config inputDrvPath)-      let outputMap = Map.fromList [(doName o, doPath o) | o <- drvOutputs inputDrv]-      liftEither (traverse (lookupOutput inputDrvPath outputMap) wantedOutputs)-    lookupOutput inputDrvPath outputMap name =-      case Map.lookup name outputMap of-        Just sp -> Right sp-        Nothing ->-          Left ("input derivation " <> formatSP inputDrvPath <> " has no output '" <> name <> "'")---- | The closure of a build's inputs under the references the store records:--- the paths besides its own outputs that an output may reference.  This is--- upstream's @inputPaths@, the closures of the requested input outputs and--- of the input sources (derivation-goal.cc:601-613 at 2.24.9).  An output--- that embeds a dependency of a dependency must record it, or a collection--- deletes it while the output still uses it.  As in upstream's, an input--- derivation's @.drv@ is in it only when an input source reaches it.------ A recorded reference that does not parse is a corrupt database, and fails--- the build rather than dropping out of the scan.-inputClosure :: Store -> [StorePath] -> IO (Either Text (Set StorePath))-inputClosure store = runExceptT . closureUnder recorded-  where-    recorded :: StorePath -> ExceptT Text IO [StorePath]-    recorded sp = do-      referenceTexts <- liftIO (queryReferences (stDB store) sp)-      liftEither (traverse parseRecorded referenceTexts)-    parseRecorded text = case parseStorePath (stDir store) text of-      Just sp -> Right sp-      Nothing -> Left ("unparseable reference in store DB: " <> text)---- | Every node reachable from the roots through the references lookup, the--- roots included.  Each node is looked up once, so a reference cycle (the--- outputs of one derivation may reference each other) ends.-closureUnder :: (Monad m, Ord a) => (a -> m [a]) -> [a] -> m (Set a)-closureUnder references = go Set.empty-  where-    go !seen [] = pure seen-    go !seen (node : pending)-      | Set.member node seen = go seen pending-      | otherwise = do-          referenced <- references node-          go (Set.insert node seen) (referenced ++ pending)---- | Format a StorePath for error messages.-formatSP :: StorePath -> Text-formatSP sp = spHash sp <> "-" <> spName sp---- ------------------------------------------------------------------------------ Build directory--- ------------------------------------------------------------------------------- | Compute a unique build directory path based on the first output hash.-computeBuildDir :: BuildConfig -> Derivation -> FilePath-computeBuildDir config drv =-  let uniqueSuffix = case drvOutputs drv of-        (out : _) -> T.unpack (spHash (doPath out))-        [] -> "no-output"-   in bcTmpDir config </> uniqueSuffix---- | Remove the build directory, ignoring a filesystem failure to remove--- it.  It runs as the build's 'finally', where a directory that will not--- go away must not replace the build's own outcome.-cleanupBuildDir :: FilePath -> IO ()-cleanupBuildDir dir = do-  exists <- doesDirectoryExist dir-  when exists $-    removeDirectoryRecursive dir `catch` \(_ :: IOException) -> pure ()---- ------------------------------------------------------------------------------ Environment--- ------------------------------------------------------------------------------- | Replace each output's @builtins.placeholder@ sentinel with its--- build-time path (the same value @$out@ carries).  Only the args and the--- environment are rewritten; the builder path is left alone, matching--- upstream, which assigns @builder = drv->builder@ unrewritten and rewrites--- only @drv->args@ (local-derivation-goal.cc:2170,2176).-rewritePlaceholders :: [(Text, FilePath)] -> Text -> Text-rewritePlaceholders outputDirs value =-  foldr (uncurry T.replace) value (placeholderRewrites outputDirs)---- | The replacements 'rewritePlaceholders' makes, one per output.-placeholderRewrites :: [(Text, FilePath)] -> [(Text, Text)]-placeholderRewrites outputDirs = [(hashPlaceholder name, T.pack path) | (name, path) <- outputDirs]---- | The build's rewrite of a derivation string: store paths to where this--- machine keeps them, then each output's placeholder to its build-time--- path.  'onStore' goes first, so nothing a placeholder expands to is--- rewritten a second time.-buildRewrite :: BuildConfig -> [(Text, FilePath)] -> Text -> Text-buildRewrite config outputDirs = rewritePlaceholders outputDirs . onStore config---- | 'buildRewrite' over bytes, for an attribute that reaches the builder--- as a file and so need not be text.  The replacements go in the order--- 'buildRewrite' makes them ('rewritePlaceholders' folds from the right),--- and on UTF-8 the two agree: an encoded needle matches only at a--- character boundary.-buildRewriteBytes :: BuildConfig -> [(Text, FilePath)] -> BS.ByteString -> BS.ByteString-buildRewriteBytes config outputDirs =-  rewriteBytes-    [ (TE.encodeUtf8 from, TE.encodeUtf8 to)-    | (from, to) <- maybeToList (storeRewrite config) <> reverse (placeholderRewrites outputDirs)-    ]---- | Apply a build-time rewrite to an environment's names as well as its--- values.  Upstream rewrites the whole @name=value@ string--- (local-derivation-goal.cc:2004), so a placeholder in a dynamic attribute--- name is substituted too; rewriting only the values would hand the builder--- a variable whose name still held the sentinel.-rewriteEnv :: (Text -> Text) -> Map Text Text -> Map Text Text-rewriteEnv rewrite = Map.fromList . map rewritePair . Map.toList-  where-    rewritePair (name, value) = (rewrite name, rewrite value)---- | What a builder receives of its derivation beyond the builder path and--- arguments.-data AttrsDelivery = AttrsDelivery-  { -- | Variables the derivation contributes to the environment.-    adEnv :: !(Map Text Text),-    -- | Files written into the build directory before the builder starts.-    adFiles :: ![(FilePath, BS.ByteString)],-    -- | The @impureEnvVars@ attribute, which matters only to a fixed-output-    -- derivation, so a malformed one fails only such a build, as upstream.-    adImpureEnvVars :: !(Either Text [Text])-  }-  deriving (Eq, Show)---- | How the derivation's attributes reach the builder: as environment--- variables, outputs included, or for a derivation carrying structured--- attributes, as @.attrs.json@ and @.attrs.sh@ in the build directory--- named by two variables, with no attribute and no output in the--- environment (upstream's @initTmpDir@ and @writeStructuredAttrs@,--- local-derivation-goal.cc at 2.24.9).------ Without structured attributes, each attribute @passAsFile@ names--- ('splitPassAsFile') is written to a file in the build directory instead,--- holding the bytes its variable would have held, and @\<name\>Path@--- names the file.  An attribute that is itself called @\<name\>Path@--- keeps its own value, as it does upstream, where it is assigned later.--- The variable joins the build directory and the file name with the--- platform's separator where upstream writes @\/@, so on Windows it is--- spelled as @NIX_BUILD_TOP@ is.  Structured attributes need no such--- escape from the environment, and upstream ignores @passAsFile@ there.------ The build's rewrite ('buildRewrite') applies to the shell file's text--- as upstream applies it, after rendering; the JSON file's strings take it--- before they are escaped, so a store directory holding backslashes still--- yields JSON.-attrsDelivery :: BuildConfig -> Derivation -> FilePath -> [(Text, FilePath)] -> Either Text AttrsDelivery-attrsDelivery config drv buildDir outputDirs = case Map.lookup structuredAttrsKey env of-  Nothing -> do-    let (variables, passed) = splitPassAsFile env-        passedPath name = buildDir </> passedFileName name-        pathVars = Map.fromList [(name <> passedFileVarSuffix, T.pack (passedPath name)) | name <- Map.keys passed]-    decoded <- Map.traverseWithKey decodeVariable variables-    Right-      AttrsDelivery-        { adEnv = unionEnvs [Map.withoutKeys outputEnv (Map.keysSet passed), rewriteEnv rewrite (unionEnvs [decoded, pathVars])],-          adFiles = [(passedPath name, passedContents name value) | (name, value) <- Map.toList passed],-          -- Read from the whole environment, as upstream's getStringsAttr-          -- reads it, so passing the attribute as a file does not drop it.-          adImpureEnvVars = T.words <$> decodeVariable envImpureEnvVars (Map.findWithDefault "" envImpureEnvVars env)-        }-  Just encodedBytes -> do-    encoded <- decodeVariable structuredAttrsKey encodedBytes-    attrs <- first (("cannot process " <> structuredAttrsKey <> " attribute of '" <> formatDrvName drv <> "': ") <>) (decodeStructuredAttrs encoded)-    let prepared = withOutputPlaceholders (map fst outputDirs) attrs-        jsonFile = buildDir </> attrsJsonFileName-        shellFile = buildDir </> attrsShellFileName-    Right-      AttrsDelivery-        { adEnv = Map.fromList [(envNixAttrsJsonFile, T.pack jsonFile), (envNixAttrsShFile, T.pack shellFile)],-          adFiles =-            [ (jsonFile, renderAttrsJson rewrite prepared),-              (shellFile, TE.encodeUtf8 (rewrite (renderAttrsShell prepared)))-            ],-          adImpureEnvVars = fromMaybe [] <$> stringsAttr envImpureEnvVars attrs-        }-  where-    env = drvEnv drv-    rewrite = buildRewrite config outputDirs-    outputEnv = Map.fromList [(name, T.pack path) | (name, path) <- outputDirs]-    -- An output's variable is the path it is written to, which is not-    -- the derivation's value when that output is already valid, so its-    -- file holds the same path.-    passedContents name value =-      maybe (buildRewriteBytes config outputDirs value) (TE.encodeUtf8 . T.pack) (lookup name outputDirs)---- | Upstream's @passAsFile@: split off the attributes the @passAsFile@--- attribute names, as files rather than variables, leaving the rest.  A--- name with no attribute behind it is ignored, and @passAsFile@ itself--- stays a variable unless it names itself.  Names are compared as bytes,--- as upstream compares them.-splitPassAsFile :: Map Text BS.ByteString -> (Map Text BS.ByteString, Map Text BS.ByteString)-splitPassAsFile env = (variables, passed)-  where-    named = Set.fromList (attrTokens (Map.findWithDefault "" envPassAsFile env))-    (passed, variables) = Map.partitionWithKey (\name _ -> Set.member (TE.encodeUtf8 name) named) env---- | Upstream's @tokenizeString@ with its default separators: the--- non-empty runs between 'tokenSeparators'.-attrTokens :: BS.ByteString -> [BS.ByteString]-attrTokens = filter (not . BS.null) . BS.splitWith (`BS.elem` tokenSeparators)---- | The file an attribute passed as a file is written to: upstream's--- @.attr-@ and the SHA-256 of the attribute's name in Nix base-32, so--- whatever the name holds, the file is one entry of the build directory.-passedFileName :: Text -> FilePath-passedFileName name = T.unpack (passedFilePrefix <> Nix32.encode (sha256Digest (TE.encodeUtf8 name)))---- | Build the process environment from the derivation's contribution--- ('adEnv') + standard vars.--- The builder path is used to derive PATH entries - the builder's own--- directory and its sibling @usr\/bin@ are included so that coreutils--- shipped alongside the builder (e.g. Git for Windows' MSYS2 tools)--- are available.  This mirrors real Nix where PATH contains only--- store paths from declared build dependencies.-buildEnvironment ::-  BuildConfig ->-  Map Text Text ->-  FilePath ->-  FilePath ->-  Map Text Text-buildEnvironment config derivationEnv builderPath buildDir =-  let -- Standard build variables-      standardEnv =-        Map.fromList-          [ (envNixBuildTop, T.pack buildDir),-            (envTmpDir, T.pack buildDir),-            (envTempDir, T.pack buildDir),-            (envTmp, T.pack buildDir),-            (envTemp, T.pack buildDir),-            (homeEnvVar, T.pack buildDir),-            (envNixStore, T.pack (unStoreDir (bcStoreDir config))),-            (envPath, buildPath builderPath),-            (envSourceDateEpoch, sourceDateEpochValue)-          ]-   in -- Priority: derivation env (output paths first) > standard env-      unionEnvs [derivationEnv, standardEnv]---- | Union environment maps left to right (an earlier map's variable wins).--- On Windows environment names are one case-insensitive namespace, so--- displacement folds names by per-character uppercase - matching the--- kernel's env-name comparison - and the winner keeps its own spelling:--- a build's @PATH@ must displace an inherited @Path@, or both would land--- in the child's environment block and which one the child sees would be--- runtime-dependent.  On Unix names are distinct by case and this is--- 'Map.unions'.-unionEnvs :: [Map Text Text] -> Map Text Text-unionEnvs envs-  | isWindows =-      let foldName = T.map toUpper-          folded =-            [ Map.fromList [(foldName name, (name, val)) | (name, val) <- Map.toList env]-            | env <- envs-            ]-       in Map.fromList (Map.elems (Map.unions folded))-  | otherwise = Map.unions envs---- | The ambient environment a builder is allowed to see.  Everything--- else is scrubbed: upstream builds in a cleared environment (its--- initEnv begins with @env.clear()@ and the child is exec'd with--- exactly that block), so an undeclared ambient variable reaching a--- build embeds machine-specific data in its output - undermining the--- reproducibility SOURCE_DATE_EPOCH exists to pin.------ On Unix the allowance is empty.  A Windows process block cannot be:--- 'windowsAmbientAllowlist' names what passes through, COMSPEC is--- synthesized from the allowed SystemRoot, and PATHEXT is pinned to--- 'pathextValue'.  Names compare case-insensitively on Windows, so the--- allowlist matches by folded name and a passed variable keeps its--- ambient spelling.-scrubAmbient :: Map Text Text -> Map Text Text-scrubAmbient ambient-  | not isWindows = Map.empty-  | otherwise =-      let foldName = T.map toUpper-          folded = Map.fromList [(foldName name, (name, val)) | (name, val) <- Map.toList ambient]-          allowed = Map.fromList [pair | key <- windowsAmbientAllowlist, Just pair <- [Map.lookup key folded]]-          synthesized =-            Map.fromList $-              (envPathext, pathextValue)-                : [ (envComspec, root <> "\\System32\\cmd.exe")-                  | Just (_, root) <- [Map.lookup systemRootKey folded]-                  ]-       in unionEnvs [allowed, synthesized]---- | Construct the build PATH from the builder's location.--- Includes the builder's directory, its sibling @usr\/bin@ (for MSYS2--- coreutils bundled with Git for Windows), and system directories.--- On a bootstrapped store, the builder's dir IS a store path, so this--- naturally becomes a store-only PATH.------ A bare-name or dot-relative builder has no directory to derive: @.@--- here would put the BUILD WORKING DIRECTORY first on PATH, so a file--- dropped into the build dir would resolve ahead of every tool.  Such--- builders get the system directories only.-buildPath :: FilePath -> Text-buildPath builderPath =-  let builderDir = takeDirectory builderPath-      parentDir = takeDirectory builderDir-      -- Builder's own dir + coreutils sibling (MSYS2 layout)-      builderDirs-        | builderDir == "." = []-        | otherwise = [builderDir, parentDir </> "usr" </> "bin"]-      systemDirs =-        if System.Info.os == "mingw32"-          then ["C:\\Windows\\System32", "C:\\Windows"]-          else ["/usr/bin", "/bin", "/usr/local/bin"]-      sep = if System.Info.os == "mingw32" then ";" else ":"-   in T.intercalate sep (map T.pack (builderDirs ++ systemDirs))---- | The home directory environment variable name (platform-dependent).-homeEnvVar :: Text-homeEnvVar =-  if System.Info.os == "mingw32"-    then "USERPROFILE"-    else "HOME"---- ------------------------------------------------------------------------------ Process execution--- ------------------------------------------------------------------------------- | Run the builder process, copying what it writes to @buildLog@, and--- report how it exited.------ Its standard output and standard error are one pipe ('openLogPipe'),--- so the log holds both in the order the builder wrote them, as--- upstream's does.  Its standard input is a pipe this process closes--- as soon as the builder is spawned, so a read sees end-of-file.------ The child's environment is exactly the build environment plus--- 'scrubAmbient'\'s allowance - the ambient environment does not flow--- through.  Filesystem and process isolation remain future work.------ @impureVars@ is the impureEnvVars carve-out: the caller passes the--- names a fixed-output derivation listed (empty otherwise), and each--- is copied from the ambient environment - the EMPTY STRING when--- absent, not omitted, matching upstream's @getEnv(i).value_or("")@.--- Upstream writes these last in initEnv, so they win even over the--- derivation's own values.  Names match exactly, as upstream's do.-runBuilder ::-  System.IO.Handle ->-  FilePath ->-  [String] ->-  Map Text Text ->-  [Text] ->-  FilePath ->-  IO (Either BuilderFailure ())-runBuilder buildLog builderPath builderArgs buildEnv impureVars workDir = do-  systemEnv <- System.Environment.getEnvironment-  let systemMap = Map.fromList [(T.pack k, T.pack v) | (k, v) <- systemEnv]-      impureAllowance =-        Map.fromList [(var, Map.findWithDefault "" var systemMap) | var <- impureVars]-      -- Impure carve-out wins, then build env, displacing case variants-      -- on Windows; the scrubbed ambient allowance fills underneath.-      mergedEnv = unionEnvs [impureAllowance, buildEnv, scrubAmbient systemMap]-      envList = [(T.unpack k, T.unpack v) | (k, v) <- Map.toList mergedEnv]-      spawnWith toLog =-        (mkBuilderProcess builderPath builderArgs)-          { Proc.cwd = Just workDir,-            Proc.env = Just envList,-            Proc.std_in = Proc.CreatePipe,-            -- The spawn closes this process's copy of the write end, so-            -- the builder's tree holds the only ones and its exit ends-            -- the log.-            Proc.std_out = Proc.UseHandle toLog,-            Proc.std_err = Proc.UseHandle toLog,-            -- Wrap the builder's whole process tree in a Win32 job with-            -- kill-on-job-close.  Without it, a builder's grandchildren-            -- (bash -> make -> cc, or anything cmd.exe spawns) outlive an-            -- interrupt: terminateProcess reaches only the direct child,-            -- so the tree is orphaned and keeps running.  With the job,-            -- terminateProcess becomes TerminateJobObject and reaps the-            -- tree, and waitForProcess waits for all of it.  Ignored on-            -- POSIX, where terminateProcess signals the builder alone and-            -- leaves its descendants running.-            -- A deliberately daemonizing grandchild changes from leaking-            -- to blocking the build until it exits; that is the correct-            -- trade for a build, which owns everything it spawned.-            Proc.use_process_jobs = True-          }-      closePipe (fromBuilder, toLog) = System.IO.hClose fromBuilder *> System.IO.hClose toLog-  exitCode <--    bracket openLogPipe closePipe $ \(fromBuilder, toLog) ->-      Proc.withCreateProcess (spawnWith toLog) $ \stdinEnd _ _ process -> do-        for_ stdinEnd System.IO.hClose-        streamBuildLog fromBuilder buildLog-        Proc.waitForProcess process-  pure $ case exitCode of-    ExitSuccess -> Right ()-    ExitFailure code -> Left (BuilderExited code)---- | Create the appropriate process spec for the builder.------ On Windows, cmd.exe uses its own command line parser - @\/c@ takes a--- raw command string, not individually-quoted arguments.  GHC's 'Proc.proc'--- wraps each arg in double quotes for the @CommandLineToArgvW@ convention,--- but cmd.exe doesn't use that convention, so a derivation like:------ @--- derivation { builder = "cmd.exe"; args = [ "\/c" "echo Hello" ]; ... }--- @------ would fail because GHC quotes @echo Hello@ as @\"echo Hello\"@, and--- cmd.exe tries to find an executable literally named @\"echo Hello\"@.------ Fix: when the builder is cmd.exe with @\/c@, use 'Proc.shell' which--- passes the command string directly to @cmd.exe \/c@ without quoting.--- For all other builders, use 'Proc.proc' (standard @CommandLineToArgvW@).-mkBuilderProcess :: FilePath -> [String] -> Proc.CreateProcess-mkBuilderProcess builder args-  | isWindows,-    isCmdExe builder,-    Just cmdString <- extractCmdString args =-      Proc.shell cmdString-  | otherwise = Proc.proc builder args---- | Check if the builder is cmd.exe (case-insensitive, handles full paths).-isCmdExe :: FilePath -> Bool-isCmdExe path = map toLower (takeFileName path) == "cmd.exe"---- | Extract the raw command string from cmd.exe args.--- Looks for @\/c@ (case-insensitive) and joins everything after it.-extractCmdString :: [String] -> Maybe String-extractCmdString (flag : cmdArgs)-  | map toLower flag == "/c" = Just (unwords cmdArgs)-extractCmdString _ = Nothing---- | Whether we are running on Windows (compile-time constant via 'System.Info').-isWindows :: Bool-isWindows = System.Info.os == "mingw32"---- ------------------------------------------------------------------------------ Built-in fetcher (builtin:fetchurl)--- ------------------------------------------------------------------------------- | Run a @builtin:fetchurl@ derivation: try URLs in order, each under the--- retry policy, and verify the written bytes against the derivation's--- @outputHash@. Nix's bootstrap fetcher is baked into the binary because--- nothing can be fetched before a fetcher exists.  Returns the same--- @Either (exit, msg) ()@ shape as 'runBuilder', so the shared--- output-registration path is reused unchanged.-runBuiltinFetchurl :: FetchRetryPolicy -> Derivation -> [(Text, FilePath)] -> IO (Either (Int, Text) ())-runBuiltinFetchurl policy drv outputDirs =-  case (fetchUrlsFromEnv (drvEnv drv), lookup envOut outputDirs, fixedOutput) of-    (Left err, _, _) -> pure (Left (1, "builtin:fetchurl: " <> err))-    (_, Nothing, _) -> pure (Left (1, "builtin:fetchurl: derivation defines no 'out' output"))-    (_, _, Nothing) -> pure (Left (1, "builtin:fetchurl: 'out' output has no fixed-output hash"))-    (Right urls@(firstUrl :| _), Just outPath, Just out)-      -- Invalid specifications reject before any network traffic.-      | recursive -> pure (Left (1, recursiveUnsupportedMessage))-      | Nothing <- hexToBytes (doHash out) ->-          pure (Left (1, malformedExpectedHash firstUrl))-      | otherwise -> case hashInitWithAlgo algo of-          Nothing ->-            pure (Left (1, "builtin:fetchurl: unsupported hash algorithm '" <> algo <> "'"))-          Just ctx -> do-            result <- tryFetchUrlsWith (fetchWithRetry outPath out ctx) urls-            pure $ case result of-              Left err -> Left (1, err)-              Right value -> Right value-      where-        (recursive, algo) = splitHashMode (doHashAlgo out)-  where-    -- builtin:fetchurl derivations are always fixed-output; the expected hash-    -- lives in the canonical output spec (doHashAlgo + doHash), not the env.-    fixedOutput = case drvOutputs drv of-      (out : _) | not (T.null (doHashAlgo out)) -> Just out-      _ -> Nothing-    fetchWithRetry outPath out ctx url =-      first attemptFailureMessage <$> retryTransient policy ioRetryEffects (fetchAndVerify outPath out ctx url)-    -- A download that completed and verifies wrong is the server's bytes,-    -- not a hiccup: upstream checks the hash after the transfer layer has-    -- given up retrying, so a mismatch is never retried.-    fetchAndVerify outPath out ctx url = do-      downloaded <- downloadUrlTo url outPath ctx-      pure $ case downloaded of-        Left failure -> Left (prefixFailure failure)-        Right digest -> first (FatalFailure . snd) (verifyFetchedDigest url out digest)-    prefixFailure failure = case failure of-      TransientFailure msg -> TransientFailure ("builtin:fetchurl: " <> msg)-      FatalFailure msg -> FatalFailure ("builtin:fetchurl: " <> msg)---- | Nova's mirror extension uses the ASCII-whitespace-separated @urls@ field.--- An absent field preserves the legacy single @url@ interface. An explicit--- empty or malformed list is an error, rather than a silent fallback.-fetchUrlsFromEnv :: Map Text BS.ByteString -> Either Text (NonEmpty Text)-fetchUrlsFromEnv env = case Map.lookup envUrls env of-  Just bytes -> do-    text <- decode envUrls bytes-    maybe (Left "'urls' is empty") Right (NE.nonEmpty (filter (not . T.null) (T.split separator text)))-  Nothing -> case Map.lookup envUrl env of-    Nothing -> Left "derivation has no 'url' or 'urls'"-    Just bytes -> do-      url <- decode envUrl bytes-      if T.null url then Left "'url' is empty" else Right (url :| [])-  where-    -- Match the fetcher expression's POSIX space class, preserving non-ASCII-    -- URL characters that 'T.words' would otherwise split into new candidates.-    separator char = isAscii char && isSpace char-    decode field = first (const ("'" <> field <> "' contains invalid UTF-8")) . TE.decodeUtf8'---- | Ordered fallback policy, independent of HTTP and files. Only the first--- successful /verified/ attempt wins; report every failure if none wins.--- Exceptions propagate, so cancellation cannot start another download.-tryFetchUrlsWith :: (Monad m) => (Text -> m (Either Text a)) -> NonEmpty Text -> m (Either Text a)-tryFetchUrlsWith attempt = go []-  where-    go !failures (url :| rest) = do-      result <- attempt url-      case result of-        Right value -> pure (Right value)-        Left err -> case NE.nonEmpty rest of-          Nothing -> pure (Left (T.intercalate "\n" (reverse (err : failures))))-          Just urls -> go (err : failures) urls---- ------------------------------------------------------------------------------ Download--- ------------------------------------------------------------------------------- | Download a URL to a file using nova-nix's own linked HTTP client--- (the same 'Network.HTTP.Client' the substituter uses) - no external--- @curl@, which is what makes this a genuine builtin.  The body streams--- to disk through the incremental hash chunk by chunk, so memory stays--- at chunk size no matter the download's size, and the returned digest--- is of exactly the written bytes. A failure of the transfer or of the--- write becomes a 'Left' carrying its retry class--- ('transferFailureHandlers'); cancellation propagates through the shared--- build cleanup. Every attempt opens the output in WriteMode and starts--- from the original hash context, so a retry never resumes a torn--- transfer: upstream resumes from the written offset when the server--- accepts ranges and otherwise gives up, which this restart subsumes.-downloadUrlTo :: Text -> FilePath -> IncrementalHash -> IO (Either AttemptFailure BS.ByteString)-downloadUrlTo url outPath ctx0 =-  fetch `catches` transferFailureHandlers url-  where-    fetch :: IO (Either AttemptFailure BS.ByteString)-    fetch = do-      manager <- HTTPS.getGlobalManager-      request <- withUserAgent <$> HTTP.parseRequest (T.unpack url)-      withTransfer request manager $ \response -> do-        let status = HTTP.responseStatus response-        if HTTP.statusCode status /= httpStatusOk-          then pure (Left (fetchStatusFailure url status))-          else System.IO.withBinaryFile outPath System.IO.WriteMode $ \handle ->-            let consume !ctx = do-                  chunk <- HTTP.brRead (HTTP.responseBody response)-                  if BS.null chunk-                    then pure (Right (hashFinalizeBytes ctx))-                    else do-                      BS.hPut handle chunk-                      consume (hashUpdateChunk ctx chunk)-             in consume ctx0---- | Verify the fetched bytes against the derivation's fixed-output hash, read--- from the canonical output spec.  @doHashAlgo@ is @sha256@/@sha512@/... (or--- @r:sha256@ for recursive); @doHash@ is the base-16 digest eval normalized the--- user's hash into.  Flat mode is fully supported across algorithms; recursive--- (unpack/executable) fetches are a separate feature - they require unpacking--- the download - and fail with a clear message rather than a wrong result.-verifyFetchHash :: Text -> DerivationOutput -> BS.ByteString -> Either (Int, Text) ()-verifyFetchHash url out body-  | recursive = Left (1, recursiveUnsupportedMessage)-  | otherwise = case (hexToBytes (doHash out), rawHashWithAlgo algo body) of-      (Nothing, _) -> Left (1, malformedExpectedHash url)-      (_, Nothing) -> Left (1, "builtin:fetchurl: unsupported hash algorithm '" <> algo <> "'")-      (Just _, Just got) -> verifyFetchedDigest url out got-  where-    (recursive, algo) = splitHashMode (doHashAlgo out)---- | Compare an already-computed digest of the fetched bytes against the--- derivation's fixed-output hash - the streaming twin of--- 'verifyFetchHash', which hashes a buffered body.-verifyFetchedDigest :: Text -> DerivationOutput -> BS.ByteString -> Either (Int, Text) ()-verifyFetchedDigest url out got = case hexToBytes (doHash out) of-  Nothing -> Left (1, malformedExpectedHash url)-  Just expected-    | expected == got -> Right ()-    | otherwise ->-        Left-          ( 1,-            "builtin:fetchurl: hash mismatch for "-              <> url-              <> "\n  expected: "-              <> algoField-              <> ":"-              <> doHash out-              <> "\n  got:      "-              <> algoField-              <> ":"-              <> bytesToHexText got-          )-  where-    algoField = doHashAlgo out---- | Split @outputHashAlgo@ into the recursive-mode marker and the bare--- algorithm name (@r:sha256@ is recursive @sha256@).-splitHashMode :: Text -> (Bool, Text)-splitHashMode algoField = case T.stripPrefix "r:" algoField of-  Just rest -> (True, rest)-  Nothing -> (False, algoField)--recursiveUnsupportedMessage :: Text-recursiveUnsupportedMessage =-  "builtin:fetchurl: recursive outputHashMode (unpack/executable) not yet supported; fetch flat and unpack in a build phase"--malformedExpectedHash :: Text -> Text-malformedExpectedHash url = "builtin:fetchurl: malformed expected hash for " <> url---- ------------------------------------------------------------------------------ Output registration--- ------------------------------------------------------------------------------- | After a successful build, register every output in the store, in--- upstream's two passes (registerOutputs, local-derivation-goal.cc:2288-2751--- at 2.24.9).  Every output is scanned first.  Then the outputs are ordered--- so that each follows the siblings it references ('orderByReferences'),--- and placed in that order.  Outputs that reference each other in a cycle--- fail the build before any is placed, so none is registered.------ The placed outputs register together in one transaction, so a--- cross-output reference finds its referent's row (see 'registerPaths').-registerOutputs ::-  BuildConfig ->-  Store ->-  Derivation ->-  StorePath ->-  Set StorePath ->-  [OutputPlan] ->-  IO BuildResult-registerOutputs config store drv drvPath inputPaths plans = do-  let -- Candidates for reference scanning: the input closure and this-      -- derivation's own outputs, upstream's @referenceablePaths@-      -- (local-derivation-goal.cc:2275-2278 at 2.24.9).-      allCandidates = Set.toList inputPaths ++ map doPath (drvOutputs drv)-      -- Outputs register with no deriver yet, so 'queryDeriver' answers-      -- Nothing for a built path, where upstream records the @.drv@-      -- (local-derivation-goal.cc:2738).-      deriver = Nothing-      -- An output may record an already-valid sibling, whose build wrote to-      -- a scratch path that is about to stop existing, so each scratch hash-      -- becomes the final one.  Upstream scans first and translates its hits;-      -- rewriting first lets the scan see final hashes and needs no-      -- translation, and the references come out the same.-      scratchRewrites = [(spHash (opScratch p), spHash (opFinal p)) | p <- plans, opValid p]-  scanned <- runExceptT (traverse (scanOutput config store allCandidates scratchRewrites) (zip (drvOutputs drv) plans))-  case orderByReferences (siblingsReferenced (drvOutputs drv)) . Map.fromList <$> scanned of-    Left errMsg -> pure (BuildFailure errMsg 1)-    Right (Left cycleEdge) -> pure (BuildFailure (outputCycleMessage drvPath cycleEdge) 1)-    Right (Right ordered) -> do-      placed <- runExceptT (traverse (ExceptT . placeOutput store deriver . snd) ordered)-      case placed of-        Left errMsg -> pure (BuildFailure errMsg 1)-        Right regs -> do-          registerPaths (stDB store) (catMaybes regs)-          case drvOutputs drv of-            (firstOut : _) -> pure (BuildSuccess (doPath firstOut))-            [] -> pure (BuildFailure "no outputs defined" 1)---- | Upstream's failure for outputs that reference each other in a cycle--- (local-derivation-goal.cc:2406-2408 at 2.24.9), naming the @.drv@ and--- the reference that closes the cycle.-outputCycleMessage :: StorePath -> ReferenceCycle Text -> Text-outputCycleMessage drvPath (ReferenceCycle node referrer) =-  "cycle detected in build of '"-    <> storePathToText defaultStoreDir drvPath-    <> "' in the references of output '"-    <> node-    <> "' from output '"-    <> referrer-    <> "'"---- | One output after the scan and before it is placed: upstream's--- @AlreadyRegistered@ and @PerhapsNeedToRegister@.-data ScannedOutput-  = -- | Registered before the build, and left as it is.-    AlreadyRegistered-  | -- | Built here: the output, where the builder wrote it, and the-    -- references the scan found in it.-    NeedsRegistering !DerivationOutput !FilePath ![StorePath]---- | Scan one output, keyed by its name: skip it if it is already valid in--- the DB, otherwise rewrite scratch hashes in it and scan it for--- references to the input closure and this derivation's outputs.-scanOutput ::-  BuildConfig ->-  Store ->-  [StorePath] ->-  [(Text, Text)] ->-  (DerivationOutput, OutputPlan) ->-  ExceptT Text IO (Text, ScannedOutput)-scanOutput config store candidates scratchRewrites (output, plan) = do-  let outDir = storePathToFilePath (bcStoreDir config) (opScratch plan)-  -- Check the build actually produced the output (file or directory).-  exists <- liftIO (doesPathExist outDir)-  unless exists (throwError ("output missing: " <> T.pack outDir))-  -- Validity is a DB fact, not mere disk presence: an output left on disk-  -- by an interrupted run is NOT valid, and build outputs are not-  -- content-addressed, so a leftover cannot be verified against its path.-  -- 'runPlannedBuild' removed any leftover before the builder ran, so the-  -- tree here is this build's (upstream's delete-then-move).-  valid <- liftIO (isValid store (doPath output))-  if valid-    then pure (doName output, AlreadyRegistered)-    else liftIO $ do-      -- One scan, not two: 'candidates' already carries this-      -- derivation's own outputs, and outDir is the final path, so a-      -- self- or cross-output reference is an ordinary hit.-      rewriteStoreHashes scratchRewrites outDir-      refs <- dedupStorePaths <$> scanReferences candidates outDir-      pure (doName output, NeedsRegistering output outDir refs)---- | The names of the sibling outputs an output's scan found.  An output--- registered before the build references none: upstream uses the--- registered copy and treats it as a leaf.-siblingsReferenced :: [DerivationOutput] -> ScannedOutput -> Set Text-siblingsReferenced outputs = referencedBy-  where-    nameByPath = Map.fromList [(doPath o, doName o) | o <- outputs]-    referencedBy AlreadyRegistered = Set.empty-    referencedBy (NeedsRegistering _ _ refs) = Set.fromList (mapMaybe (`Map.lookup` nameByPath) refs)---- | Place a scanned output in the store and check a fixed output's--- content, returning its 'PathRegistration'; @Nothing@ for an output--- registered before the build.-placeOutput :: Store -> Maybe Text -> ScannedOutput -> IO (Either Text (Maybe PathRegistration))-placeOutput store deriver scanned = case scanned of-  AlreadyRegistered -> pure (Right Nothing)-  NeedsRegistering output outDir refs -> do-    -- The builder wrote straight into the store path, so outDir IS the-    -- target and placing it moves nothing.-    let targetPath = storePathToFilePath (stDir store) (doPath output)-    reg <- placeInStore store outDir (doPath output) deriver refs-    fixedCheck <- verifyFixedOutput (volumeCaseHack (stCaseSensitivity store)) output targetPath-    case fixedCheck of-      Left err -> do-        -- Wrong bytes for a declared content address: remove the placed-        -- tree so a later run cannot meet it on disk.  'removePathForcibly'-        -- clears the read-only marks placing set.-        removePathForcibly targetPath-        pure (Left err)-      Right () -> pure (Right (Just reg))---- | A reference cycle, named by the reference that closes it: the node--- reached again while it is still on the walk's path, and the node whose--- reference reached it.-data ReferenceCycle k = ReferenceCycle-  { cycleNode :: !k,-    cycleReferrer :: !k-  }-  deriving (Eq, Show)---- | Where the walk in 'orderByReferences' is: the nodes it has entered,--- and the ones it has finished, the last finished first.-data Walk k v = Walk-  { walkEntered :: !(Set k),-    walkFinished :: ![(k, v)]-  }---- | Order nodes so that each follows every node it references, or report--- a cycle among them: upstream's @topoSort@ (src/libutil/topo-sort.hh at--- 2.24.9) with the reversal its @registerOutputs@ applies to the result--- (local-derivation-goal.cc:2411).------ The walk is upstream's depth-first one, so the order and the cycle it--- reports are upstream's too: it starts from each node in ascending--- order, follows each node's references in ascending order, ignores a--- self-reference and a reference to a node not in the map, and lists a--- node once everything it references is listed.  The first reference that--- leads back to a node still on the path is the cycle reported.-orderByReferences :: (Ord k) => (v -> Set k) -> Map k v -> Either (ReferenceCycle k) [(k, v)]-orderByReferences references nodes =-  reverse . walkFinished <$> foldM (visit Set.empty) (Walk Set.empty []) (Map.toAscList nodes)-  where-    visit onPath walk node@(key, value)-      | Set.member key (walkEntered walk) = Right walk-      | otherwise = do-          let referenced =-                [ (child, childValue)-                | child <- Set.toAscList (references value),-                  child /= key,-                  Just childValue <- [Map.lookup child nodes]-                ]-          finished <--            foldM-              (follow (Set.insert key onPath) key)-              walk {walkEntered = Set.insert key (walkEntered walk)}-              referenced-          pure finished {walkFinished = node : walkFinished finished}-    follow onPath referrer walk child@(key, _)-      | Set.member key onPath = Left (ReferenceCycle key referrer)-      | otherwise = visit onPath walk child---- | Re-check a placed fixed-output output against its declared hash.--- A fixed-output derivation declares both its store path and, via the--- output spec (@doHashAlgo@ + @doHash@), the exact content the path--- must carry - but the builder process writes the actual bytes, so the--- placed result must reproduce the declared digest before it may--- register as valid (upstream: the fixed-output check in its--- registerOutputs).  Flat mode hashes the output file's bytes;--- recursive (@r:@) mode hashes the canonical NAR of the placed tree.--- Non-fixed outputs (empty @doHashAlgo@) pass unchecked.  The tree is--- read back under the store volume's case-hack mode.-verifyFixedOutput :: NAR.CaseHack -> DerivationOutput -> FilePath -> IO (Either Text ())-verifyFixedOutput caseHack out placedPath-  | T.null (doHashAlgo out) = pure (Right ())-  | recursive = do-      -- Re-serialises the placed tree: the registration's NAR hash is-      -- always sha256, while the declared algorithm may be any.-      entry <- ExecBit.serialiseFromPath caseHack placedPath-      pure (finish (rawHashWithAlgo algo (NAR.serialise entry)))-  | otherwise = do-      isDir <- doesDirectoryExist placedPath-      if isDir-        then pure (Left (subject <> ": flat outputHashMode, but the output is a directory"))-        else finish <$> hashFileWithAlgo algo placedPath-  where-    (recursive, algo) = splitHashMode (doHashAlgo out)-    subject = "fixed-output '" <> spName (doPath out) <> "'"-    finish Nothing =-      Left (subject <> ": unsupported hash algorithm '" <> algo <> "'")-    finish (Just got) = case hexToBytes (doHash out) of-      Nothing -> Left (subject <> ": malformed expected hash")-      Just expected-        | expected == got -> Right ()-        | otherwise ->-            Left-              ( subject-                  <> ": hash mismatch\n  expected: "-                  <> doHashAlgo out-                  <> ":"-                  <> doHash out-                  <> "\n  got:      "-                  <> doHashAlgo out-                  <> ":"-                  <> bytesToHexText got-              )---- | Stream a file through the incremental hash without materializing it--- (a fixed-output file is input-sized).  'Nothing' for an unsupported--- algorithm.-hashFileWithAlgo :: Text -> FilePath -> IO (Maybe BS.ByteString)-hashFileWithAlgo algo path = case hashInitWithAlgo algo of-  Nothing -> pure Nothing-  Just initialCtx -> System.IO.withBinaryFile path System.IO.ReadMode $ \handle ->-    let consume !ctx = do-          chunk <- BS.hGet handle fixedOutputHashChunk-          if BS.null chunk-            then pure (Just (hashFinalizeBytes ctx))-            else consume (hashUpdateChunk ctx chunk)-     in consume initialCtx---- | Read-chunk size for hashing a placed output file.-fixedOutputHashChunk :: Int-fixedOutputHashChunk = 65536---- | Deduplicate store paths by their (unique) hash.-dedupStorePaths :: [StorePath] -> [StorePath]-dedupStorePaths = Map.elems . Map.fromList . map (\sp -> (spHash sp, sp))---- ------------------------------------------------------------------------------ Dependency-aware build orchestration--- ------------------------------------------------------------------------------- | Realise a derivation and what it needs, root first ("Nix.Realise").------ 1. Build the dependency graph by reading .drv files from the store.--- 2. Refuse a cycle.--- 3. Try each derivation's outputs before its inputs, so a substituted---    derivation needs only its runtime closure.  What no cache supplies---    builds locally, leaves first, and so does what a cache fails to---    deliver when 'bcFallback' allows it.------ Returns 'BuildSuccess' with the root output path on success, or--- 'BuildFailure' with exit code 1 if a derivation fails to build, a--- substitute fails under 'NoFallback', or a cache cannot be asked.-buildWithDeps :: BuildConfig -> Store -> Derivation -> StorePath -> IO BuildResult-buildWithDeps config store rootDrv rootDrvPath = do-  graph <- buildDepGraph (readDrvFromStore config) rootDrv rootDrvPath-  case graph of-    Left err -> pure (BuildFailure ("dependency graph error: " <> err) 1)-    Right depGraph ->-      case topoSort depGraph of-        TopoCycle _ ->-          pure (BuildFailure "dependency cycle detected" 1)-        TopoSorted _ -> do-          result <- realise (bcFallback config) (realiseEffects config store) depGraph rootDrvPath-          case result of-            Left failure -> pure (BuildFailure (realiseFailureMessage failure) 1)-            Right () ->-              case drvOutputs rootDrv of-                (firstOut : _) -> pure (BuildSuccess (doPath firstOut))-                [] -> pure (BuildFailure "no outputs defined" 1)---- | Read and parse a .drv file from the store, as bytes (no locale--- decode, no newline translation).-readDrvFromStore :: BuildConfig -> StorePath -> IO (Either Text Derivation)-readDrvFromStore config sp = do-  let drvFilePath = storePathToFilePath (bcStoreDir config) sp-  content <- try (BS.readFile drvFilePath)-  pure $ case content of-    Left (_ :: IOException) -> Left ("cannot read .drv file: " <> T.pack drvFilePath)-    Right bytes -> fromATerm bytes---- ------------------------------------------------------------------------------ Realisation effects--- ------------------------------------------------------------------------------- | The store, caches and builder that "Nix.Realise" drives.-realiseEffects :: BuildConfig -> Store -> RealiseEffects IO-realiseEffects config store =-  RealiseEffects-    { reSubst =-        SubstEffects-          { seValid = isValid store,-            seReferences = queryReferencesWith (bcFetchRetry config) ioRetryEffects (bcFallback config) (bcCaches config),-            seFetch = substitutePaths config store-          },-      -- Every output, not just the first: a derivation whose first output is-      -- valid and whose second was deleted would otherwise be logged cached-      -- and skipped, and the missing output would stay missing.  Upstream-      -- skips a build only when all of them are valid.-      reAllValid = fmap isJust . allOutputsValid store,-      reBuild = buildReporting config store,-      reReport = logRealised-    }---- | Build one derivation, naming it in any failure.-buildReporting :: BuildConfig -> Store -> Derivation -> StorePath -> IO (Either Text ())-buildReporting config store drv drvPath = do-  result <- buildDerivation config store drv drvPath-  pure $ case result of-    BuildSuccess _ -> Right ()-    BuildFailure msg code ->-      Left ("building " <> formatDrvName drv <> " failed: exit " <> T.pack (show code) <> ": " <> msg)---- | Format a status tag for display.-statusTag :: Realised -> Text-statusTag AlreadyValid = "[cached]"-statusTag Substituted = "[subst] "-statusTag Built = "[build] "---- | Log how a dependency was realised to stderr.-logRealised :: Realised -> Derivation -> IO ()-logRealised status drv =-  TIO.hPutStrLn System.IO.stderr ("  " <> statusTag status <> " " <> formatDrvName drv)---- | Try to substitute paths from binary caches, every one of them or none--- ('FetchOutcome').------ Registration is all-or-nothing and batched: every path is verified and--- unpacked first, then recorded in one 'registerPaths' transaction, so--- reference edges between the outputs of one derivation land after both--- endpoints' rows exist and a partial substitution registers nothing (the--- subsequent build starts from unregistered outputs and 'runPlannedBuild'--- replaces the leftover unpacked trees).------ Each substituted path arrives with its path lock STILL HELD (see--- 'Nix.Substituter.SubstSuccess'), and the exclusion must survive until--- the registration transaction commits - released earlier, another--- process could meet the unpacked-but-unregistered window and delete--- the tree the row is about to describe.  Every held lock is released--- here on every exit path (finally), including failures that never--- reach registration.------ A registration the database REFUSES - its unregistered-referent guard,--- reachable only through cache-declared references this store has never--- seen - is a failed substitution like any other: the transaction--- recorded nothing, so report it ('FetchFailed').  Upstream's copy of the--- path fails the same way when a reference is not valid.-substitutePaths :: BuildConfig -> Store -> [StorePath] -> IO FetchOutcome-substitutePaths config store paths-  | null (bcCaches config) = pure FetchMissed-  | otherwise = do-      heldLocks <- newIORef []-      registerSubstituted heldLocks-        `finally` (readIORef heldLocks >>= mapM_ releasePathLock)-  where-    registerSubstituted :: IORef [PathLock] -> IO FetchOutcome-    registerSubstituted heldLocks = do-      results <- mapM (substituteOne heldLocks) (lockOrder paths)-      case batchRegistrations results of-        Left outcome -> pure outcome-        Right rows -> do-          registered <- try (registerPaths (stDB store) rows)-          case registered of-            Right () -> pure Fetched-            Left (e :: IOException) -> do-              TIO.hPutStrLn System.IO.stderr ("  [subst] registration refused: " <> T.pack (displayException e))-              pure FetchFailed-    -- Record a returned lock the moment it exists, so the enclosing-    -- finally owns it even when a later path's attempt fails or throws.-    substituteOne heldLocks sp = do-      result <- trySubstituteWith (bcFetchRetry config) ioRetryEffects store (bcCaches config) sp-      case result of-        SubstSuccess _ lock -> atomicModifyIORef' heldLocks (\locks -> (lock : locks, ()))-        SubstError err -> TIO.hPutStrLn System.IO.stderr ("  [subst] " <> spName sp <> ": " <> err)-        _ -> pure ()-      pure result---- | What one batch's results come to: the rows to register when every path--- arrived, or why not.  One failed path fails the batch whatever the others--- did, as one failed output fails upstream's derivation goal.-batchRegistrations :: [SubstResult] -> Either FetchOutcome [PathRegistration]-batchRegistrations results-  | any failed results = Left FetchFailed-  | otherwise = maybe (Left FetchMissed) (Right . catMaybes) (traverse arrived results)-  where-    failed (SubstError _) = True-    failed _ = False-    -- An already-valid path counts as arrived but contributes no-    -- registration row (and holds no lock).-    arrived (SubstSuccess reg _) = Just (Just reg)-    arrived SubstAlreadyValid = Just Nothing-    arrived SubstNotFound = Nothing-    arrived (SubstError _) = Nothing+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | Derivation builder - executes build recipes.+--+-- == The build process+--+-- When Nix needs to build a derivation (cache miss), it:+--+-- 1. Creates a directory for the build under the store's state directory+--    ("Nix.Builder.BuildDir")+-- 2. Sets up the environment: the derivation's variables over the+--    standard ones, with a PATH of the builder's directory, its sibling+--    @usr\/bin@ and the system directories ('buildPath').  A sandboxed+--    build ("Nix.Builder.Sandbox") reaches, of the store, only its input+--    closure, the closure of its @sandbox-paths@, its outputs and its+--    build directory, and the host's network only when it is fixed-output+--    (a macOS one may also ask for local networking); an unsandboxed one+--    reaches the whole filesystem and the network.+-- 3. Runs the derivation's builder with its arguments (for a nixpkgs+--    stdenv, @bash -e@ on scripts that source the stdenv's @setup@)+-- 4. The build script runs @genericBuild@, which calls @unpackPhase@,+--    @patchPhase@, @configurePhase@, @buildPhase@, @installPhase@,+--    @fixupPhase@, etc.+-- 5. Builder writes output to @$out@ (the output store path, or a scratch+--    path for an output already valid; a Linux sandboxed build's is that+--    path beneath its chroot)+-- 6. Nix scans the output for references to other store paths+-- 7. Output is placed in the store and registered ('Nix.Store.placeInStore':+--    a Linux sandboxed build's moves out of its chroot, any other build's+--    is there already)+--+-- == Checking+--+-- Under 'BuildCheck', upstream's @nix-build --check@, 'buildWithDeps'+-- builds its derivation again beside the valid outputs and compares what+-- comes out with them ('checkDerivation').  That rebuild registers nothing+-- and leaves the outputs as they are, and under 'KeepFailed' keeps the+-- rebuild of an output that differs beside it.  What comes before it adds+-- to the store as any build does: an output that is not valid is+-- substituted first, and the inputs are substituted or built.+--+-- == Build users+--+-- When nova-nix runs as root with build users ('bcBuildUsers'), a spawned+-- builder runs as a member of their group, taken for the build+-- ('asBuilder'), and every process the member has is killed before the+-- build and once its builder ends ('endingBuildUser'), as upstream's+-- are.  An output must belong to the member before it is made root's+-- ("Nix.Builder.BuildUser").+--+-- == Outside the sandbox+--+-- On Linux and macOS an unsandboxed builder, a build user's or not, is+-- started and ended as upstream's is: in a session of its own, with+-- @\/dev\/null@ as its standard input and upstream's core limit, and with+-- every process left in its process group killed once its log ends+-- ("Nix.Builder.BuildUser").+--+-- == On Windows+--+-- The key difference is process creation.  Upstream on Linux uses+-- @fork\/exec@ with namespace isolation.  nova-nix spawns builders through+-- "System.Process", which reaches @CreateProcess@ on Windows with no POSIX+-- layer, and runs them as the invoking user, without filesystem or network+-- isolation.+--+-- The builder's process tree runs inside a Win32 job object+-- ('Proc.use_process_jobs'), so the build waits until every process in+-- the tree has exited, and an interrupt terminates the whole job instead+-- of orphaning grandchildren.+module Nix.Builder+  ( -- * Build execution+    BuildResult (..),+    BuildStop (..),+    stopReported,+    buildDerivation,+    checkDerivation,+    buildWithDeps,+    buildRequests,+    buildRequestsEach,+    readDrvFromStore,+    planMissingPaths,+    substitutablePaths,+    realiseWithoutWriting,+    checkStored,+    substitutePaths,+    substituteFromCaches,++    -- * Build configuration+    BuildConfig (..),+    SubstitutionAccess (..),+    defaultBuildConfig,++    -- * Pure pieces (exported for tests)+    AttrsDelivery (..),+    attrsDelivery,+    BuildPlace (..),+    BuildLayout (..),+    BuilderInvocation (..),+    builderInvocation,+    BuilderSpawn (..),+    buildPath,+    closureUnder,+    execWrapperConfig,+    execWrapperFor,+    spawnFor,+    ReferenceCycle (..),+    orderByReferences,+    rewriteEnv,+    rewritePlaceholders,+    scrubAmbient,+    unionEnvs,+    verifyFetchHash,+    fetchUrlsFromEnv,+    tryFetchUrlsWith,+  )+where++import Control.Exception (IOException, bracket, displayException, finally, onException, try, uninterruptibleMask_)+import Control.Monad (filterM, foldM, unless, void, when)+import Control.Monad.Except (ExceptT (..), liftEither, runExceptT, throwError, withExceptT)+import Control.Monad.IO.Class (liftIO)+import Control.Monad.State.Strict (StateT, evalStateT)+import Data.Bifunctor (bimap, first)+import qualified Data.ByteString as BS+import Data.Char (isAscii, isSpace, toLower, toUpper)+import Data.Foldable (for_)+import Data.Functor ((<&>))+import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef, writeIORef)+import Data.List (sortOn, uncons)+import Data.List.NonEmpty (NonEmpty (..))+import qualified Data.List.NonEmpty as NE+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (catMaybes, fromMaybe, mapMaybe, maybeToList)+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Text.Encoding.Error (lenientDecode)+import Data.Word (Word32)+import qualified Network.HTTP.Client as HTTP+import Nix.Builder.BuildDir (BuildEnding (..), FailedBuilds (..), WorkDir (..), buildDirFor, sandboxedBuildDir, withBuildDir, workDirIn)+import Nix.Builder.BuildUser (BuildUser, BuildUsers (NoBuildUsers), buGid, buUid, giveToBuildUser, invokingUserIds, killBuildUser, openStoreToBuildUsers, runAsBuildUser, runAsInvoker, withBuildUser, worldWritableAncestor, worldWritableMessage)+import Nix.Builder.Buildenv (builtinBuildenvBuilder, runBuiltinBuildenv)+import Nix.Builder.Job (dieOnUnhandledException)+import Nix.Builder.Log (openLogPipe, streamBuildLog)+import Nix.Builder.Sandbox (BuilderIds (..), DarwinOptions (..), DarwinPathInputs (..), DarwinPaths (..), DarwinPlan (..), DarwinProfile (..), HelperOutcome (..), Network, PathPresence (..), PlanInputs (..), SandboxBackend (..), SandboxConfig (..), SandboxFallback (..), SandboxPath (..), SandboxUse (..), backendFallback, chrootSkeleton, darwinOptions, darwinParameters, darwinPathsInSandbox, darwinProfile, darwinSetupFailureMessage, darwinStageName, defaultSandboxConfig, helperOutcome, hostSandboxBackend, renderDarwinPlan, renderPlan, rootRefusal, sandboxHome, sandboxPlan, sandboxUse, setupFailureMessage, setupStageName, unavailableMessage)+import Nix.Builder.Sandbox.Spawn (HelperRun (..), bytesFilePath, filePathBytes, processIsRoot, profileFilters, resolvedPath, runHelper, sandboxAvailability, sealChroot, warnFallback, withChroot)+import Nix.Builder.Unpack (UnpackLimits, builtinUnpackBuilder, defaultUnpackLimits, runBuiltinUnpack)+import Nix.Daemon.Protocol (ContentAddress, ContentAddressMethod (..), contentAddressFromParts)+import Nix.DependencyGraph (DepGraph, TopoResult (..), buildDepGraph, buildDepGraphFrom, topoSort)+import Nix.Derivation (Derivation (..), DerivationOutput (..), Platform, currentPlatform, extraPlatforms, fixedOutput, fromATerm, platformToText)+import Nix.Derivation.StructuredAttrs (decodeStructuredAttrs, renderAttrsJson, renderAttrsShell, stringsAttr, structuredAttrsKey, withOutputPlaceholders)+import Nix.Environment (EnvLookup (..), lookupEnvBytes)+import Nix.Hash (FileIngestionMethod (..), IncrementalHash, bytesToHexText, hashFinalizeBytes, hashInitWithAlgo, hashPlaceholder, hashUpdateChunk, hexToBytes, makeStorePath, rawHashWithAlgo, sha256Digest)+import Nix.Http (AttemptFailure (..), FetchRetryPolicy, attemptFailureMessage, catchSync, defaultFetchRetryPolicy, downloadUrlWith, ioRetryEffects, retryTransient)+import Nix.Logger (ActivityStart (..), Logger, logMessage, withActivity)+import Nix.Push (narHashMatches)+import Nix.Realise (BuildMode (..), CheckVerdict (..), ClosureOutcome, DifferingRebuild (..), FailedBuild (..), Fallback (..), FetchOutcome (..), MissingEffects (..), MissingPaths, Offer (..), RealiseEffects (..), RealiseSettings (..), Realised (..), Registration (..), RequestOutcome, SubstEffects (..), SubstitutesSetting (..), Undelivered (..), Wanted, checkedOutputPath, noWriteAccessMessage, planMissing, realise, realiseEach, realiseFailureMessage, realiseFailureStatus, realiseRequests, requestsFailureMessage, requestsFailureStatus, substituteClosure)+import Nix.Store (ArchiveEnd (..), CaseSensitivity, PathInfo (..), PathLock, PathRegistration (..), Store (..), Ultimate (..), UpstreamHazard (..), acquirePathLock, canonicalizeMetadata, finishNarUnpack, freshCopyPath, isValid, moveOutput, newNarUnpackSink, placeInStore, queryPathInfo, queryReferences, registerPaths, releasePathLock, replaceWithCopy, rewriteBytes, rewriteStoreHashes, scanReferences, sinkNarStream, upstreamManagedRefusal, volumeCaseHack)+import qualified Nix.Store.ExecBit as ExecBit+import Nix.Store.Metadata (OutputOwner (..), foreignOwnedNode, isPlainFile, ownedByAnother, writableByOthers)+import Nix.Store.Path (BadStorePath, StoreDir (..), StorePath (spHash, spName), defaultStoreDir, defaultStoreDirText, parseStorePath, parseStorePathPrefix, storePathToFilePath, storePathToText, unStoreDir)+import Nix.Store.Symlink (WalkNode (..), classifyWalkNode)+import Nix.Substituter (CacheConfig (ccUrl), CacheMemo, SubstResult (..), Substitute, emptyCacheMemo, fetchSubstituteWith, narStreamFailure, queryNextOfferWith, queryReferencesWith, substituteCache, substitutePath, substituteSizes, withXzAttempt)+import qualified NovaCache.Base32 as Nix32+import qualified NovaCache.Hash as Hash+import qualified NovaCache.NAR as NAR+import qualified NovaCache.Xz as Xz+import System.Directory (createDirectoryIfMissing, removePathForcibly)+import qualified System.Environment+import System.Exit (ExitCode (..))+import System.FilePath (isAbsolute, isPathSeparator, takeDirectory, takeFileName, (</>))+import qualified System.IO+import qualified System.Info+import qualified System.Process as Proc++-- ---------------------------------------------------------------------------+-- Named constants+-- ---------------------------------------------------------------------------++-- | Environment variable for the build top directory.+envNixBuildTop :: Text+envNixBuildTop = "NIX_BUILD_TOP"++-- | The four temp-directory names, every one pointed at the build+-- directory, matching upstream's single assignment of all four.  Tools+-- disagree about which one they read (POSIX tools take @TMPDIR@, msys+-- reads @TMPDIR@ and @TMP@, native Windows tools take @TMP@ then+-- @TEMP@), and a scrubbed environment that repoints only one leaves+-- the others to fall back to a directory the build cannot own - on+-- Windows, GetTempPath bottoms out at the Windows directory itself.+envTmpDir, envTempDir, envTmp, envTemp :: Text+envTmpDir = "TMPDIR"+envTempDir = "TEMPDIR"+envTmp = "TMP"+envTemp = "TEMP"++-- | Environment variable for the Nix store path.+envNixStore :: Text+envNixStore = "NIX_STORE"++-- | Environment variable for the cores a builder may use ('bcCores').+envNixBuildCores :: Text+envNixBuildCores = "NIX_BUILD_CORES"++-- | Ambient variables a Windows builder may inherit, by uppercase-folded+-- name.  SystemRoot is a hard execution requirement - the CLR's crypto+-- provider fails to load without it (verified live on a clean Windows 11+-- box), while plain Win32 binaries merely tolerate its absence - and+-- SystemDrive and windir are the aliases some tools consult instead of it.+windowsAmbientAllowlist :: [Text]+windowsAmbientAllowlist = [systemRootKey, "SYSTEMDRIVE", "WINDIR"]++-- | The folded name 'scrubAmbient' derives COMSPEC from.+systemRootKey :: Text+systemRootKey = "SYSTEMROOT"++-- | The command interpreter variable, synthesized from SystemRoot rather+-- than inherited: programs shelling out through the C runtime's+-- @system()@ read it from the block.+envComspec :: Text+envComspec = "COMSPEC"++-- | Executable-extension resolution, pinned instead of inherited so name+-- resolution does not drift with host configuration.  cmd.exe's own+-- built-in default when the variable is absent adds @.VBS;.JS;.WS;.MSC@;+-- a build has no business resolving those implicitly.+envPathext, pathextValue :: Text+envPathext = "PATHEXT"+pathextValue = ".COM;.EXE;.BAT;.CMD"++-- | Environment variable for PATH.+envPath :: Text+envPath = "PATH"++-- | A Unix build's @PATH@ unless the derivation sets one: upstream's+-- value, which names no directory there is, so the builder finds no+-- program its derivation does not name, and a shell does not fall back+-- to a search path of its own as it would were @PATH@ unset.+pathNotSet :: Text+pathNotSet = "/path-not-set"++-- | The system's directories a Windows build's @PATH@ ends with, where+-- @cmd.exe@ and the programs a job needs are.+windowsSystemDirs :: [FilePath]+windowsSystemDirs = ["C:\\Windows\\System32", "C:\\Windows"]++-- | The magic builder string for the built-in URL fetcher.  A derivation with+-- this builder is not executed as a process - the Builder downloads its @url@+-- and verifies it against @outputHash@ (see 'runBuiltinFetchurl').+-- Bytes, matching the 'drvBuilder' field it is compared against.+builtinFetchurlBuilder :: BS.ByteString+builtinFetchurlBuilder = "builtin:fetchurl"++-- | What every builtin builder's name starts with, which is how upstream+-- tells a builtin from a program.+builtinPrefix :: BS.ByteString+builtinPrefix = "builtin:"++-- | Derivation environment keys read by @builtin:fetchurl@.+envUrl, envUrls, envOut, envUnpack, envExecutable :: Text+envUrl = "url"+envUrls = "urls"+envOut = "out"+envUnpack = "unpack"+envExecutable = "executable"++-- | The value a derivation attribute set to @true@ has in the+-- environment, and the one upstream's @builtin:fetchurl@ compares+-- @unpack@ and @executable@ with (@builtinFetchurl@ in fetchurl.cc).+envTrue :: BS.ByteString+envTrue = "1"++-- | The URL suffix that marks the NAR @builtin:fetchurl@ restores as+-- xz-compressed (@builtinFetchurl@ in fetchurl.cc).+xzUrlSuffix :: Text+xzUrlSuffix = ".xz"++-- | Environment variable for the reproducible-builds.org build timestamp.+envSourceDateEpoch :: Text+envSourceDateEpoch = "SOURCE_DATE_EPOCH"++-- | The derivation attribute naming ambient variables a fixed-output+-- build may read, upstream's carve-out for fetchers that need proxies.+envImpureEnvVars :: Text+envImpureEnvVars = "impureEnvVars"++-- | The variables naming a structured derivation's two attribute files.+envNixAttrsJsonFile, envNixAttrsShFile :: Text+envNixAttrsJsonFile = "NIX_ATTRS_JSON_FILE"+envNixAttrsShFile = "NIX_ATTRS_SH_FILE"++-- | Where in the build directory a structured derivation's attributes+-- land, under upstream's names.+attrsJsonFileName, attrsShellFileName :: FilePath+attrsJsonFileName = ".attrs.json"+attrsShellFileName = ".attrs.sh"++-- | The attribute listing the attributes a derivation passes as files.+envPassAsFile :: Text+envPassAsFile = "passAsFile"++-- | What upstream adds to an attribute's name to name the variable holding+-- the path of its file, and what it puts before the hash of that name to+-- name the file.+passedFileVarSuffix, passedFilePrefix :: Text+passedFileVarSuffix = "Path"+passedFilePrefix = ".attr-"++-- | The bytes upstream's @tokenizeString@ splits a list attribute at by+-- default (@src\/libutil\/util.hh@ at 2.24.9).  Not 'isSpace': a form feed,+-- a vertical tab or a non-ASCII space does not separate there.+tokenSeparators :: BS.ByteString+tokenSeparators = " \t\n\r"++-- | The fixed build timestamp handed to every builder: 1980-01-01 UTC.+-- Determinism-aware tools (binutils @ld@ writes it into the PE header+-- instead of the wall clock; gcc uses it for @__DATE__@\/@__TIME__@)+-- produce identical output across builds.  1980 rather than 0 because+-- zip timestamps cannot represent dates before 1980 - the same value+-- nixpkgs' stdenv uses.  A derivation env may override it.+sourceDateEpochValue :: Text+sourceDateEpochValue = "315532800"++-- ---------------------------------------------------------------------------+-- Configuration+-- ---------------------------------------------------------------------------++-- | Configuration for the build environment.+data BuildConfig = BuildConfig+  { -- | Store directory: where outputs go, and under whose state+    -- directory a build runs ("Nix.Builder.BuildDir").+    bcStoreDir :: !StoreDir,+    -- | Binary caches to try before building (checked in priority order).+    bcCaches :: ![CacheConfig],+    -- | What a failed substitute leads to: upstream's @fallback@.+    bcFallback :: !Fallback,+    -- | Whether a derivation's @allowSubstitutes@ attribute is heeded:+    -- upstream's @always-allow-substitutes@.+    bcSubstitutes :: !SubstitutesSetting,+    -- | Whether a substitute may be fetched and written to the store.+    bcSubstitution :: !SubstitutionAccess,+    -- | What 'buildWithDeps' does with the derivation it is given:+    -- upstream's build mode, which @nix-build --check@ sets.  Nothing+    -- else reads it, and 'buildDerivation' never checks.+    bcMode :: !BuildMode,+    -- | What a builder's @NIX_BUILD_CORES@ says, passed on as it is: the+    -- count upstream's @cores@ gives once a 0 has become the machine's+    -- default, which settings do when they make this configuration.  Where+    -- a derivation's attributes reach the environment, which they do not+    -- under @__structuredAttrs@, an attribute of that name wins, as+    -- upstream sets the variable before it copies the derivation's+    -- environment.+    bcCores :: !Word32,+    -- | Extraction budget for @builtin:unpack@ builds.+    bcUnpackLimits :: !UnpackLimits,+    -- | How a download is retried: each URL of a @builtin:fetchurl@+    -- before the next is tried, and each narinfo and NAR the substituter+    -- requests, as upstream's one @download-attempts@ setting governs+    -- every transfer.+    bcFetchRetry :: !FetchRetryPolicy,+    -- | Launchers for derivations whose @system@ this machine cannot execute+    -- directly, keyed by that system string exactly as+    -- 'Nix.Derivation.platformToText' spells it (@x86_64-windows@ -> a wine+    -- binary). Prepended to the builder at the spawn boundary only, so the+    -- derivation itself - and its store paths - stay identical to a native+    -- build's. A foreign system with no entry here is refused rather than+    -- spawned natively; see 'execWrapperFor'.+    bcExecWrappers :: !(Map Text FilePath),+    -- | Whether, and how, a spawned builder runs in a sandbox+    -- ("Nix.Builder.Sandbox").+    bcSandbox :: !SandboxConfig,+    -- | Whom a spawned builder runs as: a build user, upstream's for a+    -- process that runs as root with @build-users-group@ set, or the user+    -- nova-nix runs as ("Nix.Builder.BuildUser").  A builtin runs in this+    -- process, as that user, whatever it says.+    bcBuildUsers :: !BuildUsers,+    -- | What a build that does not succeed leaves, upstream's+    -- @keep-failed@: its directory ("Nix.Builder.BuildDir"), unless its+    -- builder is a builtin, and for a check that found an output+    -- different, the rebuild of that output ('checkDerivation').+    bcFailedBuilds :: !FailedBuilds+  }+  deriving (Eq, Show)++-- | Whether a build may substitute what it needs.+data SubstitutionAccess+  = -- | It fetches a substitute from 'bcCaches' and registers what+    -- arrives.+    SubstituteFromCaches+  | -- | It refuses each substitution before any cache is asked, as+    -- upstream's substitution goal refuses one in a read-only evaluation+    -- ('Nix.Realise.noWriteAccessMessage').  An output that may not be+    -- substituted is still built, as upstream builds one there: nothing+    -- on its build path checks for read-only mode+    -- (@DerivationGoal::haveDerivation@ in derivation-goal.cc).+    RefuseSubstitution+  deriving (Eq, Show)++-- | Default build configuration.  A builder is told of one core+-- ('baselineCores'), where upstream's default is the CPU limit of the+-- process's cgroup on Linux, otherwise the machine's count, which takes+-- IO to find ("Nix.Builder.Cores"), and runs unsandboxed+-- ('defaultSandboxConfig'), where upstream sandboxes on Linux, since+-- finding the sandbox's helper takes IO too.  It builds as the user+-- nova-nix runs as, where upstream builds as a build user for root, since+-- whether this process is root takes IO to find.  A build that fails+-- keeps nothing, as upstream's @keep-failed@ defaults off.+defaultBuildConfig :: StoreDir -> BuildConfig+defaultBuildConfig dir =+  BuildConfig+    { bcStoreDir = dir,+      bcCaches = [],+      bcFallback = NoFallback,+      bcSubstitutes = HeedAllowSubstitutes,+      bcSubstitution = SubstituteFromCaches,+      bcMode = BuildNormal,+      bcCores = baselineCores,+      bcExecWrappers = Map.empty,+      bcUnpackLimits = defaultUnpackLimits,+      bcFetchRetry = defaultFetchRetryPolicy,+      bcSandbox = defaultSandboxConfig,+      bcBuildUsers = NoBuildUsers,+      bcFailedBuilds = RemoveFailed+    }++-- | The cores 'defaultBuildConfig' tells a builder of: one, which is what+-- nixpkgs' setup.sh takes an unset @NIX_BUILD_CORES@ to mean.+baselineCores :: Word32+baselineCores = 1++-- | Result of a build attempt.+data BuildResult+  = -- | Build succeeded. Output registered at this store path.+    BuildSuccess !StorePath+  | -- | Build failed with an error message and exit code.+    BuildFailure !Text !Int+  deriving (Eq, Show)++-- ---------------------------------------------------------------------------+-- Build loop+-- ---------------------------------------------------------------------------++-- | Build a derivation, given its @.drv@ path, which names it in a failure+-- as upstream's do: run its builder and capture output.+--+-- 1. Validate all inputs exist in the store+-- 2. Decide how the builder runs, refusing a sandbox that cannot be had+-- 3. Create the build directory ('withBuildDir')+-- 4. Set up environment from derivation + standard vars+-- 5. Run the builder process, which writes each output at its store path,+--    or at a scratch path for one already valid; a Linux sandboxed build+--    writes them beneath its chroot until they are registered+-- 6. On success: scan the outputs for references and register them,+--    failing on a reference cycle between them ('registerOutputs')+-- 7. On failure: clean up and report error, keeping the build directory+--    under 'KeepFailed' ('failedBuildsFor')+-- 8. Exception safety: synchronous exceptions convert to BuildFailure;+--    asynchronous exceptions propagate ('catchSync') - an interrupt+--    must abort the build, never be reported as a build failure.+--+-- A store upstream Nix's database may also manage fails the build before+-- any of this ("Nix.Store.Upstream").+buildDerivation :: BuildConfig -> Store -> Derivation -> StorePath -> IO BuildResult+buildDerivation config store drv drvPath =+  either stoppedResult BuildSuccess <$> buildOutputs config store drv drvPath++-- | Why a build stopped short of what it was for.+data BuildStop+  = -- | With the message and exit code a 'BuildFailure' reports.+    BuildStop !Text !Int+  | -- | A fixed-output derivation's output was refused, having other+    -- contents than the derivation fixes or referencing a store path,+    -- with the message: upstream's @HashMismatch@.  It exits as a build+    -- that stops otherwise does ('stopReported').+    FixedOutputRefused !Text+  deriving (Eq, Show)++-- | The message and exit code a stopped build reports.+stopReported :: BuildStop -> (Text, Int)+stopReported = \case+  BuildStop message code -> (message, code)+  FixedOutputRefused message -> (message, refusedOutputStatus)++-- | The exit code of a build whose fixed output was refused, as of one+-- that stops any other way.+refusedOutputStatus :: Int+refusedOutputStatus = 1++-- | The build result a stopped build reports.+stoppedResult :: BuildStop -> BuildResult+stoppedResult = uncurry BuildFailure . stopReported++-- | A build's synchronous exception as the stop it reports.  An+-- asynchronous one propagates ('catchSync').+stoppingOnException :: IO (Either BuildStop a) -> IO (Either BuildStop a)+stoppingOnException build =+  build `catchSync` \err -> pure (Left (BuildStop ("build exception: " <> T.pack (show err)) 1))++-- | Build under the outputs' path locks, and answer the first output's+-- path.  A derivation another process finished while we waited for them is+-- adopted rather than redone: rebuilding would delete a registered path+-- out from under whoever is already using it, which is why substitution+-- adopts a finished path too.+buildOutputs :: BuildConfig -> Store -> Derivation -> StorePath -> IO (Either BuildStop StorePath)+buildOutputs config store drv drvPath =+  stoppingOnException $+    withOutputLocks config store drv (maybe build (pure . Right))+  where+    build = buildUnderLock config store drvPath drv RedirectValid (const BuildSucceeded) (registerOutputs store drv drvPath)++-- | Check a derivation, given its @.drv@ path: build it again beside its+-- valid outputs and compare what comes out with what the store holds.+-- This is the build upstream runs under @bmCheck@, without what comes+-- before it: "Nix.Realise" substitutes an output that is not valid and+-- realises the inputs, and 'buildWithDeps' under 'BuildCheck' does both.+--+-- The rebuild registers nothing and leaves the outputs as they are.  It+-- keeps nothing it wrote, but under 'KeepFailed' the rebuild of the first+-- output that differs, which it moves to the output's path with @.check@+-- after it ('checkedOutputPath'), removing what was there, as upstream+-- does.  The verdict says which ('DifferingRebuild').  'Left' is why+-- there was no comparison to answer with, naming the derivation as+-- 'buildWithDeps' names one that failed to build: the rebuild failed (an+-- input missing, its builder failing, or what it wrote refused: an output+-- missing or open to other users, a cycle between outputs, a fixed+-- output's wrong hash); the derivation has no output, or one is not+-- valid, so there is nothing to compare a rebuild with; or the store is+-- one upstream Nix's database may also manage, refused before anything+-- is touched ("Nix.Store.Upstream").+checkDerivation :: BuildConfig -> Store -> Derivation -> StorePath -> IO (Either Text CheckVerdict)+checkDerivation config store drv drvPath =+  first (stopReport drv) <$> checkOutputs config store drv drvPath++-- | 'checkDerivation', under the outputs' path locks, which upstream holds+-- through a check as through any build (@DerivationGoal::tryToBuild@ at+-- 2.24.9).  The builder writes every output to a scratch path+-- ('RedirectAll'), so the store's copies stay as they are, and what it+-- wrote is gone when this returns, but for a rebuild 'KeepFailed' keeps.+--+-- What a check compares with is each output's registration, so that is+-- what it asks for once the locks are held, and it is the one place that+-- decides whether the outputs are valid: the rebuild that follows is+-- handed the recorded hashes and asks the database nothing more.  An+-- output with no registration fails the check with upstream's message for+-- that state.  Upstream reaches it after running the builder+-- (@assertPathValidity@); the builder's work could only replace that+-- failure with another, so it is not run.+checkOutputs :: BuildConfig -> Store -> Derivation -> StorePath -> IO (Either BuildStop CheckVerdict)+checkOutputs config store drv drvPath =+  stoppingOnException $+    withOutputLocks config store drv (const compareUnderLock)+  where+    compareUnderLock = do+      recorded <- traverse (queryPathInfo (stDB store) . doPath) (drvOutputs drv)+      case sequence recorded of+        Nothing -> pure (Left (BuildStop unexpectedlyInvalidMessage 1))+        -- A check that compared nothing has not passed.+        Just [] -> pure (Left (BuildStop noOutputsMessage 1))+        Just registrations ->+          buildUnderLock config store drvPath drv RedirectAll verdictEnding (compareOutputs (bcFailedBuilds config) store drv drvPath (map piNarHash registrations))++-- | How a check ended: one that found an output different failed, as+-- upstream's does, so it keeps the build's directory under @keep-failed@+-- as any failure does.+verdictEnding :: CheckVerdict -> BuildEnding+verdictEnding verdict = case verdict of+  OutputsMatch -> BuildSucceeded+  OutputDiffers _ _ -> BuildFailed++-- | Upstream's failure for a check that finds an output it was to compare+-- with not valid (@DerivationGoal::assertPathValidity@, derivation-goal.cc+-- at 2.24.9).+unexpectedlyInvalidMessage :: Text+unexpectedlyInvalidMessage = "some outputs are unexpectedly invalid"++-- | The failure for a derivation that defines no output.+noOutputsMessage :: Text+noOutputsMessage = "no outputs defined"++-- | Hold every output's path lock for the whole build, and report+-- whether the derivation was already finished by the time they were+-- granted.+--+-- Delete, materialize and register are one critical section under+-- @\<store-path\>.lock@, and the build path joins it.  Without it, two+-- concurrent builds of one derivation would write one output path,+-- interleave their writes into a single tree, and each register it as+-- valid.  Nothing would fail; the registered output would simply not be+-- what either build produced.  The first output's lock is also what+-- keeps a build directory's name to one build at a time+-- ("Nix.Builder.BuildDir").+--+-- Outputs are locked in 'lockOrder', so two processes racing the same+-- multi-output derivation request them in the same sequence and neither+-- can hold a lock the other needs while waiting on one it holds.  A+-- build holds locks for its own outputs only - dependencies are+-- resolved before 'buildDerivation' is called, never underneath it - so+-- that sequence is the only one there is to agree on.+--+-- The validity re-check happens under the locks, not before them:+-- checked earlier it would answer about a moment that has already+-- passed by the time the build starts.+--+-- A store upstream Nix's database may also manage is refused before any+-- lock is taken ("Nix.Store.Upstream"): a build clears each output path+-- with no row here, and a path upstream registered has none.+withOutputLocks :: BuildConfig -> Store -> Derivation -> (Maybe StorePath -> IO (Either BuildStop a)) -> IO (Either BuildStop a)+withOutputLocks config store drv act = do+  refusal <- upstreamManagedRefusal ReplacesUpstreamPaths (bcStoreDir config)+  maybe locked (\reason -> pure (Left (BuildStop reason 1))) refusal+  where+    locked = do+      heldLocks <- newIORef []+      let takeLock sp = do+            lock <- acquirePathLock (stLogger store) (bcStoreDir config) sp+            atomicModifyIORef' heldLocks (\locks -> (lock : locks, ()))+      ( do+          mapM_ takeLock (lockOrder id (map doPath (drvOutputs drv)))+          finishedElsewhere <- allOutputsValid store drv+          act finishedElsewhere+        )+        `finally` (readIORef heldLocks >>= mapM_ releasePathLock)++-- | The order a process takes more than one path lock in.  Substitution+-- holds each lock until its batch registers, and a build until it finishes,+-- so both have to use this order: the blocking lock has no timeout, and two+-- processes taking the same paths in different orders would wait forever.+lockOrder :: (a -> StorePath) -> [a] -> [a]+lockOrder = sortOn++-- | The derivation's first output path when EVERY output is already+-- registered, otherwise 'Nothing'.+--+-- Every output, never just the first: a partially valid multi-output+-- derivation still has to build, and treating it as finished would leave+-- the missing outputs missing.  This is the re-check under the output+-- locks.  A build reaches it once some output a request wanted was not+-- valid, and upstream's re-check there asks about the wanted outputs+-- alone (@DerivationGoal::tryToBuild@ at 2.24.9), so where another+-- process made those valid during the wait, upstream adopts the+-- derivation and this builds it.+allOutputsValid :: Store -> Derivation -> IO (Maybe StorePath)+allOutputsValid store drv = case map doPath (drvOutputs drv) of+  [] -> pure Nothing+  outputPaths@(firstOutput : _) -> do+    validity <- mapM (isValid store) outputPaths+    pure (if and validity then Just firstOutput else Nothing)++-- | What a build does with the outputs its builder wrote, given the+-- closure of its inputs, where each output was written, and where each is+-- on disk once its builder has ended: registers them ('registerOutputs'),+-- or compares them with the store's ('compareOutputs').+type Finish a = Set StorePath -> [OutputPlan] -> Written -> Commit -> IO (Either BuildStop a)++-- | How a build runs the step that registers its outputs: with the record+-- that they are registered, which keeps the cleanup of an interrupted+-- build from removing them, made in the same step, which no asynchronous+-- exception can break into.+type Commit = IO () -> IO ()++-- | What a build's builder left: where each output is on disk once it has+-- ended, at its scratch path in the store, or for a Linux sandboxed build+-- at that path in the chroot, where it stays until it is registered;+-- whether the builder left an output writable by its group or anyone else+-- ('writableByOthers'), read for a Linux sandboxed build before the+-- chroot's seal changes the mode ('sealChroot'); and whom every node of an+-- output must belong to, the user the builder ran as.+data Written = Written+  { writtenPath :: OutputPlan -> FilePath,+    writtenOpen :: OutputPlan -> IO Bool,+    writtenOwner :: !OutputOwner+  }++-- | Whom a build's builder runs as.+data BuilderIdentity+  = -- | The user nova-nix runs as.+    AsInvoker+  | -- | A build user, held for the build.+    AsBuildUser !BuildUser++-- | The build user a builder runs as, if it runs as one.+buildUserOf :: BuilderIdentity -> Maybe BuildUser+buildUserOf identity = case identity of+  AsInvoker -> Nothing+  AsBuildUser user -> Just user++-- | Whom a builder's outputs belong to while it writes them.+outputOwnerOf :: BuilderIdentity -> OutputOwner+outputOwnerOf identity = case identity of+  AsInvoker -> OwnedByInvoker+  AsBuildUser user -> OwnedByBuildUser (buUid user)++-- | Which outputs the builder is handed a scratch path for+-- ('outputPlan').+data Redirected+  = -- | Those that are valid, which a build has to leave as they are.+    RedirectValid+  | -- | Every one.  A check's outputs are all valid: 'checkOutputs' has+    -- their registrations in hand, under the locks this runs under.+    RedirectAll++-- | The build itself, of the derivation at a @.drv@ path, with every+-- output's lock already held, given how its result says it ended, which+-- decides whether a build directory is kept ("Nix.Builder.BuildDir").+buildUnderLock :: BuildConfig -> Store -> StorePath -> Derivation -> Redirected -> (a -> BuildEnding) -> Finish a -> IO (Either BuildStop a)+buildUnderLock config store drvPath drv redirected succeeded finish = runExceptT $ do+  -- 1. Validate inputs (sources + input-derivation outputs) exist, and+  --    take their closure: what an output may reference besides the+  --    derivation's own outputs.+  inputPaths <- withExceptT stopped (ExceptT (validateInputs config store drv >>= either (pure . Left) (inputClosure store)))+  -- The build directory is named by the first output, whose lock keeps+  -- it to one build at a time.  A derivation with no output has no lock+  -- to name one by, and its build fails whatever its builder does+  -- ('registerOutputs'), so it fails here, before a directory is made or+  -- a builder runs.+  firstOutput <- case drvOutputs drv of+    [] -> throwError (stopped noOutputsMessage)+    output : _ -> pure output+  -- 2. Compute output paths (but do NOT pre-create them - the builder is+  --    responsible for creating $out, $dev, etc.).+  --+  --    $out is the final store path, as upstream's is: a temporary path+  --    recorded by the build (a compiler driver, a libtool archive) would+  --    outlive the directory it named.+  outputValidity <- liftIO $ case redirected of+    RedirectValid -> mapM (isValid store . doPath) (drvOutputs drv)+    RedirectAll -> pure (map (const True) (drvOutputs drv))+  plans <- liftEither (first (\nameErr -> stopped ("output name is not a store path name: " <> T.pack (show nameErr))) (traverse outputPlan (zip (drvOutputs drv) outputValidity)))+  -- 3. Decide how the builder runs, which says where in the build+  --    directory it works, refusing a sandbox that cannot be had before+  --    a directory is made, as upstream refuses one before it makes its+  --    own.+  let context = BuildContext store drvPath inputPaths+  run <- withExceptT stopped (ExceptT (builderRunFor config context drv))+  -- 4. Take the build user the builder runs as, if it runs as one+  --    ('asBuilder'), then create the build directory, empty, the+  --    directory the builder works in that user's, and remove it however+  --    the build ends, unless it failed and keeps it ('failedBuildsFor').+  ExceptT $+    asBuilder config context run (takeDirectory (buildDirFor (bcStoreDir config) (doPath firstOutput))) $ \identity ->+      withBuildDir (stLogger store) (bcStoreDir config) (doPath firstOutput) (runWorkDir run) (failedBuildsFor config drv) (either (const BuildFailed) succeeded) $ \buildDir -> do+        for_ (buildUserOf identity) (\user -> giveToBuildUser user (workDirIn (runWorkDir run) buildDir))+        runPlannedBuild config context drv run identity buildDir plans (finish inputPaths plans)+  where+    stopped reason = BuildStop reason 1++-- | Run a build as whom its builder runs as, given the directory that+-- holds build directories: for a spawned builder under build users, a build+-- user taken for the build ('withBuildUser'), as upstream takes one, with+-- every process the user has killed first ('killBuildUser'), the store's+-- directory opened to the build users ('openStoreToBuildUsers'), and the+-- directory holding builds made and refused when it or an ancestor is one+-- every user may write ('worldWritableAncestor'); otherwise the user+-- nova-nix runs as, who runs every builtin.+asBuilder :: BuildConfig -> BuildContext -> BuilderRun -> FilePath -> (BuilderIdentity -> IO (Either BuildStop a)) -> IO (Either BuildStop a)+asBuilder config context run buildsDir action = case run of+  RunsBuiltin _ -> action AsInvoker+  RunsSpawned _ -> do+    taken <- withBuildUser (buildLogger context) (bcBuildUsers config) (storePathToText defaultStoreDir (bxDrvPath context)) (maybe (action AsInvoker) asUser)+    pure (either (Left . stopped) id taken)+  where+    stopped reason = BuildStop reason 1+    asUser user = runExceptT $ do+      ExceptT (first stopped <$> killBuildUser user)+      liftIO (openStoreToBuildUsers (unStoreDir (bcStoreDir config)) user)+      liftIO (createDirectoryIfMissing True buildsDir)+      writable <- liftIO (worldWritableAncestor buildsDir)+      for_ writable (throwError . stopped . worldWritableMessage)+      ExceptT (action (AsBuildUser user))++-- | What a build that does not succeed leaves of its directory: what+-- 'bcFailedBuilds' says, unless its builder is a builtin, of which+-- upstream keeps nothing, since one might hold privileged files, such as+-- a copy of netrc.  A builtin is a builder named with upstream's prefix+-- ('builtinPrefix'), whether or not nova-nix runs it.+failedBuildsFor :: BuildConfig -> Derivation -> FailedBuilds+failedBuildsFor config drv+  | builtinPrefix `BS.isPrefixOf` drvBuilder drv = RemoveFailed+  | otherwise = bcFailedBuilds config++-- | How a derivation's builder runs, decided before its build directory+-- is made.+data BuilderRun+  = -- | In this process, a builtin, given where each output, by name, is+    -- on disk.+    RunsBuiltin !([(Text, FilePath)] -> IO (Either (Int, Text) ()))+  | -- | Spawned, where 'placementFor' put it.+    RunsSpawned !Placement++-- | Where a spawned builder runs.+data Placement+  = -- | Where its directory and outputs are, with no sandbox.+    PlacedUnsandboxed+  | -- | In the Linux sandbox, through this helper, on this network.+    PlacedInLinuxSandbox !FilePath !Network+  | -- | Under macOS's sandbox profile, through this helper, on this+    -- network.+    PlacedInDarwinSandbox !FilePath !Network++-- | The builtins nova-nix runs in this process, and every other builder+-- spawned where 'placementFor' puts it.  'Left' is why it cannot run.+-- @builtin:fetchurl@ restores a NAR's names under the store volume's case+-- sensitivity.+builderRunFor :: BuildConfig -> BuildContext -> Derivation -> IO (Either Text BuilderRun)+builderRunFor config context drv = case drvBuilder drv of+  b+    | b == builtinFetchurlBuilder -> builtin (runBuiltinFetchurl (buildLogger context) (bcFetchRetry config) (stCaseSensitivity (bxStore context)) drv)+    | b == builtinUnpackBuilder -> builtin (runBuiltinUnpack (bcStoreDir config) (bcUnpackLimits config) drv)+    | b == builtinBuildenvBuilder -> builtin (runBuiltinBuildenv (buildLogger context) (bcStoreDir config) drv)+  _ -> fmap RunsSpawned <$> placementFor config context drv+  where+    builtin = pure . Right . RunsBuiltin++-- | Where in its build directory a builder works: a builder in the Linux+-- sandbox in the directory inside it that the sandbox shows at+-- @sandbox-build-dir@ ('Nix.Builder.BuildDir.sandboxedBuildDir'), as+-- upstream's Linux sandbox does, and every other in the directory itself.+runWorkDir :: BuilderRun -> WorkDir+runWorkDir run = case run of+  RunsSpawned (PlacedInLinuxSandbox _ _) -> WorksInSandboxedBuildDir+  RunsSpawned (PlacedInDarwinSandbox _ _) -> WorksInBuildDir+  RunsSpawned PlacedUnsandboxed -> WorksInBuildDir+  RunsBuiltin _ -> WorksInBuildDir++-- | Where the builder writes each output, and where that has to end up.+--+-- The two coincide for an output being built: writing into the final store+-- path is what this whole arrangement is for.  They differ for an output+-- that is already valid, which the builder is still handed (a package with+-- a @dev@ output has one builder writing both) but which must not be+-- touched: it is registered, its @NarHash@ describes its current bytes,+-- and 'placeInStore' has already sealed it read-only.  A check builds a+-- derivation whose outputs are all valid, so there every output is written+-- to a scratch path, as upstream writes a valid output wherever it builds+-- outside a Linux chroot (@startBuilder@ in local-derivation-goal.cc at+-- 2.24.9, @startBuild@ in unix-derivation-builder.cc at 2.36.0).+-- nova-nix's sandbox writes one to a scratch path too, where upstream's+-- chroot leaves the output's own path free (@needsHashRewrite@, in+-- local-derivation-goal.cc at 2.24.9 and chroot-derivation-builder.hh at+-- 2.36.0).+data OutputPlan = OutputPlan+  { -- | The derivation output's name, as it reaches the environment.+    opName :: !Text,+    -- | Where the output has to be when the build is done.+    opFinal :: !StorePath,+    -- | Where the builder is told to write.+    opScratch :: !StorePath,+    -- | Whether 'opFinal' is already registered, and so must survive.+    opValid :: !Bool+  }++-- | Plan one output, given whether its final path is already valid.+outputPlan :: (DerivationOutput, Bool) -> Either BadStorePath OutputPlan+outputPlan (out, valid)+  | not valid = Right (OutputPlan (doName out) (doPath out) (doPath out) False)+  | otherwise = do+      fallback <- fallbackOutputPath (doPath out)+      pure (OutputPlan (doName out) (doPath out) fallback True)++-- | A scratch store path for an output that must not be written to, built+-- so it cannot collide with any real store path.+--+-- Upstream's @makeFallbackPath@ (the @StorePath@ overload, in+-- @src/libstore/unix/build/local-derivation-goal.cc@ at 2.24.9) with the+-- same shape: a bogus @rewrite:@ path type and an all-zeroes inner hash,+-- keyed on the output path it stands in for.+-- Upstream's type string also names the @.drv@ path+-- (@rewrite:\<drv\>:\<path\>@), so the scratch path a builder sees differs+-- from upstream's.  The output path already names one output of one+-- derivation, so the result is just as unique.+fallbackOutputPath :: StorePath -> Either BadStorePath StorePath+fallbackOutputPath sp =+  makeStorePath+    defaultStoreDir+    ("rewrite:" <> spHash sp <> "-" <> spName sp)+    (BS.replicate 32 0)+    (spName sp)++-- | Parse @--exec-wrapper SYSTEM=PATH@ specs into the map 'bcExecWrappers'+-- wants.+--+-- @SYSTEM@ is a derivation's own @system@ string, spelled as+-- 'Nix.Derivation.platformToText' spells it, because 'execWrapperFor'+-- matches it by equality and nothing else.+--+-- A system named twice is an error rather than last-one-wins: two specs for+-- one system is a mistake in the invocation either way, and silently+-- picking one of them means a build runs through a launcher the operator+-- did not think they had asked for.+execWrapperConfig :: [String] -> Either Text (Map Text FilePath)+execWrapperConfig = foldl' step (Right Map.empty)+  where+    step acc spec = do+      wrappers <- acc+      (system, path) <- one spec+      if Map.member system wrappers+        then Left ("--exec-wrapper names " <> system <> " twice")+        else Right (Map.insert system path wrappers)+    one spec = case break (== '=') spec of+      (system, '=' : path)+        | not (null system), not (null path) -> Right (T.pack system, path)+      _ -> Left ("--exec-wrapper expects SYSTEM=PATH, got: " <> T.pack spec)++-- | How this machine can spawn a derivation's builder.+data BuilderSpawn+  = -- | The derivation targets this machine's platform, or one it executes+    -- as well ('extraPlatforms'); spawn it directly.+    SpawnNative+  | -- | Spawn through this launcher, named for the derivation's system.+    SpawnThrough !FilePath+  | -- | Nothing here can execute this derivation's builder; the payload is+    -- the system string that has no launcher.+    SpawnUnsupported !Text+  deriving (Eq, Show)++-- | How to spawn this derivation's builder on this machine.+--+-- \"This is my platform\" and \"I have no launcher for this platform\" are+-- different answers: collapsing them to \"spawn directly\" runs a foreign+-- builder natively and reports whatever the loader says, after the whole+-- closure has already been realized. A system this machine cannot execute+-- and has not been told how to is refused instead.+execWrapperFor :: BuildConfig -> Derivation -> BuilderSpawn+execWrapperFor = spawnFor currentPlatform++-- | 'execWrapperFor' with the host named, so the rule can be checked for+-- every host on whichever one runs the suite.  A derivation for the host's+-- own system, or for one the host executes through its compatibility layer+-- ('extraPlatforms'), spawns directly whatever launchers are configured:+-- upstream runs its extra platforms natively and has no launcher notion.+spawnFor :: Platform -> BuildConfig -> Derivation -> BuilderSpawn+spawnFor host config drv+  | platform == host || platform `elem` extraPlatforms host = SpawnNative+  | otherwise = case Map.lookup system (bcExecWrappers config) of+      Just launcher -> SpawnThrough launcher+      Nothing -> SpawnUnsupported system+  where+    platform = drvPlatform drv+    system = platformToText platform++-- | What a build knows besides its configuration and derivation: the+-- store, the @.drv@ path, and the closure of its inputs.+data BuildContext = BuildContext+  { bxStore :: !Store,+    bxDrvPath :: !StorePath,+    bxInputs :: !(Set StorePath)+  }++-- | Where a build reports: its store's logger.+buildLogger :: BuildContext -> Logger+buildLogger = stLogger . bxStore++-- | The build, once every output knows where it is written and where it+-- belongs and the builder where it runs: run the builder, then @finish@+-- with where each output it wrote is now.+runPlannedBuild :: BuildConfig -> BuildContext -> Derivation -> BuilderRun -> BuilderIdentity -> FilePath -> [OutputPlan] -> (Written -> Commit -> IO (Either BuildStop a)) -> IO (Either BuildStop a)+runPlannedBuild config context drv run identity buildDir plans finish = do+  let scratchDir = scratchPathOf config+      outputDirs = [(opName p, scratchDir p) | p <- plans]+      -- Every scratch path is the build's to use: the ones that are final+      -- paths may hold a tree an interrupted run left behind, and the+      -- fallbacks may hold one an interrupted run failed to discard, as+      -- the name beside one may hold a fresh copy one left half made.+      clearScratch = for_ plans $ \p -> removePathForcibly (scratchDir p) *> removePathForcibly (freshCopyPath (scratchDir p))+  clearScratch+  -- The cleanup contract: outputs are written at their store paths, not+  -- in the build directory, so an interrupt or a throw between the+  -- builder starting and registration committing would otherwise strand+  -- an unregistered tree at a real store path.  Once @finish@ has+  -- succeeded there is nothing left to take back, and the flag says so: a+  -- build's registrations are committed, and a check wrote to scratch+  -- paths alone.+  committed <- newIORef False+  let cleanupUnlessCommitted = do+        done <- readIORef committed+        unless done clearScratch+      commit registration = uninterruptibleMask_ (registration *> writeIORef committed True)+      -- 6. Success: validate that the builder created all expected+      --    outputs, wherever they are now.  Outputs may be files or+      --    directories - both are valid (real Nix allows $out to be a+      --    single file, a directory tree, or a symlink).+      afterBuilder written = do+        missing <- filterM (nothingAt . writtenPath written) plans+        case missing of+          _ : _ -> do+            let names = T.intercalate ", " (map opName missing)+            -- The builder may have produced some outputs before omitting+            -- another.  None were registered, so take those orphaned+            -- trees back out of the store.+            clearScratch+            pure (Left (BuildStop ("builder succeeded but outputs missing: " <> names) 1))+          [] -> do+            finished <- finish written commit+            case finished of+              Right _ -> do+                writeIORef committed True+                -- Only the fallbacks go; the registered trees stay.+                -- After a build they are the redirected copies of outputs+                -- that were already valid, which upstream discards+                -- unread.  After a check they are every output the+                -- builder wrote, compared by now and not kept, whatever+                -- the comparison found, but a rebuild that differs, which+                -- under 'KeepFailed' is at its @.check@ path by now.  A+                -- Linux sandboxed build's are still in its chroot, which+                -- goes with them.+                for_ [p | p <- plans, opValid p] (removePathForcibly . scratchDir)+              Left _ -> clearScratch+            pure finished+      inStore = Written scratchDir (writableByOthers . scratchDir) OwnedByInvoker+  ( do+      -- 5. Run the builder.  A builtin builder runs in this process and+      --    writes the outputs where they are on disk; a spawned one runs+      --    where 'placementFor' put it, and what follows it runs while+      --    its outputs are where it left them.+      ran <- case run of+        RunsBuiltin builtin -> builtin outputDirs >>= either (pure . Left . uncurry BuilderRefused) (\() -> Right <$> afterBuilder inStore)+        RunsSpawned placement -> runSpawnedBuilder config context drv identity placement buildDir plans afterBuilder+      case ran of+        Left failure -> do+          -- Whatever the builder wrote is in the store now, so failure has+          -- to take it back out: an unregistered tree there is invisible to+          -- the database and would only confuse the next run.+          clearScratch+          pure (Left (builderStop failure))+        Right finished -> pure finished+    )+    `onException` cleanupUnlessCommitted++-- | Where the builder writes an output, on disk.+scratchPathOf :: BuildConfig -> OutputPlan -> FilePath+scratchPathOf config p = storePathToFilePath (bcStoreDir config) (opScratch p)++-- | Where a derivation's spawned builder runs: in the sandbox when the+-- settings and the derivation ask for it ('sandboxUse') and this system+-- can make one, otherwise where its directory and outputs are.  A Linux+-- system that cannot make the sandbox runs the build unsandboxed under+-- @sandbox-fallback@, after one warning a process ('warnFallback'), and+-- refuses it otherwise, as upstream does; on macOS it refuses the build+-- whatever @sandbox-fallback@ says ('backendFallback'), as upstream does+-- too.  'Left' is the refusal, in upstream's words ("Nix.Builder.Sandbox").+-- A sandboxed build as root with no build users is refused+-- ('rootRefusal').+placementFor :: BuildConfig -> BuildContext -> Derivation -> IO (Either Text Placement)+placementFor config context drv =+  case sandboxUse hostSandboxBackend (scMode sandbox) (bxDrvPath context) drv of+    Left reason -> pure (Left reason)+    Right Unsandboxed -> pure (Right PlacedUnsandboxed)+    Right (Sandboxed network) -> do+      root <- processIsRoot+      -- Before anything is made, and whatever sandbox-fallback says.+      if root && bcBuildUsers config == NoBuildUsers+        then pure (Left rootRefusal)+        else do+          available <- sandboxAvailability (scHelper sandbox)+          case (available, backendFallback hostSandboxBackend (scFallback sandbox)) of+            (Right (LinuxBackend, helper), _) -> pure (Right (PlacedInLinuxSandbox helper network))+            (Right (DarwinBackend, helper), _) -> pure (Right (PlacedInDarwinSandbox helper network))+            (Left cause, FallBackUnsandboxed) -> Right PlacedUnsandboxed <$ warnFallback (buildLogger context) cause+            (Left cause, RefuseUnsandboxed) -> pure (Left (unavailableMessage hostSandboxBackend cause))+  where+    sandbox = bcSandbox config++-- | Run a derivation's spawned builder where 'placementFor' put it, as+-- whom it runs as.  Once the builder has succeeded, @continue@ runs with+-- where its outputs are.+runSpawnedBuilder :: BuildConfig -> BuildContext -> Derivation -> BuilderIdentity -> Placement -> FilePath -> [OutputPlan] -> (Written -> IO r) -> IO (Either BuilderFailure r)+runSpawnedBuilder config context drv identity placement buildDir plans continue = case placement of+  PlacedUnsandboxed -> unsandboxed+  PlacedInLinuxSandbox helper network -> runSandboxedBuild config context drv identity buildDir plans helper network continue+  PlacedInDarwinSandbox helper network -> runDarwinSandboxedBuild config context drv identity buildDir plans helper network continue+  where+    -- The builder runs where its directory and outputs are, so it is told+    -- of each where it is on disk.+    layout = BuildLayout (inPlace buildDir) [(opName p, inPlace (scratchPathOf config p)) | p <- plans] buildDir+    unsandboxed = case builderInvocation config drv layout of+      Left reason -> pure (Left (BuilderRefused 1 reason))+      Right invocation -> do+        writeBuilderFiles identity invocation+        ran <- endingBuildUser identity (runBuilderAs (buildLogger context) identity invocation)+        traverse (\() -> continue (Written (scratchPathOf config) (writableByOthers . scratchPathOf config) (outputOwnerOf identity))) ran++-- | Write the files a builder reads from its build directory, each given to+-- the build user the builder runs as, if it runs as one, as upstream gives+-- them.+writeBuilderFiles :: BuilderIdentity -> BuilderInvocation -> IO ()+writeBuilderFiles identity invocation = for_ (invFiles invocation) $ \(path, contents) -> do+  BS.writeFile path contents+  for_ (buildUserOf identity) (`giveToBuildUser` path)++-- | Run a builder's process, and for a build user kill every process the+-- user has once it ends, however it ends, as upstream kills them before it+-- reads an output, so that nothing the builder left behind changes an+-- output while it is read or outlives the build.  A kill that fails fails+-- the build, whatever the builder did, as upstream's does.+endingBuildUser :: BuilderIdentity -> IO (Either BuilderFailure a) -> IO (Either BuilderFailure a)+endingBuildUser identity run = case identity of+  AsInvoker -> run+  AsBuildUser user -> do+    ran <- run `onException` killBuildUser user+    killed <- killBuildUser user+    pure (either (Left . BuilderNotEnded) (const ran) killed)++-- | Run an unsandboxed builder as whom it runs as: as the user nova-nix+-- runs as, through the process library on Windows ('runBuilder') and+-- elsewhere as upstream starts one ('runAsInvoker'), or as a build user+-- ('runAsBuildUser').+runBuilderAs :: Logger -> BuilderIdentity -> BuilderInvocation -> IO (Either BuilderFailure ())+runBuilderAs logger identity invocation = case identity of+  AsInvoker+    | isWindows -> runBuilder logger invocation+    | otherwise -> started (runAsInvoker logger)+  AsBuildUser user -> started (runAsBuildUser logger user)+  where+    started run = do+      environment <- builderEnvironment invocation+      ran <- run (invProgram invocation) (invArgs invocation) (map TE.encodeUtf8 environment) (invWorkDir invocation)+      pure $ case ran of+        Left reason -> Left (BuilderRefused 1 reason)+        Right ExitSuccess -> Right ()+        Right (ExitFailure code) -> Left (BuilderExited code)++-- | The ids a builder runs as outside its sandbox.+builderIdsOf :: BuilderIdentity -> IO BuilderIds+builderIdsOf identity = case identity of+  AsInvoker -> uncurry BuilderIds <$> invokingUserIds+  AsBuildUser user -> pure (BuilderIds (buUid user) (buGid user))++-- | Run a builder in the sandbox, in a chroot beside its build directory+-- ("Nix.Builder.Sandbox.Spawn") through the helper, then @continue@ with+-- each output where the builder wrote it, in the chroot, which is+-- removed once @continue@ ends: an output leaves the chroot only when it+-- is registered, as upstream's leaves its chroot last (@registerOutputs@ in+-- local-derivation-goal.cc at 2.24.9), so a check or an output that was+-- already valid never enters the store.  The builder sees its build directory+-- at @sandbox-build-dir@ and each output at its own path, which on disk is+-- that path beneath the chroot's root, upstream's @toRealPathChroot@+-- (@registerOutputs@ in local-derivation-goal.cc at 2.24.9).  The chroot is+-- in the store's state directory, so the move into the store is a rename+-- ('Nix.Store.placeInStore').  The directory the builder sees is one inside+-- the build directory, made with it ('sandboxedBuildDir').  An+-- @--exec-wrapper@ launcher is bound into the chroot as a @sandbox-paths@+-- entry naming itself.+runSandboxedBuild :: BuildConfig -> BuildContext -> Derivation -> BuilderIdentity -> FilePath -> [OutputPlan] -> FilePath -> Network -> (Written -> IO r) -> IO (Either BuilderFailure r)+runSandboxedBuild config context drv identity outerBuildDir plans helper network continue = do+  paths <- buildSandboxPaths config drv+  closure <- sandboxPathsClosure config context paths+  case closure of+    Left reason -> pure (Left (BuilderSandboxFailed reason))+    Right closurePaths -> do+      let buildDir = sandboxedBuildDir outerBuildDir+      storeBytes <- filePathBytes (unStoreDir (bcStoreDir config))+      buildDirBytes <- filePathBytes buildDir+      seenBuildDir <- bytesFilePath (scBuildDir sandbox)+      inputBytes <- traverse (filePathBytes . storeFile) (Set.toAscList (bxInputs context))+      closureBytes <- traverse (filePathBytes . storeFile) closurePaths+      -- Each output's final path and the path it is written to are kept+      -- out of the chroot, as upstream keeps every known output path out+      -- (@startBuilder@ in local-derivation-goal.cc at 2.24.9).+      outputBytes <- traverse filePathBytes (Set.toAscList (Set.fromList (concat [[storeFile (opFinal p), scratchPathOf config p] | p <- plans])))+      builderIds <- builderIdsOf identity+      chrooted <- withChroot (buildLogger context) outerBuildDir (buGid <$> buildUserOf identity) (chrootSkeleton storeBytes (scBuildDir sandbox) network paths) $ \root -> do+        rootBytes <- filePathBytes root+        let seenLayout = BuildLayout (BuildPlace seenBuildDir buildDir) [(opName p, BuildPlace (scratchPathOf config p) (root <> scratchPathOf config p)) | p <- plans] sandboxHome+            planInputs environment =+              PlanInputs+                { piRoot = rootBytes,+                  piStoreDir = storeBytes,+                  piBuildDirSeen = scBuildDir sandbox,+                  piBuildDirOnDisk = buildDirBytes,+                  piInputs = inputBytes,+                  piSandboxPaths = paths,+                  piSandboxClosure = closureBytes,+                  piOutputs = outputBytes,+                  piEnvironment = environment,+                  piNetwork = network,+                  piCaFile = scCaFile sandbox,+                  piDevShmSize = scDevShmSize sandbox,+                  piDropGroups = scDropGroups sandbox,+                  piBuilderIds = builderIds+                }+        case builderInvocation config drv seenLayout of+          Left reason -> pure (Left (BuilderRefused 1 reason))+          Right invocation -> do+            environment <- builderEnvironment invocation+            case sandboxPlan (planInputs (map TE.encodeUtf8 environment)) of+              Left reason -> pure (Left (BuilderSandboxFailed reason))+              Right plan -> do+                writeBuilderFiles identity invocation+                ran <- endingBuildUser identity (runSandboxedBuilder (buildLogger context) helper (renderPlan plan) (helperOutcome setupStageName . setupFailureMessage plan) invocation)+                case ran of+                  Left failure -> pure (Left failure)+                  Right () -> do+                    -- No process is left in the build's PID namespace;+                    -- one outside it, handed a descriptor by a+                    -- fixed-output builder, may be.  The chroot is closed+                    -- to every other user before anything reads an output+                    -- there ('sealChroot').+                    sealed <- sealChroot root (unStoreDir (bcStoreDir config))+                    case sealed of+                      Left reason -> pure (Left (BuilderSandboxFailed reason))+                      Right open -> Right <$> continue (Written (\p -> root <> scratchPathOf config p) (pure . (`Set.member` open) . takeFileName . scratchPathOf config) (outputOwnerOf identity))+      pure (either (Left . BuilderSandboxFailed) id chrooted)+  where+    sandbox = bcSandbox config+    storeFile = storePathToFilePath (bcStoreDir config)++-- | A sandboxed build's @sandbox-paths@ entries: the setting's, and an+-- @--exec-wrapper@ launcher the build runs through, as an entry naming+-- itself.+buildSandboxPaths :: BuildConfig -> Derivation -> IO [SandboxPath]+buildSandboxPaths config drv = do+  launcherPaths <- case execWrapperFor config drv of+    SpawnThrough launcher -> (\bytes -> [SandboxPath bytes bytes RequiredPath]) <$> filePathBytes launcher+    _ -> pure []+  pure (scPaths (bcSandbox config) ++ launcherPaths)++-- | The closures of the @sandbox-paths@ entries whose source is in the+-- store, which the sandbox holds beside them+-- (@LocalDerivationGoal::startBuilder@ at 2.24.9,+-- @DerivationBuildingGoal::buildLocally@ at 2.36.0).  A source that names no+-- store path adds nothing.+sandboxPathsClosure :: BuildConfig -> BuildContext -> [SandboxPath] -> IO (Either Text [StorePath])+sandboxPathsClosure config context paths = do+  let inStore = [sp | entry <- paths, Right source <- [TE.decodeUtf8' (spSource entry)], Just sp <- [parseStorePathPrefix (bcStoreDir config) source]]+  fmap Set.toAscList <$> inputClosure (bxStore context) inStore++-- | The temporary directory a process takes from @TMPDIR@, as upstream+-- takes its own: the variable's value when it is set and not empty,+-- otherwise @\/tmp@.+temporaryDirIn :: EnvLookup -> BS.ByteString+temporaryDirIn found = case found of+  EnvValue value | not (BS.null value) -> value+  _ -> "/tmp"++-- | Run a builder under the macOS sandbox's profile, through the helper,+-- then @continue@ with each output where the builder wrote it.  macOS's+-- sandbox has no chroot: the builder sees its build directory and its+-- outputs where they are on disk, as an unsandboxed one does and as+-- upstream's does (@tmpDirInSandbox@ in unix-derivation-builder-impl.hh+-- at 2.36.0), and is told upstream's @HOME@.  The profile+-- ('darwinProfile') names the store directory and the build directory+-- with their links resolved here, since macOS's sandbox matches a file by+-- its resolved path.  A derivation's impure host paths, and the refusals+-- of a path the profile cannot name, are upstream's+-- ('darwinPathsInSandbox', 'profileFilters').+runDarwinSandboxedBuild :: BuildConfig -> BuildContext -> Derivation -> BuilderIdentity -> FilePath -> [OutputPlan] -> FilePath -> Network -> (Written -> IO r) -> IO (Either BuilderFailure r)+runDarwinSandboxedBuild config context drv identity buildDir plans helper network continue = runExceptT $ do+  options <- liftEither (first BuilderSandboxFailed (darwinOptions (bxDrvPath context) drv))+  paths <- liftIO (buildSandboxPaths config drv)+  closurePaths <- ExceptT (first BuilderSandboxFailed <$> sandboxPathsClosure config context paths)+  storeBytes <- liftIO (filePathBytes (unStoreDir (bcStoreDir config)))+  realStore <- liftIO (resolvedPath storeBytes)+  buildBytes <- liftIO (filePathBytes buildDir)+  realBuild <- liftIO (resolvedPath buildBytes)+  realStoreDir <- liftIO (StoreDir <$> bytesFilePath realStore)+  let resolved = filePathBytes . storePathToFilePath realStoreDir+  inputBytes <- liftIO (traverse resolved (Set.toAscList (bxInputs context)))+  closureBytes <- liftIO (traverse resolved closurePaths)+  outputBytes <- liftIO (traverse (resolved . opScratch) plans)+  darwinPaths <-+    liftEither . first BuilderSandboxFailed $+      darwinPathsInSandbox+        DarwinPathInputs+          { dpiDrvPath = bxDrvPath context,+            dpiStoreDir = storeBytes,+            dpiRealStoreDir = realStore,+            dpiBuildDir = buildBytes,+            dpiRealBuildDir = realBuild,+            dpiSandboxPaths = paths,+            dpiSandboxClosure = closureBytes,+            dpiImpureHostDeps = doImpureHostDeps options,+            dpiAllowedImpureHostDeps = scAllowedImpureHostDeps (bcSandbox config),+            dpiInputs = inputBytes+          }+  filters <- ExceptT (first BuilderSandboxFailed <$> profileFilters (dpPaths darwinPaths))+  let layout = BuildLayout (inPlace buildDir) [(opName p, inPlace (scratchPathOf config p)) | p <- plans] sandboxHome+      profile =+        darwinProfile+          DarwinProfile+            { dprViolationLog = scViolationLog (bcSandbox config),+              dprNetwork = network,+              dprStoreDir = realStore,+              dprOutputs = outputBytes,+              dprPaths = filters,+              dprAncestry = dpAncestry darwinPaths,+              dprExtra = doExtraProfile options+            }+  invocation <- liftEither (first (BuilderRefused 1) (builderInvocation config drv layout))+  environment <- liftIO (builderEnvironment invocation)+  tmpDir <- liftIO $ case identity of+    AsInvoker -> pure realBuild+    AsBuildUser _ -> lookupEnvBytes (TE.encodeUtf8 envTmpDir) >>= resolvedPath . temporaryDirIn+  let buildUser = (\user -> BuilderIds (buUid user) (buGid user)) <$> buildUserOf identity+      plan = DarwinPlan realBuild profile buildUser (darwinParameters realBuild tmpDir (doLocalNetworking options)) (map TE.encodeUtf8 environment)+  liftIO (writeBuilderFiles identity invocation)+  ExceptT (endingBuildUser identity (runSandboxedBuilder (buildLogger context) helper (renderDarwinPlan plan) (helperOutcome darwinStageName . darwinSetupFailureMessage plan) invocation))+  liftIO (continue (Written (scratchPathOf config) (writableByOthers . scratchPathOf config) (outputOwnerOf identity)))++-- | Why the builder step of a build failed, with the exit code the+-- build reports.+data BuilderFailure+  = -- | The builder ran and exited unsuccessfully.  What it wrote is+    -- already in the build log, which upstream's default logger does not+    -- repeat in the failure: it shows the log's last lines there only+    -- when it has not been printing them (@log-lines@, derivation-goal.cc+    -- at 2.24.9).+    BuilderExited !Int+  | -- | The builder did not run, or a builtin builder refused, for the+    -- reason given.+    BuilderRefused !Int !Text+  | -- | The sandbox could not be made, for the reason given, in upstream's+    -- words ("Nix.Builder.Sandbox").+    BuilderSandboxFailed !Text+  | -- | The build user's processes could not all be killed once the+    -- builder ended, for the reason given ('killBuildUser').+    BuilderNotEnded !Text++-- | The stop a failed builder step reports.+builderStop :: BuilderFailure -> BuildStop+builderStop failure = case failure of+  BuilderExited code -> BuildStop "builder failed" code+  BuilderRefused code reason -> BuildStop ("builder failed: " <> reason) code+  BuilderSandboxFailed reason -> BuildStop reason 1+  BuilderNotEnded reason -> BuildStop reason 1++-- | Decode a derivation's builder path and arguments from their identity+-- bytes to the 'Text' the process-spawn boundary needs.  @Left@ names the+-- offending field.  The environment is decoded where 'attrsDelivery'+-- decides what of it reaches the builder as variables.+decodeBuilderStrings :: Derivation -> Either Text (Text, [Text])+decodeBuilderStrings drv = do+  builderText <- decodeSpawnField "the builder path" (drvBuilder drv)+  argTexts <- traverse (decodeSpawnField "a builder argument") (drvArgs drv)+  pure (builderText, argTexts)++-- | Decode one derivation string for the spawn, @what@ naming it in the+-- failure.+decodeSpawnField :: Text -> BS.ByteString -> Either Text Text+decodeSpawnField what bytes = case TE.decodeUtf8' bytes of+  Right t -> Right t+  Left _ -> Left ("cannot spawn builder: " <> what <> " contains invalid UTF-8")++-- | 'decodeSpawnField' for an environment variable.+decodeVariable :: Text -> BS.ByteString -> Either Text Text+decodeVariable name = decodeSpawnField ("environment variable '" <> name <> "'")++-- ---------------------------------------------------------------------------+-- Input validation+-- ---------------------------------------------------------------------------++-- | Rewrite a derivation string's store paths from their identity (the+-- canonical @\/nix\/store@ spelling) to where this machine actually keeps+-- them, at the spawn boundary. A no-op when the two coincide.+onStore :: BuildConfig -> Text -> Text+onStore config = maybe id (uncurry T.replace) (storeRewrite config)++-- | The replacement 'onStore' makes, when the two spellings differ.+storeRewrite :: BuildConfig -> Maybe (Text, Text)+storeRewrite config+  | storeDirText == defaultStoreDirText = Nothing+  | otherwise = Just (defaultStoreDirText <> "/", storeDirText <> "/")+  where+    storeDirText = T.pack (unStoreDir (bcStoreDir config))++-- | Check that all inputs needed to build a derivation are present in the+-- store, and return them: the input sources, then the input derivations'+-- requested outputs.+--+-- Input sources must be valid.  For input derivations, the artifacts a build+-- actually reads are their realized OUTPUT paths, not the @.drv@ recipe files,+-- so we resolve each requested output (by reading the input @.drv@ the build+-- driver materialized) and validate those outputs.  "Nix.Realise" realizes a+-- derivation's inputs before it builds, so their outputs are present by the+-- time it is validated.+validateInputs :: BuildConfig -> Store -> Derivation -> IO (Either Text [StorePath])+validateInputs config store drv = do+  -- Check input sources+  srcResults <- mapM (isValid store) (drvInputSrcs drv)+  let missingSrcs = [sp | (sp, valid) <- zip (drvInputSrcs drv) srcResults, not valid]+  if not (null missingSrcs)+    then pure (Left ("missing input sources: " <> T.intercalate ", " (map formatSP missingSrcs)))+    else do+      resolved <- resolveInputOutputs config drv+      case resolved of+        Left err -> pure (Left err)+        Right requiredOutputs -> do+          outResults <- mapM (isValid store) requiredOutputs+          let missingOutputs = [sp | (sp, valid) <- zip requiredOutputs outResults, not valid]+          if not (null missingOutputs)+            then pure (Left ("missing input derivation outputs: " <> T.intercalate ", " (map formatSP missingOutputs)))+            else pure (Right (drvInputSrcs drv ++ requiredOutputs))++-- | Resolve each input derivation's requested output names to their store+-- paths by reading the input @.drv@ from the store.  @Left@ if an input @.drv@+-- cannot be read or names an output the derivation does not define.+resolveInputOutputs :: BuildConfig -> Derivation -> IO (Either Text [StorePath])+resolveInputOutputs config drv =+  runExceptT (concat <$> traverse resolveOne (Map.toList (drvInputDrvs drv)))+  where+    resolveOne (inputDrvPath, wantedOutputs) = do+      inputDrv <- ExceptT (readDrvFromStore config inputDrvPath)+      let outputMap = Map.fromList [(doName o, doPath o) | o <- drvOutputs inputDrv]+      liftEither (traverse (lookupOutput inputDrvPath outputMap) wantedOutputs)+    lookupOutput inputDrvPath outputMap name =+      case Map.lookup name outputMap of+        Just sp -> Right sp+        Nothing ->+          Left ("input derivation " <> formatSP inputDrvPath <> " has no output '" <> name <> "'")++-- | The closure of a build's inputs under the references the store records:+-- the paths besides its own outputs that an output may reference.  This is+-- upstream's @inputPaths@, the closures of the requested input outputs and+-- of the input sources (@DerivationGoal::inputsRealised@ in+-- derivation-goal.cc at 2.24.9, @DerivationBuildingGoal::tryToBuild@ in+-- derivation-building-goal.cc at 2.36.0).  An output that embeds a+-- dependency of a dependency must record it, or a collection deletes it+-- while the output still uses it.  As in upstream's, an input derivation's+-- @.drv@ is in it only when an input source reaches it.+--+-- A recorded reference that does not parse is a corrupt database, and fails+-- the build rather than dropping out of the scan.+inputClosure :: Store -> [StorePath] -> IO (Either Text (Set StorePath))+inputClosure store = runExceptT . closureUnder recorded+  where+    recorded :: StorePath -> ExceptT Text IO [StorePath]+    recorded sp = do+      referenceTexts <- liftIO (queryReferences (stDB store) sp)+      liftEither (traverse parseRecorded referenceTexts)+    parseRecorded text = case parseStorePath (stDir store) text of+      Just sp -> Right sp+      Nothing -> Left ("unparseable reference in store DB: " <> text)++-- | Every node reachable from the roots through the references lookup, the+-- roots included.  Each node is looked up once, so a reference cycle (the+-- outputs of one derivation may reference each other) ends.+closureUnder :: (Monad m, Ord a) => (a -> m [a]) -> [a] -> m (Set a)+closureUnder references = go Set.empty+  where+    go !seen [] = pure seen+    go !seen (node : pending)+      | Set.member node seen = go seen pending+      | otherwise = do+          referenced <- references node+          go (Set.insert node seen) (referenced ++ pending)++-- | Format a StorePath for error messages.+formatSP :: StorePath -> Text+formatSP sp = spHash sp <> "-" <> spName sp++-- ---------------------------------------------------------------------------+-- Environment+-- ---------------------------------------------------------------------------++-- | A path a build uses: where its builder is told it is, and where it is+-- on disk, which is where this process writes and reads it.  The two+-- differ when the builder's view of the filesystem is not this+-- process's.+data BuildPlace = BuildPlace+  { -- | The path as the builder is told of it.+    placeSeen :: !FilePath,+    -- | The path on disk.+    placeOnDisk :: !FilePath+  }+  deriving (Eq, Show)++-- | A path the builder is told of where it is on disk.+inPlace :: FilePath -> BuildPlace+inPlace path = BuildPlace path path++-- | Where a build's directory and its outputs are.+data BuildLayout = BuildLayout+  { -- | The build directory, upstream's @tmpDir@ on disk and+    -- @tmpDirInSandbox@ as the builder sees it+    -- (@initTmpDir@ in local-derivation-goal.cc at 2.24.9,+    -- @tmpDirInSandbox@ in chroot-derivation-builder.cc at 2.36.0).+    layoutBuildDir :: !BuildPlace,+    -- | Each output by name, at the path the builder writes it to.+    layoutOutputs :: ![(Text, BuildPlace)],+    -- | The @HOME@ the builder is told of: its build directory when it+    -- runs unsandboxed, and upstream's @\/homeless-shelter@ in the+    -- sandbox ('Nix.Builder.Sandbox.sandboxHome').+    layoutHome :: !FilePath+  }+  deriving (Eq, Show)++-- | How a spawned builder is started.+data BuilderInvocation = BuilderInvocation+  { -- | The program spawned: the builder, or the launcher that runs it.+    invProgram :: !FilePath,+    -- | Its arguments.+    invArgs :: ![String],+    -- | The build's environment, before the ambient variables a builder+    -- may inherit ('scrubAmbient').+    invEnv :: !(Map Text Text),+    -- | The ambient variables copied into it, the @impureEnvVars@+    -- carve-out.+    invImpureVars :: ![Text],+    -- | The files written before it starts, at their paths on disk.+    invFiles :: ![(FilePath, BS.ByteString)],+    -- | The directory it is started in, on disk.+    invWorkDir :: !FilePath+  }+  deriving (Eq, Show)++-- | How a derivation's builder is started, given where the build's+-- directory and outputs are.  What the builder is told of, its arguments+-- and environment, names the build directory and each output as the+-- builder sees it, as upstream's environment names @tmpDirInSandbox@+-- (@initTmpDir@ and @writeStructuredAttrs@ in local-derivation-goal.cc at+-- 2.24.9, @initEnv@ in unix-derivation-builder.cc and+-- @DesugaredEnv::create@ in derivation-env-desugar.cc at 2.36.0); the+-- files it finds are written, and it is started, where the directory is+-- on disk.+--+-- Derivation strings are bytes, and spawning a process needs text, so+-- invalid UTF-8 in the builder, an argument or a variable refuses the+-- build rather than spawning a mangled one.  The builder and each+-- argument end at their first NUL, as exec takes them ('asExecString').+-- An attribute that reaches the builder as a file stays bytes+-- ('attrsDelivery').+builderInvocation :: BuildConfig -> Derivation -> BuildLayout -> Either Text BuilderInvocation+builderInvocation config drv layout = case (execWrapperFor config drv, decodeBuilderStrings drv) of+  (SpawnUnsupported system, _) ->+    Left ("no way to run a " <> system <> " builder on this machine; pass --exec-wrapper " <> system <> "=PATH to name a launcher for it")+  (_, Left errMsg) -> Left errMsg+  (spawn, Right (builderText, argTexts)) -> do+    let builderPath = T.unpack (asExecString (onStore config builderText))+        builderArgs = map (T.unpack . asExecString . buildRewrite config seenOutputs) argTexts+        -- Env still names the real builder - a launcher only+        -- changes what's spawned, not what the derivation says.+        (spawnPath, spawnArgs) = case spawn of+          SpawnThrough launcher -> (launcher, builderPath : builderArgs)+          _ -> (builderPath, builderArgs)+        -- Only a fixed-output derivation's impureEnvVars reach+        -- the spawn.  Upstream passes them to a derivation whose+        -- type is not sandboxed (initEnv in local-derivation-goal.cc+        -- at 2.24.9, unix-derivation-builder.cc at 2.36.0): a+        -- fixed-output one, or an impure one+        -- (DerivationType::isSandboxed and BasicDerivation::type in+        -- derivations.cc at 2.24.9, derivation::Type::isSandboxed and+        -- derivation::type there at 2.36.0), which takes the+        -- impure-derivations experimental feature nova-nix does+        -- not implement.+        impureVars delivery = case fixedOutput drv of+          Just _ -> adImpureEnvVars delivery+          Nothing -> Right []+    delivery <- attrsDelivery config drv (placeSeen buildDir) seenOutputs+    passed <- impureVars delivery+    Right+      BuilderInvocation+        { invProgram = spawnPath,+          invArgs = spawnArgs,+          invEnv = buildEnvironment config (adEnv delivery) builderPath (placeSeen buildDir) (layoutHome layout),+          invImpureVars = passed,+          invFiles = [(placeOnDisk buildDir </> name, bytes) | (name, bytes) <- adFiles delivery],+          invWorkDir = placeOnDisk buildDir+        }+  where+    buildDir = layoutBuildDir layout+    seenOutputs = [(name, placeSeen place) | (name, place) <- layoutOutputs layout]++-- | Replace each output's @builtins.placeholder@ sentinel with its+-- build-time path (the same value @$out@ carries).  The args, the+-- environment and the files attributes reach the builder as+-- ('attrsDelivery') are rewritten; the builder path is left alone, as+-- upstream Nix leaves it.+rewritePlaceholders :: [(Text, FilePath)] -> Text -> Text+rewritePlaceholders outputDirs value =+  foldr (uncurry T.replace) value (placeholderRewrites outputDirs)++-- | The replacements 'rewritePlaceholders' makes, one per output.+placeholderRewrites :: [(Text, FilePath)] -> [(Text, Text)]+placeholderRewrites outputDirs = [(hashPlaceholder name, T.pack path) | (name, path) <- outputDirs]++-- | The build's rewrite of a derivation string: store paths to where this+-- machine keeps them, then each output's placeholder to its build-time+-- path.  'onStore' goes first, so nothing a placeholder expands to is+-- rewritten a second time.+buildRewrite :: BuildConfig -> [(Text, FilePath)] -> Text -> Text+buildRewrite config outputDirs = rewritePlaceholders outputDirs . onStore config++-- | 'buildRewrite' over bytes, for an attribute that reaches the builder+-- as a file and so need not be text.  The replacements go in the order+-- 'buildRewrite' makes them ('rewritePlaceholders' folds from the right),+-- and on UTF-8 the two agree: an encoded needle matches only at a+-- character boundary.+buildRewriteBytes :: BuildConfig -> [(Text, FilePath)] -> BS.ByteString -> BS.ByteString+buildRewriteBytes config outputDirs =+  rewriteBytes+    [ (TE.encodeUtf8 from, TE.encodeUtf8 to)+    | (from, to) <- maybeToList (storeRewrite config) <> reverse (placeholderRewrites outputDirs)+    ]++-- | Apply a build-time rewrite to an environment's names as well as its+-- values.  Upstream rewrites the whole @name=value@ string (@runChild@ in+-- local-derivation-goal.cc at 2.24.9, unix-derivation-builder.cc at+-- 2.36.0), so a placeholder in a dynamic attribute name is substituted+-- too; rewriting only the values would hand the builder a variable whose+-- name still held the sentinel.+rewriteEnv :: (Text -> Text) -> Map Text Text -> Map Text Text+rewriteEnv rewrite = Map.fromList . map rewritePair . Map.toList+  where+    rewritePair (name, value) = (rewrite name, rewrite value)++-- | What a builder receives of its derivation beyond the builder path and+-- arguments.+data AttrsDelivery = AttrsDelivery+  { -- | Variables the derivation contributes to the environment.+    adEnv :: !(Map Text Text),+    -- | Files the builder finds in its build directory when it starts,+    -- by name in that directory.+    adFiles :: ![(FilePath, BS.ByteString)],+    -- | The @impureEnvVars@ attribute, which matters only to a fixed-output+    -- derivation, so a malformed one fails only such a build, as upstream.+    adImpureEnvVars :: !(Either Text [Text])+  }+  deriving (Eq, Show)++-- | How the derivation's attributes reach the builder: as environment+-- variables, outputs included, or for a derivation carrying structured+-- attributes, as @.attrs.json@ and @.attrs.sh@ in the build directory+-- named by two variables, with no attribute and no output in the+-- environment (upstream's @initTmpDir@ and @writeStructuredAttrs@,+-- local-derivation-goal.cc at 2.24.9).+--+-- Without structured attributes, each attribute @passAsFile@ names+-- ('splitPassAsFile') is written to a file in the build directory instead,+-- holding the bytes its variable would have held, and @\<name\>Path@+-- names the file.  An attribute that is itself called @\<name\>Path@+-- keeps its own value, as it does upstream, where it is assigned later.+-- The variable joins the build directory and the file name with the+-- platform's separator where upstream writes @\/@, so on Windows it is+-- spelled as @NIX_BUILD_TOP@ is.  Structured attributes need no such+-- escape from the environment, and upstream ignores @passAsFile@ there.+--+-- The build's rewrite ('buildRewrite') applies to the shell file's text+-- as upstream applies it, after rendering; the JSON file's strings take it+-- before they are escaped, so a store directory holding backslashes still+-- yields JSON.+--+-- The build directory and the outputs are given where the builder sees+-- them, and the files are named in that directory, so they can be+-- written wherever it is on disk.+attrsDelivery :: BuildConfig -> Derivation -> FilePath -> [(Text, FilePath)] -> Either Text AttrsDelivery+attrsDelivery config drv buildDir outputDirs = case Map.lookup structuredAttrsKey env of+  Nothing -> do+    let (variables, passed) = splitPassAsFile env+        pathVars = Map.fromList [(name <> passedFileVarSuffix, T.pack (buildDir </> passedFileName name)) | name <- Map.keys passed]+    decoded <- Map.traverseWithKey decodeVariable variables+    Right+      AttrsDelivery+        { adEnv = unionEnvs [Map.withoutKeys outputEnv (Map.keysSet passed), rewriteEnv rewrite (unionEnvs [decoded, pathVars])],+          adFiles = [(passedFileName name, passedContents name value) | (name, value) <- Map.toList passed],+          -- Read from the whole environment, as upstream's getStringsAttr+          -- reads it, so passing the attribute as a file does not drop it.+          adImpureEnvVars = T.words <$> decodeVariable envImpureEnvVars (Map.findWithDefault "" envImpureEnvVars env)+        }+  Just encodedBytes -> do+    encoded <- decodeVariable structuredAttrsKey encodedBytes+    attrs <- first (("cannot process " <> structuredAttrsKey <> " attribute of '" <> formatDrvName drv <> "': ") <>) (decodeStructuredAttrs encoded)+    let prepared = withOutputPlaceholders (map fst outputDirs) attrs+    Right+      AttrsDelivery+        { adEnv =+            Map.fromList+              [ (envNixAttrsJsonFile, T.pack (buildDir </> attrsJsonFileName)),+                (envNixAttrsShFile, T.pack (buildDir </> attrsShellFileName))+              ],+          adFiles =+            [ (attrsJsonFileName, renderAttrsJson rewrite prepared),+              (attrsShellFileName, TE.encodeUtf8 (rewrite (renderAttrsShell prepared)))+            ],+          adImpureEnvVars = fromMaybe [] <$> stringsAttr envImpureEnvVars attrs+        }+  where+    env = drvEnv drv+    rewrite = buildRewrite config outputDirs+    outputEnv = Map.fromList [(name, T.pack path) | (name, path) <- outputDirs]+    -- An output's variable is the path it is written to, which is not+    -- the derivation's value when that output is already valid, so its+    -- file holds the same path.+    passedContents name value =+      maybe (buildRewriteBytes config outputDirs value) (TE.encodeUtf8 . T.pack) (lookup name outputDirs)++-- | Upstream's @passAsFile@: split off the attributes the @passAsFile@+-- attribute names, as files rather than variables, leaving the rest.  A+-- name with no attribute behind it is ignored, and @passAsFile@ itself+-- stays a variable unless it names itself.  Names are compared as bytes,+-- as upstream compares them.+splitPassAsFile :: Map Text BS.ByteString -> (Map Text BS.ByteString, Map Text BS.ByteString)+splitPassAsFile env = (variables, passed)+  where+    named = Set.fromList (attrTokens (Map.findWithDefault "" envPassAsFile env))+    (passed, variables) = Map.partitionWithKey (\name _ -> Set.member (TE.encodeUtf8 name) named) env++-- | Upstream's @tokenizeString@ with its default separators: the+-- non-empty runs between 'tokenSeparators'.+attrTokens :: BS.ByteString -> [BS.ByteString]+attrTokens = filter (not . BS.null) . BS.splitWith (`BS.elem` tokenSeparators)++-- | The file an attribute passed as a file is written to: upstream's+-- @.attr-@ and the SHA-256 of the attribute's name in Nix base-32, so+-- whatever the name holds, the file is one entry of the build directory.+passedFileName :: Text -> FilePath+passedFileName name = T.unpack (passedFilePrefix <> Nix32.encode (sha256Digest (TE.encodeUtf8 name)))++-- | Build the process environment from the derivation's contribution+-- ('adEnv') + standard vars, naming the build directory as the builder+-- sees it and its home.  Its PATH is the builder's 'buildPath', which a+-- PATH the derivation sets displaces.+buildEnvironment ::+  BuildConfig ->+  Map Text Text ->+  FilePath ->+  FilePath ->+  FilePath ->+  Map Text Text+buildEnvironment config derivationEnv builderPath buildDir home =+  let -- Standard build variables+      standardEnv =+        Map.fromList+          [ (envNixBuildTop, T.pack buildDir),+            (envTmpDir, T.pack buildDir),+            (envTempDir, T.pack buildDir),+            (envTmp, T.pack buildDir),+            (envTemp, T.pack buildDir),+            (homeEnvVar, T.pack home),+            (envNixStore, T.pack (unStoreDir (bcStoreDir config))),+            (envNixBuildCores, T.pack (show (bcCores config))),+            (envPath, buildPath builderPath),+            (envSourceDateEpoch, sourceDateEpochValue)+          ]+   in -- Priority: derivation env (output paths first) > standard env+      unionEnvs [derivationEnv, standardEnv]++-- | Union environment maps left to right (an earlier map's variable wins).+-- On Windows environment names are one case-insensitive namespace, so+-- displacement folds names by per-character uppercase - matching the+-- kernel's env-name comparison - and the winner keeps its own spelling:+-- a build's @PATH@ must displace an inherited @Path@, or both would land+-- in the child's environment block and which one the child sees would be+-- runtime-dependent.  On Unix names are distinct by case and this is+-- 'Map.unions'.+unionEnvs :: [Map Text Text] -> Map Text Text+unionEnvs envs+  | isWindows =+      let foldName = T.map toUpper+          folded =+            [ Map.fromList [(foldName name, (name, val)) | (name, val) <- Map.toList env]+            | env <- envs+            ]+       in Map.fromList (Map.elems (Map.unions folded))+  | otherwise = Map.unions envs++-- | The ambient environment a builder is allowed to see.  Everything+-- else is scrubbed: upstream builds in a cleared environment (its+-- initEnv begins with @env.clear()@ and the child is exec'd with+-- exactly that block), so an undeclared ambient variable reaching a+-- build embeds machine-specific data in its output - undermining the+-- reproducibility SOURCE_DATE_EPOCH exists to pin.+--+-- On Unix the allowance is empty.  A Windows process block cannot be:+-- 'windowsAmbientAllowlist' names what passes through, COMSPEC is+-- synthesized from the allowed SystemRoot, and PATHEXT is pinned to+-- 'pathextValue'.  Names compare case-insensitively on Windows, so the+-- allowlist matches by folded name and a passed variable keeps its+-- ambient spelling.+scrubAmbient :: Map Text Text -> Map Text Text+scrubAmbient ambient+  | not isWindows = Map.empty+  | otherwise =+      let foldName = T.map toUpper+          folded = Map.fromList [(foldName name, (name, val)) | (name, val) <- Map.toList ambient]+          allowed = Map.fromList [pair | key <- windowsAmbientAllowlist, Just pair <- [Map.lookup key folded]]+          synthesized =+            Map.fromList $+              (envPathext, pathextValue)+                : [ (envComspec, root <> "\\System32\\cmd.exe")+                  | Just (_, root) <- [Map.lookup systemRootKey folded]+                  ]+       in unionEnvs [allowed, synthesized]++-- | Construct the build PATH from the builder's location.  On Unix it is+-- 'pathNotSet', as upstream Nix's is.  On Windows it includes the+-- builder's directory, its sibling @usr\/bin@ (for MSYS2 coreutils+-- bundled with Git for Windows), and 'windowsSystemDirs', which follow it+-- even when the builder's directory is a store path.+--+-- A builder whose directory depends on the working directory, a bare+-- name or a relative path such as @./tools/bash@, adds no directory: the+-- working directory is the build directory, so a file dropped there+-- would resolve ahead of every tool.+buildPath :: FilePath -> Text+buildPath builderPath+  | isWindows = T.intercalate ";" (map T.pack (builderDirs ++ windowsSystemDirs))+  | otherwise = pathNotSet+  where+    builderDir = takeDirectory builderPath+    builderDirs+      | independentOfWorkDir builderDir = [builderDir, takeDirectory builderDir </> "usr" </> "bin"]+      | otherwise = []++-- | Whether a directory names one place whatever the working directory:+-- absolute, or, on Windows, rooted on the working directory's drive.+independentOfWorkDir :: FilePath -> Bool+independentOfWorkDir dir = isAbsolute dir || maybe False (isPathSeparator . fst) (uncons dir)++-- | The home directory environment variable name (platform-dependent).+homeEnvVar :: Text+homeEnvVar =+  if System.Info.os == "mingw32"+    then "USERPROFILE"+    else "HOME"++-- ---------------------------------------------------------------------------+-- Process execution+-- ---------------------------------------------------------------------------++-- | Run the builder process on Windows, through the process library,+-- handing what it writes to the logger a line at a time+-- ('streamBuildLog'), and report how it exited.+--+-- Its standard output and standard error are one pipe ('openLogPipe'),+-- so the log holds both in the order the builder wrote them, as+-- upstream's does.  Its standard input is a pipe this process closes+-- as soon as the builder is spawned, so a read sees end-of-file.+--+-- The child's environment is exactly the build environment plus+-- 'scrubAmbient'\'s allowance - the ambient environment does not flow+-- through ('builderProcessEnv').  It runs unsandboxed, with the+-- filesystem and the network in reach; 'runSandboxedBuilder' runs a+-- sandboxed one.+--+-- 'invImpureVars' is the impureEnvVars carve-out: the names a+-- fixed-output derivation listed (empty otherwise), each copied from+-- the ambient environment - the EMPTY STRING when+-- absent, not omitted, matching upstream's @getEnv(i).value_or("")@.+-- Upstream writes these last in initEnv, so they win even over the+-- derivation's own values.  Names match exactly, as upstream's do.+runBuilder :: Logger -> BuilderInvocation -> IO (Either BuilderFailure ())+runBuilder logger invocation = do+  envList <- builderProcessEnv invocation+  let spawnWith toLog =+        (mkBuilderProcess (invProgram invocation) (invArgs invocation))+          { Proc.cwd = Just (invWorkDir invocation),+            Proc.env = Just envList,+            Proc.std_in = Proc.CreatePipe,+            -- The spawn closes this process's copy of the write end, so+            -- the builder's tree holds the only ones and its exit ends+            -- the log.+            Proc.std_out = Proc.UseHandle toLog,+            Proc.std_err = Proc.UseHandle toLog,+            -- Wrap the builder's whole process tree in a Win32 job with+            -- kill-on-job-close.  Without it, a builder's grandchildren+            -- (bash -> make -> cc, or anything cmd.exe spawns) outlive an+            -- interrupt: terminateProcess reaches only the direct child,+            -- so the tree is orphaned and keeps running.  With the job,+            -- terminateProcess becomes TerminateJobObject and reaps the+            -- tree, and waitForProcess waits for all of it.+            -- A deliberately daemonizing grandchild changes from leaking+            -- to blocking the build until it exits; that is the correct+            -- trade for a build, which owns everything it spawned.  The+            -- job also ends a process at an unhandled exception without+            -- Windows Error Reporting ("Nix.Builder.Job").+            Proc.use_process_jobs = True+          }+      closePipe (fromBuilder, toLog) = System.IO.hClose fromBuilder *> System.IO.hClose toLog+  exitCode <-+    bracket openLogPipe closePipe $ \(fromBuilder, toLog) ->+      Proc.withCreateProcess (spawnWith toLog) $ \stdinEnd _ _ process -> do+        -- Before the builder's input ends, so a builder that reads it to+        -- the end runs on in a job with the limit in place.+        dieOnUnhandledException process+        for_ stdinEnd System.IO.hClose+        -- A build that is stopped ends the builder's job, and with it the+        -- whole tree, and unwinds only once the tree has ended, as+        -- 'runAsInvoker' reaps its builder before it unwinds.+        (streamBuildLog fromBuilder logger *> Proc.waitForProcess process)+          `onException` uninterruptibleMask_ (Proc.terminateProcess process *> void (Proc.waitForProcess process))+  pure $ case exitCode of+    ExitSuccess -> Right ()+    ExitFailure code -> Left (BuilderExited code)++-- | A builder's string as exec takes it, a C string: its text up to the+-- first NUL, as upstream's execve takes each argument and each+-- @NAME=VALUE@ entry it builds (stringsToCharPtrs in util.cc at 2.24.9 and+-- 2.34.9, and @runChild@ in local-derivation-goal.cc at 2.24.9).  Cut+-- here, a NUL reaches neither the process library, which refuses one in an+-- environment entry and on Windows would end an entry or the command line+-- at it, nor the sandbox helper's plan.+asExecString :: Text -> Text+asExecString = T.takeWhile (/= '\0')++-- | The environment a builder process gets, as the entries of its exec:+-- the invocation's, the @impureEnvVars@ carve-out over it, and+-- 'scrubAmbient'\'s allowance under it ('runBuilder'), each @NAME=VALUE@+-- ending at its first NUL ('asExecString').+builderEnvironment :: BuilderInvocation -> IO [Text]+builderEnvironment invocation = do+  systemEnv <- System.Environment.getEnvironment+  let systemMap = Map.fromList [(T.pack k, T.pack v) | (k, v) <- systemEnv]+      impureAllowance =+        Map.fromList [(var, Map.findWithDefault "" var systemMap) | var <- invImpureVars invocation]+  -- Impure carve-out wins, then build env, displacing case variants on+  -- Windows; the scrubbed ambient allowance fills underneath.+  pure [asExecString (name <> "=" <> value) | (name, value) <- Map.toList (unionEnvs [impureAllowance, invEnv invocation, scrubAmbient systemMap])]++-- | 'builderEnvironment' as the process library takes one: a name and a+-- value, which it joins with @=@.  An entry with no @=@, which a name+-- holding a NUL leaves, is one it cannot pass, and is left out; upstream+-- passes it, and no getenv finds a variable in it.  The sandbox helper,+-- and on Linux and macOS the start of an unsandboxed builder+-- ('runAsInvoker'), pass every entry as it is.+builderProcessEnv :: BuilderInvocation -> IO [(String, String)]+builderProcessEnv invocation = mapMaybe asPair <$> builderEnvironment invocation+  where+    asPair entry = case T.breakOn "=" entry of+      (name, rest) | Just (_, value) <- T.uncons rest -> Just (T.unpack name, T.unpack value)+      _ -> Nothing++-- | Run a builder through the sandbox helper ('runHelper'), given the+-- logger its lines go to, the plan as the helper reads it, with the+-- builder's environment in it ('builderEnvironment'), and how a run is+-- read for the program it executes ('helperOutcome').+runSandboxedBuilder :: Logger -> FilePath -> BS.ByteString -> (BS.ByteString -> Either Text () -> ExitCode -> BS.ByteString -> HelperOutcome) -> BuilderInvocation -> IO (Either BuilderFailure ())+runSandboxedBuilder logger helper plan outcomeOf invocation = do+  program <- filePathBytes (invProgram invocation)+  run <- runHelper logger helper plan (invWorkDir invocation) (invProgram invocation : invArgs invocation)+  pure $ case outcomeOf program (hrDelivered run) (hrExit run) (hrStatus run) of+    SetupIncomplete reason -> Left (BuilderSandboxFailed reason)+    BuilderRan ExitSuccess -> Right ()+    BuilderRan (ExitFailure code) -> Left (BuilderExited code)++-- | Create the appropriate process spec for the builder.+--+-- On Windows, cmd.exe uses its own command line parser - @\/c@ takes a+-- raw command string, not individually-quoted arguments.  GHC's 'Proc.proc'+-- wraps each arg in double quotes for the @CommandLineToArgvW@ convention,+-- but cmd.exe doesn't use that convention, so a derivation like:+--+-- @+-- derivation { builder = "cmd.exe"; args = [ "\/c" "echo Hello" ]; ... }+-- @+--+-- would fail because GHC quotes @echo Hello@ as @\"echo Hello\"@, and+-- cmd.exe tries to find an executable literally named @\"echo Hello\"@.+--+-- Fix: when the builder is cmd.exe with @\/c@, use 'Proc.shell' which+-- passes the command string directly to @cmd.exe \/c@ without quoting.+-- For all other builders, use 'Proc.proc' (standard @CommandLineToArgvW@).+mkBuilderProcess :: FilePath -> [String] -> Proc.CreateProcess+mkBuilderProcess builder args+  | isWindows,+    isCmdExe builder,+    Just cmdString <- extractCmdString args =+      Proc.shell cmdString+  | otherwise = Proc.proc builder args++-- | Check if the builder is cmd.exe (case-insensitive, handles full paths).+isCmdExe :: FilePath -> Bool+isCmdExe path = map toLower (takeFileName path) == "cmd.exe"++-- | Extract the raw command string from cmd.exe args.+-- Looks for @\/c@ (case-insensitive) and joins everything after it.+extractCmdString :: [String] -> Maybe String+extractCmdString (flag : cmdArgs)+  | map toLower flag == "/c" = Just (unwords cmdArgs)+extractCmdString _ = Nothing++-- | Whether we are running on Windows (compile-time constant via 'System.Info').+isWindows :: Bool+isWindows = System.Info.os == "mingw32"++-- ---------------------------------------------------------------------------+-- Built-in fetcher (builtin:fetchurl)+-- ---------------------------------------------------------------------------++-- | Run a @builtin:fetchurl@ derivation: try URLs in order, each under the+-- retry policy, make the output from what each serves, and verify it+-- against the derivation's @outputHash@.  Nix's bootstrap fetcher is+-- baked into the binary because nothing can be fetched before a fetcher+-- exists.  Returns @Either (exit, msg) ()@, which the build reports as a+-- refused builder, so the shared output-registration path is reused+-- unchanged.+--+-- The output is made as upstream's builtin makes it (@builtinFetchurl@ in+-- fetchurl.cc): the download is the output file, or, when @unpack@ is+-- true, a NAR restored as the output ('Unpacking'); then, when+-- @executable@ is true, the output is made executable ('Marking').  The+-- hash it is held to is the one the derivation declares, in the mode it+-- declares whatever made the output, as upstream's @registerOutputs@+-- holds it ('fixedOutputDigest'): a flat hash needs a regular file its+-- owner may not execute and is of its bytes, and a recursive one is of+-- the output's NAR.  @\<nix\/fetchurl.nix\>@ declares a recursive hash+-- for either attribute.  The store's volume decides how a NAR's names+-- are written and read back.+runBuiltinFetchurl :: Logger -> FetchRetryPolicy -> CaseSensitivity -> Derivation -> [(Text, FilePath)] -> IO (Either (Int, Text) ())+runBuiltinFetchurl logger policy sensitivity drv outputDirs =+  case (fetchUrlsFromEnv env, lookup envOut outputDirs, hashedOutput) of+    (Left err, _, _) -> pure (Left (1, "builtin:fetchurl: " <> err))+    (_, Nothing, _) -> pure (Left (1, "builtin:fetchurl: derivation defines no 'out' output"))+    (_, _, Nothing) -> pure (Left (1, "builtin:fetchurl: 'out' output has no fixed-output hash"))+    (Right urls@(firstUrl :| _), Just outPath, Just out)+      -- Invalid specifications reject before any network traffic.+      | Nothing <- hexToBytes (doHash out) ->+          pure (Left (1, malformedExpectedHash firstUrl))+      | otherwise -> case hashInitWithAlgo algo of+          Nothing ->+            pure (Left (1, "builtin:fetchurl: unsupported hash algorithm '" <> algo <> "'"))+          Just ctx -> do+            result <- tryFetchUrlsWith (fetchWithRetry outPath out ctx) urls+            pure $ case result of+              Left err -> Left (1, err)+              Right value -> Right value+      where+        algo = snd (splitHashMode (doHashAlgo out))+  where+    env = drvEnv drv+    unpacking+      | attrIsTrue envUnpack env = RestoreNar+      | otherwise = KeepDownload+    marking+      | attrIsTrue envExecutable env = MarkExecutable+      | otherwise = LeaveMode+    -- builtin:fetchurl derivations are always fixed-output; the expected hash+    -- lives in the canonical output spec (doHashAlgo + doHash), not the env.+    hashedOutput = case drvOutputs drv of+      (out : _) | not (T.null (doHashAlgo out)) -> Just out+      _ -> Nothing+    fetchWithRetry outPath out ctx url =+      first attemptFailureMessage <$> retryTransient policy (ioRetryEffects logger) (fetchAndVerify outPath out ctx url)+    -- Every attempt makes the output from nothing (a restore creates each+    -- node exclusively, so what an earlier attempt left would refuse it)+    -- and hashes from the original context, so a retry never resumes a+    -- torn transfer: upstream resumes from the written offset when the+    -- server accepts ranges and otherwise gives up, which this restart+    -- subsumes.  An output that cannot be marked or that verifies wrong+    -- is the server's bytes, not a hiccup: upstream checks the hash after+    -- the transfer layer has given up retrying, so a mismatch is never+    -- retried.+    fetchAndVerify outPath out ctx url = runExceptT $ do+      liftIO (removePathForcibly outPath)+      writtenDigest <- withExceptT prefixFailure (ExceptT (downloadUrlWith url (makeOutput outPath ctx url)))+      ExceptT (markOutput outPath)+      withExceptT FatalFailure (ExceptT (verifyOutput outPath out url writtenDigest))+    -- Making the output yields the digest of the bytes written when+    -- they are the output file as it was served.+    makeOutput outPath ctx url body = case unpacking of+      KeepDownload -> Right . Just <$> writeBody outPath ctx body+      RestoreNar -> fmap (const Nothing) <$> restoreNarBody sensitivity outPath (narEncodingOf url) body+    -- The root is read without following a link ('Marking').+    markOutput outPath = case marking of+      LeaveMode -> pure (Right ())+      MarkExecutable -> do+        node <- classifyWalkNode outPath+        case node of+          WalkRegular -> Right () <$ ExecBit.markExecutable outPath+          WalkDirectory -> pure (Right ())+          WalkSymlink -> pure (Left (unmarkable outPath "the output is a symlink"))+          WalkAbsent -> pure (Left (unmarkable outPath "the output does not exist"))+    unmarkable outPath reason =+      FatalFailure ("builtin:fetchurl: making '" <> T.pack outPath <> "' executable: " <> reason)+    -- A flat hash of a download written as it was served is the digest+    -- taken as it streamed to disk; any other output is hashed as it now+    -- is on disk.+    verifyOutput outPath out url writtenDigest = case (splitHashMode (doHashAlgo out), writtenDigest) of+      ((False, _), Just digest) -> pure (first snd (verifyFetchedDigest url out digest))+      _ -> do+        digest <- fixedOutputDigest (volumeCaseHack sensitivity) out outPath+        pure (either (Left . ("builtin:fetchurl: " <>)) (first snd . verifyFetchedDigest url out) digest)+    prefixFailure failure = case failure of+      TransientFailure msg -> TransientFailure ("builtin:fetchurl: " <> msg)+      FatalFailure msg -> FatalFailure ("builtin:fetchurl: " <> msg)++-- | What @builtin:fetchurl@ makes its output from: the download as it+-- is, or the NAR the download holds, restored.  Upstream restores when+-- the derivation's @unpack@ is true (@builtinFetchurl@ in fetchurl.cc).+data Unpacking = KeepDownload | RestoreNar++-- | Whether @builtin:fetchurl@ makes its output executable once it is+-- made: upstream does when the derivation's @executable@ is true, with a+-- @chmod@ to @0755@ that the store's canonical metadata then makes+-- @0555@ (@builtinFetchurl@ in fetchurl.cc).  Here a regular file is marked+-- executable ('ExecBit.markExecutable'), on POSIX by its owner's execute+-- bit, which the canonical metadata makes @0555@ alike.  A directory is+-- left as it is: a NAR records no mode for one, and canonical metadata+-- makes every directory @0555@.+--+-- A symlink root fails the URL, and the next is tried.  Upstream's+-- @chmod@ follows the link, in the build's child process: after the+-- @chroot@ when the build is sandboxed, and as the build user when there+-- are build users (@runChild@ in local-derivation-goal.cc at 2.24.9,+-- unix-derivation-builder.cc at 2.36.0).  There a target outside the+-- build is absent or not the build user's to change, so the @chmod@ fails+-- the build; only a build with neither changes the file the link names.+-- nova-nix runs every builtin as the invoking user with neither, so it+-- does not follow the link.+data Marking = LeaveMode | MarkExecutable++-- | How the NAR a download holds is encoded.+data NarEncoding = PlainNar | XzNar++-- | The encoding of the NAR a URL serves: xz when the URL ends in+-- 'xzUrlSuffix', as upstream decides (@builtinFetchurl@ in fetchurl.cc).+-- Upstream asks it of the derivation's @url@ whatever URL it fetches;+-- here it is asked of each URL tried, which for a derivation+-- @\<nix\/fetchurl.nix\>@ writes is that @url@ alone.+narEncodingOf :: Text -> NarEncoding+narEncodingOf url+  | xzUrlSuffix `T.isSuffixOf` url = XzNar+  | otherwise = PlainNar++-- | Whether a derivation attribute is true as upstream's+-- @builtin:fetchurl@ reads one: its value is exactly 'envTrue', and+-- anything else, an absent attribute included, is false.+attrIsTrue :: Text -> Map Text BS.ByteString -> Bool+attrIsTrue key env = Map.lookup key env == Just envTrue++-- | Nova's mirror extension uses the ASCII-whitespace-separated @urls@ field.+-- An absent field falls back to the single @url@ attribute. An explicit+-- empty or malformed list is an error, rather than a silent fallback.+fetchUrlsFromEnv :: Map Text BS.ByteString -> Either Text (NonEmpty Text)+fetchUrlsFromEnv env = case Map.lookup envUrls env of+  Just bytes -> do+    text <- decode envUrls bytes+    maybe (Left "'urls' is empty") Right (NE.nonEmpty (filter (not . T.null) (T.split separator text)))+  Nothing -> case Map.lookup envUrl env of+    Nothing -> Left "derivation has no 'url' or 'urls'"+    Just bytes -> do+      url <- decode envUrl bytes+      if T.null url then Left "'url' is empty" else Right (url :| [])+  where+    -- Match the fetcher expression's POSIX space class, preserving non-ASCII+    -- URL characters that 'T.words' would otherwise split into new candidates.+    separator char = isAscii char && isSpace char+    decode field = first (const ("'" <> field <> "' contains invalid UTF-8")) . TE.decodeUtf8'++-- | Ordered fallback policy, independent of HTTP and files. Only the first+-- successful /verified/ attempt wins; report every failure if none wins.+-- Exceptions propagate, so cancellation cannot start another download.+tryFetchUrlsWith :: (Monad m) => (Text -> m (Either Text a)) -> NonEmpty Text -> m (Either Text a)+tryFetchUrlsWith attempt = go []+  where+    go !failures (url :| rest) = do+      result <- attempt url+      case result of+        Right value -> pure (Right value)+        Left err -> case NE.nonEmpty rest of+          Nothing -> pure (Left (T.intercalate "\n" (reverse (err : failures))))+          Just urls -> go (err : failures) urls++-- ---------------------------------------------------------------------------+-- Download+-- ---------------------------------------------------------------------------++-- | Write a response body to the output file as it streams, through the+-- incremental hash chunk by chunk, so memory stays at chunk size no+-- matter the download's size, and return the digest of exactly the+-- written bytes.+writeBody :: FilePath -> IncrementalHash -> HTTP.BodyReader -> IO BS.ByteString+writeBody outPath ctx0 body =+  System.IO.withBinaryFile outPath System.IO.WriteMode $ \handle ->+    let consume !ctx = do+          chunk <- HTTP.brRead body+          if BS.null chunk+            then pure (hashFinalizeBytes ctx)+            else do+              BS.hPut handle chunk+              consume (hashUpdateChunk ctx chunk)+     in consume ctx0++-- | Restore the NAR a response body holds as the output, through the+-- store's streaming restore, as the substituter restores one: names are+-- spelled for the store's volume, and nothing is held whole.  An xz body+-- is decompressed on the way ('fetchurlXzLimits').  The store refusing+-- what the archive holds is fatal, and a body that ends short of a whole+-- archive is transient ('narStreamFailure').  The archive ends at its+-- root node's close and the body after it is left unread, as upstream's+-- restore stops reading the download there.+restoreNarBody :: CaseSensitivity -> FilePath -> NarEncoding -> HTTP.BodyReader -> IO (Either AttemptFailure ())+restoreNarBody sensitivity outPath encoding body = case encoding of+  PlainNar -> restore (HTTP.brRead body)+  XzNar -> withXzAttempt fetchurlXzLimits (HTTP.brRead body) restore+  where+    restore source = do+      sink <- newNarUnpackSink sensitivity outPath+      streamed <- sinkNarStream AtRootClose sink source+      case streamed of+        Left failure -> pure (Left (narStreamFailure failure))+        Right _ -> first FatalFailure <$> finishNarUnpack sink++-- | The bounds on decompressing an @.xz@ download.  The output has none,+-- as upstream's has none: it streams to disk, never held whole, and the+-- hash the output is held to vouches for it.  The decoder's memory has+-- nova-cache's default bound, the hardening the substituter applies,+-- where upstream's decoder, libarchive's, has none.+fetchurlXzLimits :: Xz.XzLimits+fetchurlXzLimits =+  Xz.XzLimits+    { Xz.xzMaxOutputBytes = maxBound,+      Xz.xzMaxDecoderMemoryBytes = Xz.defaultXzDecoderMemoryBytes+    }++-- | Verify a downloaded body, as the flat output file it makes, against+-- the derivation's fixed-output hash, read from the canonical output+-- spec.  @doHashAlgo@ is @sha256@/@sha512@/... (or @r:sha256@ for+-- recursive); @doHash@ is the base-16 digest eval normalized the user's+-- hash into.  A recursive hash is of the output's NAR, which the body+-- alone does not settle (the builtin may restore it, or mark it+-- executable), so it is refused rather than compared with the body's+-- flat digest.+verifyFetchHash :: Text -> DerivationOutput -> BS.ByteString -> Either (Int, Text) ()+verifyFetchHash url out body+  | recursive = Left (1, "builtin:fetchurl: a recursive hash is of the output's NAR, not of the downloaded bytes")+  | otherwise = case (hexToBytes (doHash out), rawHashWithAlgo algo body) of+      (Nothing, _) -> Left (1, malformedExpectedHash url)+      (_, Nothing) -> Left (1, "builtin:fetchurl: unsupported hash algorithm '" <> algo <> "'")+      (Just _, Just got) -> verifyFetchedDigest url out got+  where+    (recursive, algo) = splitHashMode (doHashAlgo out)++-- | Compare a digest of the output, in its declared algorithm and mode,+-- with the derivation's fixed-output hash, naming the URL it came from:+-- the digest of the bytes as they were written, or of the output on+-- disk ('fixedOutputDigest').  'verifyFetchHash' is its twin over a+-- buffered body.+verifyFetchedDigest :: Text -> DerivationOutput -> BS.ByteString -> Either (Int, Text) ()+verifyFetchedDigest url out got = case hexToBytes (doHash out) of+  Nothing -> Left (1, malformedExpectedHash url)+  Just expected+    | expected == got -> Right ()+    | otherwise ->+        Left+          ( 1,+            "builtin:fetchurl: hash mismatch for "+              <> url+              <> "\n  expected: "+              <> algoField+              <> ":"+              <> doHash out+              <> "\n  got:      "+              <> algoField+              <> ":"+              <> bytesToHexText got+          )+  where+    algoField = doHashAlgo out++-- | Split @outputHashAlgo@ into the recursive-mode marker and the bare+-- algorithm name (@r:sha256@ is recursive @sha256@).+splitHashMode :: Text -> (Bool, Text)+splitHashMode algoField = case T.stripPrefix "r:" algoField of+  Just rest -> (True, rest)+  Nothing -> (False, algoField)++malformedExpectedHash :: Text -> Text+malformedExpectedHash url = "builtin:fetchurl: malformed expected hash for " <> url++-- ---------------------------------------------------------------------------+-- Output registration+-- ---------------------------------------------------------------------------++-- | After a successful build, register every output in the store, in+-- upstream's two passes (registerOutputs in local-derivation-goal.cc at+-- 2.24.9, derivation-builder-impl.cc at 2.36.0).  Every output is scanned+-- first.  Then the outputs are ordered so that each follows the siblings it+-- references ('orderByReferences'), and placed in that order.  Outputs that+-- reference each other in a cycle fail the build before any is placed, so+-- none is registered.+--+-- The placed outputs register together in one transaction, so a+-- cross-output reference finds its referent's row (see 'registerPaths').+registerOutputs ::+  Store ->+  Derivation ->+  StorePath ->+  Set StorePath ->+  [OutputPlan] ->+  Written ->+  Commit ->+  IO (Either BuildStop StorePath)+registerOutputs store drv drvPath inputPaths plans written commit = runExceptT $ do+  scanned <- withExceptT scanStop (traverse (scanOutput store scan written) (zip (drvOutputs drv) plans))+  ordered <- liftEither (orderScanned drvPath (siblingsReferenced (drvOutputs drv)) scanned)+  regs <- withExceptT FixedOutputRefused (traverse (ExceptT . placeOutput store drvPath deriver . snd) ordered)+  liftIO (commit (registerPaths (stDB store) (catMaybes regs)))+  case drvOutputs drv of+    (firstOut : _) -> pure (doPath firstOut)+    [] -> throwError (BuildStop noOutputsMessage 1)+  where+    scan = outputScan drv inputPaths plans+    -- Every output names the @.drv@ that built it, as upstream's+    -- @newInfo.deriver = drvPath@ does (@registerOutputs@ in+    -- local-derivation-goal.cc at 2.24.9, derivation-builder-impl.cc at+    -- 2.36.0), spelled as the store's own rows spell a path, the form a+    -- substituted path's deriver takes ('Nix.Substituter.parseDeriver').+    deriver = Just (T.pack (storePathToFilePath (stDir store) drvPath))++-- | After a successful rebuild under 'BuildCheck', compare every output+-- with the NAR hash the store recorded for it, the hashes in the order of+-- the derivation's outputs: upstream's @registerOutputs@ under @bmCheck@+-- (local-derivation-goal.cc at 2.24.9).  Every output is scanned and the+-- outputs ordered as a build's are, so a reference cycle between them+-- fails a check as it fails a build (its @wanted@ flag and its @topoSort@+-- of the outputs).  Each is then compared in that order, an output after+-- the siblings it references, and the first that differs ends the+-- comparison, where upstream's loop throws (its @bmCheck@ branch).+--+-- Nothing is registered and no valid output is touched.  The rebuild of+-- the output that differs is discarded with the rest, or under+-- 'KeepFailed' moved to the output's path with @.check@ after it+-- ('checkedOutputPath'), as upstream moves it under @keep-failed@:+-- rewritten and canonical, as it was compared, unregistered, and+-- replacing whatever was at that path.  Upstream marks a path it has+-- checked as ultimately trusted and signs it; the check here does+-- neither.+compareOutputs ::+  FailedBuilds ->+  Store ->+  Derivation ->+  StorePath ->+  [Text] ->+  Set StorePath ->+  [OutputPlan] ->+  Written ->+  Commit ->+  IO (Either BuildStop CheckVerdict)+compareOutputs failedBuilds store drv drvPath recordedHashes inputPaths plans written _ = runExceptT $ do+  built <- withExceptT scanStop (traverse rebuilt (zip3 (drvOutputs drv) plans recordedHashes))+  ordered <- liftEither (orderScanned drvPath (siblings . boReferences . fst) built)+  differing <- ExceptT (firstDifference (volumeCaseHack (stCaseSensitivity store)) drvPath (map snd ordered))+  liftIO (maybe (pure OutputsMatch) (differingVerdict failedBuilds store) differing)+  where+    scan = outputScan drv inputPaths plans+    siblings = siblingNames (drvOutputs drv)+    rebuilt (output, plan, recorded) = do+      outDir <- writtenOutput (writtenPath written plan)+      open <- liftIO (writtenOpen written plan)+      scanned <- preparedOutput scan output outDir open (writtenOwner written)+      pure (doName output, (scanned, recorded))++-- | The stop a failed scan or placement reports.+scanStop :: Text -> BuildStop+scanStop message = BuildStop message 1++-- | Order scanned outputs so that each follows the siblings it references+-- ('orderByReferences'), or stop the build at a cycle among them.+orderScanned :: StorePath -> (v -> Set Text) -> [(Text, v)] -> Either BuildStop [(Text, v)]+orderScanned drvPath references scanned =+  first (scanStop . outputCycleMessage drvPath) (orderByReferences references (Map.fromList scanned))++-- | Upstream's failure for outputs that reference each other in a cycle+-- (@registerOutputs@ in local-derivation-goal.cc at 2.24.9,+-- derivation-builder-impl.cc at 2.36.0), naming the @.drv@ and the+-- reference that closes the cycle.+outputCycleMessage :: StorePath -> ReferenceCycle Text -> Text+outputCycleMessage drvPath (ReferenceCycle node referrer) =+  "cycle detected in build of '"+    <> storePathToText defaultStoreDir drvPath+    <> "' in the references of output '"+    <> node+    <> "' from output '"+    <> referrer+    <> "'"++-- | What the scan of a build's outputs rewrites and looks for.+data OutputScan = OutputScan+  { -- | Each redirected output's scratch hash and the final one it+    -- becomes.  An output may record a sibling, or itself, whose build+    -- wrote to a scratch path that is about to stop existing.  Upstream+    -- scans first and translates its hits; rewriting first lets the scan+    -- see final hashes and needs no translation, and the references come+    -- out the same.+    osScratchRewrites :: ![(Text, Text)],+    -- | Candidates for reference scanning: the input closure and this+    -- derivation's own outputs, upstream's @referenceablePaths@+    -- (@registerOutputs@ in local-derivation-goal.cc at 2.24.9,+    -- derivation-builder-impl.cc at 2.36.0).+    osCandidates :: ![StorePath]+  }++-- | The scan for a derivation's outputs, given the closure of its inputs+-- and where each output was written.+outputScan :: Derivation -> Set StorePath -> [OutputPlan] -> OutputScan+outputScan drv inputPaths plans =+  OutputScan+    { osScratchRewrites = [(spHash (opScratch p), spHash (opFinal p)) | p <- plans, opValid p],+      osCandidates = Set.toList inputPaths ++ map doPath (drvOutputs drv)+    }++-- | One output after the scan and before it is placed: upstream's+-- @AlreadyRegistered@ and @PerhapsNeedToRegister@.+data ScannedOutput+  = -- | Registered before the build, and left as it is.+    AlreadyRegistered+  | -- | Built here.+    NeedsRegistering !BuiltOutput++-- | An output the builder wrote, after the scan.+data BuiltOutput = BuiltOutput+  { boOutput :: !DerivationOutput,+    -- | Where the builder wrote it.+    boDir :: !FilePath,+    -- | The references the scan found in it.+    boReferences :: ![StorePath]+  }++-- | Where the builder's output is now, which has to be there (a file, a+-- directory, or a symlink, whatever it names).+writtenOutput :: FilePath -> ExceptT Text IO FilePath+writtenOutput outDir = do+  absent <- liftIO (nothingAt outDir)+  when absent (throwError ("output missing: " <> T.pack outDir))+  pure outDir++-- | Whether nothing is at a path, read without following a link, as+-- upstream reads an output (@maybeLstat@ in @registerOutputs@,+-- local-derivation-goal.cc at 2.24.9, derivation-builder-impl.cc at+-- 2.36.0): one that is a symlink is there whatever it names, a sibling+-- output still in the chroot, or nothing at all.+nothingAt :: FilePath -> IO Bool+nothingAt path = do+  node <- classifyWalkNode path+  pure $ case node of+    WalkAbsent -> True+    WalkRegular -> False+    WalkDirectory -> False+    WalkSymlink -> False++-- | Scan one output of a build, keyed by its name: skip it if it is+-- already valid in the DB, otherwise make ready what the builder wrote+-- ('preparedOutput').+scanOutput ::+  Store ->+  OutputScan ->+  Written ->+  (DerivationOutput, OutputPlan) ->+  ExceptT Text IO (Text, ScannedOutput)+scanOutput store scan written (output, plan) = do+  outDir <- writtenOutput (writtenPath written plan)+  -- Validity is a DB fact, not mere disk presence: an output left on disk+  -- by an interrupted run is NOT valid, and build outputs are not+  -- content-addressed, so a leftover cannot be verified against its path.+  -- 'runPlannedBuild' removed any leftover before the builder ran, so the+  -- tree here is this build's (upstream's delete-then-move).+  valid <- liftIO (isValid store (doPath output))+  scanned <-+    if valid+      then pure AlreadyRegistered+      else do+        open <- liftIO (writtenOpen written plan)+        NeedsRegistering <$> preparedOutput scan output outDir open (writtenOwner written)+  pure (doName output, scanned)++-- | An output the builder wrote, made ready where it is to be placed or+-- compared, in upstream Nix's order: one that lets its group or anyone+-- else write it, or a build user's that another user owns, is refused,+-- since someone other than the build may have changed it, and so is one+-- holding a node a user other than the builder's owns; it is made canonical, so nothing in it is setuid or writable by+-- another user, before it is read or changed; a fixed output is replaced with+-- a fresh copy of itself, made canonical again, so a descriptor the builder+-- passed out names an inode that is not registered; and its hashes are+-- rewritten and its references scanned ('scanBuilt').  Whether others could+-- write the output is read from what the builder left, before a Linux+-- sandboxed build's seal changed its mode.  Its chroot is closed to+-- other users before this ('Nix.Builder.Sandbox.Spawn.sealChroot'); a process+-- of the same user can still change an output while it is read.+preparedOutput :: OutputScan -> DerivationOutput -> FilePath -> Bool -> OutputOwner -> ExceptT Text IO BuiltOutput+preparedOutput scan output outDir open owner = do+  foreignRoot <- liftIO (ownedByAnother owner outDir)+  when (open || foreignRoot) (throwError ("suspicious ownership or permission on '" <> T.pack outDir <> "' for output '" <> doName output <> "'; rejecting this build output"))+  othersNode <- liftIO (foreignOwnedNode owner outDir)+  for_ othersNode (\node -> throwError ("invalid ownership on file '" <> T.pack node <> "'"))+  liftIO (canonicalizeMetadata outDir)+  -- The copy is made canonical in its turn, and it is the copy that is+  -- read: its inodes are new, so no descriptor another user holds+  -- reaches what is scanned, hashed and moved into the store.+  unless (T.null (doHashAlgo output)) (liftIO (replaceWithCopy outDir *> canonicalizeMetadata outDir))+  liftIO (scanBuilt scan output outDir)++-- | Rewrite scratch hashes in an output the builder wrote, then scan it+-- for references to the input closure and this derivation's outputs.+--+-- One scan, not two: the candidates already carry this derivation's own+-- outputs, and after the rewrite the tree names them by their final+-- hashes, so a self- or cross-output reference is an ordinary hit.+scanBuilt :: OutputScan -> DerivationOutput -> FilePath -> IO BuiltOutput+scanBuilt scan output outDir = do+  rewriteStoreHashes (osScratchRewrites scan) outDir+  refs <- dedupStorePaths <$> scanReferences (osCandidates scan) outDir+  pure (BuiltOutput output outDir refs)++-- | The names of the sibling outputs among an output's references.+siblingNames :: [DerivationOutput] -> [StorePath] -> Set Text+siblingNames outputs = Set.fromList . mapMaybe (`Map.lookup` nameByPath)+  where+    nameByPath = Map.fromList [(doPath o, doName o) | o <- outputs]++-- | The names of the sibling outputs an output's scan found.  An output+-- registered before the build references none: upstream uses the+-- registered copy and treats it as a leaf.+siblingsReferenced :: [DerivationOutput] -> ScannedOutput -> Set Text+siblingsReferenced outputs = referencedBy+  where+    siblings = siblingNames outputs+    referencedBy AlreadyRegistered = Set.empty+    referencedBy (NeedsRegistering built) = siblings (boReferences built)++-- | Compare rebuilt outputs, each with the NAR hash the store recorded for+-- it, in order, up to the first that differs, which is answered, or+-- cannot be compared.+firstDifference :: NAR.CaseHack -> StorePath -> [(BuiltOutput, Text)] -> IO (Either BuildStop (Maybe BuiltOutput))+firstDifference _ _ [] = pure (Right Nothing)+firstDifference caseHack drvPath (rebuilt : rest) = do+  compared <- compareOutput caseHack drvPath rebuilt+  case compared of+    Right Nothing -> firstDifference caseHack drvPath rest+    ended -> pure ended++-- | The verdict on a rebuilt output that differs from the valid one, its+-- rebuild kept or discarded as 'compareOutputs' says.+differingVerdict :: FailedBuilds -> Store -> BuiltOutput -> IO CheckVerdict+differingVerdict failedBuilds store built =+  OutputDiffers output <$> case failedBuilds of+    RemoveFailed -> pure RebuildDiscarded+    KeepFailed -> RebuildKept <$ (removePathForcibly kept *> moveOutput (boDir built) kept)+  where+    output = doPath (boOutput built)+    kept = checkedOutputPath (stDir store) output++-- | Compare one rebuilt output with the NAR hash the store recorded for+-- the valid one, which is all upstream compares (@newInfo.narHash !=+-- oldInfo.narHash@ in @registerOutputs@, local-derivation-goal.cc at+-- 2.24.9, derivation-builder-impl.cc at 2.36.0).  The rebuilt tree's hash+-- is 'ExecBit.narHashOfPath', which streams the archive that registration+-- serialises whole ('Nix.Store.registrationFor'), under the same case-hack+-- mode and source of the executable bit.+--+-- A fixed output is held to its declared hash first, as a build holds it:+-- upstream raises that mismatch for a checked fixed output and never+-- reaches the comparison (the @CAFixed@ case, the @bmCheck@ branch and the+-- final rethrow of @delayedException@ in @registerOutputs@ at 2.24.9).+-- 'Right' answers the output when it differs.+compareOutput :: NAR.CaseHack -> StorePath -> (BuiltOutput, Text) -> IO (Either BuildStop (Maybe BuiltOutput))+compareOutput caseHack drvPath (built, recorded) = do+  fixedCheck <- verifyFixedOutput caseHack drvPath (boOutput built) (boReferences built) (boDir built)+  case fixedCheck of+    Left err -> pure (Left (FixedOutputRefused err))+    Right () -> do+      rebuilt <- Hash.formatNixHash <$> ExecBit.narHashOfPath caseHack (boDir built)+      pure (Right (if narHashMatches recorded rebuilt then Nothing else Just built))++-- | Place a scanned output in the store and check a fixed output's+-- content, returning its t'PathRegistration'; @Nothing@ for an output+-- registered before the build.  The output is ultimately trusted, as+-- upstream marks an output it built, and a fixed output has the content+-- address it was checked against ('fixedOutputAddress').  'Left' is why a+-- fixed output was refused.+placeOutput :: Store -> StorePath -> Maybe Text -> ScannedOutput -> IO (Either Text (Maybe PathRegistration))+placeOutput store drvPath deriver scanned = case scanned of+  AlreadyRegistered -> pure (Right Nothing)+  NeedsRegistering (BuiltOutput output outDir refs) -> do+    -- An unsandboxed or macOS sandboxed builder wrote straight into the+    -- store path, so there outDir IS the target and placing it moves+    -- nothing; a Linux sandboxed one's moves out of the chroot here.+    let targetPath = storePathToFilePath (stDir store) (doPath output)+    reg <- placeInStore store outDir (doPath output) deriver refs+    fixedCheck <- verifyFixedOutput (volumeCaseHack (stCaseSensitivity store)) drvPath output refs targetPath+    case fixedCheck of+      Left err -> do+        -- Wrong bytes for a declared content address: remove the placed+        -- tree so a later run cannot meet it on disk.  'removePathForcibly'+        -- clears the read-only marks placing set.+        removePathForcibly targetPath+        pure (Left err)+      Right () -> pure (Right (Just reg {prUltimate = Ultimate, prContentAddress = fixedOutputAddress output}))++-- | The content address a fixed output's declaration gives it: its+-- method, algorithm and hash, which 'verifyFixedOutput' holds the output+-- to.  None for an output that is not fixed.+fixedOutputAddress :: DerivationOutput -> Maybe ContentAddress+fixedOutputAddress out+  | T.null (doHashAlgo out) = Nothing+  | otherwise = hexToBytes (doHash out) >>= contentAddressFromParts (FixedMethod ingestion) algo+  where+    (recursive, algo) = splitHashMode (doHashAlgo out)+    ingestion+      | recursive = NarIngestion+      | otherwise = FlatIngestion++-- | A reference cycle, named by the reference that closes it: the node+-- reached again while it is still on the walk's path, and the node whose+-- reference reached it.+data ReferenceCycle k = ReferenceCycle+  { cycleNode :: !k,+    cycleReferrer :: !k+  }+  deriving (Eq, Show)++-- | Where the walk in 'orderByReferences' is: the nodes it has entered,+-- and the ones it has finished, the last finished first.+data Walk k v = Walk+  { walkEntered :: !(Set k),+    walkFinished :: ![(k, v)]+  }++-- | Order nodes so that each follows every node it references, or report+-- a cycle among them: upstream's @topoSort@ (src/libutil/topo-sort.hh at+-- 2.24.9) with the reversal its @registerOutputs@ applies to the result+-- (local-derivation-goal.cc at 2.24.9, derivation-builder-impl.cc at+-- 2.36.0).+--+-- The walk is upstream's depth-first one, so the order and the cycle it+-- reports are upstream's too: it starts from each node in ascending+-- order, follows each node's references in ascending order, ignores a+-- self-reference and a reference to a node not in the map, and lists a+-- node once everything it references is listed.  The first reference that+-- leads back to a node still on the path is the cycle reported.+orderByReferences :: (Ord k) => (v -> Set k) -> Map k v -> Either (ReferenceCycle k) [(k, v)]+orderByReferences references nodes =+  reverse . walkFinished <$> foldM (visit Set.empty) (Walk Set.empty []) (Map.toAscList nodes)+  where+    visit onPath walk node@(key, value)+      | Set.member key (walkEntered walk) = Right walk+      | otherwise = do+          let referenced =+                [ (child, childValue)+                | child <- Set.toAscList (references value),+                  child /= key,+                  Just childValue <- [Map.lookup child nodes]+                ]+          finished <-+            foldM+              (follow (Set.insert key onPath) key)+              walk {walkEntered = Set.insert key (walkEntered walk)}+              referenced+          pure finished {walkFinished = node : walkFinished finished}+    follow onPath referrer walk child@(key, _)+      | Set.member key onPath = Left (ReferenceCycle key referrer)+      | otherwise = visit onPath walk child++-- | Re-check a placed fixed-output output against its declared hash.+-- A fixed-output derivation declares both its store path and, via the+-- output spec (@doHashAlgo@ + @doHash@), the exact content the path+-- must carry - but the builder process writes the actual bytes, so the+-- placed result must reproduce the declared digest before it may+-- register as valid (upstream: the fixed-output check in its+-- registerOutputs).  Flat mode hashes the bytes of an output that must+-- be a regular file its owner may not execute; recursive (@r:@) mode+-- hashes the canonical NAR of the placed tree ('fixedOutputDigest').+-- Non-fixed outputs (empty @doHashAlgo@) pass unchecked.+--+-- A fixed output that references any store path, itself included, is+-- refused once its digest is taken, in upstream's order: an output its+-- hash mode cannot take fails first, and a reference before a hash that+-- does not match (the @CAFixed@ case of @registerOutputs@ in+-- local-derivation-goal.cc at 2.24.9).  Its path comes from its content+-- alone, which a reference would leave incomplete.  Upstream registers such+-- an output under the path its references give it before it fails the build;+-- nova-nix registers nothing, as for a hash that does not match.+verifyFixedOutput :: NAR.CaseHack -> StorePath -> DerivationOutput -> [StorePath] -> FilePath -> IO (Either Text ())+verifyFixedOutput caseHack drvPath out refs placedPath+  | T.null (doHashAlgo out) = pure (Right ())+  | otherwise = (>>= unreferenced) <$> fixedOutputDigest caseHack out placedPath+  where+    unreferenced got+      | null refs = matches got+      | otherwise = Left ("illegal path references in fixed-output derivation '" <> storePathToText defaultStoreDir drvPath <> "'")+    subject = fixedOutputSubject out+    matches got = case hexToBytes (doHash out) of+      Nothing -> Left (subject <> ": malformed expected hash")+      Just expected+        | expected == got -> Right ()+        | otherwise ->+            Left+              ( subject+                  <> ": hash mismatch\n  expected: "+                  <> doHashAlgo out+                  <> ":"+                  <> doHash out+                  <> "\n  got:      "+                  <> doHashAlgo out+                  <> ":"+                  <> bytesToHexText got+              )++-- | A fixed output's digest on disk, in its declared algorithm and mode:+-- of a flat output's file bytes, or of a recursive output's NAR, read+-- back under the store volume's case-hack mode and through the exec-bit+-- source of truth registration reads ('ExecBit.withNarSource').  Both+-- stream.  The NAR is serialised again rather than taken from the+-- registration, whose NAR hash is always sha256 where the declared+-- algorithm may be any.+--+-- A flat output must first be a regular file its owner may not execute,+-- read without following a symlink ('isPlainFile'), or it fails with+-- upstream's words for any other (@newInfoFromCA@ in @registerOutputs@,+-- local-derivation-goal.cc at 2.24.9, derivation-builder-impl.cc at 2.36.0):+-- a directory, a symlink whose target's bytes would otherwise be hashed, or+-- an executable file, whose mode a flat hash does not record.+fixedOutputDigest :: NAR.CaseHack -> DerivationOutput -> FilePath -> IO (Either Text BS.ByteString)+fixedOutputDigest caseHack out path+  | recursive = maybe unsupported Right <$> narDigestWithAlgo caseHack algo path+  | otherwise = do+      plain <- isPlainFile path+      if plain+        then maybe unsupported Right <$> hashFileWithAlgo algo path+        else+          pure+            ( Left+                ( "output path '"+                    <> T.pack path+                    <> "' should be a non-executable regular file since recursive hashing is not enabled (one of outputHashMode={flat,text} is true)"+                )+            )+  where+    (recursive, algo) = splitHashMode (doHashAlgo out)+    subject = fixedOutputSubject out+    unsupported = Left (subject <> ": unsupported hash algorithm '" <> algo <> "'")++-- | How a fixed output's check names it.+fixedOutputSubject :: DerivationOutput -> Text+fixedOutputSubject out = "fixed-output '" <> spName (doPath out) <> "'"++-- | Stream a file through the incremental hash without materializing it+-- (a fixed-output file is input-sized).  'Nothing' for an unsupported+-- algorithm.+hashFileWithAlgo :: Text -> FilePath -> IO (Maybe BS.ByteString)+hashFileWithAlgo algo path = case hashInitWithAlgo algo of+  Nothing -> pure Nothing+  Just initialCtx -> System.IO.withBinaryFile path System.IO.ReadMode $ \handle ->+    Just <$> digestSource initialCtx (BS.hGet handle fixedOutputHashChunk)++-- | Stream a path's NAR through the incremental hash, the exec-bit+-- source of truth answering each file's flag.  'Nothing' for an+-- unsupported algorithm.+narDigestWithAlgo :: NAR.CaseHack -> Text -> FilePath -> IO (Maybe BS.ByteString)+narDigestWithAlgo caseHack algo path = case hashInitWithAlgo algo of+  Nothing -> pure Nothing+  Just initialCtx -> Just <$> ExecBit.withNarSource caseHack path (digestSource initialCtx)++-- | Fold a chunk source through the incremental hash up to its first+-- empty chunk, which ends it.+digestSource :: IncrementalHash -> IO BS.ByteString -> IO BS.ByteString+digestSource initialCtx pull = consume initialCtx+  where+    consume !ctx = do+      chunk <- pull+      if BS.null chunk+        then pure (hashFinalizeBytes ctx)+        else consume (hashUpdateChunk ctx chunk)++-- | Read-chunk size for hashing a placed output file.+fixedOutputHashChunk :: Int+fixedOutputHashChunk = 65536++-- | Deduplicate store paths by their (unique) hash.+dedupStorePaths :: [StorePath] -> [StorePath]+dedupStorePaths = Map.elems . Map.fromList . map (\sp -> (spHash sp, sp))++-- ---------------------------------------------------------------------------+-- Dependency-aware build orchestration+-- ---------------------------------------------------------------------------++-- | Realise a derivation and what it needs, root first ("Nix.Realise").+--+-- 1. Build the dependency graph by reading .drv files from the store.+-- 2. Refuse a cycle.+-- 3. Try each derivation's outputs before its inputs, so a substituted+--    derivation needs only its runtime closure.  The root's outputs are+--    all wanted, and of each input only those its dependent's @.drv@+--    names.  What no cache supplies builds locally, leaves first, and so+--    does what a cache fails to deliver when 'bcFallback' allows it, and+--    a derivation that forbids substitutes unless 'bcSubstitutes'+--    overrides it.+--+-- Under 'BuildCheck' ('bcMode') the root is not realised but checked: an+-- output of its that is not valid is substituted, its inputs are realised+-- as above, and it is built again beside its valid outputs and compared+-- with them ('checkDerivation').+--+-- Returns 'BuildSuccess' with the root output path on success, or+-- 'BuildFailure' with the status the build exits with+-- ('realiseFailureStatus'): 104 if a check found an output different, and+-- 1 for any other failure: a derivation fails to build, a substitute fails+-- under 'NoFallback', a cache cannot be asked, a derivation's attributes+-- cannot be read, a check has no valid output to compare with, a+-- dependent asks for an output a derivation does not have, or the graph+-- cannot be read or holds a cycle.+--+-- A store upstream Nix's database may also manage is refused, with+-- status 1, before anything is read or any cache asked+-- ("Nix.Store.Upstream").  Each build and substitution refuses it too,+-- but by then the realisation has asked the caches, and it reports a+-- refused substitute as a failed download.+buildWithDeps :: BuildConfig -> Store -> Derivation -> StorePath -> IO BuildResult+buildWithDeps config store rootDrv rootDrvPath = do+  refusal <- upstreamManagedRefusal ReplacesUpstreamPaths (bcStoreDir config)+  maybe realiseRoot (\reason -> pure (BuildFailure reason 1)) refusal+  where+    realiseRoot = do+      graph <- acyclicGraph <$> buildDepGraph (readDrvFromStore config) rootDrv rootDrvPath+      either (pure . stoppedResult) realiseGraph graph+    realiseGraph depGraph = do+      result <- evalStateT (realise (realiseSettings config) (bcMode config) (realiseEffects config store) depGraph rootDrvPath) emptyCacheMemo+      case result of+        Left failure -> pure (BuildFailure (realiseFailureMessage (bcStoreDir config) failure) (realiseFailureStatus failure))+        Right () ->+          case drvOutputs rootDrv of+            (firstOut : _) -> pure (BuildSuccess (doPath firstOut))+            [] -> pure (BuildFailure noOutputsMessage 1)++-- | Realise several derivations the store holds, each for the outputs a+-- request names ("Nix.Realise"'s 'realiseRequests'): each requested+-- @.drv@ and every input it reaches is read from the store, a cycle among+-- them is refused, and the requests are realised with one record of what+-- is realised.  They are realised and never checked, whatever 'bcMode'+-- says; 'checkStored' checks a derivation.  It stops with the message and+-- status the build reports, which for one request for every output of a+-- derivation are those 'buildWithDeps' gives the same failure.+--+-- A store upstream Nix's database may also manage is refused, with+-- status 1, before anything is read or any cache asked+-- ("Nix.Store.Upstream").+buildRequests :: BuildConfig -> Store -> [(StorePath, Set Text)] -> IO (Either BuildStop ())+buildRequests config store requests = do+  refusal <- upstreamManagedRefusal ReplacesUpstreamPaths (bcStoreDir config)+  maybe (realiseRequestsWith config (realiseEffects config store) requests) (\reason -> pure (Left (BuildStop reason 1))) refusal++-- | Realise several derivations the store holds as 'buildRequests' does,+-- or under 'BuildCheck' check each, and say how each one asked for ended+-- ("Nix.Realise"'s 'realiseEach'): one left unrealised when another+-- failed is not there.  A store upstream Nix's database may also manage,+-- a @.drv@ that cannot be read, a cycle and a failure that ends the call+-- stop it, as they stop 'buildRequests'.+buildRequestsEach :: BuildConfig -> BuildMode -> Store -> [(StorePath, Set Text)] -> IO (Either BuildStop (Map StorePath RequestOutcome))+buildRequestsEach config mode store requests = do+  refusal <- upstreamManagedRefusal ReplacesUpstreamPaths (bcStoreDir config)+  maybe realiseIn (\reason -> pure (Left (BuildStop reason 1))) refusal+  where+    realiseIn = do+      graph <- acyclicGraph <$> buildDepGraphFrom (readDrvFromStore config) (map fst requests)+      either (pure . Left) (\depGraph -> first stopOf <$> evalStateT (realiseEach (realiseSettings config) mode (realiseEffects config store) depGraph requests) emptyCacheMemo) graph+    stopOf failure = BuildStop (realiseFailureMessage (bcStoreDir config) failure) (realiseFailureStatus failure)++-- | Realise requests as 'buildRequests' does where nothing may be written:+-- in a store upstream Nix's database also manages, for an evaluation that+-- runs read-only.  A path is valid as the answer given says, every+-- substitution is refused before a cache is asked, as upstream's+-- read-only evaluation refuses it ('Nix.Realise.noWriteAccessMessage'),+-- and an output that has to be built is refused for the reason given.+-- Nothing is written, and nothing is opened but the @.drv@ files it reads+-- and what the validity answer reads, so a refusal of a substitution comes+-- before the refusal of the store.+realiseWithoutWriting :: Logger -> BuildConfig -> (StorePath -> IO Bool) -> Text -> [(StorePath, Set Text)] -> IO (Either BuildStop ())+realiseWithoutWriting logger config valid reason = realiseRequestsWith config effects+  where+    refused = pure . QueryFailed . noWriteAccessMessage+    effects =+      RealiseEffects+        { reSubst =+            SubstEffects+              { seValid = liftIO . valid,+                seReferences = refused,+                seNextOffer = const . refused,+                seFetch = \_ batch -> pure (NotFetched (fmap (\(path, _) -> (path, DeliveryFailed)) batch))+              },+          reBuild = \_ _ _ -> pure (Left (BuilderStopped reason)),+          reCheck = \_ _ -> pure (Left reason),+          reReport = \status drv -> liftIO (logRealised logger status drv)+        }++-- | Read each requested @.drv@ and every input it reaches from the store,+-- refuse a cycle among them, and realise the requests over the effects+-- given, with the message and status a build that stops reports.+realiseRequestsWith :: BuildConfig -> RealiseEffects Substitute Realising -> [(StorePath, Set Text)] -> IO (Either BuildStop ())+realiseRequestsWith config effects requests = do+  graph <- acyclicGraph <$> buildDepGraphFrom (readDrvFromStore config) (map fst requests)+  either (pure . Left) realiseIn graph+  where+    realiseIn depGraph = do+      result <- evalStateT (realiseRequests (realiseSettings config) effects depGraph requests) emptyCacheMemo+      pure (first (\failure -> BuildStop (requestsFailureMessage (bcStoreDir config) failure) (requestsFailureStatus failure)) result)++-- | Check one derivation the store holds, every output of it, as+-- 'buildWithDeps' does under 'BuildCheck', whatever 'bcMode' says: its+-- @.drv@ is read from the store, and a check that passes answers+-- @Right ()@.  A store upstream Nix's database may also manage is+-- refused, with status 1, before anything is read ("Nix.Store.Upstream").+checkStored :: BuildConfig -> Store -> StorePath -> IO (Either BuildStop ())+checkStored config store drvPath = do+  refusal <- upstreamManagedRefusal ReplacesUpstreamPaths (bcStoreDir config)+  maybe (readDrvFromStore config drvPath >>= either (pure . Left . unreadableGraph) check) (\reason -> pure (Left (BuildStop reason 1))) refusal+  where+    check drv = stopOf <$> buildWithDeps config {bcMode = BuildCheck} store drv drvPath+    stopOf (BuildSuccess _) = Right ()+    stopOf (BuildFailure message code) = Left (BuildStop message code)++-- | A graph that was read and holds no cycle, or the stop a build reports+-- for it.+acyclicGraph :: Either Text DepGraph -> Either BuildStop DepGraph+acyclicGraph (Left err) = Left (unreadableGraph err)+acyclicGraph (Right graph) = case topoSort graph of+  TopoCycle _ -> Left (BuildStop "dependency cycle detected" 1)+  TopoSorted _ -> Right graph++-- | The stop a build reports for a @.drv@ it cannot read.+unreadableGraph :: Text -> BuildStop+unreadableGraph err = BuildStop ("dependency graph error: " <> err) 1++-- | The realisation settings a build configuration gives.+realiseSettings :: BuildConfig -> RealiseSettings+realiseSettings config = RealiseSettings {rsFallback = bcFallback config, rsSubstitutes = bcSubstitutes config}++-- | Read and parse a .drv file from the store, as bytes (no locale+-- decode, no newline translation).+readDrvFromStore :: BuildConfig -> StorePath -> IO (Either Text Derivation)+readDrvFromStore config sp = do+  let drvFilePath = storePathToFilePath (bcStoreDir config) sp+  content <- try (BS.readFile drvFilePath)+  pure $ case content of+    Left (_ :: IOException) -> Left ("cannot read .drv file: " <> T.pack drvFilePath)+    Right bytes -> fromATerm bytes++-- ---------------------------------------------------------------------------+-- Realisation effects+-- ---------------------------------------------------------------------------++-- | A realisation's effects, which carry a t'CacheMemo' through the run,+-- so each cache is opened once and asked about each path once.+type Realising = StateT CacheMemo IO++-- | The store, caches and builder that "Nix.Realise" drives, each build+-- and check an activity of the store's logger.+realiseEffects :: BuildConfig -> Store -> RealiseEffects Substitute Realising+realiseEffects config store =+  RealiseEffects+    { reSubst = substEffects config store,+      reBuild = \drv drvPath _ -> liftIO (asActivity (Building drvPath) (\reporting -> buildReporting config reporting drv drvPath)),+      reCheck = \drv drvPath -> liftIO (asActivity (Checking drvPath) (\reporting -> checkDerivation config reporting drv drvPath)),+      reReport = \status drv -> liftIO (logRealised (stLogger store) status drv)+    }+  where+    asActivity start action = withActivity (stLogger store) start (\logger -> action store {stLogger = logger})++-- | The store and caches a substitution uses: 'bcCaches' asked under+-- 'bcFallback' and 'bcFetchRetry', and what arrives registered in the+-- store ('substitutePaths').  Under 'RefuseSubstitution' the first path+-- asked about is refused instead, a failed query, which ends the call+-- whatever 'bcFallback' says, as upstream's refusal is thrown before+-- @fallback@ is read.  A t'Substitute' names the path it was offered+-- for, which is the path "Nix.Realise" pairs it with.+substEffects :: BuildConfig -> Store -> SubstEffects Substitute Realising+substEffects config store =+  SubstEffects+    { seValid = liftIO . isValid store,+      seReferences = case bcSubstitution config of+        SubstituteFromCaches -> queryReferencesWith (stLogger store) (bcFetchRetry config) (ioRetryEffects (stLogger store)) (bcFallback config) (bcCaches config)+        RefuseSubstitution -> pure . QueryFailed . noWriteAccessMessage,+      seNextOffer = const (queryNextOfferWith (stLogger store) (bcFetchRetry config) (ioRetryEffects (stLogger store)) (bcFallback config)),+      seFetch = \registration -> liftIO . substitutePaths config store registration . fmap snd+    }++-- | Work out what realising some paths would take ("Nix.Realise"'s+-- 'planMissing'), asking 'bcCaches' as a build asks them and reading each+-- derivation from the store.+planMissingPaths :: BuildConfig -> Store -> [Wanted] -> IO (Either Text MissingPaths)+planMissingPaths config store wanted = evalStateT (planMissing (bcSubstitutes config) effects wanted) emptyCacheMemo+  where+    substituting = substEffects config store+    effects =+      MissingEffects+        { meValid = seValid substituting,+          meDerivation = liftIO . readDrvFromStore config,+          meOffer = seReferences substituting,+          meSizes = substituteSizes+        }++-- | Which of the paths a cache in 'bcCaches' offers, or why one could not+-- be asked.+substitutablePaths :: BuildConfig -> Store -> [StorePath] -> IO (Either Text (Set StorePath))+substitutablePaths config store paths = evalStateT (fmap (Set.fromList . catMaybes) . sequence <$> traverse offered paths) emptyCacheMemo+  where+    offered path =+      seReferences (substEffects config store) path <&> \case+        Offered _ _ -> Right (Just path)+        NotOffered -> Right Nothing+        QueryFailed why -> Left why++-- | Substitute paths from 'bcCaches' with everything they reference,+-- references first ('substituteClosure'), as a build substitutes a+-- derivation's outputs, and build nothing.  The paths are one batch: when+-- no cache holds one of them, or one references a path no cache holds,+-- none of them is substituted, though a reference that arrived first+-- stays.  A store+-- upstream Nix's database may also manage refuses each path once its+-- narinfo is read ('fetchSubstituteWith'), and the outcome is a failed one.+substituteFromCaches :: BuildConfig -> Store -> [StorePath] -> IO ClosureOutcome+substituteFromCaches config store paths =+  evalStateT (substituteClosure (substEffects config store) paths) emptyCacheMemo++-- | Build one derivation, naming it in any failure.+buildReporting :: BuildConfig -> Store -> Derivation -> StorePath -> IO (Either FailedBuild ())+buildReporting config store drv drvPath = bimap failure (const ()) <$> buildOutputs config store drv drvPath+  where+    failure stop = case stop of+      FixedOutputRefused _ -> FixedOutputMismatch (stopReport drv stop)+      BuildStop _ _ -> BuilderStopped (stopReport drv stop)++-- | A stopped build as the realisation reports it, naming the derivation.+stopReport :: Derivation -> BuildStop -> Text+stopReport drv stop =+  "building " <> formatDrvName drv <> " failed: exit " <> T.pack (show code) <> ": " <> message+  where+    (message, code) = stopReported stop++-- | Format a status tag for display.+statusTag :: Realised -> Text+statusTag AlreadyValid = "[cached]"+statusTag Substituted = "[subst] "+statusTag Built = "[build] "+statusTag Checked = "[check] "++-- | Tell the logger how a dependency was realised.+logRealised :: Logger -> Realised -> Derivation -> IO ()+logRealised logger status drv =+  logMessage logger ("  " <> statusTag status <> " " <> formatDrvName drv)++-- | Substitute paths, each from the cache that offered it, every one of+-- them or none ('FetchOutcome'), or under 'RegisterNone' fetch them and+-- register nothing, to learn which a cache delivers.+--+-- Registration is all-or-nothing and batched: every path is verified and+-- unpacked first, then recorded in one 'registerPaths' transaction, so+-- reference edges between the outputs of one derivation land after both+-- endpoints' rows exist and a partial substitution registers nothing (the+-- subsequent build starts from unregistered outputs and 'runPlannedBuild'+-- replaces the leftover unpacked trees).+--+-- Each substituted path arrives with its path lock STILL HELD (see+-- 'Nix.Substituter.SubstSuccess'), and the exclusion must survive until+-- the registration transaction commits - released earlier, another+-- process could meet the unpacked-but-unregistered window and delete+-- the tree the row is about to describe.  Every held lock is released+-- here on every exit path (finally), including failures that never+-- reach registration.+--+-- A registration the database REFUSES - its unregistered-referent guard,+-- reachable only through cache-declared references this store has never+-- seen - is a failed substitution like any other: the transaction+-- recorded nothing, so every path of the batch counts as not delivered+-- ('DeliveryFailed').  Upstream's copy of the path fails the same way when+-- a reference is not valid.+--+-- Each path comes from the cache that offered it, as the narinfo the+-- reference query read describes it ('fetchSubstituteWith'), and no+-- narinfo is requested again.+substitutePaths :: BuildConfig -> Store -> Registration -> NonEmpty Substitute -> IO FetchOutcome+substitutePaths config store registration offered = do+  heldLocks <- newIORef []+  registerSubstituted heldLocks+    `finally` (readIORef heldLocks >>= mapM_ releasePathLock)+  where+    registerSubstituted :: IORef [PathLock] -> IO FetchOutcome+    registerSubstituted heldLocks = do+      results <- traverse (substituteOne heldLocks) (lockOrder substitutePath (NE.toList offered))+      case (batchRegistrations results, registration) of+        (Left outcome, _) -> pure outcome+        -- The trees stay unpacked and unregistered, as a batch that does+        -- not land leaves them.+        (Right _, RegisterNone) -> pure Fetched+        (Right rows, RegisterAll) -> do+          registered <- try (registerPaths (stDB store) rows)+          case registered of+            Right () -> pure Fetched+            Left (e :: IOException) -> do+              logMessage (stLogger store) ("  [subst] registration refused: " <> T.pack (displayException e))+              pure (NotFetched (fmap (\substitute -> (substitutePath substitute, DeliveryFailed)) offered))+    -- Record a returned lock the moment it exists, so the enclosing+    -- finally owns it even when a later path's attempt fails or throws.+    substituteOne heldLocks substitute = do+      let sp = substitutePath substitute+      result <-+        withActivity (stLogger store) (Substituting sp (ccUrl (substituteCache substitute))) $ \logger ->+          fetchSubstituteWith (bcFetchRetry config) (ioRetryEffects logger) store {stLogger = logger} substitute+      case result of+        SubstSuccess _ lock -> atomicModifyIORef' heldLocks (\locks -> (lock : locks, ()))+        SubstError err -> logMessage (stLogger store) ("  [subst] " <> spName sp <> ": " <> err)+        _ -> pure ()+      pure (sp, result)++-- | What one batch's results come to: the rows to register when every path+-- arrived, or the paths that did not.  Nothing is registered unless every+-- path arrived, as one failed output fails upstream's derivation goal.+batchRegistrations :: [(StorePath, SubstResult)] -> Either FetchOutcome [PathRegistration]+batchRegistrations results =+  case NE.nonEmpty [(sp, why) | (sp, result) <- results, Just why <- [undelivered result]] of+    Just short -> Left (NotFetched short)+    -- An already-valid path counts as arrived but contributes no+    -- registration row (and holds no lock).+    Nothing -> Right [reg | (_, SubstSuccess reg _) <- results]+  where+    undelivered (SubstSuccess _ _) = Nothing+    undelivered SubstAlreadyValid = Nothing+    undelivered SubstNotFound = Just Gone+    undelivered (SubstError _) = Just DeliveryFailed  -- | Format a derivation name for status output (display-only, so the -- byte-string env value decodes lossily).
+ src/Nix/Builder/BuildDir.hs view
@@ -0,0 +1,220 @@+{-# LANGUAGE ScopedTypeVariables #-}++-- | Where a build runs, and how its directory comes to exist.+--+-- == Where+--+-- A build directory is under the store's state directory, in+-- @.nova-nix\/builds@, where upstream's has been by default since 2.30.0+-- (@stateDir + "\/builds"@ in @LocalBuildStoreConfig::getBuildDir@,+-- local-store.cc).  At 2.24.9 upstream roots it at @TMPDIR@, which on+-- Linux is usually @\/tmp@, where any local user can create the name a+-- build is about to take.  Whoever can write the state directory can+-- already rewrite the store's database there, so a build directory under+-- it is open to no one the store is not.  A store has its own state+-- directory, so builds into two stores never share one.+--+-- The directory is named by the hash of the derivation's first output,+-- whose path lock the build holds from before the directory is made until+-- after it is removed (@withOutputLocks@ in "Nix.Builder").  No two builds+-- into one store use one name at a time, so whatever is found at the name+-- was left by an earlier build that could not remove it, one that was+-- killed for instance, and is removed, or moved aside where it cannot be+-- ('clearLeftover').  Upstream instead names each directory+-- @nix-build-\<drv name\>-\<n\>@ and counts up until a name is free,+-- which leaves such a directory where it is.+--+-- == Creation+--+-- The directory is created by a call that fails when anything already+-- answers to the name, so a build never runs in a directory it did not+-- create.  It is open to the user nova-nix runs as alone+-- ('OwnerAccess'), so other users can neither read what the build+-- unpacks nor change it while it runs; a build that runs as a build user+-- gives the directory its builder works in to that user+-- ("Nix.Builder.BuildUser").  On POSIX it is created with mode+-- 0700, as upstream's @createTempDir@ makes its build directories+-- (file-system.cc).  On Windows it is created with a protected access control+-- list granting that user alone full control, which what the build makes in+-- it inherits ("Nix.Store.Access").+--+-- == When a build fails+--+-- A build's directory is removed when the build ends, however it ends,+-- unless the build did not succeed and @keep-failed@ is on ('KeepFailed'):+-- then it stays, and the directory the builder worked in is named to the+-- logger, as upstream keeps and names it.  A build that does not+-- succeed is one that stopped short of registering its outputs, or a+-- check that found one different, whether it stopped with a failure or an+-- exception, an interrupt included, as upstream keeps the directory of+-- every build that does not succeed.+--+-- Three things differ from upstream.  The directory keeps mode 0700, where+-- upstream opens it, and the directory its builder worked in, with 0755,+-- so that the user who asked for the build can read what a build user+-- wrote there: here the build runs as the user nova-nix runs as, who can+-- read it, or as a build user for root, who can read anything.  A kept directory+-- stays until the next build of the same derivation, which removes it as+-- it removes any directory an earlier build left at the name+-- ('clearLeftover'), where upstream's stays until it is removed by hand,+-- its name being one no later build takes.  The name is what makes a+-- rebuild see the paths the first build saw, which a check relies on+-- ("Nix.Builder"), so keeping a directory cannot be what moves the next+-- build elsewhere.  And on Windows a failed build's directory is kept too,+-- where upstream's Windows builds remove theirs whatever @keep-failed@+-- says.+module Nix.Builder.BuildDir+  ( -- * The directory+    buildDirFor,+    sandboxedBuildDir,+    WorkDir (..),+    workDirIn,+    FailedBuilds (..),+    BuildEnding (..),+    withBuildDir,+    clearLeftover,+    createBuildDir,+  )+where++import Control.Exception (IOException, catch, displayException, mask, onException, throwIO)+import qualified Data.Text as T+import Nix.Logger (Logger, logMessage, logWarning)+import Nix.Store.Access (DirAccess (OwnerAccess), createDirectoryWith)+import Nix.Store.DB (metaDirName)+import Nix.Store.Path (StoreDir (..), StorePath (spHash))+import System.Directory (createDirectoryIfMissing, doesPathExist, pathIsSymbolicLink, removePathForcibly, renamePath)+import System.FilePath (takeDirectory, (</>))++-- | The directory under the store's state directory that holds every+-- build directory: upstream's name for its own under its state+-- directory.+buildsDirName :: FilePath+buildsDirName = "builds"++-- | Where a build of the derivation whose first output is this path runs.+buildDirFor :: StoreDir -> StorePath -> FilePath+buildDirFor dir firstOutput =+  unStoreDir dir </> metaDirName </> buildsDirName </> T.unpack (spHash firstOutput)++-- | Where in its build directory a sandboxed build's own directory is,+-- the one bound where the builder sees it, as upstream puts its @tmpDir@+-- at @topTmpDir + "/build"@ in a chroot build (@startBuilder@ in+-- local-derivation-goal.cc at 2.24.9).  The builder owns what it sees and can+-- open it to anyone; the build directory above it, which it cannot reach,+-- stays closed to every other user.+sandboxedBuildDir :: FilePath -> FilePath+sandboxedBuildDir dir = dir </> "build"++-- | Where in its build directory a build's builder works.+data WorkDir+  = -- | In the build directory itself, as an unsandboxed builder does and+    -- one in macOS's sandbox, which sees the directory where it is.+    WorksInBuildDir+  | -- | In the directory inside it that a sandboxed build on Linux shows+    -- the builder ('sandboxedBuildDir').+    WorksInSandboxedBuildDir+  deriving (Eq, Show)++-- | The directory a builder works in, given its build directory.+workDirIn :: WorkDir -> FilePath -> FilePath+workDirIn workDir dir = case workDir of+  WorksInBuildDir -> dir+  WorksInSandboxedBuildDir -> sandboxedBuildDir dir++-- | What becomes of a build's directory when the build does not succeed:+-- upstream's @keep-failed@.+data FailedBuilds+  = -- | It is removed, as it is when the build succeeds.+    RemoveFailed+  | -- | It is kept, and the directory the builder worked in is named to+    -- the logger.+    KeepFailed+  deriving (Eq, Show)++-- | How a build ended, which decides whether its directory may be kept.+data BuildEnding+  = -- | It registered its outputs, or its check found them the same.+    BuildSucceeded+  | -- | It did not.+    BuildFailed+  deriving (Eq, Show)++-- | Remove what an earlier build left at a path, or where it cannot be+-- removed, move it aside, to the first free name of the path with+-- @.leftover.@ and a number after it, beside it in the state directory,+-- and warn the logger, so the build goes on.  A build can leave+-- what its user cannot remove: a directory another user made in it,+-- through a descriptor a fixed-output builder handed out, which the user+-- may neither empty nor change, and which removal would otherwise trip on+-- at every build of the derivation, the name being the derivation's.+-- What cannot be moved either fails with the removal's error.+clearLeftover :: Logger -> FilePath -> IO ()+clearLeftover logger path = removePathForcibly path `catch` setAside+  where+    setAside (failure :: IOException) = do+      aside <- freeName (1 :: Int)+      renamePath path aside `catch` \(_ :: IOException) -> throwIO failure+      logWarning logger ("cannot remove '" <> T.pack path <> "', which an earlier build left (" <> T.pack (displayException failure) <> "); it is now '" <> T.pack aside <> "'")+    freeName number = do+      let candidate = path <> ".leftover." <> show number+      taken <- (||) <$> doesPathExist candidate <*> pathIsSymbolicLink candidate `catch` \(_ :: IOException) -> pure False+      if taken then freeName (number + 1) else pure candidate++-- | Run a build in its directory ('buildDirFor'), given the derivation's+-- first output, whose path lock the caller holds, where in the directory+-- its builder works, what becomes of the directory if the build fails, and+-- how the build's result says it ended.  What an earlier build left at the+-- name is removed, or moved aside ('clearLeftover'), and the directory is+-- created ('createBuildDir'), with the one the builder works in when that+-- is inside it, so the directory a failed build names is always there.+-- The build is given the build directory.  When it ends, however it ends,+-- the directory is removed, unless the build failed under 'KeepFailed';+-- an exception is a failure.  When the creation fails, whatever took the+-- name first is left as it is, since this build did not make it.+-- What it says goes to the logger.+withBuildDir :: Logger -> StoreDir -> StorePath -> WorkDir -> FailedBuilds -> (a -> BuildEnding) -> (FilePath -> IO a) -> IO a+withBuildDir logger storeDir firstOutput workDir failedBuilds ending build = do+  createDirectoryIfMissing True (takeDirectory dir)+  clearLeftover logger dir+  mask $ \restore -> do+    createBuildDir dir+    createWorkDir `onException` removeBuildDir dir+    result <- restore (build dir) `onException` leave BuildFailed+    leave (ending result)+    pure result+  where+    dir = buildDirFor storeDir firstOutput+    createWorkDir = case workDir of+      WorksInBuildDir -> pure ()+      WorksInSandboxedBuildDir -> createBuildDir (sandboxedBuildDir dir)+    leave BuildSucceeded = removeBuildDir dir+    leave BuildFailed = case failedBuilds of+      RemoveFailed -> removeBuildDir dir+      KeepFailed -> logMessage logger (keptMessage (workDirIn workDir dir))++-- | The note naming a kept build directory, in upstream's words, the path+-- in the double quotes upstream puts a path in.+keptMessage :: FilePath -> T.Text+keptMessage path = "note: keeping build directory \"" <> T.pack path <> "\""++-- | Create a build directory, open to the user nova-nix runs as alone+-- ('OwnerAccess'), failing with an+-- 'System.IO.Error.isAlreadyExistsError' exception when anything already+-- answers to the name, a symlink included, which is not followed.  On+-- POSIX its mode is 0700, narrowed by the umask.+createBuildDir :: FilePath -> IO ()+createBuildDir = createDirectoryWith OwnerAccess++-- | Remove a build directory, ignoring a filesystem failure to remove it:+-- it runs as the build ends, where a directory that will not go away+-- must not replace the build's own outcome, and the next build of the+-- derivation removes what is left.  'removePathForcibly' makes a+-- read-only directory writable before emptying it, as upstream's+-- @deletePath@ does, so a tree the builder copied read-only out of the+-- store goes too.+removeBuildDir :: FilePath -> IO ()+removeBuildDir dir = removePathForcibly dir `catch` ignore+  where+    ignore :: IOException -> IO ()+    ignore _ = pure ()
+ src/Nix/Builder/BuildUser.hs view
@@ -0,0 +1,663 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | Build users: the accounts a build runs as when nova-nix runs as root,+-- as upstream's do, so that a builder can change neither the store nor+-- another build, and every process it leaves can be found by its user.+--+-- == The setting+--+-- @build-users-group@ names the group whose members are the build users.+-- Upstream defaults it to @nixbld@ for root and to nothing for anyone+-- else, and builds as its members only when it runs as root on Linux or+-- macOS ('buildUsersFor'); a build run otherwise runs as the user nova-nix+-- runs as.  A daemon is to refuse a connection from a peer whose primary+-- group is the one the setting names ('peerInBuildUsersGroup').+--+-- == The pool+--+-- Each build takes one member for itself, as upstream's does: a member is+-- free when no process holds the lock on its file in the user pool,+-- @userpool\/UID@ in upstream's state directory, which every process that+-- builds as these users shares, nova-nix's and upstream's alike, so that+-- no two builds run as one user at once.  The choice is made over a+-- t'UserDatabase', a capability record, so the rules run over a model of+-- the user database in tests ('acquireBuildUser'), and a build waits,+-- polling as upstream does, while every member is taken ('withBuildUser').+--+-- == The processes+--+-- Every process of the build user is killed before its build starts and+-- after it ends ('killBuildUser'), as upstream kills them, so a process a+-- builder left behind cannot outlive its build or reach the next one.  A+-- builder outside the sandbox is started as the build user by a small C+-- shim that drops to the user between the fork and the exec+-- ('spawnAsBuildUser'), with the groups looked up beforehand, since the+-- process library can drop to another user only by looking the user up in+-- the forked child of this threaded process.  On Linux and macOS the shim+-- starts every builder outside the sandbox, a build that runs as the user+-- nova-nix runs as too, with no drop ('runAsInvoker'), so each starts as+-- upstream's child starts one and ends as upstream ends one.+module Nix.Builder.BuildUser+  ( -- * The setting+    ProcessPrivilege (..),+    processPrivilege,+    defaultBuildUsersGroup,+    BuildUsers (NoBuildUsers),+    buildUsersFor,+    userPoolDir,++    -- * Who may not connect+    peerInBuildUsersGroup,++    -- * Choosing a build user+    BuildUser,+    buUid,+    buGid,+    buSupplementaryGids,+    Member (..),+    UserDatabase (..),+    acquireBuildUser,+    withBuildUser,+    waitingForBuildUserMessage,++    -- * A build user's processes and files+    killBuildUser,+    giveToBuildUser,+    runAsBuildUser,+    runAsInvoker,+    openStoreToBuildUsers,+    worldWritableAncestor,+    worldWritableMessage,+    invokingUserIds,+  )+where++import Control.Monad.Except (ExceptT (..), runExceptT, throwError)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Word (Word32)+import System.Exit (ExitCode (..))+import qualified System.FilePath.Posix as PosixPath++#if defined(mingw32_HOST_OS)++import Nix.Logger (Logger)++#else++import Control.Concurrent (threadDelay)+import Control.Exception (IOException, bracket, displayException, finally, mask, onException, try, uninterruptibleMask_)+import Control.Monad (unless, void)+import Data.Bits (complement, (.&.))+import Data.List (dropWhileEnd)+import Foreign.C.Error (Errno (..), eINVAL, ePERM)+import Foreign.C.String (CString, peekCString)+import Foreign.C.Types (CInt (..), CUInt (..))+import Foreign.Marshal.Alloc (alloca)+import Foreign.Marshal.Array (withArray0, withArrayLen)+import Foreign.Marshal.Utils (withMany)+import Foreign.Ptr (Ptr, nullPtr)+import Foreign.Storable (peek)+import qualified GHC.Foreign as GHC+import GHC.IO.Encoding (getFileSystemEncoding)+import GHC.IO.FD (fdFD)+import GHC.IO.Handle.FD (handleToFd)+import Nix.Builder.Log (openLogPipe, streamBuildLog)+import Nix.Builder.Sandbox (errnoSuffix, setupContext)+import Nix.Logger (Logger, logBuildLine, logMessage)+import System.Directory (createDirectoryIfMissing)+import System.FileLock (FileLock, SharedExclusive (Exclusive), tryLockFile, unlockFile)+import System.FilePath (dropTrailingPathSeparator, takeDirectory, (</>))+import System.IO (hClose)+import System.Posix.Files (fileGroup, fileMode, fileOwner, fileTypeModes, getFileStatus, getSymbolicLinkStatus, otherWriteMode, setFileMode, setOwnerAndGroup)+import System.Posix.IO (OpenFileFlags (..), OpenMode (ReadWrite, WriteOnly), closeFd, defaultFileFlags, openFd)+import System.Posix.Process (ProcessStatus (..), getProcessStatus)+import qualified System.Info+import System.IO.Error (catchIOError, ioeGetErrorString, isPermissionError)+import System.Posix.Signals (sigKILL, signalProcessGroup)+import System.Posix.Types (Fd (..), ProcessID)+import qualified System.Posix.User.ByteString as User++#endif++#if defined(linux_HOST_OS)+import Foreign.Marshal.Array (allocaArray, peekArray)+import Foreign.Storable (poke)+#endif++-- ---------------------------------------------------------------------------+-- The setting+-- ---------------------------------------------------------------------------++-- | Whether nova-nix runs as root, which upstream's build users need.+data ProcessPrivilege = RunsAsRoot | RunsUnprivileged+  deriving (Eq, Show)++-- | Whether this process runs as root: its real user is uid 0, upstream's+-- test.  Never on Windows, which has no uid.+processPrivilege :: IO ProcessPrivilege+#if defined(mingw32_HOST_OS)+processPrivilege = pure RunsUnprivileged+#else+processPrivilege = (\uid -> if uid == 0 then RunsAsRoot else RunsUnprivileged) <$> User.getRealUserID+#endif++-- | @build-users-group@ where no source sets it: upstream's @nixbld@ for+-- root, and for anyone else nothing, which builds as the user nova-nix+-- runs as.+defaultBuildUsersGroup :: ProcessPrivilege -> ByteString+defaultBuildUsersGroup privilege = case privilege of+  RunsAsRoot -> "nixbld"+  RunsUnprivileged -> ""++-- | Whom a spawned builder runs as.  Only 'buildUsersFor' makes the+-- first, for root, so a build user is taken only where builds are to run+-- as one ('withBuildUser').+data BuildUsers+  = -- | A member of this group, taken from the pool in this directory.+    BuildUsersOf !ByteString !FilePath+  | -- | The user nova-nix runs as.+    NoBuildUsers+  deriving (Eq, Show)++-- | Whom builds run as, given whether nova-nix runs as root, the user pool's+-- directory ('userPoolDir') and @build-users-group@: its members, for root+-- on Linux and macOS with the group named, as upstream decides; otherwise+-- the user nova-nix runs as, whose builds cannot be another user's.+buildUsersFor :: ProcessPrivilege -> FilePath -> ByteString -> BuildUsers+buildUsersFor privilege pool group+  | buildUsersSupported, privilege == RunsAsRoot, not (BS.null group) = BuildUsersOf group pool+  | otherwise = NoBuildUsers++-- | Whether this system has build users: Linux and macOS, as upstream's.+buildUsersSupported :: Bool+#if defined(linux_HOST_OS) || defined(darwin_HOST_OS)+buildUsersSupported = True+#else+buildUsersSupported = False+#endif++-- | The user pool's directory, given @NIX_STATE_DIR@ where it is set and+-- not empty: @userpool@ in upstream's state directory, which upstream's+-- daemon shares, so that its builds and nova-nix's never take one user at+-- once.  It is a POSIX path on every system, since build users exist only+-- on Linux and macOS ('buildUsersFor'), and a Windows build of nova-nix+-- names it the same.+userPoolDir :: Maybe FilePath -> FilePath+userPoolDir stateDir = fromMaybe defaultStateDir stateDir PosixPath.</> "userpool"+  where+    defaultStateDir = "/nix/var/nix"++-- ---------------------------------------------------------------------------+-- Who may not connect+-- ---------------------------------------------------------------------------++-- | Whether a daemon is to refuse a peer for its primary group, given+-- @build-users-group@ and the name of the peer's primary group, where the+-- system gives one: a peer whose primary group is the build users' is+-- refused, whatever @trusted-users@ says, as upstream's daemon refuses+-- one, since a build user is whom a build runs as.  Linux and macOS both+-- give a socket's peer its primary group, as upstream reads it on each.+peerInBuildUsersGroup :: ByteString -> Maybe ByteString -> Bool+peerInBuildUsersGroup group peerGroup = not (BS.null group) && peerGroup == Just group++-- ---------------------------------------------------------------------------+-- Choosing a build user+-- ---------------------------------------------------------------------------++-- | A member of the build users' group a build may run as: its uid, the+-- build users' group, and its supplementary groups but that one.+data Member = Member+  { memberUid :: !Word32,+    memberGid :: !Word32,+    memberGroups :: ![Word32]+  }+  deriving (Eq, Show)++-- | A member a build holds and runs as.  Only 'withBuildUser' makes one,+-- for a process that runs as root with build users ('buildUsersFor'), its+-- lock held and its uid neither root's nor this process's, so a build+-- user's processes, which 'killBuildUser' ends and 'runAsBuildUser'+-- starts, are never the caller's own.+newtype BuildUser = BuildUser Member+  deriving (Eq, Show)++-- | A build user's uid.+buUid :: BuildUser -> Word32+buUid (BuildUser member) = memberUid member++-- | The build users' group, which a build user builds as.+buGid :: BuildUser -> Word32+buGid (BuildUser member) = memberGid member++-- | A build user's supplementary groups but the build users' own.+buSupplementaryGids :: BuildUser -> [Word32]+buSupplementaryGids (BuildUser member) = memberGroups member++-- | What choosing a build user reads and locks, over a monad, holding a+-- lock of type @lock@.+data UserDatabase m lock = UserDatabase+  { -- | A group's id and its members' names, by its name, or nothing when+    -- there is no such group.+    udGroup :: ByteString -> m (Maybe (Word32, [ByteString])),+    -- | A user's uid and primary group, by name, or nothing when there is+    -- no such user.+    udUser :: ByteString -> m (Maybe (Word32, Word32)),+    -- | Every group a user is in, given its name and primary group: the+    -- groups a build as it keeps.+    udGroups :: ByteString -> Word32 -> m [Word32],+    -- | Take the lock on a uid's file in the pool, or nothing when another+    -- holder has it; 'Left' is why the file cannot be opened.+    udTryLock :: Word32 -> m (Either Text (Maybe lock)),+    -- | Give a lock back.+    udRelease :: lock -> m ()+  }++-- | The first member of the build users' group whose lock is free, with+-- the lock, given the uids this process runs as and the group's name;+-- nothing while every member is taken; or, in upstream's words, why there+-- is none to take: the group is missing or has no members, a member names+-- no user, or the member a build would take is the user nova-nix runs as.+-- Members are tried in the order the group lists them, and each is looked+-- up only as far as the first free one, as upstream looks them up.  On+-- Linux the user keeps its supplementary groups, as upstream lets an+-- administrator give a build one such as @kvm@.+acquireBuildUser :: (Monad m) => UserDatabase m lock -> [Word32] -> ByteString -> m (Either Text (Maybe (Member, lock)))+acquireBuildUser database ownUids group = do+  found <- udGroup database group+  case found of+    Nothing -> pure (Left ("the group '" <> shown group <> "' specified in 'build-users-group' does not exist"))+    Just (_, []) -> pure (Left ("the build users group '" <> shown group <> "' has no members"))+    Just (gid, members) -> runExceptT (firstFree gid members)+  where+    inner action = ExceptT (Right <$> action)+    firstFree _ [] = pure Nothing+    firstFree gid (member : rest) = do+      entry <- inner (udUser database member)+      case entry of+        Nothing -> throwError ("the user '" <> shown member <> "' in the group '" <> shown group <> "' does not exist")+        Just (uid, primary) -> do+          locked <- ExceptT (udTryLock database uid)+          case locked of+            Nothing -> firstFree gid rest+            Just lock+              | uid `elem` ownUids -> do+                  inner (udRelease database lock)+                  throwError ("the Nix user should not be a member of '" <> shown group <> "'")+              | otherwise -> do+                  groups <- inner (udGroups database member primary)+                  pure (Just (Member uid gid (filter (/= gid) groups), lock))+    -- A name in a message, shown with any byte that is not UTF-8 replaced.+    shown = TE.decodeUtf8Lenient++-- | The line a build waiting for a free build user says once, in+-- upstream's words, given the @.drv@ path.+waitingForBuildUserMessage :: Text -> Text+waitingForBuildUserMessage drvPath = "waiting for a free build user ID for '" <> drvPath <> "'"++-- | Run an action as whom builds run as, given the @.drv@ path the build+-- is of: with no build users, as the user nova-nix runs as ('Nothing');+-- otherwise as a free member of the build users' group, taken+-- ('acquireBuildUser') and given back when the action ends, however it+-- ends.  While every member is taken the build says so once+-- ('waitingForBuildUserMessage') and looks again at upstream's default+-- @poll-interval@, since a member another process gives back announces+-- nothing.  'Left' is why there is no member to take, a process that is+-- not root among the reasons, whatever privilege 'buildUsersFor' was+-- told of.+withBuildUser :: Logger -> BuildUsers -> Text -> (Maybe BuildUser -> IO a) -> IO (Either Text a)++-- | Kill every process of a build user, as upstream kills them before and+-- after a build, from a child of this process that is that user, so the+-- kill reaches the user's processes alone.  'Left' is why it could not, in+-- upstream's words.+killBuildUser :: BuildUser -> IO (Either Text ())++-- | Give a file or directory nova-nix made for a build to its build user,+-- as upstream gives a build its directory and the files it writes there.+giveToBuildUser :: BuildUser -> FilePath -> IO ()++-- | Run a builder as a build user, outside any sandbox, given the logger+-- its lines go to ('streamBuildLog'), the program, its arguments, its+-- environment as @NAME=VALUE@ entries, and the directory it starts in.+-- It is started and ended as 'runAsInvoker' starts and ends one, with the+-- user's uid, the build users' group and the user's supplementary groups,+-- set between the fork and the exec.  The processes it leaves outside its+-- process group are the caller's to kill ('killBuildUser').+runAsBuildUser :: Logger -> BuildUser -> FilePath -> [String] -> [ByteString] -> FilePath -> IO (Either Text ExitCode)++-- | Run a builder outside any sandbox as the user nova-nix runs as, given+-- what 'runAsBuildUser' is given but the user, as upstream runs one.  The+-- program is executed by its path, with no search of @PATH@, and gets its+-- base name as its first argument.  It leads a session of its own, so it+-- has no controlling terminal and its process group holds what it starts;+-- it has @\/dev\/null@, open to read and write, as its standard input,+-- and writes its standard output and error to one pipe, the build log,+-- with every other descriptor of this process closed; and its core limit+-- is set as upstream's child sets it, a soft limit of 0 and no hard limit,+-- which a process that is not root is refused where its hard limit is+-- finite, keeping its soft limit.  Once the log ends, or when an+-- interrupt comes, every process left in its group is sent SIGKILL and+-- the builder is reaped, as upstream takes a builder's status, so a+-- builder that closed its log and ran on ends on SIGKILL.  Answers how it+-- exited, a signal as the process library reports one (the signal's+-- number, negated), or why its setup failed, in upstream's words for each+-- step; a program that could not be executed is, as upstream's, a line in+-- the build log and an exit of 1.  Linux and macOS only.+runAsInvoker :: Logger -> FilePath -> [String] -> [ByteString] -> FilePath -> IO (Either Text ExitCode)++-- | Open a store's directory to the build users, as upstream opens it+-- when it runs as root with build users: owned by root and their group,+-- with mode 1775, so a builder can write its outputs there and remove none+-- but its own.  A directory already so is left as it is.+openStoreToBuildUsers :: FilePath -> BuildUser -> IO ()++-- | The first of a directory and its ancestors, read without following a+-- symlink, whose mode lets every user write it, which on Linux every+-- symlink's does; nothing when there is none.  Upstream refuses to build+-- as a build user in a directory below one, since any user could replace+-- the build's directory there.+worldWritableAncestor :: FilePath -> IO (Maybe FilePath)++-- | Upstream's refusal of a build directory below a directory every user+-- may write.+worldWritableMessage :: FilePath -> Text+worldWritableMessage path = "Path \"" <> T.pack path <> "\" is world-writable or a symlink. That's not allowed for security."++-- | The ids of the user nova-nix runs as: its real uid and gid.  Windows+-- has none, and answers zero for each.+invokingUserIds :: IO (Word32, Word32)++#if defined(mingw32_HOST_OS)++withBuildUser _ users _ action = case users of+  NoBuildUsers -> Right <$> action Nothing+  BuildUsersOf _ _ -> pure (Left unsupported)++killBuildUser _ = pure (Left unsupported)++giveToBuildUser _ _ = pure ()++runAsBuildUser _ _ _ _ _ _ = pure (Left unsupported)++runAsInvoker _ _ _ _ _ = pure (Left unsupported)++openStoreToBuildUsers _ _ = pure ()++worldWritableAncestor _ = pure Nothing++invokingUserIds = pure (0, 0)++-- | Why a build user is refused where there are none.+unsupported :: Text+unsupported = "build users need Linux or macOS"++#else++withBuildUser logger users drvPath action = case users of+  NoBuildUsers -> Right <$> action Nothing+  BuildUsersOf group pool -> do+    ownUids <- traverse (fmap fromIntegral) [User.getRealUserID, User.getEffectiveUserID]+    if any (/= 0) ownUids+      then pure (Left ("builds run as the members of '" <> TE.decodeUtf8Lenient group <> "' only for root, and this process is not root"))+      else do+        createDirectoryIfMissing True pool+        let attempt announced = mask $ \restore -> do+              found <- acquireBuildUser (systemUserDatabase pool) ownUids group+              case found of+                Left reason -> pure (Left reason)+                Right (Just (member, lock)) -> Right <$> (restore (action (Just (BuildUser member))) `finally` unlockFile lock)+                Right Nothing -> restore $ do+                  unless announced (logMessage logger (waitingForBuildUserMessage drvPath))+                  threadDelay freeUserPollMicros+                  attempt True+        attempt False++-- | How long a build waiting for a free build user waits before it looks+-- again: upstream's default @poll-interval@, five seconds.+freeUserPollMicros :: Int+freeUserPollMicros = 5 * 1000000++-- | The system's user database and the pool's locks.  A group or user+-- the system cannot look up is one it does not have, as upstream reads a+-- failed lookup.  A member's lock file is made with mode 0600, as+-- upstream makes it, and locked with @flock@, as upstream's is, so a+-- holder in either excludes the other.+systemUserDatabase :: FilePath -> UserDatabase IO FileLock+systemUserDatabase pool =+  UserDatabase+    { udGroup = \name -> either (\(_ :: IOException) -> Nothing) (\entry -> Just (fromIntegral (User.groupID entry), User.groupMembers entry)) <$> try (User.getGroupEntryForName name),+      udUser = \name -> either (\(_ :: IOException) -> Nothing) (\entry -> Just (fromIntegral (User.userID entry), fromIntegral (User.userGroupID entry))) <$> try (User.getUserEntryForName name),+      udGroups = groupList,+      udTryLock = \uid -> do+        let file = pool </> show uid+        opened <- try (openFd file WriteOnly defaultFileFlags {creat = Just lockFileMode, cloexec = True} >>= closeFd)+        case opened of+          Left (failure :: IOException) -> pure (Left ("opening user lock \"" <> T.pack file <> "\": " <> T.pack (displayException failure)))+          Right () -> Right <$> tryLockFile file Exclusive,+      udRelease = unlockFile+    }+  where+    lockFileMode = 0o600++killBuildUser user = alloca $ \statusPtr -> do+  failure <- c_nn_kill_user (fromIntegral (buUid user)) statusPtr+  status <- peek statusPtr+  if failure /= 0+    then pure (Left (refused (Errno failure)))+    else killOutcome status+  where+    -- The shim refuses uid 0 and a caller that is not root before it+    -- forks, which a build user never is; any other errno is the fork's+    -- or the wait's.+    refused errno@(Errno number)+      | errno == eINVAL = cannot "uid 0 is root's, whose kill would reach every process"+      | errno == ePERM = cannot "only root may kill a build user's processes"+      | otherwise = "unable to fork" <> errnoSuffix (fromIntegral number)+    killOutcome status+      | status == 0 = pure (Right ())+      | status > signalledBase = do+          let signal = status - signalledBase+          description <- c_nn_signal_text signal >>= peekCString+          pure (Left (cannot ("failed due to signal " <> T.pack (show signal) <> " (" <> T.pack description <> ")")))+      | otherwise = pure (Left (cannot ("failed with exit code " <> T.pack (show status))))+    cannot reason = "cannot kill processes for uid '" <> T.pack (show (buUid user)) <> "': " <> reason+    -- What nn_kill_user adds to the number of a signal that ended its child.+    signalledBase = 256++giveToBuildUser user path = setOwnerAndGroup path (fromIntegral (buUid user)) (fromIntegral (buGid user))++runAsBuildUser logger user program arguments environment workDir =+  runStarted logger (spawnAsBuildUser user program arguments environment workDir)++runAsInvoker logger program arguments environment workDir =+  runStarted logger (spawnAsInvoker program arguments environment workDir)++-- | Why a builder did not start: a step of its setup failed, given in+-- upstream's words for the build's failure, or its program could not be+-- executed, given as the line upstream's child writes to the build log.+data StartFailure+  = SetupFailed !Text+  | ExecFailed !Text++-- | Run the builder a start begins, given its standard input and its log,+-- to its end, as 'runAsInvoker' says.+runStarted :: Logger -> (Fd -> Fd -> IO (Either StartFailure ProcessID)) -> IO (Either Text ExitCode)+runStarted logger start =+  bracket openLogPipe closePipe $ \(fromBuilder, toLog) ->+    bracket (openFd nullDevice ReadWrite defaultFileFlags {cloexec = True}) closeFd $ \input -> do+      output <- Fd . fdFD <$> handleToFd toLog+      -- Until the builder is reaped its process id names it alone, and+      -- names its process group, so a kill of the group can reach no other+      -- process; the reap runs where no interrupt can cut it short, once+      -- the group has been sent SIGKILL.+      mask $ \restore -> do+        spawned <- start input output+        case spawned of+          Left (SetupFailed reason) -> pure (Left reason)+          -- Upstream's child writes why its exec failed to the build log+          -- and exits 1.+          Left (ExecFailed line) -> Right (ExitFailure 1) <$ logBuildLine logger (TE.encodeUtf8 line)+          Right pid -> do+            let reap = getProcessStatus True False pid+                -- An interrupt may come once the group has ended, which+                -- the kill then fails on.+                quietly action = void (try action :: IO (Either IOException ()))+                stop = uninterruptibleMask_ (quietly (signalProcessGroup sigKILL pid) *> quietly (void reap))+                -- The builder's tree holds the only write ends once this+                -- process closes its own, so the tree's end ends the log.+                follow = hClose toLog *> streamBuildLog fromBuilder logger+            (restore follow *> endGroup logger pid) `onException` stop+            Right . exitOf <$> uninterruptibleMask_ reap+  where+    closePipe (fromBuilder, toLog) = hClose fromBuilder *> hClose toLog+    nullDevice = "/dev/null"+    exitOf ended = case ended of+      Just (Exited code) -> code+      Just (Terminated signal _) -> ExitFailure (negate (fromIntegral signal))+      Just (Stopped signal) -> ExitFailure (negate (fromIntegral signal))+      Nothing -> ExitFailure 1++-- | Send SIGKILL to what is left of a builder's process group once its log+-- has ended.  A kill that fails is logged, as upstream logs it, and the+-- builder is still reaped for its own status; but macOS refuses the+-- signal to a group whose only process is the builder, ended and not yet+-- reaped (EPERM), which upstream passes over.+endGroup :: Logger -> ProcessID -> IO ()+endGroup logger pid = signalProcessGroup sigKILL pid `catchIOError` \err -> unless (zombieGroup err) (logMessage logger (killFailure err))+  where+    zombieGroup err = isPermissionError err && System.Info.os == "darwin"+    killFailure err = "error: killing process " <> T.pack (show pid) <> ": " <> T.pack (ioeGetErrorString err)++openStoreToBuildUsers storeDir user = do+  status <- getFileStatus storeDir+  let group = fromIntegral (buGid user)+  unless (fileOwner status == 0 && fileGroup status == group && fileMode status .&. complement fileTypeModes == storeMode) $ do+    setOwnerAndGroup storeDir 0 group+    setFileMode storeDir storeMode+  where+    storeMode = 0o1775++worldWritableAncestor start = go (dropTrailingPathSeparator start)+  where+    go path = do+      status <- getSymbolicLinkStatus path+      let parent = takeDirectory path+      if fileMode status .&. otherWriteMode /= 0+        then pure (Just path)+        else if parent == path then pure Nothing else go parent++invokingUserIds = (\uid gid -> (fromIntegral uid, fromIntegral gid)) <$> User.getRealUserID <*> User.getRealGroupID++-- | Start a builder as a build user, outside any sandbox: the program, its+-- arguments, its environment as @NAME=VALUE@ entries, the directory it+-- starts in, and the descriptors its standard input and its standard+-- output and error are, every other descriptor closed.  Answers its+-- process id once the program has replaced the child, or why it could+-- not, in upstream's words for each step.+spawnAsBuildUser :: BuildUser -> FilePath -> [String] -> [ByteString] -> FilePath -> Fd -> Fd -> IO (Either StartFailure ProcessID)+spawnAsBuildUser user = spawnWith $ \cProgram argv envp cWorkDir input output pidPtr stepPtr ->+  withArrayLen (map fromIntegral (buSupplementaryGids user)) $ \groupCount groups ->+    c_nn_spawn_as_user cProgram argv envp cWorkDir input output (fromIntegral (buUid user)) (fromIntegral (buGid user)) (fromIntegral groupCount) groups pidPtr stepPtr++-- | Start a builder as the user nova-nix runs as, given what+-- 'spawnAsBuildUser' is given but the user.+spawnAsInvoker :: FilePath -> [String] -> [ByteString] -> FilePath -> Fd -> Fd -> IO (Either StartFailure ProcessID)+spawnAsInvoker = spawnWith c_nn_spawn_as_invoker++-- | Start a builder through the shim's call given, which takes the+-- program, its argument and environment vectors, its directory, its+-- input and output descriptors, and where to put its process id and the+-- step that failed.  Its first argument is the program's base name, as+-- upstream passes it.+spawnWith ::+  (CString -> Ptr CString -> Ptr CString -> CString -> CInt -> CInt -> Ptr CInt -> Ptr CInt -> IO CInt) ->+  FilePath ->+  [String] ->+  [ByteString] ->+  FilePath ->+  Fd ->+  Fd ->+  IO (Either StartFailure ProcessID)+spawnWith spawn program arguments environment workDir (Fd input) (Fd output) = do+  encoding <- getFileSystemEncoding+  let withPath = GHC.withCString encoding+  withPath program $ \cProgram ->+    withMany withPath (baseName program : arguments) $ \cArguments ->+      withArray0 nullPtr cArguments $ \argv ->+        withMany BS.useAsCString environment $ \cEnvironment ->+          withArray0 nullPtr cEnvironment $ \envp ->+            withPath workDir $ \cWorkDir ->+              alloca $ \pidPtr ->+                alloca $ \stepPtr -> do+                  failure <- spawn cProgram argv envp cWorkDir input output pidPtr stepPtr+                  if failure == 0+                    then Right . fromIntegral <$> peek pidPtr+                    else Left . startFailure failure <$> peek stepPtr+  where+    startFailure failure step+      | step == execStep = ExecFailed (stepText step <> errnoSuffix (fromIntegral failure))+      | otherwise = SetupFailed (setupContext <> stepText step <> errnoSuffix (fromIntegral failure))+    -- NN_SPAWN_EXEC in nn_buildusers.h.+    execStep = 10+    -- The base name upstream takes of a path: what follows its last slash,+    -- trailing slashes aside.+    baseName path = case break (== '/') (reverse (dropWhileEnd (== '/') path)) of+      (name, _) -> reverse name+    -- The values of nn_spawn_step in nn_buildusers.h.+    stepText :: CInt -> Text+    stepText step = case step of+      1 -> "creating pipe"+      2 -> "unable to fork"+      3 -> "creating a new session"+      4 -> "cannot dup null device into stdin"+      5 -> "cannot dup output pipe into stdout"+      6 -> "changing into \"" <> T.pack workDir <> "\""+      7 -> "cannot set supplementary groups of build user"+      8 -> "setgid failed"+      9 -> "setuid failed"+      _ -> "executing '" <> T.pack program <> "'"++-- | Every group a user is in, given its name and primary group, as the+-- system's @getgrouplist@ answers on Linux, where upstream keeps a build+-- user's supplementary groups; none elsewhere, where upstream keeps none.+groupList :: ByteString -> Word32 -> IO [Word32]+#if defined(linux_HOST_OS)+groupList name primary = BS.useAsCString name (grow initialGroups)+  where+    -- getgrouplist answers -1, with the count it needs in place of the+    -- count it was given, only when the list does not fit.+    grow capacity cName = allocaArray capacity $ \groups ->+      alloca $ \countPtr -> do+        poke countPtr (fromIntegral capacity :: CInt)+        answer <- c_getgrouplist cName (fromIntegral primary) groups countPtr+        count <- fromIntegral <$> peek countPtr+        if answer < 0+          then grow (max count (2 * capacity)) cName+          else map fromIntegral <$> peekArray count groups+    initialGroups = 32++foreign import ccall safe "grp.h getgrouplist"+  c_getgrouplist :: CString -> CUInt -> Ptr CUInt -> Ptr CInt -> IO CInt+#else+groupList _ _ = pure []+#endif++foreign import ccall safe "nn_buildusers.h nn_kill_user"+  c_nn_kill_user :: CUInt -> Ptr CInt -> IO CInt++foreign import ccall unsafe "nn_buildusers.h nn_signal_text"+  c_nn_signal_text :: CInt -> IO CString++foreign import ccall safe "nn_buildusers.h nn_spawn_as_user"+  c_nn_spawn_as_user :: CString -> Ptr CString -> Ptr CString -> CString -> CInt -> CInt -> CUInt -> CUInt -> CInt -> Ptr CUInt -> Ptr CInt -> Ptr CInt -> IO CInt++foreign import ccall safe "nn_buildusers.h nn_spawn_as_invoker"+  c_nn_spawn_as_invoker :: CString -> Ptr CString -> Ptr CString -> CString -> CInt -> CInt -> Ptr CInt -> Ptr CInt -> IO CInt++#endif
+ src/Nix/Builder/Buildenv.hs view
@@ -0,0 +1,239 @@+-- | __builtin:buildenv__, upstream's builder of a user environment+-- (@builtinBuildenv@ in builtins\/buildenv.cc): the builder of the+-- derivation @nix-env@ evaluates from its @buildenv.nix@.  Its output is+-- the tree ("Nix.Profile.Tree") of the packages its @derivations@+-- attribute names, with @manifest.nix@ linked to its @manifest@.+--+-- Like @builtin:fetchurl@ and @builtin:unpack@, it runs in this process.+-- The paths in @derivations@ and @manifest@ are in eval's canonical+-- @\/nix\/store@ spelling, and each is read and linked as the store spells+-- it on disk ('storePackagePath'), as @builtin:unpack@ renders @srcs@.+module Nix.Builder.Buildenv+  ( -- * Builder name+    builtinBuildenvBuilder,++    -- * The derivations attribute+    Element (..),+    Activity (..),+    DerivationsError (..),+    parseDerivations,+    elementPackages,+    derivationsErrorText,++    -- * Running+    runBuiltinBuildenv,+  )+where++import Control.Monad (guard)+import Control.Monad.Except (ExceptT (..), liftEither, runExceptT, throwError)+import Control.Monad.IO.Class (liftIO)+import Data.Bifunctor (first)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BS8+import Data.Char (isDigit)+import Data.Foldable (traverse_)+import Data.Int (Int32)+import qualified Data.Map.Strict as Map+import Data.Text (Text)+import qualified Data.Text.Encoding as TE+import Nix.Derivation (Derivation (..))+import Nix.Logger (Logger, logWarning)+import Nix.Profile.Tree (Built (..), Package (..), buildEnvFailureText, buildProfile, storePackagePath, storeTreeReader, warningText, writeTree)+import Nix.Store.Path (StoreDir)+import Nix.Store.Symlink (createSymlinkOfKind)+import System.Directory (createDirectoryIfMissing)+import System.OsPath (OsPath, (</>))+import qualified System.OsPath as OP+import Text.Read (readMaybe)++-- ---------------------------------------------------------------------------+-- Named constants+-- ---------------------------------------------------------------------------++-- | The builder string a derivation names this builtin by.  Bytes, as the+-- 'drvBuilder' field it is compared with is.+builtinBuildenvBuilder :: ByteString+builtinBuildenvBuilder = "builtin:buildenv"++-- | The attribute naming the packages.+derivationsKey :: Text+derivationsKey = "derivations"++-- | The attribute naming the file @manifest.nix@ links to.+manifestKey :: Text+manifestKey = "manifest"++-- | The output the tree is made in.+outputName :: Text+outputName = "out"++-- | The name of the link to the manifest, in the output.  ASCII, which+-- 'OP.unsafeFromChar' narrows to one path unit per character without+-- loss.+manifestLinkName :: OsPath+manifestLinkName = OP.pack (map OP.unsafeFromChar "manifest.nix")++-- | The one activity token that makes an element inactive.+inactiveToken :: ByteString+inactiveToken = "false"++-- | The characters C's @isspace@ takes as space in the C locale, which+-- @stoi@ and @stoul@ skip before a number.+cSpaces :: String+cSpaces = " \t\n\v\f\r"++-- ---------------------------------------------------------------------------+-- The derivations attribute+-- ---------------------------------------------------------------------------++-- | Whether an element's packages go into the tree.+data Activity = Active | Inactive+  deriving (Eq, Show)++-- | One element of the @derivations@ attribute, which @buildenv.nix@ makes+-- of each package as its activity, its priority, its output count and its+-- output paths.+data Element = Element+  { -- | 'Inactive' when the token is @false@, and 'Active' for any other.+    elementActivity :: !Activity,+    -- | The priority, as @stoi@ reads it.+    elementPriority :: !Int,+    -- | The output paths, as the attribute spells them.+    elementPaths :: ![ByteString]+  }+  deriving (Eq, Show)++-- | Why the @derivations@ attribute names no elements.  Upstream trusts+-- the attribute's shape, so where it reads past the last token its+-- behaviour is undefined, and where @stoi@ or @stoul@ throws the build+-- fails with no more than the function's name.+data DerivationsError+  = -- | The attribute ends before an element's priority, its output count+    -- or its last path.+    EndsInsideElement+  | -- | A priority that is not an int: no digit leads it, or it is out of+    -- range.+    BadPriority !ByteString+  | -- | An output count that is not a count: no digit leads it, or it is+    -- negative.+    BadOutputCount !ByteString+  deriving (Eq, Show)++-- | Read the @derivations@ attribute: whitespace-separated tokens with the+-- empty ones dropped, as upstream's @tokenizeString@ gives them, in groups+-- of an activity, a priority, an output count and that many paths+-- (@builtinBuildenv@ in buildenv.cc).+parseDerivations :: ByteString -> Either DerivationsError [Element]+parseDerivations = elementsOf . filter (not . BS.null) . BS8.splitWith (`elem` tokenSeparators)+  where+    -- tokenizeString's default separators (its declaration in strings.hh).+    tokenSeparators = " \t\n\r" :: String++-- | The elements a token list holds, in order.+elementsOf :: [ByteString] -> Either DerivationsError [Element]+elementsOf tokens = case tokens of+  [] -> Right []+  activity : rest -> do+    (priorityToken, afterPriority) <- nextToken rest+    priority <- maybe (Left (BadPriority priorityToken)) Right (stoi priorityToken)+    (countToken, afterCount) <- nextToken afterPriority+    count <- maybe (Left (BadOutputCount countToken)) Right (stoulCount countToken)+    (paths, after) <- takeExactly count afterCount+    (Element (activityOf activity) priority paths :) <$> elementsOf after+  where+    nextToken remaining = case remaining of+      token : after -> Right (token, after)+      [] -> Left EndsInsideElement+    activityOf token+      | token == inactiveToken = Inactive+      | otherwise = Active++-- | The first @count@ tokens and the rest, when there are that many.+takeExactly :: Integer -> [ByteString] -> Either DerivationsError ([ByteString], [ByteString])+takeExactly count tokens+  | count > toInteger (maxBound :: Int) = Left EndsInsideElement+  | length taken == wanted = Right (taken, after)+  | otherwise = Left EndsInsideElement+  where+    wanted = fromInteger count+    (taken, after) = splitAt wanted tokens++-- | The int @stoi@ reads from a token: 'leadingInteger', within an int's+-- range.  Whatever follows the digits is ignored, so a float priority,+-- which @buildenv.nix@ writes as @5.500000@, reads as 5.+stoi :: ByteString -> Maybe Int+stoi token = do+  value <- leadingInteger token+  guard (value >= toInteger (minBound :: Int32) && value <= toInteger (maxBound :: Int32))+  pure (fromInteger value)++-- | The count @stoul@ reads from a token: 'leadingInteger', where @-0@ is+-- zero and any other negative number is refused, since @stoul@ wraps it+-- to a count larger than any attribute holds.+stoulCount :: ByteString -> Maybe Integer+stoulCount token = do+  value <- leadingInteger token+  guard (value >= 0)+  pure value++-- | The decimal number at the start of a token, as @strtol@ reads one:+-- C whitespace, then a sign, then at least one digit.+leadingInteger :: ByteString -> Maybe Integer+leadingInteger token = case BS8.uncons unspaced of+  Just ('-', rest) -> negate <$> digits rest+  Just ('+', rest) -> digits rest+  _ -> digits unspaced+  where+    unspaced = BS8.dropWhile (`elem` cSpaces) token+    digits = readMaybe . BS8.unpack . BS8.takeWhile isDigit++-- | Each path of each active element, with the element's priority, in+-- order: upstream's builder passes an inactive one to @buildProfile@,+-- which never reads it (buildenv.cc).+elementPackages :: [Element] -> [(ByteString, Int)]+elementPackages elements = [(path, priority) | Element Active priority paths <- elements, path <- paths]++-- | A @derivations@ failure in words.+derivationsErrorText :: DerivationsError -> Text+derivationsErrorText failure = case failure of+  EndsInsideElement -> "the 'derivations' attribute ends inside an element"+  BadPriority token -> "the 'derivations' attribute gives '" <> shown token <> "' as a priority, which is not an int"+  BadOutputCount token -> "the 'derivations' attribute gives '" <> shown token <> "' as an output count, which is not a count"+  where+    shown = TE.decodeUtf8Lenient++-- ---------------------------------------------------------------------------+-- Running+-- ---------------------------------------------------------------------------++-- | Run a @builtin:buildenv@ derivation: make its @out@ output the tree of+-- the packages @derivations@ names, giving the logger each warning the+-- tree gives, and link @manifest.nix@ in it to @manifest@.  Upstream reads+-- @manifest@ once the tree is made, so a tree that fails is the failure+-- reported when both do.  Returns a failure's exit code and message, which+-- "Nix.Builder" reports as a refused builder, so the shared validation and+-- registration there follow.+runBuiltinBuildenv :: Logger -> StoreDir -> Derivation -> [(Text, FilePath)] -> IO (Either (Int, Text) ())+runBuiltinBuildenv logger storeDir drv outputDirs = first failed <$> runExceptT build+  where+    failed reason = (1, "builtin:buildenv: " <> reason)+    build = do+      outDir <- maybe (throwError "derivation defines no 'out' output") pure (lookup outputName outputDirs)+      liftIO (createDirectoryIfMissing True outDir)+      elements <- attribute derivationsKey >>= liftEither . first derivationsErrorText . parseDerivations+      packages <- traverse (\(path, priority) -> (`Package` priority) <$> named derivationsKey path) (elementPackages elements)+      out <- liftIO (OP.encodeFS outDir)+      Built warnings tree <- liftIO (buildProfile (storeTreeReader storeDir) out packages)+      liftIO (traverse_ (logWarning logger . warningText) warnings)+      linked <- liftEither (first buildEnvFailureText tree)+      ExceptT (writeTree out linked)+      manifest <- attribute manifestKey >>= named manifestKey+      ExceptT (createSymlinkOfKind (out </> manifestLinkName) manifest)+    attribute :: Text -> ExceptT Text IO ByteString+    attribute key = maybe (throwError ("attribute '" <> key <> "' missing")) pure (Map.lookup key (drvEnv drv))+    named :: Text -> ByteString -> ExceptT Text IO OsPath+    named key path =+      liftIO (storePackagePath storeDir path)+        >>= maybe (throwError ("the '" <> key <> "' attribute names '" <> TE.decodeUtf8Lenient path <> "', which is not a store path")) pure
+ src/Nix/Builder/Cores.hs view
@@ -0,0 +1,245 @@+{-# LANGUAGE CPP #-}++-- | The default of upstream's @cores@ setting, which a builder's+-- @NIX_BUILD_CORES@ carries when no source sets it or a source sets it+-- to 0: the CPU limit of the process's cgroup on Linux, otherwise the+-- machine's hardware threads, as upstream's default is.+--+-- The limit is upstream's @getMaxCPU@ in current-process.cc: the+-- @cpu.max@ of the process's cgroup v2 group, under the first @cgroup2@+-- mount, as its quota over its period rounded up.  A file upstream cannot+-- read, or a line it cannot parse, gives 0 there, which is no limit, and+-- no limit here; where upstream's number parsing throws past its catch+-- instead, this module still answers no limit ('cpuMaxCores' says+-- when).  Each file is parsed by a pure function, and+-- the reads are an effect the caller passes in ('ReadKernelFile'), so the+-- whole rule runs in tests over an in-memory map.  The choice to read the+-- files only on Linux, where upstream reads them, is the caller's.+module Nix.Builder.Cores+  ( -- * The default+    defaultCores,+    hardwareConcurrency,+    ReadKernelFile,+    cgroupCoreLimit,++    -- * The files+    cgroup2MountPoint,+    parseCgroups,+    cpuMaxCores,+  )+where++import Control.Monad (guard, mfilter, (<=<))+import Data.Bits (toIntegralSized)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BS8+import Data.Char (isDigit, ord)+import Data.Int (Int32)+import Data.List (find)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe, listToMaybe, mapMaybe)+import Data.Word (Word32)+import Nix.HostPath (hostPathFromBytes)+import System.OsPath (OsPath)+#if defined(mingw32_HOST_OS)+import GHC.Conc (getNumProcessors)+#else+import Foreign.C.Types (CLong (..))+#endif++-- ---------------------------------------------------------------------------+-- The default+-- ---------------------------------------------------------------------------++-- | Upstream's @getDefaultCores@: the cgroup's limit when it is positive,+-- otherwise the hardware thread count, raised to 1 as+-- @std::max(1U, std::thread::hardware_concurrency())@ raises it.+defaultCores :: Maybe Word32 -> Word32 -> Word32+defaultCores limit hardware = case limit of+  Just cores | cores > 0 -> cores+  _ -> max 1 hardware++-- | Upstream's @std::thread::hardware_concurrency@ on this machine, which+-- 'defaultCores' raises to 1.  On Linux and macOS it is the call+-- upstream's C++ runtime makes, @sysconf(_SC_NPROCESSORS_ONLN)@+-- (cbits\/nn_cpus.c).  libc++ 16.0.6, which nixpkgs 24.05 builds upstream+-- with on macOS, makes that call.  libstdc++ calls glibc's @get_nprocs@,+-- and glibc's @sysconf@ answers that name with the same function+-- (sysdeps\/posix\/sysconf.c at glibc 2.39), which counts the CPUs+-- @\/sys\/devices\/system\/cpu\/online@ lists.  The glibc is the+-- host's here and nixpkgs' 2.39 upstream; they agree on every release but+-- 2.34, whose @get_nprocs@ counts the process's affinity mask instead.  A+-- negative answer, @sysconf@'s error, is 0, as both runtimes make it.  On+-- Windows, where upstream has no local builder, it is GHC's+-- @getNumProcessors@ ("GHC.Conc").+hardwareConcurrency :: IO Word32+#if defined(mingw32_HOST_OS)+-- The RTS counts in a uint32_t that getNumProcessors widens to an Int, so+-- narrowing it back loses nothing.+hardwareConcurrency = fromIntegral <$> getNumProcessors+#else+hardwareConcurrency = fromMaybe 0 . toIntegralSized <$> c_nn_online_processors++foreign import ccall unsafe "nn_cpus.h nn_online_processors"+  c_nn_online_processors :: IO CLong+#endif++-- | How 'cgroupCoreLimit' reads a kernel file: its bytes, or 'Nothing'+-- when it cannot be read.+type ReadKernelFile m = OsPath -> m (Maybe ByteString)++-- | Upstream's @getMaxCPU@ over the given reads: the cores the @cpu.max@+-- of the process's cgroup v2 group allows, or 'Nothing' when no step+-- reaches a number.  The group is the one @\/proc\/self\/cgroup@ lists+-- under the empty name ('parseCgroups'), and an empty path is none.  Its+-- @cpu.max@ is read at the first @cgroup2@ mount ('cgroup2MountPoint')+-- joined to the group's path with a @\/@ between, which the path's own+-- leading @\/@ doubles, as upstream joins them.+cgroupCoreLimit :: (Monad m) => ReadKernelFile m -> m (Maybe Word32)+cgroupCoreLimit readKernelFile = do+  mountPoint <- (>>= cgroup2MountPoint) <$> readBytes procMountsPath+  whenFound mountPoint $ \mount -> do+    group <- (>>= unifiedGroup) <$> readBytes procSelfCgroupPath+    whenFound group $ \path ->+      (>>= cpuMaxCores) <$> readBytes (BS.intercalate "/" [mount, path, cpuMaxFileName])+  where+    readBytes = maybe (pure Nothing) readKernelFile . hostPathFromBytes+    unifiedGroup = mfilter (not . BS.null) . Map.lookup unifiedHierarchy <=< parseCgroups+    whenFound found next = maybe (pure Nothing) next found++-- ---------------------------------------------------------------------------+-- The files+-- ---------------------------------------------------------------------------++-- | The mount point of the first @cgroup2@ file system in the bytes of+-- @\/proc\/mounts@, as upstream's @getCgroupFS@ (linux/cgroup.cc at+-- 2.24.9) finds it through glibc's @getmntent@ (misc/mntent_r.c and+-- misc/mntent.c at glibc 2.39).  A line is read only as far as the 4095+-- bytes glibc's buffer holds; a line that is blank or whose first byte+-- after spaces and tabs is @#@ is skipped; and the fields are the runs of+-- bytes other than space and tab.  The mount point is decoded as glibc's+-- @decode_name@ decodes it: @\\040@, @\\011@ and @\\012@ are a space,+-- a tab and a newline, @\\134@ and @\\\\@ are a backslash, and any+-- other backslash stands for itself.  The first four are how the kernel+-- writes those bytes in a mount point (@show_vfsmnt@,+-- fs/proc_namespace.c).  glibc decodes the type too, but no escape+-- decodes to a byte @cgroup2@ holds, so the type compares the same+-- undecoded.+cgroup2MountPoint :: ByteString -> Maybe ByteString+cgroup2MountPoint = listToMaybe . mapMaybe (cgroup2Entry . BS.take mntentLineLimit) . BS8.lines+  where+    cgroup2Entry line = case mountFields line of+      _ : dir : fsType : _ | fsType == cgroup2Type -> Just (decodeMountField dir)+      _ -> Nothing+    mountFields line = case BS8.uncons (BS8.dropWhile isMountBlank line) of+      Just (lead, _) | lead == mntentComment -> []+      _ -> filter (not . BS.null) (BS8.splitWith isMountBlank line)+    isMountBlank c = c == ' ' || c == '\t'++-- | glibc's @decode_name@, whose escapes 'cgroup2MountPoint' lists.  In+-- a device or type the kernel also writes @#@ as @\\043@, which glibc+-- leaves as written.+decodeMountField :: ByteString -> ByteString+decodeMountField = BS.concat . chunks+  where+    chunks field = case BS8.break (== '\\') field of+      (plain, escaped) -> plain : maybe [] (escapeChunks . snd) (BS.uncons escaped)+    escapeChunks rest = case find ((`BS.isPrefixOf` rest) . fst) mountEscapes of+      Just (code, decoded) -> decoded : chunks (BS.drop (BS.length code) rest)+      Nothing -> "\\" : chunks rest++-- | What follows a backslash in an escape glibc decodes, and the byte it+-- stands for.+mountEscapes :: [(ByteString, ByteString)]+mountEscapes = [("040", " "), ("011", "\t"), ("012", "\n"), ("\\", "\\"), ("134", "\\")]++-- | Upstream's @getCgroups@ (linux/cgroup.cc at 2.24.9) over the bytes of+-- @\/proc\/self\/cgroup@: each non-empty line is @ID:CONTROLLERS:PATH@ as+-- its @std::regex@ @([0-9]+):([^:]*):(.*)@ matches it, keyed by the+-- controller list with a @name=@ prefix dropped, and a later line replaces+-- an earlier one of the same name.  A line that does not match makes the+-- whole file 'Nothing', as upstream throws.  The regex's grammar is+-- ECMAScript, whose @.@ matches no carriage return, so a path holding one+-- does not match.+parseCgroups :: ByteString -> Maybe (Map ByteString ByteString)+parseCgroups = fmap Map.fromList . traverse cgroupLine . filter (not . BS.null) . BS8.split '\n'+  where+    cgroupLine line = do+      let (hierarchyId, afterId) = BS8.break (== ':') line+      guard (not (BS.null hierarchyId) && BS8.all isDigit hierarchyId)+      (controllers, afterControllers) <- BS8.break (== ':') <$> dropColon afterId+      path <- dropColon afterControllers+      guard (BS8.notElem '\r' path)+      pure (fromMaybe controllers (BS.stripPrefix namedHierarchyPrefix controllers), path)+    dropColon = fmap snd . mfilter ((== ':') . fst) . BS8.uncons++-- | The cores a cgroup's @cpu.max@ allows, as upstream's @getMaxCPU@+-- reads it: exactly two tokens between spaces and newlines, a quota of+-- @max@ meaning no limit, and otherwise+-- @std::ceil(std::stoi(quota) \/ std::stof(period))@, which is 0 for a+-- quota of 0.  That division is in single precision, and so is this one:+-- its rounding decides the count for a quota a little over a whole number+-- of periods, so 20000001 over 1000000 is 20 there and here, not 21.  The+-- kernel writes both as decimal integers.  A token that is not one, a+-- quota past @int@, and a period of 0 are 'Nothing' here.  Upstream+-- instead reads a token's leading number and ignores the rest+-- (@std::stoi@, @std::stof@), throws an exception its @catch (Error &)@+-- does not catch when there is no number or it is out of range, and+-- divides by zero.+cpuMaxCores :: ByteString -> Maybe Word32+cpuMaxCores contents = case filter (not . BS.null) (BS8.splitWith (`BS8.elem` cpuMaxSeparators) contents) of+  [quota, period] | quota /= unlimitedQuota -> do+    quotaMicros <- decimal quota >>= toIntegralSized :: Maybe Int32+    periodMicros <- mfilter (> 0) (decimal period)+    toIntegralSized (ceiling (fromIntegral quotaMicros / fromInteger periodMicros :: Float) :: Integer)+  _ -> Nothing++-- | A whole run of decimal digits as an 'Integer'; anything else, the+-- empty run included, is 'Nothing'.+decimal :: ByteString -> Maybe Integer+decimal digits+  | not (BS.null digits) && BS8.all isDigit digits = Just (BS8.foldl' step 0 digits)+  | otherwise = Nothing+  where+    step acc digit = acc * 10 + toInteger (ord digit - ord '0')++-- ---------------------------------------------------------------------------+-- Names+-- ---------------------------------------------------------------------------++procMountsPath, procSelfCgroupPath, cpuMaxFileName :: ByteString+procMountsPath = "/proc/mounts"+procSelfCgroupPath = "/proc/self/cgroup"+cpuMaxFileName = "cpu.max"++-- | The file system type of the cgroup v2 hierarchy.+cgroup2Type :: ByteString+cgroup2Type = "cgroup2"++-- | The name 'parseCgroups' gives the cgroup v2 hierarchy, whose line in+-- @\/proc\/self\/cgroup@ lists no controllers.+unifiedHierarchy :: ByteString+unifiedHierarchy = ""++-- | What a named cgroup v1 hierarchy's controller list starts with.+namedHierarchyPrefix :: ByteString+namedHierarchyPrefix = "name="++-- | The quota @cpu.max@ holds for a group with no limit.+unlimitedQuota :: ByteString+unlimitedQuota = "max"++-- | The separators upstream's @tokenizeString@ splits @cpu.max@ at.+cpuMaxSeparators :: ByteString+cpuMaxSeparators = " \n"++-- | The most of a line @getmntent@ reads: its buffer is 4096 bytes, less+-- the NUL @fgets@ ends it with, and the rest of a longer line is dropped.+mntentLineLimit :: Int+mntentLineLimit = 4095++-- | What starts a comment line @getmntent@ skips.+mntentComment :: Char+mntentComment = '#'
+ src/Nix/Builder/Job.hs view
@@ -0,0 +1,63 @@+{-# LANGUAGE CPP #-}++-- | The Windows job an unsandboxed builder runs in, which the process+-- library makes for each builder ('System.Process.use_process_jobs') and+-- every process the builder starts joins.+--+-- A process that meets an unhandled exception, as a configure test that+-- divides by zero to see whether that raises SIGFPE does, has Windows+-- Error Reporting start WerFault.exe from inside it: a program from+-- outside the store, which can wait on a dialog no one answers.  Upstream+-- has a crashing builder dump no core.  The job's+-- @JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION@ is the counterpart here:+-- Windows' unhandled-exception filter then returns to the process's own+-- handler, which ends it with the exception's code as its exit code,+-- without invoking the reporter.  An error mode would not hold: the one a+-- process passes to those it starts (@SEM_NOGPFAULTERRORBOX@) is one each+-- may replace, as busybox-w32 replaces it with @SEM_FAILCRITICALERRORS@+-- alone when it starts, while the limit is the job's.  The sandbox helper+-- gives its own job the same limit (sandbox\/windows.c).+--+-- The process library starts the builder before it hands back the job,+-- so the limit is set a moment after the builder starts.+module Nix.Builder.Job+  ( dieOnUnhandledException,+  )+where++import qualified System.Process as Proc++#if defined(mingw32_HOST_OS)++import Foreign.C.String (CString, peekCString)+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (Ptr)+import Foreign.Storable (peek)+import System.Process.Internals (ProcessHandle__ (..), withProcessHandle)+import System.Win32.Types (ErrCode, failWith)++#endif++-- | Have the job a builder was started in end each of its processes at+-- an unhandled exception, without Windows Error Reporting, keeping the+-- job's other limits.  A failure throws the 'IOError' naming the call+-- that failed, as a builder that could not be started does.  A process+-- in no job of the process library's, as one started without+-- 'Proc.use_process_jobs' is and every process off Windows is, is left+-- as it is.+dieOnUnhandledException :: Proc.ProcessHandle -> IO ()+#if defined(mingw32_HOST_OS)+dieOnUnhandledException process = withProcessHandle process $ \handle -> case handle of+  OpenExtHandle _ job -> alloca $ \failedOut -> do+    code <- c_nn_job_die_on_unhandled_exception job failedOut+    case code of+      0 -> pure ()+      _ -> peek failedOut >>= peekCString >>= \call -> failWith call code+  OpenHandle _ -> pure ()+  ClosedHandle _ -> pure ()++foreign import ccall unsafe "nn_winfs.h nn_job_die_on_unhandled_exception"+  c_nn_job_die_on_unhandled_exception :: Ptr () -> Ptr CString -> IO ErrCode+#else+dieOnUnhandledException _ = pure ()+#endif
src/Nix/Builder/Log.hs view
@@ -4,10 +4,10 @@ -- -- Upstream gives the builder one channel for its standard output and -- standard error, so what it wrote arrives in the order it wrote it,--- and its default logger prints each line to standard error as the line--- completes, filtered for the terminal.  The line discipline and the--- filter are pure ('feedBuildLog', 'endBuildLog', 'filterLogLine'); the--- pipe and the copy loop are the IO around them.+-- and hands its logger each line as the line completes.  The line+-- discipline is pure ('feedBuildLog', 'endBuildLog'); the pipe and the+-- copy loop are the IO around it, and the logger ("Nix.Logger") decides+-- where a line goes. module Nix.Builder.Log   ( -- * Line discipline     PendingLine,@@ -15,37 +15,28 @@     feedBuildLog,     endBuildLog, -    -- * Terminal filter-    EscapeFilter (..),-    filterLogLine,-     -- * Streaming     openLogPipe,     streamBuildLog,   ) where -import Data.Bits ((.&.)) import qualified Data.ByteString as BS-import qualified Data.ByteString.Builder as BB import qualified Data.ByteString.Char8 as BS8-import qualified Data.ByteString.Lazy as BL import Data.Foldable (for_)-import Data.Word (Word8)-import Nix.Environment (EnvLookup (..), lookupEnvBytes)+import Nix.Logger (Logger (..)) import qualified System.Process as Proc  #if defined(mingw32_HOST_OS) -import Control.Exception (IOException, catch)-import System.IO (Handle, hIsTerminalDevice)+import System.IO (Handle)  #else -import Control.Exception (IOException, catch, onException)+import Control.Exception (onException) import GHC.IO.FD (fdFD) import GHC.IO.Handle.FD (handleToFd)-import System.IO (Handle, hClose, hIsTerminalDevice)+import System.IO (Handle, hClose) import System.Posix.IO (FdOption (CloseOnExec), setFdOption) import System.Posix.Types (Fd (..)) @@ -129,160 +120,14 @@ lineBytes (PendingLine before fromCursor) = BS.concat (reverse (fromCursor : before))  -- ------------------------------------------------------------------------------ Terminal filter--- ------------------------------------------------------------------------------- | Which escape sequences a build-log line keeps on its way to the user.-data EscapeFilter-  = -- | Keep colour (an SGR sequence, CSI ending in @m@) and drop the rest,-    -- for a terminal that renders it.-    KeepColour-  | -- | Drop every escape sequence.-    DropEscapes-  deriving (Eq, Show)---- | A build-log line as upstream's logger writes it to standard error--- (@filterANSIEscapes@, terminal.cc at 2.24.9, at the unlimited width--- @SimpleLogger::log@ passes): an escape sequence is dropped unless the--- filter keeps it, a tab becomes spaces up to the next multiple of--- eight columns, a bell or carriage return is dropped, and every other--- byte is kept.  A column is one character as upstream groups one: a--- UTF-8 lead byte with as many continuation bytes as it announces and--- as follow it, or any other byte alone.-filterLogLine :: EscapeFilter -> BS.ByteString -> BS.ByteString-filterLogLine escapes = BL.toStrict . BB.toLazyByteString . go 0-  where-    go :: Int -> BS.ByteString -> BB.Builder-    go !column bytes =-      let (plain, rest) = BS.span isPlainAscii bytes-       in BB.byteString plain <> special (column + BS.length plain) rest-    special column bytes = case BS.uncons bytes of-      Nothing -> mempty-      Just (byte, rest)-        | byte == escapeByte ->-            let (escape, after) = escapeSequence rest-                escapeBytes = BS.cons byte (BS.take (BS.length rest - BS.length after) rest)-             in kept escape escapeBytes <> go column after-        | byte == tabByte ->-            let width = tabStop - column `mod` tabStop-             in BB.byteString (BS.replicate width spaceByte) <> go (column + width) rest-        | byte == bellByte || byte == carriageReturnByte -> go column rest-        | otherwise ->-            let continued = BS.takeWhile isContinuation (BS.take (continuationCount byte) rest)-             in BB.word8 byte <> BB.byteString continued <> go (column + 1) (BS.drop (BS.length continued) rest)-    kept escape escapeBytes-      | escapes == KeepColour && escape == ColourEscape = BB.byteString escapeBytes-      | otherwise = mempty-    isPlainAscii byte =-      byte < asciiLimit-        && byte /= escapeByte-        && byte /= tabByte-        && byte /= bellByte-        && byte /= carriageReturnByte---- | What an escape sequence does, as far as the filter cares.-data EscapeKind = ColourEscape | OtherEscape-  deriving (Eq)---- | The kind of escape the bytes after an ESC begin, and the bytes after--- its sequence, which upstream's filter reads as a CSI's parameter,--- intermediate and final bytes, or the one byte a two-byte escape takes,--- or nothing.-escapeSequence :: BS.ByteString -> (EscapeKind, BS.ByteString)-escapeSequence bytes = case BS.uncons bytes of-  Just (byte, afterBracket)-    | byte == csiByte ->-        let afterParameters = BS.dropWhile (within csiParameterBytes) afterBracket-            afterIntermediates = BS.dropWhile (within csiIntermediateBytes) afterParameters-         in case BS.uncons afterIntermediates of-              Just (final, after)-                | within csiFinalBytes final -> (if final == sgrFinalByte then ColourEscape else OtherEscape, after)-              _ -> (OtherEscape, afterIntermediates)-    | within escapeFinalBytes byte -> (OtherEscape, afterBracket)-  _ -> (OtherEscape, bytes)---- | How many continuation bytes a UTF-8 lead byte announces.-continuationCount :: Word8 -> Int-continuationCount lead-  | lead .&. 0xE0 == 0xC0 = 1-  | lead .&. 0xF0 == 0xE0 = 2-  | lead .&. 0xF8 == 0xF0 = 3-  | otherwise = 0---- | Whether a byte continues a UTF-8 character.-isContinuation :: Word8 -> Bool-isContinuation byte = byte .&. 0xC0 == 0x80---- | Whether a byte lies in an inclusive range.-within :: (Word8, Word8) -> Word8 -> Bool-within (low, high) byte = low <= byte && byte <= high---- | The control bytes the filter treats specially, and the space a tab--- expands to.-escapeByte, tabByte, bellByte, carriageReturnByte, spaceByte :: Word8-escapeByte = 0x1B-tabByte = 0x09-bellByte = 0x07-carriageReturnByte = 0x0D-spaceByte = 0x20---- | The byte opening a control sequence after an ESC (@[@), and the--- final byte of a colour one (@m@).-csiByte, sgrFinalByte :: Word8-csiByte = 0x5B-sgrFinalByte = 0x6D---- | The ECMA-48 byte ranges upstream's filter reads a sequence by.-csiParameterBytes, csiIntermediateBytes, csiFinalBytes, escapeFinalBytes :: (Word8, Word8)-csiParameterBytes = (0x30, 0x3F)-csiIntermediateBytes = (0x20, 0x2F)-csiFinalBytes = (0x40, 0x7E)-escapeFinalBytes = (0x40, 0x5F)---- | The first byte that is not ASCII.-asciiLimit :: Word8-asciiLimit = 0x80---- | The columns between tab stops.-tabStop :: Int-tabStop = 8---- | The filter upstream's logger applies (@isTTY@, terminal.cc at--- 2.24.9): colour survives only on a terminal, with @TERM@ set to--- something other than @dumb@, and neither @NO_COLOR@ nor @NOCOLOR@--- set.  Upstream asks about its standard error; this asks about the--- handle the log goes to, which is standard error by default.-escapeFilterFor :: Handle -> IO EscapeFilter-escapeFilterFor buildLog = do-  terminal <- hIsTerminalDevice buildLog-  term <- lookupEnvBytes termVar-  noColour <- traverse lookupEnvBytes noColourVars-  pure $-    if terminal && rendersColour term && all (== EnvUnset) noColour-      then KeepColour-      else DropEscapes-  where-    rendersColour term = case term of-      EnvUnset -> False-      EnvValue value -> value /= dumbTerm-      EnvUnpairedSurrogate -> True---- | The variable naming the terminal type, and the type upstream reads--- as rendering no colour.-termVar, dumbTerm :: BS.ByteString-termVar = "TERM"-dumbTerm = "dumb"---- | The variables whose presence, whatever their value, turns colour off.-noColourVars :: [BS.ByteString]-noColourVars = ["NO_COLOR", "NOCOLOR"]---- --------------------------------------------------------------------------- -- Streaming -- ---------------------------------------------------------------------------  -- | A pipe to hand a builder as both its standard output and its--- standard error, as @(read end, write end)@.+-- standard error, or the sandbox helper as its standard error, which the+-- helper makes the builder's output on Linux and copies a pipe of the+-- builder's to on macOS ('Nix.Builder.Sandbox.Spawn.runHelper'), as+-- @(read end, write end)@. -- -- One channel keeps the order the builder wrote in.  Upstream's channel -- is a pseudoterminal: the builder's standard error is its slave side,@@ -323,40 +168,28 @@  #endif --- | Copy a builder's output to the build log a line at a time as each--- line completes, until every holder of the pipe's write end has--- closed it.+-- | Hand a builder's output to the logger ('logBuildLine') a line at a+-- time as each line completes, until every holder of the pipe's write+-- end has closed it, then the line left pending, if it holds any bytes. ----- A line goes out filtered ('filterLogLine', under 'escapeFilterFor'--- the log) in one write ending in a line feed, as upstream's default--- logger writes a build-log line to standard error (@SimpleLogger@,--- logging.cc at 2.24.9).  Upstream first reads a line beginning--- @\@nix @ as a JSON log message from the builder and does not print--- one that parses (@handleJSONLogMessage@); here every line is printed.--- Upstream points @NIX_LOG_FD@ at standard error so stdenv writes such--- lines, and nova-nix sets no @NIX_LOG_FD@.+-- Upstream first reads a line beginning @\@nix @ as a JSON log message+-- from the builder and does not log one that parses; here every line is+-- logged.  Upstream points @NIX_LOG_FD@ at standard error so stdenv+-- writes such lines, and nova-nix sets no @NIX_LOG_FD@. ----- A line the log fails to take is dropped and the build goes on, as--- upstream's @writeToStderr@ ignores a failing write (logging.cc), so a--- reader of standard error that went away does not fail the build.  The--- output is read to its end either way, so the builder never blocks on--- a full pipe.-streamBuildLog :: Handle -> Handle -> IO ()-streamBuildLog fromBuilder buildLog = do-  escapes <- escapeFilterFor buildLog-  let writeLine line = BS.hPut buildLog (BS8.snoc (filterLogLine escapes line) '\n') `catch` dropLine+-- The output is read to its end, so the builder never blocks on a full+-- pipe.+streamBuildLog :: Handle -> Logger -> IO ()+streamBuildLog fromBuilder logger = go emptyPendingLine+  where     go pending = do       chunk <- BS.hGetSome fromBuilder readSize       if BS.null chunk-          then for_ (endBuildLog pending) writeLine+        then for_ (endBuildLog pending) (logBuildLine logger)         else do           let (complete, rest) = feedBuildLog pending chunk-            for_ complete writeLine+          for_ complete (logBuildLine logger)           go rest-  go emptyPendingLine-  where-    dropLine :: IOException -> IO ()-    dropLine _ = pure ()  -- | How much builder output one read takes at most.  The lines written -- do not depend on it.
+ src/Nix/Builder/Sandbox.hs view
@@ -0,0 +1,1865 @@+-- | What the build sandbox is, worked out without IO: its settings, whether+-- a build is sandboxed, which network it gets, the plan the+-- @nova-nix-sandbox@ helper carries out, the chroot it carries it out in+-- on Linux, the profile it applies on macOS, and the helper's report of a+-- step that failed.+--+-- == The sandbox+--+-- On Linux a sandboxed build runs in fresh user, mount, PID, IPC and UTS+-- namespaces, and a network namespace of its own unless it is+-- fixed-output, with a chroot that holds its inputs, as upstream's+-- @LocalDerivationGoal@ builds one (local-derivation-goal.cc at 2.24.9,+-- called LDG here).  On macOS it runs under a profile of macOS's sandbox+-- that lets it read its inputs and write its outputs and build directory,+-- as upstream's @DarwinDerivationBuilder@ applies one+-- (darwin-derivation-builder.cc at 2.36.0, over+-- @UnixDerivationBuilderImpl@ in unix-derivation-builder.cc there).  The+-- work is split three ways: this module decides and plans;+-- "Nix.Builder.Sandbox.Spawn" makes the chroot's skeleton, looks at the+-- paths a profile names, probes the system and runs the helper; and the+-- helper, a C program of its own, carries the plan out.  The helper's core+-- (@sandbox\/nova-nix-sandbox.c@) reads the plan and reports a failed step+-- as it does on every OS, and links the backend for its OS+-- ('SandboxBackend'), which makes the sandbox: on Linux+-- (@sandbox\/linux.c@) the namespaces, the mounts and the root, between+-- the namespaces' creation and the builder's exec, where the process+-- library runs nothing; on macOS (@sandbox\/darwin.c@) the profile,+-- applied in the builder's process just before its exec.  The helper's+-- Windows backend (@sandbox\/windows.c@) starts the builder as a build+-- slot's account, whose token it is handed, on the window station of+-- that token's logon, attached to a pseudoconsole, in a job that caps+-- each process's memory, and ends the slot's processes before and after+-- the build, as a t'WindowsPlan' says; 'hostSandboxBackend' names no+-- backend on Windows, where no build runs through the helper.+--+-- == The protocol+--+-- The helper is spawned with an empty environment, so its dynamic loader+-- reads none of the variables a derivation sets; the builder's+-- environment travels in the plan, which the helper reads ('renderPlan')+-- on its standard input: a version line, a line holding the length of the+-- rest, then tokens, each its length, a colon, its bytes and a NUL.  The+-- pipe stays open after the plan, and its end kills the build.  On its standard+-- output the helper writes at most one record, @STAGE ERRNO INDEX@, for a+-- step that failed ('parseStatus'), so nothing there means the builder+-- ran.  On Linux the builder's start closes that output; on macOS the+-- helper alone writes it, relaying a failed step the builder's process+-- reports and reporting a failure to watch the build log, which can come+-- after the builder ran.  The stage names here and in the helper are one+-- list.+module Nix.Builder.Sandbox+  ( -- * Settings+    SandboxMode (..),+    sandboxSettingName,+    parseSandboxMode,+    renderSandboxMode,+    SandboxFallback (..),+    DropGroups (..),+    SandboxPath (..),+    PathPresence (..),+    parseSandboxPaths,+    ViolationLog (..),+    SandboxConfig (..),+    defaultSandboxConfig,++    -- * The backends+    SandboxBackend (..),+    hostSandboxBackend,+    backendFallback,+    darwinSandboxPaths,+    darwinImpureHostPrefixes,++    -- * The decision+    SandboxUse (..),+    sandboxUse,+    Network (..),+    buildNetwork,+    LocalNetworking (..),+    DarwinOptions (..),+    darwinOptions,++    -- * The plan+    sandboxUid,+    sandboxGid,+    sandboxHome,+    rootRefusal,+    BuilderIds (..),+    PlanInputs (..),+    SandboxPlan (..),+    Bind (..),+    BindAccess (..),+    SourceResolution (..),+    sandboxPlan,+    planVersionLine,+    renderPlan,++    -- * The macOS profile+    DarwinPathInputs (..),+    DarwinPath (..),+    DarwinPaths (..),+    darwinPathsInSandbox,+    darwinPathTarget,+    PathFound (..),+    ProfileFilter (..),+    profileFilter,+    DarwinProfile (..),+    darwinProfile,++    -- * The macOS plan+    DarwinPlan (..),+    darwinParameters,+    renderDarwinPlan,++    -- * The Windows plan+    WindowsPlan (..),+    renderWindowsPlan,++    -- * The chroot+    SkeletonEntry (..),+    chrootSkeleton,+    passwdFile,+    groupFile,++    -- * What the helper reports+    SetupStage (..),+    setupStageName,+    DarwinStage (..),+    darwinStageName,+    WindowsStage (..),+    windowsStageName,+    ProbeStage (..),+    probeStageName,+    StatusRecord (..),+    parseStatus,+    Unavailability (..),+    unavailabilityCause,+    unavailableMessage,+    setupFailureMessage,+    darwinSetupFailureMessage,+    fallbackWarning,+    setupContext,+    errnoSuffix,+    HelperOutcome (..),+    helperOutcome,+  )+where++import Data.Bool (bool)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BS8+import Data.Either (partitionEithers)+import Data.Int (Int32)+import Data.List (find, isPrefixOf)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe)+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Word (Word32, Word64)+import Foreign.C.Error (Errno (..), eNOENT, eNOTDIR, ePERM, errnoToIOError)+import GHC.IO.Exception (IOException (ioe_description))+import Nix.Derivation (Derivation, fixedOutput)+import Nix.Realise (derivationAttrs, derivationBoolAttr, derivationStringAttr, derivationStringsAttr)+import Nix.Store.Access (Sid, sidText)+import Nix.Store.Path (StorePath, defaultStoreDir, storePathToText)+import System.Exit (ExitCode)+import qualified System.Info+import Text.Read (readMaybe)++-- ---------------------------------------------------------------------------+-- Settings+-- ---------------------------------------------------------------------------++-- | Upstream's @sandbox@ setting (@sandboxMode@ in globals.hh at 2.24.9,+-- local-settings.hh from 2.34.9).+data SandboxMode+  = -- | Every build is sandboxed, and @__noChroot@ is an error.+    SandboxEnabled+  | -- | A build is sandboxed unless it is fixed-output or sets+    -- @__noChroot@.+    SandboxRelaxed+  | -- | No build is sandboxed.+    SandboxDisabled+  deriving (Eq, Show)++-- | The setting's own name, which its value errors name whatever alias set+-- it.+sandboxSettingName :: ByteString+sandboxSettingName = "sandbox"++-- | Upstream's @BaseSetting\<SandboxMode\>::parse@ (globals.cc):+-- @true@, @relaxed@ or @false@, and nothing else, not even the other+-- Boolean spellings.+parseSandboxMode :: ByteString -> Either Text SandboxMode+parseSandboxMode value = case value of+  "true" -> Right SandboxEnabled+  "relaxed" -> Right SandboxRelaxed+  "false" -> Right SandboxDisabled+  _ -> Left ("option '" <> TE.decodeUtf8Lenient sandboxSettingName <> "' has invalid value '" <> TE.decodeUtf8Lenient value <> "'")++-- | The spelling of a mode that 'parseSandboxMode' reads back, as+-- upstream writes the setting's value.+renderSandboxMode :: SandboxMode -> ByteString+renderSandboxMode mode = case mode of+  SandboxEnabled -> "true"+  SandboxRelaxed -> "relaxed"+  SandboxDisabled -> "false"++-- | Upstream's @sandbox-fallback@: what a sandboxed build does on a Linux+-- system that cannot make the namespaces ('backendFallback').+data SandboxFallback+  = -- | Build unsandboxed, upstream's default.+    FallBackUnsandboxed+  | -- | Fail the build.+    RefuseUnsandboxed+  deriving (Eq, Show)++-- | Upstream's @require-drop-supplementary-groups@: whether a build fails+-- when the invoking user's supplementary groups cannot be dropped.+data DropGroups+  = -- | Fail, upstream's default for root.+    RequireDropGroups+  | -- | Keep them and go on, upstream's default for anyone else.+    TolerateKeptGroups+  deriving (Eq, Show)++-- | Whether a path a bind names must exist.+data PathPresence+  = RequiredPath+  | -- | A missing source is passed over, as a @sandbox-paths@ entry ending+    -- in @?@ is.+    OptionalPath+  deriving (Eq, Show)++-- | One @sandbox-paths@ entry: the path in the sandbox and the host path+-- bound there, both bytes as the setting holds them.+data SandboxPath = SandboxPath+  { spTarget :: !ByteString,+    spSource :: !ByteString,+    spPresence :: !PathPresence+  }+  deriving (Eq, Show)++-- | Upstream's reading of @sandbox-paths@ (@startBuilder@ in LDG): in the+-- set's order, an empty entry skipped, a trailing @?@ making the source+-- optional, and @target=source@ split at the first @=@, a bare path binding+-- itself.  A later entry for a target replaces an earlier one+-- ('sandboxPlan').+parseSandboxPaths :: Set ByteString -> [SandboxPath]+parseSandboxPaths = concatMap entry . Set.toAscList+  where+    entry raw = case BS8.unsnoc raw of+      Nothing -> []+      Just (rest, '?') -> placed rest OptionalPath+      Just _ -> placed raw RequiredPath+    placed text presence = case BS8.break (== '=') text of+      (target, rest) | Just (_, source) <- BS8.uncons rest -> [SandboxPath target source presence]+      _ -> [SandboxPath text text presence]++-- | Upstream's @darwin-log-sandbox-violations@: whether macOS's sandbox+-- logs what a build's profile refuses.+data ViolationLog+  = -- | Refusals go unlogged, upstream's default.+    ViolationsUnlogged+  | -- | Refusals go to the system log.+    ViolationsLogged+  deriving (Eq, Show)++-- | How builds are sandboxed: the settings, and where the helper is.+data SandboxConfig = SandboxConfig+  { scMode :: !SandboxMode,+    scFallback :: !SandboxFallback,+    -- | The @sandbox-paths@ entries, read ('parseSandboxPaths').+    scPaths :: ![SandboxPath],+    -- | Upstream's @sandbox-build-dir@: where the builder sees its build+    -- directory on Linux.+    scBuildDir :: !ByteString,+    -- | Upstream's @sandbox-dev-shm-size@: the size of the tmpfs at+    -- @\/dev\/shm@, in mount(8)'s @size@ syntax.+    scDevShmSize :: !ByteString,+    scDropGroups :: !DropGroups,+    -- | Upstream's @allowed-impure-host-deps@: the host paths at or+    -- beneath which a derivation's @__impureHostDeps@ may name one, on+    -- macOS.+    scAllowedImpureHostDeps :: !(Set ByteString),+    scViolationLog :: !ViolationLog,+    -- | Upstream's @ssl-cert-file@: the CA bundle a fixed-output build in+    -- the Linux sandbox sees at @\/etc\/ssl\/certs\/ca-certificates.crt@,+    -- when there is one.+    scCaFile :: !(Maybe ByteString),+    -- | Where the @nova-nix-sandbox@ helper is, when it was found.+    scHelper :: !(Maybe FilePath)+  }+  deriving (Eq, Show)++-- | No build sandboxed, upstream's defaults where they are the same on+-- every OS (fallback on, @\/build@, half of memory for @\/dev\/shm@,+-- refusals unlogged), and the plainest value of each default that depends+-- on the OS, on whether the process is root, or on what only IO can find:+-- no paths, kept groups tolerated, no impure host paths allowed, and no CA+-- bundle or helper.+defaultSandboxConfig :: SandboxConfig+defaultSandboxConfig =+  SandboxConfig+    { scMode = SandboxDisabled,+      scFallback = FallBackUnsandboxed,+      scPaths = [],+      scBuildDir = "/build",+      scDevShmSize = "50%",+      scDropGroups = TolerateKeptGroups,+      scAllowedImpureHostDeps = Set.empty,+      scViolationLog = ViolationsUnlogged,+      scCaFile = Nothing,+      scHelper = Nothing+    }++-- ---------------------------------------------------------------------------+-- The backends+-- ---------------------------------------------------------------------------++-- | The sandbox an OS makes, as the helper's backend for that OS makes it+-- (@sandbox\/linux.c@, @sandbox\/darwin.c@).  Each holds a build to rules+-- of its own.+data SandboxBackend+  = -- | Namespaces, and a chroot of the build's inputs.+    LinuxBackend+  | -- | A profile macOS's sandbox holds the builder to.+    DarwinBackend+  deriving (Eq, Show)++-- | The backend for the OS nova-nix was built for, where the helper has+-- one.+hostSandboxBackend :: Maybe SandboxBackend+hostSandboxBackend = case System.Info.os of+  "linux" -> Just LinuxBackend+  "darwin" -> Just DarwinBackend+  _ -> Nothing++-- | What a sandboxed build does where the sandbox cannot be made, under+-- the given backend: upstream reads @sandbox-fallback@ on Linux alone, and+-- on macOS a sandbox that cannot be made fails the build+-- (@makeDerivationBuilder@ in unix-derivation-builder.cc at 2.36.0).+backendFallback :: Maybe SandboxBackend -> SandboxFallback -> SandboxFallback+backendFallback backend fallback = case backend of+  Just DarwinBackend -> RefuseUnsandboxed+  _ -> fallback++-- | The @sandbox-paths@ a macOS build sees by default: upstream's macOS+-- defaults (globals.cc at 2.36.0), the system's frameworks, libraries and+-- shells, without its temporary directories @\/private\/tmp@ and+-- @\/private\/var\/tmp@.  Those hold the invoking user's files and+-- sockets, where upstream's build user owns nothing.  Undo when builds run+-- as build users of their own, under a daemon.+darwinSandboxPaths :: Set ByteString+darwinSandboxPaths =+  Set.fromList+    [ "/System/Library/Frameworks",+      "/System/Library/PrivateFrameworks",+      "/bin/sh",+      "/bin/bash",+      "/usr/lib"+    ]++-- | The @allowed-impure-host-deps@ prefixes on macOS by default, upstream's+-- (globals.cc at 2.36.0).  A path beneath @\/dev@ a derivation names this+-- way is refused if it is a terminal ('darwinProfile').+darwinImpureHostPrefixes :: Set ByteString+darwinImpureHostPrefixes = Set.fromList ["/System/Library", "/usr/lib", "/dev", "/bin/sh"]++-- ---------------------------------------------------------------------------+-- The decision+-- ---------------------------------------------------------------------------++-- | Whether a build is sandboxed, and if it is, which network it gets.+data SandboxUse = Sandboxed !Network | Unsandboxed+  deriving (Eq, Show)++-- | The network a sandboxed build gets.+data Network+  = -- | On Linux a namespace of its own, holding only a loopback+    -- interface; on macOS no network, but the loopback one a derivation+    -- asks for ('LocalNetworking').+    PrivateNetwork+  | -- | The host's.+    HostNetwork+  deriving (Eq, Show)++-- | A fixed-output derivation reaches the host's network, as upstream Nix+-- leaves it unsandboxed; every other build gets a private one+-- ('PrivateNetwork').+-- 'fixedOutput' is the rule the @impureEnvVars@ carve-out follows too.+buildNetwork :: Derivation -> Network+buildNetwork drv = case fixedOutput drv of+  Just _ -> HostNetwork+  Nothing -> PrivateNetwork++-- | Upstream's choice of a sandboxed build (@tryLocalBuild@ in LDG,+-- @makeDerivationBuilder@ in unix-derivation-builder.cc at 2.36.0), for+-- the derivation at a @.drv@ path, built where the given backend makes+-- the sandbox.  Under @sandbox = true@ every build is sandboxed, a+-- derivation setting @__noChroot@ is refused, and on macOS so is one+-- setting @__sandboxProfile@; under @relaxed@ one that is fixed-output or+-- sets @__noChroot@ is not sandboxed.+sandboxUse :: Maybe SandboxBackend -> SandboxMode -> StorePath -> Derivation -> Either Text SandboxUse+sandboxUse backend mode drvPath drv = case mode of+  SandboxDisabled -> Right Unsandboxed+  SandboxEnabled -> do+    attrs <- derivationAttrs drvPath drv+    noChroot <- derivationBoolAttr drvPath noChrootAttr False attrs+    profile <- case backend of+      Just DarwinBackend -> derivationStringAttr drvPath sandboxProfileAttr attrs+      _ -> Right Nothing+    case (noChroot, profile) of+      (True, _) -> Left ("derivation '" <> shownDrvPath <> "' has '" <> noChrootAttr <> "' set, but that's not allowed when 'sandbox' is 'true'")+      (False, Just text)+        | not (BS.null text) -> Left ("derivation '" <> shownDrvPath <> "' specifies a sandbox profile, but this is only allowed when 'sandbox' is 'relaxed'")+      _ -> Right (Sandboxed (buildNetwork drv))+  SandboxRelaxed -> do+    noChroot <- noChrootSet+    pure $ case (fixedOutput drv, noChroot) of+      (Nothing, False) -> Sandboxed PrivateNetwork+      _ -> Unsandboxed+  where+    noChrootSet = derivationAttrs drvPath drv >>= derivationBoolAttr drvPath noChrootAttr False+    shownDrvPath = storePathToText defaultStoreDir drvPath++-- | The attribute a derivation asks to build outside the sandbox with.+noChrootAttr :: Text+noChrootAttr = "__noChroot"++-- | The attributes a derivation asks the macOS sandbox for things with+-- (@derivationOptionsFromStructuredAttrs@ in derivation-options.cc at+-- 2.36.0).+sandboxProfileAttr, impureHostDepsAttr, localNetworkingAttr :: Text+sandboxProfileAttr = "__sandboxProfile"+impureHostDepsAttr = "__impureHostDeps"+localNetworkingAttr = "__darwinAllowLocalNetworking"++-- | Whether a macOS build may use the loopback network, which its+-- profile otherwise refuses a build that is not fixed-output.+data LocalNetworking = LocalNetworkingDenied | LocalNetworkingAllowed+  deriving (Eq, Show)++-- | What a derivation asks of the macOS sandbox: upstream's+-- @additionalSandboxProfile@, @impureHostDeps@ and @allowLocalNetworking@+-- (@derivationOptionsFromStructuredAttrs@ in derivation-options.cc at+-- 2.36.0).+data DarwinOptions = DarwinOptions+  { -- | @__sandboxProfile@: profile text the build's profile holds after+    -- its own rules, with only the build's mark after it.+    doExtraProfile :: !ByteString,+    -- | @__impureHostDeps@: host paths the build may read, each beneath+    -- an @allowed-impure-host-deps@ entry.+    doImpureHostDeps :: !(Set ByteString),+    -- | @__darwinAllowLocalNetworking@.+    doLocalNetworking :: !LocalNetworking+  }+  deriving (Eq, Show)++-- | A derivation's t'DarwinOptions', for the derivation at a @.drv@ path:+-- none of them when it sets none.+darwinOptions :: StorePath -> Derivation -> Either Text DarwinOptions+darwinOptions drvPath drv = do+  attrs <- derivationAttrs drvPath drv+  profile <- derivationStringAttr drvPath sandboxProfileAttr attrs+  deps <- derivationStringsAttr drvPath impureHostDepsAttr attrs+  local <- derivationBoolAttr drvPath localNetworkingAttr False attrs+  pure+    DarwinOptions+      { doExtraProfile = fromMaybe "" profile,+        doImpureHostDeps = maybe Set.empty Set.fromList deps,+        doLocalNetworking = bool LocalNetworkingDenied LocalNetworkingAllowed local+      }++-- ---------------------------------------------------------------------------+-- The plan+-- ---------------------------------------------------------------------------++-- | The ids a build runs as in its user namespace, which upstream uses+-- when it has no build users (@sandboxUid@ and @sandboxGid@ in+-- local-derivation-goal.hh at 2.24.9, linux-derivation-builder.cc at+-- 2.36.0).+sandboxUid, sandboxGid :: Word32+sandboxUid = 1000+sandboxGid = 100++-- | The @HOME@ a sandboxed build is told of, upstream's, which does not+-- exist, so a program looking for its settings there finds none+-- (@homeDir@ and @initEnv@ in LDG).+sandboxHome :: FilePath+sandboxHome = "/homeless-shelter"++-- | Why a sandboxed build is refused when nova-nix runs as root with no+-- build users ("Nix.Builder.BuildUser"): its builder would map to root on+-- the host and own every file root owns there.  Upstream builds so; nova-nix+-- refuses, and a fallback to an unsandboxed build would be no answer to+-- that, so this refusal stands whatever @sandbox-fallback@ says.+rootRefusal :: Text+rootRefusal = "a sandboxed build as root needs build users: set 'build-users-group' to a group of build users, run nova-nix as a user other than root, or pass '--no-sandbox' to build without the sandbox"++-- | The ids a builder runs as outside its sandbox: a build user's, or the+-- invoking user's.  On Linux the sandbox's own ('sandboxUid',+-- 'sandboxGid') map to them, as upstream maps them.+data BuilderIds = BuilderIds+  { builderUid :: !Word32,+    builderGid :: !Word32+  }+  deriving (Eq, Show)++-- | What a sandboxed build's plan is made from.  Paths are bytes; each+-- input path is where the builder sees it, which is where it is on disk.+data PlanInputs = PlanInputs+  { -- | The chroot's root on disk.+    piRoot :: !ByteString,+    -- | The store directory.+    piStoreDir :: !ByteString,+    -- | The build directory as the builder sees it ('scBuildDir').+    piBuildDirSeen :: !ByteString,+    -- | The build directory on disk.+    piBuildDirOnDisk :: !ByteString,+    -- | The closure of the build's inputs, upstream's @inputPaths@.+    piInputs :: ![ByteString],+    -- | The @sandbox-paths@ entries.+    piSandboxPaths :: ![SandboxPath],+    -- | The closure of the entries whose source is in the store.+    piSandboxClosure :: ![ByteString],+    -- | Each output as the builder sees it.+    piOutputs :: ![ByteString],+    -- | The builder's environment, as @NAME=VALUE@ entries.+    piEnvironment :: ![ByteString],+    piNetwork :: !Network,+    piCaFile :: !(Maybe ByteString),+    piDevShmSize :: !ByteString,+    piDropGroups :: !DropGroups,+    -- | Whom the builder runs as outside the sandbox.+    piBuilderIds :: !BuilderIds+  }+  deriving (Eq, Show)++-- | Whether the builder may write through a bind.+data BindAccess = ReadOnlyBind | ReadWriteBind+  deriving (Eq, Show)++-- | Whether the helper resolves a source's symlinks before it binds it, as+-- upstream's @canonPath(path, true)@ does for the device nodes and host+-- files it adds (@runChild@ in LDG).+data SourceResolution = SourceAsGiven | SourceResolved+  deriving (Eq, Show)++-- | A host path bound into the chroot.+data Bind = Bind+  { bindTarget :: !ByteString,+    bindSource :: !ByteString,+    bindAccess :: !BindAccess,+    bindPresence :: !PathPresence,+    bindResolution :: !SourceResolution+  }+  deriving (Eq, Show)++-- | What the helper does for one build on Linux.+data SandboxPlan = SandboxPlan+  { planRoot :: !ByteString,+    planBuildDir :: !ByteString,+    planDevShmSize :: !ByteString,+    planNetwork :: !Network,+    planDropGroups :: !DropGroups,+    planBuilderIds :: !BuilderIds,+    -- | In the order they are made, which is the targets' sorted order,+    -- as upstream walks its @pathsInChroot@ map, so a directory is bound+    -- before anything bound beneath it.+    planBinds :: ![Bind],+    -- | The builder's environment, as @NAME=VALUE@ entries, which the+    -- helper passes to the builder's @execve@ and never takes as its own.+    planEnvironment :: ![ByteString]+  }+  deriving (Eq, Show)++-- | The device nodes a build sees when nothing binds @\/dev@ whole+-- (@runChild@ in LDG).  @\/dev\/kvm@ joins them upstream only for a store+-- with the @kvm@ system feature, which nova-nix has no setting for.+deviceNodes :: [ByteString]+deviceNodes = ["/dev/full", "/dev/null", "/dev/random", "/dev/tty", "/dev/urandom", "/dev/zero"]++-- | The host files a fixed-output build sees, where they exist+-- (@runChild@ in LDG).+hostNetworkFiles :: [ByteString]+hostNetworkFiles = ["/etc/resolv.conf", "/etc/services", "/etc/hosts"]++-- | Where a fixed-output build sees the CA bundle (@runChild@ in LDG).+caBundleTarget :: ByteString+caBundleTarget = "/etc/ssl/certs/ca-certificates.crt"++-- | The path a build sees its whole @\/dev@ at when an entry binds it.+devDir :: ByteString+devDir = "/dev"++-- | The binds of a sandboxed build, built up as upstream builds+-- @pathsInChroot@ (@startBuilder@ and @runChild@ in LDG): the @sandbox-paths@+-- entries, a later one for a target replacing an earlier; the build+-- directory; the closure of the entries in the store; the input closure;+-- then no output.  Then, without replacing an entry already there, the+-- device nodes unless @\/dev@ is bound whole, and for a fixed-output+-- build the host's network files and the CA bundle, each optional.+--+-- Every host path is bound read-only, the build directory alone writable,+-- where upstream binds them plainly: the builder runs as the+-- invoking user, so a writable bind would let a build change a valid store+-- path, the bundled shell later builds run, an @--exec-wrapper@ launcher,+-- or any file of the user's a @sandbox-paths@ entry names.  A bind is+-- read-only through every mount beneath its source, which a recursive bind+-- brings along.  A device node stays usable on a read-only mount.  Outside+-- the plan the helper binds two host paths writable: where the kernel will+-- not mount a devpts of the sandbox's own, it binds the host's+-- @\/dev\/pts@ and @\/dev\/ptmx@ instead, as upstream does.+--+-- A build directory that holds the store directory is upstream's error+-- (@startBuilder@ in LDG).  A target that is not absolute, or has a @..@+-- component, is refused, since joined to the chroot's root it names a path+-- outside it; upstream joins its targets as they are (@runChild@ in LDG).+sandboxPlan :: PlanInputs -> Either Text SandboxPlan+sandboxPlan inputs+  | piBuildDirSeen inputs `BS.isPrefixOf` piStoreDir inputs = Left "`sandbox-build-dir` must not contain the storeDir"+  | Just target <- find leavesRoot (piBuildDirSeen inputs : map spTarget (piSandboxPaths inputs)) = Left (outsideSandboxMessage target)+  | otherwise =+      Right+        SandboxPlan+          { planRoot = piRoot inputs,+            planBuildDir = piBuildDirSeen inputs,+            planDevShmSize = piDevShmSize inputs,+            planNetwork = piNetwork inputs,+            planDropGroups = piDropGroups inputs,+            planBuilderIds = piBuilderIds inputs,+            planBinds = [Bind target source access presence resolution | (target, Entry source access presence resolution) <- Map.toAscList withHostPaths],+            planEnvironment = piEnvironment inputs+          }+  where+    configured = foldl' (\m sp -> Map.insert (spTarget sp) (Entry (spSource sp) ReadOnlyBind (spPresence sp) SourceAsGiven) m) Map.empty (piSandboxPaths inputs)+    withBuildDir = Map.insert (piBuildDirSeen inputs) (Entry (piBuildDirOnDisk inputs) ReadWriteBind RequiredPath SourceAsGiven) configured+    withStore = foldl' (\m p -> Map.insert p (Entry p ReadOnlyBind RequiredPath SourceAsGiven) m) withBuildDir (piSandboxClosure inputs ++ piInputs inputs)+    withoutOutputs = foldl' (flip Map.delete) withStore (piOutputs inputs)+    devices+      | Map.member devDir withoutOutputs = []+      | otherwise = [(node, Entry node ReadOnlyBind RequiredPath SourceResolved) | node <- deviceNodes]+    networkFiles = case piNetwork inputs of+      PrivateNetwork -> []+      HostNetwork ->+        [(file, Entry file ReadOnlyBind OptionalPath SourceResolved) | file <- hostNetworkFiles]+          ++ [(caBundleTarget, Entry caFile ReadOnlyBind OptionalPath SourceResolved) | Just caFile <- [piCaFile inputs], not (BS.null caFile)]+    withHostPaths = foldl' (\m (target, entry) -> Map.insertWith keepExisting target entry m) withoutOutputs (devices ++ networkFiles)+    keepExisting _ existing = existing++-- | A bind before it has a target, as the map holds it.+data Entry = Entry !ByteString !BindAccess !PathPresence !SourceResolution++-- | Whether a target names no path in the sandbox: it is not absolute, or+-- has a @..@ component.+leavesRoot :: ByteString -> Bool+leavesRoot target = not ("/" `BS.isPrefixOf` target) || ".." `elem` BS8.split '/' target++-- | The refusal of a sandbox target that names no path in the sandbox:+-- one 'leavesRoot' finds on Linux, or a relative one on macOS.+outsideSandboxMessage :: ByteString -> Text+outsideSandboxMessage target = "the sandbox path '" <> TE.decodeUtf8Lenient target <> "' is not an absolute path without a '..' component, so it names no path in the sandbox"++-- | The first line of a plan, which names the format's version.  The+-- helper refuses any other.+planVersionLine :: ByteString+planVersionLine = "nova-nix-sandbox-plan 5\n"++-- | A plan as the helper reads it, given its tokens: the version line, a+-- line holding the length in bytes of the rest, then each token, its+-- length in decimal, a colon, its bytes and a NUL.  A token's length says+-- where it ends, so no bytes in a field, a NUL among them, can end it+-- early or start another; the helper, which uses each token as a C+-- string, refuses one that holds a NUL.  The plan's length lets the+-- helper read it and leave the pipe open behind it.+framePlan :: [ByteString] -> ByteString+framePlan tokens = planVersionLine <> BS8.pack (show (BS.length body)) <> "\n" <> body+  where+    body = foldMap token tokens+    token bytes = BS8.pack (show (BS.length bytes)) <> ":" <> bytes <> "\0"++-- | A Linux plan as the helper reads it ('framePlan'): the backend, then+-- each key and its values in one fixed order.  A bind is its target, its+-- source and its flags: @-@ for none, else @r@ (read-only), @o@+-- (optional) and @c@ (resolve the source's symlinks).  An @env@ token is+-- one entry of the builder's environment.+renderPlan :: SandboxPlan -> ByteString+renderPlan plan =+  framePlan+    ( concat+        [ ["backend", "linux"],+          ["root", planRoot plan],+          ["build-dir", planBuildDir plan],+          ["dev-shm-size", planDevShmSize plan],+          ["sandbox-uid", BS8.pack (show sandboxUid)],+          ["sandbox-gid", BS8.pack (show sandboxGid)],+          ["host-uid", BS8.pack (show (builderUid (planBuilderIds plan)))],+          ["host-gid", BS8.pack (show (builderGid (planBuilderIds plan)))],+          ["network", networkToken (planNetwork plan)],+          ["drop-groups", dropGroupsToken (planDropGroups plan)]+        ]+        ++ concatMap bindTokens (planBinds plan)+        ++ concatMap (\entry -> ["env", entry]) (planEnvironment plan)+    )+  where+    networkToken network = case network of+      PrivateNetwork -> "private"+      HostNetwork -> "host"+    dropGroupsToken groups = case groups of+      RequireDropGroups -> "require"+      TolerateKeptGroups -> "tolerate"+    bindTokens bind = ["bind", bindTarget bind, bindSource bind, bindFlags bind]+    bindFlags bind = case flagLetters bind of+      "" -> "-"+      letters -> letters+    flagLetters bind =+      BS8.pack+        ( ['r' | bindAccess bind == ReadOnlyBind]+            ++ ['o' | bindPresence bind == OptionalPath]+            ++ ['c' | bindResolution bind == SourceResolved]+        )++-- ---------------------------------------------------------------------------+-- The chroot+-- ---------------------------------------------------------------------------++-- | What the chroot holds before the helper binds anything into it, each+-- path as the builder sees it.+data SkeletonEntry+  = -- | A directory, and its mode.+    SkeletonDir !ByteString !Word32+  | -- | The store directory, writable by its owner and its group and+    -- sticky, whose group is the build users' when the build runs as one,+    -- as upstream's is, so the builder can write its outputs there.+    SkeletonStoreDir !ByteString+  | -- | A file, and its contents.+    SkeletonFile !ByteString !ByteString+  | -- | A symlink, and its target.+    SkeletonLink !ByteString !ByteString+  deriving (Eq, Show)++-- | Upstream's chroot before the binds (@startBuilder@ in LDG): a+-- writable @\/tmp@, @\/etc@ with the build user's @passwd@ and @group@ and,+-- for a build with a network of its own, @hosts@, or for a fixed-output+-- one @nsswitch.conf@; the store directory ('SkeletonStoreDir');+-- @\/proc@; and unless @\/dev@ is bound whole, @\/dev\/shm@, @\/dev\/pts@+-- and the links into @\/proc\/self\/fd@ (@runChild@ in LDG).  A+-- directory above the store directory is created with the default mode.+-- The helper gives @\/etc@ upstream's mode, 0555, once its binds are in+-- place.+chrootSkeleton :: ByteString -> ByteString -> Network -> [SandboxPath] -> [SkeletonEntry]+chrootSkeleton storeDir buildDirSeen network paths =+  [SkeletonDir "/tmp" stickyWritable, SkeletonDir "/etc" plainDir, SkeletonFile "/etc/passwd" (passwdFile buildDirSeen), SkeletonFile "/etc/group" groupFile]+    ++ networkFile+    ++ [SkeletonStoreDir storeDir, SkeletonDir "/proc" plainDir]+    ++ devEntries+  where+    networkFile = case network of+      PrivateNetwork -> [SkeletonFile "/etc/hosts" "127.0.0.1 localhost\n::1 localhost\n"]+      HostNetwork -> [SkeletonFile "/etc/nsswitch.conf" "hosts: files dns\nservices: files\n"]+    devEntries+      | any ((== devDir) . spTarget) paths = []+      | otherwise =+          [ SkeletonDir devDir plainDir,+            SkeletonDir "/dev/shm" plainDir,+            SkeletonDir "/dev/pts" plainDir,+            SkeletonLink "/dev/fd" "/proc/self/fd",+            SkeletonLink "/dev/stdin" "/proc/self/fd/0",+            SkeletonLink "/dev/stdout" "/proc/self/fd/1",+            SkeletonLink "/dev/stderr" "/proc/self/fd/2"+          ]+    stickyWritable = 0o1777+    plainDir = 0o755++-- | Upstream's @\/etc\/passwd@ for a build (@startBuilder@ in LDG), whose+-- home is the build directory as the builder sees it.+passwdFile :: ByteString -> ByteString+passwdFile home =+  BS.concat+    [ "root:x:0:0:Nix build user:",+      home,+      ":/noshell\n",+      "nixbld:x:",+      BS8.pack (show sandboxUid),+      ":",+      BS8.pack (show sandboxGid),+      ":Nix build user:",+      home,+      ":/noshell\n",+      "nobody:x:65534:65534:Nobody:/:/noshell\n"+    ]++-- | Upstream's @\/etc\/group@ for a build (@startBuilder@ in LDG).+groupFile :: ByteString+groupFile = BS.concat ["root:x:0:\n", "nixbld:!:", BS8.pack (show sandboxGid), ":\n", "nogroup:x:65534:\n"]++-- ---------------------------------------------------------------------------+-- The macOS profile+-- ---------------------------------------------------------------------------++-- | A host path a macOS build may read and run, as upstream's+-- @pathsInChroot@ holds one (@DarwinDerivationBuilder::setUser@): where+-- the build sees it, where+-- it is on the host, and whether it may be missing.  The profile names+-- the path the build sees, which must be where it is.+data DarwinPath = DarwinPath+  { darwinTarget :: !ByteString,+    darwinSource :: !ByteString,+    darwinPresence :: !PathPresence+  }+  deriving (Eq, Show)++-- | What a macOS build's paths are made from, each as bytes.  A profile+-- matches a path as the kernel resolves it, so the store directory and+-- the build directory are given resolved as well as as the builder sees+-- them, and the inputs and the closure are given beneath the resolved+-- store directory.+data DarwinPathInputs = DarwinPathInputs+  { -- | The @.drv@ path, which a refused impure path names.+    dpiDrvPath :: !StorePath,+    dpiStoreDir :: !ByteString,+    dpiRealStoreDir :: !ByteString,+    dpiBuildDir :: !ByteString,+    dpiRealBuildDir :: !ByteString,+    -- | The @sandbox-paths@ entries.+    dpiSandboxPaths :: ![SandboxPath],+    -- | The closure of the entries whose source is in the store.+    dpiSandboxClosure :: ![ByteString],+    -- | The derivation's @__impureHostDeps@.+    dpiImpureHostDeps :: !(Set ByteString),+    -- | @allowed-impure-host-deps@.+    dpiAllowedImpureHostDeps :: !(Set ByteString),+    -- | The closure of the build's inputs, upstream's @inputPaths@.+    dpiInputs :: ![ByteString]+  }+  deriving (Eq, Show)++-- | A macOS build's paths: each it may read and run, in the targets'+-- sorted order, and the directories above them it may read.+data DarwinPaths = DarwinPaths+  { dpPaths :: ![DarwinPath],+    dpAncestry :: ![ByteString]+  }+  deriving (Eq, Show)++-- | The paths of a macOS build, built up as upstream builds them+-- (@DerivationBuildingGoal::buildLocally@,+-- @UnixDerivationBuilderImpl::getPathsInSandbox@ and+-- @DarwinDerivationBuilder::setUser@ at 2.36.0): the @sandbox-paths@+-- entries, a later one for a target+-- replacing an earlier; the closure of the entries in the store; the+-- build directory; each @__impureHostDeps@ path, which may be missing;+-- then the input closure.+--+-- The ancestry is every directory above a path but an input, and the+-- store directory with every directory above it but the root, read+-- before the inputs join, which share it.  The store directory and the+-- build directory count both as the builder sees them and as they+-- resolve, so a build can follow a link on its way to either.+--+-- An impure path is refused, in upstream's words, unless it is an entry+-- of @allowed-impure-host-deps@ or beneath one, each compared once its+-- @.@ and @..@ components are resolved.  A @sandbox-paths@ target that is+-- not absolute is refused, in the words the Linux sandbox refuses it+-- with, where upstream loops forever looking for the root above it.+darwinPathsInSandbox :: DarwinPathInputs -> Either Text DarwinPaths+darwinPathsInSandbox inputs+  | Just target <- find (not . ("/" `BS.isPrefixOf`)) (map spTarget (dpiSandboxPaths inputs)) = Left (outsideSandboxMessage target)+  | otherwise = do+      impure <- traverse allowedImpure (Set.toAscList (dpiImpureHostDeps inputs))+      let configured = foldl' (\m sp -> Map.insert (spTarget sp) (DarwinPath (spTarget sp) (spSource sp) (spPresence sp)) m) Map.empty (dpiSandboxPaths inputs)+          withClosure = foldl' (\m p -> Map.insert p (itself RequiredPath p) m) configured (dpiSandboxClosure inputs)+          withBuildDir = Map.insert (dpiRealBuildDir inputs) (itself RequiredPath (dpiRealBuildDir inputs)) withClosure+          withImpure = foldl' (\m p -> Map.insert p (itself OptionalPath p) m) withBuildDir impure+          withInputs = foldl' (\m p -> Map.insert p (itself RequiredPath p) m) withImpure (dpiInputs inputs)+          ancestry =+            Set.fromList (concatMap pathParents (dpiBuildDir inputs : Map.keys withImpure))+              <> Set.fromList (concatMap selfAndParents [dpiStoreDir inputs, dpiRealStoreDir inputs])+      Right (DarwinPaths (Map.elems withInputs) (Set.toAscList ancestry))+  where+    itself presence path = DarwinPath path path presence+    allowedImpure dep = do+      canonical <- canonicalPath dep+      let search [] = Left ("derivation '" <> storePathToText defaultStoreDir (dpiDrvPath inputs) <> "' requested impure path '" <> TE.decodeUtf8Lenient dep <> "', but it was not in allowed-impure-host-deps")+          search (prefix : rest) = do+            allowed <- canonicalPath prefix+            case dirOrInDir canonical allowed of+              True -> Right dep+              False -> search rest+      search (Set.toAscList (dpiAllowedImpureHostDeps inputs))+    selfAndParents path+      | path == "/" = []+      | otherwise = path : selfAndParents (parentDir path)++-- | Every directory above an absolute path, the root included, as+-- upstream walks @parent_path@ up to it (@DarwinDerivationBuilder::setUser@).+pathParents :: ByteString -> [ByteString]+pathParents path+  | path == "/" = []+  | otherwise = let up = parentDir path in up : pathParents up++-- | @std::filesystem::path::parent_path@ of an absolute path: the path+-- without its last component, or the root above a top-level one.  A path+-- with a trailing slash has an empty last component, so its parent is+-- the path without the slash.+parentDir :: ByteString -> ByteString+parentDir path = case BS8.dropWhileEnd (== '/') (fst (BS8.breakEnd (== '/') path)) of+  "" -> "/"+  dir -> dir++-- | Upstream's @canonPath@ without resolving links+-- (file-system.cc and file-path-impl.hh at 2.36.0): an absolute+-- path with its empty and @.@ components dropped and each @..@ taking+-- the component before it away, the root's staying.+canonicalPath :: ByteString -> Either Text ByteString+canonicalPath path+  | BS.null path = Left "cannot canonicalise an empty path"+  | not ("/" `BS.isPrefixOf` path) = Left ("not an absolute path: \"" <> TE.decodeUtf8Lenient path <> "\"")+  | otherwise = Right ("/" <> BS.intercalate "/" (reverse (foldl' step [] (BS8.split '/' path))))+  where+    step kept component = case component of+      "" -> kept+      "." -> kept+      ".." -> drop 1 kept+      _ -> component : kept++-- | Upstream's @isDirOrInDir@ (file-system.cc at 2.36.0) for two+-- canonical paths: the same path, or one whose components start with all+-- of the other's.+dirOrInDir :: ByteString -> ByteString -> Bool+dirOrInDir path dir = path == dir || (length dirParts < length pathParts && dirParts `isPrefixOf` pathParts)+  where+    pathParts = components path+    dirParts = components dir+    components = filter (not . BS.null) . BS8.split '/'++-- | The one path the profile can name for an entry, its target, which+-- upstream's refuses unless the entry's source is the same path+-- (@DarwinDerivationBuilder::setUser@).+darwinPathTarget :: DarwinPath -> Either Text ByteString+darwinPathTarget path+  | darwinTarget path == darwinSource path = Right (darwinTarget path)+  | otherwise = Left (setupContext <> "can't map " <> quoted (darwinTarget path) <> " to " <> quoted (darwinSource path) <> ": mismatched impure paths not supported on Darwin")+  where+    quoted bytes = "\"" <> TE.decodeUtf8Lenient bytes <> "\""++-- | What @lstat@ found at a path.+data PathFound+  = FoundDirectory+  | -- | A file, a link or anything else that is not a directory.+    FoundOther+  | -- | Nothing could be found, with the @errno@ that said why.+    LstatFailed !Int+  deriving (Eq, Show)++-- | How the profile names a host path: a directory with everything+-- beneath it, or the one node at the path (@DarwinDerivationBuilder::setUser@).+data ProfileFilter = Subpath !ByteString | Literal !ByteString+  deriving (Eq, Show)++-- | What an entry adds to the profile, given what @lstat@ found at its+-- target, as upstream decides it (@DarwinDerivationBuilder::setUser@,+-- with @maybeLstat@ in unix/file-system.cc at 2.36.0): nothing for a+-- missing entry that+-- may be missing; for a missing one that may not, upstream's error, whose+-- quote is never closed as upstream's format leaves it; and for any other+-- failure, @maybeLstat@'s.  A path is missing when @lstat@ says @ENOENT@+-- or @ENOTDIR@.+profileFilter :: DarwinPath -> PathFound -> Either Text (Maybe ProfileFilter)+profileFilter path found = case found of+  FoundDirectory -> Right (Just (Subpath target))+  FoundOther -> Right (Just (Literal target))+  LstatFailed number+    | Errno (fromIntegral number) `notElem` [eNOENT, eNOTDIR] -> Left (setupContext <> "getting status of \"" <> shown <> "\"" <> errnoSuffix number)+    | darwinPresence path == OptionalPath -> Right Nothing+    | otherwise -> Left (setupContext <> "getting attributes of required path '" <> shown <> errnoSuffix number)+  where+    target = darwinTarget path+    shown = TE.decodeUtf8Lenient target++-- | What a macOS build's profile is made from.+data DarwinProfile = DarwinProfile+  { dprViolationLog :: !ViolationLog,+    dprNetwork :: !Network,+    -- | The store directory, resolved.+    dprStoreDir :: !ByteString,+    -- | The paths the outputs are written to, resolved.+    dprOutputs :: ![ByteString],+    -- | The paths the build reads and runs ('darwinPathsInSandbox'), each+    -- as 'profileFilter' names it.+    dprPaths :: ![ProfileFilter],+    dprAncestry :: ![ByteString],+    -- | The derivation's @__sandboxProfile@.+    dprExtra :: !ByteString+  }+  deriving (Eq, Show)++-- | A macOS build's profile, nova-nix's own text written to upstream+-- Nix's rules: everything is denied unless an allow form here allows it,+-- and what is refused is logged only under 'ViolationsLogged'.  The build+-- may write its outputs and its build directory ('profileBase'); a+-- fixed-output build reaches the network ('profileNetwork'); the inputs+-- and every other path ('darwinPathsInSandbox') may be read and run; and+-- each directory of the ancestry may be read, so a path to them resolves.+-- The terminals are refused after every rule that could allow one+-- ('profileTerminals'), the derivation's own text follows, and the build's+-- mark ('profileMark') comes last.+--+-- macOS compiles the path filters of one operation into one table of at+-- most 64 KiB, however many forms hold them, so the paths in the store+-- are grouped by the first byte of their name, their hash's, each group+-- behind a prefix filter of its own, which gets a table of its own, as+-- upstream groups them; the prefix holds every path of its group, so it+-- allows nothing more.  Every other path is in one form of its own.+--+-- A later rule for an operation overrides an earlier one for it, so+-- writes beneath the store directory are denied after the scratch rule,+-- and the build directory, which nova-nix keeps in the store, and the+-- outputs are allowed again after the denial.  The allowing rule names+-- @file-write*@, since one for the wider @file*@ does not override a+-- denial of @file-write*@.+--+-- Upstream allows writes to the inputs and paths too, under build users+-- who own none of them.  nova-nix's builder runs as the invoking user,+-- who owns the store and the files a @sandbox-paths@ entry may name, so+-- this profile lets the build read and run them alone, as the Linux+-- sandbox binds every host path read-only.  A path is written in a+-- string escaped for the profile's reader ('profileString'), as upstream+-- escapes it.  An allow form of paths is never written with no path,+-- which would allow its operations everywhere.+darwinProfile :: DarwinProfile -> ByteString+darwinProfile profile =+  BS.concat+    [ "(version 1)\n",+      denyDefault,+      profileBase,+      networkRules,+      storeRules,+      section "The outputs the build writes." "file-read* file-write* process-exec" (map Subpath (dprOutputs profile)),+      section "The host paths the build reads and runs." readAndRun otherPaths,+      bucketForms,+      section "The directories above them, so a path to them resolves." "file-read*" (map Literal (dprAncestry profile)),+      profileTerminals,+      endLine (dprExtra profile),+      profileMark+    ]+  where+    denyDefault = case dprViolationLog profile of+      ViolationsUnlogged -> "(deny default (with no-log))\n"+      ViolationsLogged -> "(deny default)\n"+    networkRules = case dprNetwork profile of+      PrivateNetwork -> ""+      HostNetwork -> profileNetwork+    readAndRun = "file-read* process-exec"+    storePrefix = dprStoreDir profile <> "/"+    -- A store path's bucket is the first byte of its name, its hash's.+    bucketOf pathFilter = BS.uncons =<< BS.stripPrefix storePrefix (filterPath pathFilter)+    (storePaths, otherPaths) = partitionEithers [maybe (Right pathFilter) (\(byte, _) -> Left (byte, pathFilter)) (bucketOf pathFilter) | pathFilter <- dprPaths profile]+    buckets = Map.toAscList (Map.fromListWith (flip (++)) [(byte, [pathFilter]) | (byte, pathFilter) <- storePaths])+    bucketForms = case buckets of+      [] -> ""+      _ -> "; The store paths the build reads and runs, a form for each first\n; character of their hash.\n" <> foldMap bucketForm buckets+    bucketForm (byte, filters) =+      BS.concat+        [ "(allow " <> readAndRun <> "\n",+          "\t(require-all\n",+          "\t\t(prefix " <> profileString (BS.snoc storePrefix byte) <> ")\n",+          "\t\t(require-any\n",+          foldMap (\pathFilter -> "\t\t" <> filterLine pathFilter) filters,+          "\t\t)))\n"+        ]+    storeRules =+      BS8.unlines+        [ "; The store, which no rule above opens to writes, and the build",+          "; directory within it, opened again.",+          "(deny file-write* (subpath " <> profileString (dprStoreDir profile) <> "))",+          "(allow file-read* file-write* process-exec network-outbound network-inbound (subpath (param \"_NIX_BUILD_TOP\")))"+        ]++-- | A comment, then an allow form of the operations over the filters, one+-- to a line, or nothing for no filter.+section :: ByteString -> ByteString -> [ProfileFilter] -> ByteString+section _ _ [] = ""+section text operations filters = "; " <> text <> "\n(allow " <> operations <> "\n" <> foldMap filterLine filters <> ")\n"++-- | The path a filter names.+filterPath :: ProfileFilter -> ByteString+filterPath pathFilter = case pathFilter of+  Subpath path -> path+  Literal path -> path++-- | A filter's line in an allow form.+filterLine :: ProfileFilter -> ByteString+filterLine profileFilterValue = case profileFilterValue of+  Subpath path -> "\t(subpath " <> profileString path <> ")\n"+  Literal path -> "\t(literal " <> profileString path <> ")\n"++-- | A string of the profile's language holding these bytes: a backslash+-- and a double quote are escaped with a backslash, as its reader takes+-- them.+profileString :: ByteString -> ByteString+profileString bytes = "\"" <> BS.concatMap escape bytes <> "\""+  where+    escape byte+      | byte == backslash || byte == doubleQuote = BS.pack [backslash, byte]+      | otherwise = BS.singleton byte+    backslash = 0x5c+    doubleQuote = 0x22++-- | The rules every macOS build's profile holds, after its default+-- refusal (the rules of upstream's @sandbox-defaults.sb@ at 2.36.0).  The+-- parameters are the helper's ('darwinParameters').  @TMPDIR@ is defined+-- as upstream's profile defines it, for a derivation's own text to use.+--+-- Three of upstream's rules are left out, since each reaches the+-- invoking user's own resources, which upstream's build user cannot:+-- writes, programs and Unix sockets in the temporary directory nova-nix+-- runs with, where the user's live sockets and files are+-- ('darwinParameters'); pseudo-terminals, through which a build would+-- read and write the user's terminals ('profileTerminals'); and POSIX+-- shared memory and System V's shared memory and semaphores, through+-- which it would attach the user's own, named or keyed as they are (a+-- PostgreSQL server's System V segment, for one).  POSIX semaphores,+-- which Python's multiprocessing takes, are kept, though a build can open+-- one of the user's by name too.  Undo each when builds run as build+-- users of their own, under a daemon, whose resources are theirs alone.+--+-- Two exposures no rule closes while the builder runs as the invoking+-- user, which build users would: a build may still create System V+-- segments and semaphores, which no rule refuses, though it can neither+-- attach, use nor remove one, so each it creates outlives the build,+-- counts against the system's limit of them (@kern.sysv.shmmni@+-- segments), and may hold a key one of the user's programs wants; and a+-- build may read the command lines of the user's other processes+-- (@KERN_PROCARGS2@), which neither @sysctl-read@ nor+-- @process-info*@ rules reach, where the kernel refuses a build user+-- another user's.+profileBase :: ByteString+profileBase =+  BS8.unlines+    [ "; Scratch space: /tmp itself and the build's own directory, where the",+      "; build may also use Unix sockets.",+      "(define TMPDIR (param \"_GLOBAL_TMP_DIR\"))",+      "(allow file* process-exec network-outbound network-inbound",+      "\t(literal \"/tmp\")",+      "\t(subpath (param \"_NIX_BUILD_TOP\")))",+      "; Processes: the build may start them and signal its own, and may",+      "; make no file setuid or setgid.",+      "(allow process-fork)",+      "(allow signal (target same-sandbox))",+      "(deny file-write-setugid)",+      "; System information, POSIX semaphores, sockets, and user and group",+      "; lookups.",+      "(allow sysctl-read)",+      "(allow ipc-posix-sem)",+      "(allow system-socket)",+      "(allow mach-lookup (global-name \"com.apple.system.opendirectoryd.libinfo\"))",+      "; Devices: the standard ones and DTrace's helper.",+      "(allow file*",+      "\t(literal \"/dev/null\")",+      "\t(literal \"/dev/zero\")",+      "\t(literal \"/dev/random\")",+      "\t(literal \"/dev/urandom\")",+      "\t(literal \"/dev/tty\")",+      "\t(literal \"/dev/stdin\")",+      "\t(literal \"/dev/stdout\")",+      "\t(literal \"/dev/stderr\")",+      "\t(subpath \"/dev/fd\")",+      "\t(literal \"/dev/dtracehelper\"))",+      "; The shell /bin/sh selects.",+      "(allow file* (literal \"/private/var/select/sh\"))",+      "; System files programs read: the system's version, time zones,",+      "; locales, and Rosetta, which runs a program built for the other",+      "; architecture.",+      "(allow file-read*",+      "\t(literal \"/System/Library/CoreServices/SystemVersion.plist\")",+      "\t(literal \"/System/Library/CoreServices/SystemVersionCompat.plist\")",+      "\t(subpath \"/usr/share/zoneinfo\")",+      "\t(subpath \"/usr/share/locale\")",+      "\t(subpath \"/Library/Apple/usr/libexec/oah\")",+      "\t(subpath \"/System/Library/Apple/usr/libexec/oah\")",+      "\t(subpath \"/System/Library/LaunchDaemons/com.apple.oahd.plist\")",+      "\t(subpath \"/Library/Apple/System/Library/LaunchDaemons/com.apple.oahd.plist\"))",+      "; The attributes of /dev, and of /etc and /var, links a path through",+      "; them follows.",+      "(allow file-read-metadata",+      "\t(literal \"/dev\")",+      "\t(literal \"/etc\")",+      "\t(literal \"/var\")",+      "\t(literal \"/private/var/tmp\"))",+      "; Loopback networking, with the name lookups it takes, for a build",+      "; that asks for it.",+      "(if (param \"_ALLOW_LOCAL_NETWORKING\")",+      "    (begin",+      "      (allow network* (remote ip \"localhost:*\"))",+      "      (allow network-inbound (local ip \"*:*\"))",+      "      (allow file-read-metadata",+      "\t(literal \"/etc/resolv.conf\")",+      "\t(literal \"/private/etc/resolv.conf\")",+      "\t(literal \"/etc/hosts\"))",+      "      (allow file-read*",+      "\t(literal \"/private/var/run/resolv.conf\")",+      "\t(literal \"/private/etc/hosts\"))",+      "      (allow network-outbound (remote unix-socket (path-literal \"/private/var/run/mDNSResponder\")))))"+    ]++-- | The build's mark, by which the helper finds the build's processes to+-- end them: a Mach service name the profile allows and one it refuses,+-- each random and made by the helper for this build alone.  No service+-- holds either name, so the first grants nothing.  Under @sandbox = true@+-- nothing else is in the profile, and no process of the build can change+-- its sandbox, so the mark holds.  Under @relaxed@ the rules come after a+-- derivation's own text, and text that would swallow them leaves a+-- profile macOS's sandbox refuses, but that text can redefine the+-- profile's own forms (@param@, @allow@, @deny@) and so drop the mark,+-- leaving its processes to outlive the build; @relaxed@ trusts the+-- derivation as it does one that asks for no sandbox at all.  Undo with+-- the helper's sweep, when builds run as build users of their own, under+-- a daemon.+profileMark :: ByteString+profileMark =+  BS8.unlines+    [ "; The build's mark, which the helper finds its processes by.",+      "(allow mach-lookup (global-name (param \"_NOVA_NIX_BUILD_TOKEN\")))",+      "(deny mach-lookup (global-name (param \"_NOVA_NIX_BUILD_DECOY\")))"+    ]++-- | Text with a newline at its end, unless it is empty or has one, so+-- what follows it starts a line of its own rather than ending a comment.+endLine :: ByteString -> ByteString+endLine text+  | BS.null text || "\n" `BS.isSuffixOf` text = text+  | otherwise = text <> "\n"++-- | The refusal of the terminals, after every rule that could allow one:+-- a terminal's device is the invoking user's, as the console's is, and+-- an @__impureHostDeps@ path @\/dev@, which the profile lets a build read+-- beneath, would let it read what the user types there.  No earlier rule+-- lets a build write beneath @\/dev@ but to its standard devices, and+-- opening @\/dev\/ptmx@ takes writing as well as reading, so the deny's+-- write half, and its line for @\/dev\/ptmx@, refuse nothing today; they+-- keep the terminals refused should an earlier rule widen.+-- @\/dev\/tty@, a process's controlling terminal, stays allowed, since a+-- builder leads a session with none.  Undo when builds run as build users+-- of their own, under a daemon.+profileTerminals :: ByteString+profileTerminals =+  BS8.unlines+    [ "; Terminals, which are the user's.",+      "(deny file-read* file-write*",+      "\t(literal \"/dev/ptmx\")",+      "\t(regex #\"^/dev/pty\")",+      "\t(regex #\"^/dev/tty.\")",+      "\t(literal \"/dev/console\"))"+    ]++-- | The rules a fixed-output build's profile adds (the rules of upstream's+-- @sandbox-network.sb@ at 2.36.0): any network, name lookups, and the+-- certificate checks of trustd.+profileNetwork :: ByteString+profileNetwork =+  BS8.unlines+    [ "; The network, for a fixed-output build, with name lookups and",+      "; certificate checks.",+      "(allow network* (local ip) (remote ip))",+      "(allow file-read-metadata",+      "\t(literal \"/etc/resolv.conf\")",+      "\t(literal \"/private/etc/resolv.conf\"))",+      "(allow file-read* (literal \"/private/var/run/resolv.conf\"))",+      "(allow network-outbound (remote unix-socket (path-literal \"/private/var/run/mDNSResponder\")))",+      "(allow mach-lookup",+      "\t(global-name \"com.apple.SystemConfiguration.DNSConfiguration\")",+      "\t(global-name \"com.apple.trustd\")",+      "\t(global-name \"com.apple.trustd.agent\"))"+    ]++-- ---------------------------------------------------------------------------+-- The macOS plan+-- ---------------------------------------------------------------------------++-- | What the helper does for one build on macOS.+data DarwinPlan = DarwinPlan+  { -- | The build directory, resolved as the profile names it, where the+    -- builder starts.+    darwinPlanBuildDir :: !ByteString,+    darwinPlanProfile :: !ByteString,+    -- | The build user the builder runs as, or nothing for the invoking+    -- user.+    darwinPlanBuildUser :: !(Maybe BuilderIds),+    -- | The values of the parameters the profile reads, by name.+    darwinPlanParameters :: ![(ByteString, ByteString)],+    -- | The builder's environment, as @NAME=VALUE@ entries.+    darwinPlanEnvironment :: ![ByteString]+  }+  deriving (Eq, Show)++-- | The parameters a macOS build's profile reads, as upstream names them+-- (@DarwinDerivationBuilder::setUser@), given the build directory and the+-- directory the build may keep temporary files in, both resolved:+-- @_NIX_BUILD_TOP@, the build directory; @_GLOBAL_TMP_DIR@, the+-- temporary directory, without trailing slashes, which a subpath filter+-- does not match through; and @_ALLOW_LOCAL_NETWORKING@ for a derivation+-- that asks for it.+--+-- Upstream's temporary directory is the one Nix runs with, @TMPDIR@ or+-- @\/tmp@, where its build user owns nothing, and so is a build's here+-- when it runs as a build user.  A builder run as the invoking user,+-- whose live Unix sockets and files are there, is given its build+-- directory in its place, which its @TMPDIR@ names already.+darwinParameters :: ByteString -> ByteString -> LocalNetworking -> [(ByteString, ByteString)]+darwinParameters buildDir tmpDir local =+  [("_NIX_BUILD_TOP", buildDir), ("_GLOBAL_TMP_DIR", BS8.dropWhileEnd (== '/') tmpDir)]+    ++ [("_ALLOW_LOCAL_NETWORKING", "1") | local == LocalNetworkingAllowed]++-- | A macOS plan as the helper reads it ('framePlan'): the backend, the+-- build directory, the profile and the build user's ids, @-@ for each when+-- the builder runs as the invoking user, then each parameter's name and+-- value, then the builder's environment.+renderDarwinPlan :: DarwinPlan -> ByteString+renderDarwinPlan plan =+  framePlan+    ( concat+        [ ["backend", "darwin"],+          ["build-dir", darwinPlanBuildDir plan],+          ["profile", darwinPlanProfile plan],+          ["build-uid", maybe noBuildUser (BS8.pack . show . builderUid) (darwinPlanBuildUser plan)],+          ["build-gid", maybe noBuildUser (BS8.pack . show . builderGid) (darwinPlanBuildUser plan)]+        ]+        ++ concat [["param", name, value] | (name, value) <- darwinPlanParameters plan]+        ++ concatMap (\entry -> ["env", entry]) (darwinPlanEnvironment plan)+    )+  where+    noBuildUser = "-"++-- ---------------------------------------------------------------------------+-- The Windows plan+-- ---------------------------------------------------------------------------++-- | What the helper does for one build on Windows (@sandbox\/windows.c@):+-- start the builder as a build slot's account, from the token the+-- process that starts the helper hands it, with its image opened as the+-- slot, on the window station of that token's logon, attached to a+-- pseudoconsole the helper owns, and in a job that caps each process's+-- memory and lets none break away, ending every process of the slot's+-- account before the builder starts and after the build.  The builder's+-- command line is the helper's own past its verb.+data WindowsPlan = WindowsPlan+  { -- | The directory the builder starts in.+    windowsPlanBuildDir :: !ByteString,+    -- | The value of the helper's handle to the slot account's primary+    -- token, which it inherits from the process that starts it.  The+    -- helper takes 1 to 2^31 - 1, the values a handle has.+    windowsPlanToken :: !Word32,+    -- | The slot's account, whose token that must be, and whose+    -- processes the helper ends before and after the build.+    windowsPlanSlot :: !Sid,+    -- | The most memory each process of the build may commit, in bytes,+    -- which the helper takes above 0.+    windowsPlanMemoryCap :: !Word64,+    -- | The builder's environment, as @NAME=VALUE@ entries, which the+    -- helper takes as UTF-8, and none of them empty.+    windowsPlanEnvironment :: ![ByteString]+  }+  deriving (Eq, Show)++-- | A Windows plan as the helper reads it ('framePlan'): the backend, the+-- build directory, the token's handle, the slot's SID and the memory+-- cap, then the builder's environment.+renderWindowsPlan :: WindowsPlan -> ByteString+renderWindowsPlan plan =+  framePlan+    ( concat+        [ ["backend", "windows"],+          ["build-dir", windowsPlanBuildDir plan],+          ["token", BS8.pack (show (windowsPlanToken plan))],+          ["slot-sid", TE.encodeUtf8 (sidText (windowsPlanSlot plan))],+          ["memory-cap", BS8.pack (show (windowsPlanMemoryCap plan))]+        ]+        ++ concatMap (\entry -> ["env", entry]) (windowsPlanEnvironment plan)+    )++-- ---------------------------------------------------------------------------+-- What the helper reports+-- ---------------------------------------------------------------------------++-- | A step of @nova-nix-sandbox run@ that can fail on Linux.+data SetupStage+  = StageStdout+  | StageSigchld+  | StagePlan+  | StageStdin+  | StageSetgroups+  | StageSync+  | StageSignals+  | StageClone+  | StageUidMap+  | StageSetgroupsDeny+  | StageGidMap+  | StageRelease+  | StagePdeathsig+  | StageSetsid+  | StageLoopbackSocket+  | StageLoopback+  | StageHostname+  | StageDomainname+  | StagePrivate+  | StageBindRoot+  | StageBindSource+  | StageBindTarget+  | StageBind+  | StageRemount+  | StageProc+  | StageDevShm+  | StageDevpts+  | StageEtc+  | StageChdirRoot+  | StageRealRoot+  | StagePivot+  | StageChroot+  | StageUmount+  | StageRmdir+  | StageSetgid+  | StageSetuid+  | StageChdir+  | StageKeyring+  | StageNoNewPrivs+  | StageExec+  deriving (Eq, Show, Enum, Bounded)++-- | The token the helper writes for a stage.+setupStageName :: SetupStage -> ByteString+setupStageName stage = case stage of+  StageStdout -> "stdout"+  StageSigchld -> "sigchld"+  StagePlan -> "plan"+  StageStdin -> "stdin"+  StageSetgroups -> "setgroups"+  StageSync -> "sync"+  StageSignals -> "signals"+  StageClone -> "clone"+  StageUidMap -> "uid-map"+  StageSetgroupsDeny -> "setgroups-deny"+  StageGidMap -> "gid-map"+  StageRelease -> "release"+  StagePdeathsig -> "pdeathsig"+  StageSetsid -> "setsid"+  StageLoopbackSocket -> "loopback-socket"+  StageLoopback -> "loopback"+  StageHostname -> "hostname"+  StageDomainname -> "domainname"+  StagePrivate -> "private"+  StageBindRoot -> "bind-root"+  StageBindSource -> "bind-source"+  StageBindTarget -> "bind-target"+  StageBind -> "bind"+  StageRemount -> "remount"+  StageProc -> "proc"+  StageDevShm -> "dev-shm"+  StageDevpts -> "devpts"+  StageEtc -> "etc"+  StageChdirRoot -> "chdir-root"+  StageRealRoot -> "real-root"+  StagePivot -> "pivot"+  StageChroot -> "chroot"+  StageUmount -> "umount"+  StageRmdir -> "rmdir"+  StageSetgid -> "setgid"+  StageSetuid -> "setuid"+  StageChdir -> "chdir"+  StageKeyring -> "keyring"+  StageNoNewPrivs -> "no-new-privs"+  StageExec -> "exec"++-- | A step of @nova-nix-sandbox run@ that can fail on Windows, whose+-- record carries the Win32 error code of the call that failed, but for+-- the plan's, which carries an errno value as on every OS.+data WindowsStage+  = WindowsStagePlan+  | -- | Enabling the privileges that start a process as another account.+    WindowsStagePrivileges+  | -- | The plan's token: a handle this process holds, to a primary+    -- token.+    WindowsStageToken+  | WindowsStageSlotSid+  | -- | The token's user is not the plan's slot.+    WindowsStageTokenUser+  | -- | Ending the processes running as the slot's account before the+    -- builder starts.  The record's index is the process that could not+    -- be ended, and a sweep that outlasts its wait carries+    -- @ERROR_TIMEOUT@.+    WindowsStageSweep+  | -- | Opening NUL, the builder's standard input.+    WindowsStageStdin+  | -- | Copying the build log for the builder to inherit.+    WindowsStageLog+  | WindowsStageConsole+  | WindowsStageJob+  | WindowsStageEnvironment+  | WindowsStageBuildDir+  | WindowsStageCommandLine+  | -- | The list of the handles and the pseudoconsole the builder starts+    -- with.+    WindowsStageAttributes+  | -- | Impersonating the slot, whose access the builder's image is+    -- opened with.+    WindowsStageImpersonate+  | WindowsStageExec+  | -- | Ending the impersonation once the builder is started.+    WindowsStageRevert+  | -- | Assigning the builder to the build's job.+    WindowsStageAssign+  | -- | Starting the thread that watches the lifeline.+    WindowsStageLifeline+  | WindowsStageResume+  deriving (Eq, Show, Enum, Bounded)++-- | The token the helper writes for a Windows stage.+windowsStageName :: WindowsStage -> ByteString+windowsStageName stage = case stage of+  WindowsStagePlan -> "plan"+  WindowsStagePrivileges -> "privileges"+  WindowsStageToken -> "token"+  WindowsStageSlotSid -> "slot-sid"+  WindowsStageTokenUser -> "token-user"+  WindowsStageSweep -> "sweep"+  WindowsStageStdin -> "stdin"+  WindowsStageLog -> "log"+  WindowsStageConsole -> "console"+  WindowsStageJob -> "job"+  WindowsStageEnvironment -> "environment"+  WindowsStageBuildDir -> "build-dir"+  WindowsStageCommandLine -> "command-line"+  WindowsStageAttributes -> "attributes"+  WindowsStageImpersonate -> "impersonate"+  WindowsStageExec -> "exec"+  WindowsStageRevert -> "revert"+  WindowsStageAssign -> "assign"+  WindowsStageLifeline -> "lifeline"+  WindowsStageResume -> "resume"++-- | A check of @nova-nix-sandbox probe@ that can fail.+data ProbeStage+  = ProbeSigchld+  | ProbeUsernsMissing+  | ProbeUsernsMax+  | ProbeUsernsClone+  | ProbeUserns+  | ProbeAppArmor+  | ProbeMountns+  | ProbeProcRemount+  | -- | macOS's sandbox refused the probe's profile.+    ProbeSandbox+  | -- | The privileges that start a process as another account could+    -- not be enabled, on Windows.+    ProbePrivileges+  deriving (Eq, Show, Enum, Bounded)++-- | The token the helper writes for a probe check.+probeStageName :: ProbeStage -> ByteString+probeStageName stage = case stage of+  ProbeSigchld -> "sigchld"+  ProbeUsernsMissing -> "userns-missing"+  ProbeUsernsMax -> "userns-max"+  ProbeUsernsClone -> "userns-clone"+  ProbeUserns -> "userns"+  ProbeAppArmor -> "apparmor"+  ProbeMountns -> "mountns"+  ProbeProcRemount -> "proc-remount"+  ProbeSandbox -> "sandbox"+  ProbePrivileges -> "privileges"++-- | The helper's report of a step that failed: the step, the @errno@ it+-- failed with (0 for none), and the plan entry or process it concerns.+data StatusRecord stage = StatusRecord+  { recordStage :: !stage,+    recordErrno :: !Int,+    recordIndex :: !(Maybe Int)+  }+  deriving (Eq, Show)++-- | Read what the helper wrote on its status output: nothing, which means+-- it did not fail, or one record.  Anything else is the refusal of a+-- status that cannot be read, since a helper that wrote something it+-- should not have has not run as this module expects.+parseStatus :: (Enum stage, Bounded stage) => (stage -> ByteString) -> ByteString -> Either Text (Maybe (StatusRecord stage))+parseStatus stageName bytes+  | BS.null bytes = Right Nothing+  | otherwise = case BS8.lines bytes of+      [line]+        | "\n" `BS.isSuffixOf` bytes,+          [name, errnoText, indexText] <- BS8.split ' ' line -> do+            stage <- maybe (Left unreadable) Right (lookup name named)+            number <- maybe (Left unreadable) Right (decimal errnoText)+            index <- maybe (Left unreadable) Right (indexOf indexText)+            Right (Just (StatusRecord stage number index))+      _ -> Left unreadable+  where+    named = [(stageName stage, stage) | stage <- [minBound .. maxBound]]+    unreadable = "the sandbox helper wrote a status that cannot be read: '" <> TE.decodeUtf8Lenient bytes <> "'"+    -- A record's numbers are an errno and an index, so one past a 32-bit+    -- int is no record the helper writes, and not read as a wrapped Int.+    decimal text+      | not (BS.null text), BS8.all (`elem` ['0' .. '9']) text = readMaybe (BS8.unpack text) >>= inRecordRange+      | otherwise = Nothing+    inRecordRange :: Integer -> Maybe Int+    inRecordRange number+      | number <= toInteger (maxBound :: Int32) = Just (fromInteger number)+      | otherwise = Nothing+    indexOf text+      | text == "-1" = Just Nothing+      | otherwise = Just <$> decimal text++-- | Why a sandboxed build cannot run in a sandbox on this system.+data Unavailability+  = -- | The platform has no sandbox nova-nix can make.+    PlatformUnsupported+  | -- | The helper was not found.+    HelperNotFound+  | -- | The helper could not be run, for the reason given.+    HelperUnrunnable !Text+  | -- | A check of the probe failed.+    ProbeFailed !(StatusRecord ProbeStage)+  | -- | The probe's report could not be read.+    ProbeUnreadable !Text+  deriving (Eq, Show)++-- | The cause, in a line, in upstream Nix's words where its probe logs+-- the same cause (at debug level); a cause that names nova-nix or its+-- helper is nova-nix's own.+unavailabilityCause :: Unavailability -> Text+unavailabilityCause cause = case cause of+  PlatformUnsupported -> "sandboxing builds is not supported on this platform"+  HelperNotFound -> "the sandbox helper 'nova-nix-sandbox' was not found beside nova-nix"+  HelperUnrunnable reason -> "the sandbox helper could not be run: " <> reason+  ProbeUnreadable reason -> reason+  ProbeFailed record -> case recordStage record of+    ProbeSigchld -> "the sandbox helper cannot reset SIGCHLD" <> errnoSuffix (recordErrno record)+    ProbeUsernsMissing -> "'/proc/self/ns/user' does not exist; your kernel was likely built without CONFIG_USER_NS=y"+    ProbeUsernsMax -> "user namespaces appear to be disabled; check '/proc/sys/user/max_user_namespaces'"+    ProbeUsernsClone -> "user namespaces appear to be disabled; check '/proc/sys/kernel/unprivileged_userns_clone'"+    ProbeUserns -> "user namespaces do not work on this system" <> errnoSuffix (recordErrno record)+    ProbeAppArmor -> "AppArmor restricts unprivileged user namespaces ('/proc/sys/kernel/apparmor_restrict_unprivileged_userns' is 1), and no AppArmor profile lets nova-nix-sandbox use them"+    ProbeMountns -> "mount namespaces do not work on this system" <> errnoSuffix (recordErrno record)+    ProbeProcRemount -> "PID namespaces do not work on this system: cannot remount /proc"+    ProbeSandbox -> "macOS's sandbox refuses a profile from nova-nix's process, as it refuses one from a process already in a sandbox"+    ProbePrivileges -> "the sandbox helper cannot enable SeAssignPrimaryTokenPrivilege and SeIncreaseQuotaPrivilege, which start a build as a build account"++-- | Upstream's refusal of a sandboxed build on a system without the+-- namespaces, with @sandbox-fallback@ off (@tryLocalBuild@ in LDG,+-- @makeDerivationBuilder@ in unix-derivation-builder.cc at 2.36.0), or+-- for a cause upstream has no probe for, that cause.  Under the macOS+-- backend a failed probe is upstream's refusal of a profile macOS's+-- sandbox would not take (@DarwinDerivationBuilder::setUser@), which fails+-- the build whatever @sandbox-fallback@ says ('backendFallback').+unavailableMessage :: Maybe SandboxBackend -> Unavailability -> Text+unavailableMessage backend cause = case (backend, cause) of+  (Just DarwinBackend, ProbeFailed _) -> profileRefused+  (Just DarwinBackend, ProbeUnreadable _) -> profileRefused+  (_, ProbeFailed _) -> namespacesUnsupported+  (_, ProbeUnreadable _) -> namespacesUnsupported+  _ -> ownCause+  where+    profileRefused = setupContext <> "failed to configure sandbox"+    ownCause = unavailabilityCause cause <> "; use '--no-sandbox' to disable sandboxing"+    namespacesUnsupported = "this system does not support the kernel namespaces that are required for sandboxing; use '--no-sandbox' to disable sandboxing"++-- | The one warning a process prints when its builds fall back to running+-- unsandboxed, naming why.  Upstream says nothing there (@tryLocalBuild@ in+-- LDG), but its root daemon rarely falls back, where nova-nix without one+-- falls back on every stock Ubuntu.+fallbackWarning :: Unavailability -> Text+fallbackWarning cause = "warning: building without a sandbox, since " <> unavailabilityCause cause++-- | A failed setup step: the words of the @SysError@ upstream's+-- @startBuilder@ or @runChild@ throws for the step (LDG), with errno's+-- text after them, behind the line of context upstream adds to a failure+-- from the child (@startBuilder@ in LDG).  Upstream prints that context as a+-- trace line and then the error after an @error:@ of its own; here the two+-- are one line.  The plan names the bind an index points at and the host+-- directory bound as the build directory, and the program is the one the+-- helper executes.+setupFailureMessage :: SandboxPlan -> ByteString -> StatusRecord SetupStage -> Text+setupFailureMessage plan program record =+  setupContext <> case recordStage record of+    StageStdout -> sys "cannot dup stderr into stdout"+    StageSigchld -> sys "resetting SIGCHLD"+    StagePlan -> sys "the sandbox helper cannot read its plan"+    StageStdin -> sys "cannot open '/dev/null'"+    StageSetgroups+      | Errno (fromIntegral (recordErrno record)) == ePERM -> "setgroups failed. Set the require-drop-supplementary-groups option to false to skip this step."+      | otherwise -> sys "setgroups failed"+    StageSync -> sys "creating pipe"+    StageSignals -> sys "setting signal handlers"+    StageClone -> "unable to start build process"+    StageUidMap -> sys ("opening file '" <> procFile "uid_map" <> "'")+    StageSetgroupsDeny -> sys ("opening file '" <> procFile "setgroups" <> "'")+    StageGidMap -> sys ("opening file '" <> procFile "gid_map" <> "'")+    StageRelease -> sys "writing to the build process"+    StagePdeathsig -> sys "setting death signal"+    StageSetsid -> sys "creating a new session"+    StageLoopbackSocket -> sys "cannot open IP socket"+    StageLoopback -> sys "cannot set loopback interface flags"+    StageHostname -> sys "cannot set host name"+    StageDomainname -> sys "cannot set domain name"+    StagePrivate -> sys "unable to make '/' private"+    StageBindRoot -> sys ("unable to bind mount '" <> shown (planRoot plan) <> "'")+    StageBindSource -> sys ("getting attributes of path '" <> maybe "" (shown . bindSource) bind <> "'")+    StageBindTarget -> sys ("creating directory '" <> inRoot (maybe "" bindTarget bind) <> "'")+    StageBind -> sys ("bind mount from '" <> maybe "" (shown . bindSource) bind <> "' to '" <> inRoot (maybe "" bindTarget bind) <> "' failed")+    StageRemount -> sys ("cannot remount '" <> inRoot (maybe "" bindTarget bind) <> "' read-only")+    StageProc -> sys "mounting /proc"+    StageDevShm -> sys "mounting /dev/shm"+    StageDevpts -> sys "mounting /dev/pts"+    StageEtc -> sys ("setting permissions on '" <> inRoot "/etc" <> "'")+    StageChdirRoot -> sys ("cannot change directory to '" <> shown (planRoot plan) <> "'")+    StageRealRoot -> sys "cannot create real-root directory"+    StagePivot -> sys ("cannot pivot old root directory onto '" <> inRoot "/real-root" <> "'")+    StageChroot -> sys ("cannot change root directory to '" <> shown (planRoot plan) <> "'")+    StageUmount -> sys "cannot unmount real root filesystem"+    StageRmdir -> sys "cannot remove real-root directory"+    StageSetgid -> sys "setgid failed"+    StageSetuid -> sys "setuid failed"+    StageChdir -> sys ("changing into '" <> shown hostBuildDir <> "'")+    StageKeyring -> sys "unable to join a new session keyring"+    StageNoNewPrivs -> sys "unable to set 'no new privileges'"+    StageExec -> sys ("executing '" <> shown program <> "'")+  where+    sys message = message <> errnoSuffix (recordErrno record)+    bind = recordIndex record >>= \index -> lookup index (zip [0 ..] (planBinds plan))+    -- Upstream names the build directory on the host there (@runChild@ in+    -- LDG).+    hostBuildDir = maybe (planBuildDir plan) bindSource (find ((== planBuildDir plan) . bindTarget) (planBinds plan))+    procFile name = "/proc/" <> maybe "" (T.pack . show) (recordIndex record) <> "/" <> name+    inRoot path = shown (planRoot plan <> path)+    shown = TE.decodeUtf8Lenient++-- | The line of context upstream puts before a failure of the builder's+-- process before its exec (@LocalDerivationGoal::startBuilder@ at 2.24.9,+-- @UnixDerivationBuilderImpl::processSandboxSetupMessages@ at 2.36.0).+setupContext :: Text+setupContext = "while setting up the build environment: "++-- | A step of @nova-nix-sandbox run@ that can fail on macOS.+data DarwinStage+  = DarwinStageStdout+  | DarwinStageSigchld+  | DarwinStagePlan+  | DarwinStageStdin+  | DarwinStageLog+  | DarwinStageLogMode+  | DarwinStageReport+  | DarwinStageLogWatch+  | DarwinStageRelay+  | DarwinStageOutput+  | DarwinStageSweep+  | DarwinStageSignals+  | DarwinStageFork+  | DarwinStageSetsid+  | DarwinStageChdir+  | DarwinStageSetgroups+  | DarwinStageSetgid+  | DarwinStageSetuid+  | DarwinStageSandbox+  | DarwinStageExec+  deriving (Eq, Show, Enum, Bounded)++-- | The token the helper writes for a macOS stage.+darwinStageName :: DarwinStage -> ByteString+darwinStageName stage = case stage of+  DarwinStageStdout -> "stdout"+  DarwinStageSigchld -> "sigchld"+  DarwinStagePlan -> "plan"+  DarwinStageStdin -> "stdin"+  DarwinStageLog -> "log"+  DarwinStageLogMode -> "logmode"+  DarwinStageReport -> "report"+  DarwinStageLogWatch -> "logwatch"+  DarwinStageRelay -> "relay"+  DarwinStageOutput -> "output"+  DarwinStageSweep -> "sweep"+  DarwinStageSignals -> "signals"+  DarwinStageFork -> "fork"+  DarwinStageSetsid -> "setsid"+  DarwinStageChdir -> "chdir"+  DarwinStageSetgroups -> "setgroups"+  DarwinStageSetgid -> "setgid"+  DarwinStageSetuid -> "setuid"+  DarwinStageSandbox -> "sandbox"+  DarwinStageExec -> "exec"++-- | A failed macOS setup step, as 'setupFailureMessage' reports a Linux+-- one, in the words of upstream Nix's errors, given the plan and the+-- program the helper executes.  A profile macOS's sandbox refuses is+-- reported with the words of upstream's line for it, @failed to configure+-- sandbox@, which the helper writes to the build log with the sandbox's+-- own reason after them.  Upstream reads that line as one of the child's+-- setup messages and reports the end of its pipe instead, while waiting+-- for the build environment to initialize, the line among its previous+-- messages.  A failure to watch the build log goes on the status channel,+-- since the log it could not watch cannot carry it: before the builder+-- starts when the log cannot be watched at all, as @\/dev\/null@ cannot,+-- or once the build has ended when watching it fails during the build,+-- and then only when the builder's process reported no failed step of+-- its own, which the helper relays, so the channel holds one record at+-- most.  A failure to read that report is the helper's own.+darwinSetupFailureMessage :: DarwinPlan -> ByteString -> StatusRecord DarwinStage -> Text+darwinSetupFailureMessage plan program record = case recordStage record of+  DarwinStageStdout -> setup (sys "cannot dup stderr into stdout")+  DarwinStageSigchld -> setup (sys "resetting SIGCHLD")+  DarwinStagePlan -> setup (sys "the sandbox helper cannot read its plan")+  DarwinStageStdin -> setup (sys "opening '/dev/null'")+  DarwinStageLog -> setup (sys "preparing the pipe the builder writes its log to")+  DarwinStageLogMode -> setup (sys "making writes to the build log non-blocking")+  DarwinStageReport -> setup (sys "creating pipe")+  DarwinStageLogWatch -> sys "the sandbox helper cannot watch the build log, which must be pollable (a pipe or a regular file, not /dev/null)"+  DarwinStageRelay -> sys "the sandbox helper cannot read the builder's report of its setup"+  DarwinStageOutput -> setup (sys "redirecting the builder's output to its log pipe")+  DarwinStageSweep -> setup (sys "the sandbox helper cannot prepare to end the build's processes")+  DarwinStageSignals -> setup (sys "setting signal handlers")+  DarwinStageFork -> setup (sys "unable to fork")+  DarwinStageSetsid -> setup (sys "creating a new session")+  DarwinStageChdir -> setup (sys ("changing into \"" <> TE.decodeUtf8Lenient (darwinPlanBuildDir plan) <> "\""))+  DarwinStageSetgroups -> setup (sys "cannot set supplementary groups of build user")+  DarwinStageSetgid -> setup (sys "setgid failed")+  DarwinStageSetuid -> setup (sys "setuid failed")+  DarwinStageSandbox -> setup "failed to configure sandbox"+  DarwinStageExec -> setup (sys ("executing '" <> TE.decodeUtf8Lenient program <> "'"))+  where+    setup = (setupContext <>)+    sys message = message <> errnoSuffix (recordErrno record)++-- | What the helper's run of a builder came to.+data HelperOutcome+  = -- | The sandbox was made and the builder ran, and the helper exited+    -- so: as the builder did, or with a failure of its own after it.+    BuilderRan !ExitCode+  | -- | The sandbox was not made, for the reason given.+    SetupIncomplete !Text+  deriving (Eq, Show)++-- | Read a run of the helper, given its backend's stage names and its+-- report of a failed step ('setupFailureMessage',+-- 'darwinSetupFailureMessage'), whether the plan reached it, how it+-- exited and what it wrote on its status output.  A record is the step+-- that failed.  With none, the exit is the builder's, which the helper+-- relays, or the helper's own failure after the builder ran, its reason in+-- the build log; unless the plan never reached it: then the helper ended+-- before it could report anything.+helperOutcome :: (Enum stage, Bounded stage) => (stage -> ByteString) -> (StatusRecord stage -> Text) -> Either Text () -> ExitCode -> ByteString -> HelperOutcome+helperOutcome stageName failureMessage delivered exitCode status = case parseStatus stageName status of+  Left unreadable -> SetupIncomplete unreadable+  Right (Just record) -> SetupIncomplete (failureMessage record)+  Right Nothing -> case delivered of+    Left failure -> SetupIncomplete ("the sandbox helper ended before it read its plan: " <> failure)+    Right () -> BuilderRan exitCode++-- | @": "@ and the system's text for an @errno@, as upstream's @SysError@+-- appends it, or nothing for none.+errnoSuffix :: Int -> Text+errnoSuffix 0 = ""+errnoSuffix number = ": " <> T.pack (ioe_description (errnoToIOError "" (Errno (fromIntegral number)) Nothing Nothing))
+ src/Nix/Builder/Sandbox/Spawn.hs view
@@ -0,0 +1,538 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TupleSections #-}++-- | The build sandbox's IO: whether this system can sandbox a build, the+-- run of the @nova-nix-sandbox@ helper that carries a build's plan out,+-- the chroot a sandboxed build runs in on Linux, the paths a macOS+-- build's profile names, and the one warning a process prints when its+-- builds fall back to running unsandboxed.  What is decided is+-- "Nix.Builder.Sandbox"; this module only carries it out.+--+-- == The helper+--+-- The helper's command line, plan and status record are its core's, the+-- same whichever backend it links, so probing it and running it are+-- written once here.  What a backend needs around the run is not: on+-- Linux, a chroot made from its skeleton before the run, sealed after it,+-- and removed; on macOS, the paths its profile names, each looked at+-- ('profileFilters'), and the store and build directories resolved+-- ('resolvedPath').+--+-- == Where it runs+--+-- The helper is built for Linux, macOS and Windows, and nova-nix probes+-- and runs it where 'hostSandboxBackend' names a backend, Linux and+-- macOS.  The chroot code is POSIX, so it runs in the test suite on macOS+-- as well; Windows has no chroot, and there making or sealing one, or+-- looking at a profile's paths, refuses.+--+-- == Process state+--+-- Upstream probes the namespaces once per process and keeps the answer+-- (function statics in @userNamespacesSupported@ and+-- @mountAndPidNamespacesSupported@, namespaces.cc at 2.24.9 and+-- linux-namespaces.cc at 2.36.0).  The answer here is kept in one+-- process-wide cell ('probeCache'), with whether the fallback warning was+-- printed: both describe this process and this system, not a build, and+-- asking again for every derivation of a closure would run the probe and+-- print the warning once per derivation.+module Nix.Builder.Sandbox.Spawn+  ( -- * Availability+    sandboxAvailability,+    warnFallback,+    processIsRoot,++    -- * Running the helper+    HelperRun (..),+    runHelper,++    -- * The chroot+    chrootDirFor,+    withChroot,+    mountPointsWithin,+    sealChroot,++    -- * The macOS profile's paths+    profileFilters,+    resolvedPath,++    -- * Paths as bytes+    filePathBytes,+    bytesFilePath,+  )+where++import Control.Concurrent.MVar (MVar, modifyMVar, newMVar)+import Control.Exception (IOException, bracket, displayException, try)+import qualified Control.Exception as E+import Control.Monad (void, when)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BS8+import Data.Foldable (for_)+import qualified Data.Map.Strict as Map+import Data.Set (Set)+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Word (Word32)+import Nix.Builder.Log (openLogPipe, streamBuildLog)+import Nix.Logger (Logger, logMessage)+import System.Exit (ExitCode (..))+import System.IO (hClose, hFlush)+import System.IO.Unsafe (unsafePerformIO)+import qualified System.Process as Proc+#if defined(mingw32_HOST_OS)+import Nix.Builder.Sandbox (DarwinPath, ProfileFilter, SandboxBackend, SkeletonEntry (..), Unavailability (..), fallbackWarning, hostSandboxBackend, parseStatus, probeStageName, unavailabilityCause)+import System.Directory (canonicalizePath)+#else+import Data.Maybe (catMaybes)+import GHC.IO.Exception (IOException (ioe_errno))+import Nix.Builder.Sandbox (DarwinPath, PathFound (..), ProfileFilter, SandboxBackend, SkeletonEntry (..), Unavailability (..), darwinPathTarget, fallbackWarning, hostSandboxBackend, parseStatus, probeStageName, profileFilter)+import qualified Data.Set as Set+import qualified GHC.Foreign as GHC+import GHC.IO.Encoding (getFileSystemEncoding)+import System.Directory (canonicalizePath, createDirectoryIfMissing, listDirectory, removePathForcibly)+import System.FilePath (splitDirectories, (</>))+import System.Posix.Directory (createDirectory)+import System.Posix.Files (createSymbolicLink, fileOwner, getSymbolicLinkStatus, isDirectory, setFileMode, setOwnerAndGroup)+import Nix.Builder.BuildDir (clearLeftover)+import Nix.Store.Metadata (writableByOthers)+import System.Posix.Types (FileMode)+import System.Posix.User (getEffectiveUserID, getRealUserID)+#endif++-- ---------------------------------------------------------------------------+-- Availability+-- ---------------------------------------------------------------------------++-- | What the probe found for a helper, and whether the fallback warning+-- has been given.+data ProbeState = ProbeState+  { psAnswers :: !(Map.Map FilePath (Either Unavailability FilePath)),+    psWarned :: !Bool+  }++-- | The process's probe answers and warning.  A NOINLINE top-level cell+-- made once, by 'unsafePerformIO': it holds only what this process+-- learned about the system it runs on, and every reader takes it through+-- 'modifyMVar', so the answer is the same however many threads build.+probeCache :: MVar ProbeState+probeCache = unsafePerformIO (newMVar (ProbeState Map.empty False))+{-# NOINLINE probeCache #-}++-- | Whether a sandboxed build can run here, with which backend, and which+-- helper runs it: on a platform with a backend ('hostSandboxBackend'),+-- with the helper found, its probe passing.  The probe runs once per+-- process for each helper, the first time a sandboxed build asks.+sandboxAvailability :: Maybe FilePath -> IO (Either Unavailability (SandboxBackend, FilePath))+sandboxAvailability helper = case (hostSandboxBackend, helper) of+  (Nothing, _) -> pure (Left PlatformUnsupported)+  (Just _, Nothing) -> pure (Left HelperNotFound)+  (Just backend, Just path) -> fmap (backend,) <$> probeOnce path+  where+    probeOnce path = modifyMVar probeCache $ \state -> case Map.lookup path (psAnswers state) of+      Just answer -> pure (state, answer)+      Nothing -> do+        answer <- probe path+        pure (state {psAnswers = Map.insert path answer (psAnswers state)}, answer)++-- | Run the helper's probe.+probe :: FilePath -> IO (Either Unavailability FilePath)+probe helper = do+  ran <- try (Proc.readCreateProcessWithExitCode ((Proc.proc helper [helperProbeVerb]) {Proc.env = Just []}) "")+  pure $ case ran of+    Left (failure :: IOException) -> Left (HelperUnrunnable (T.pack (show failure)))+    Right (ExitSuccess, "", _) -> Right helper+    Right (_, out, _) -> case parseStatus probeStageName (BS8.pack out) of+      Right (Just record) -> Left (ProbeFailed record)+      Right Nothing -> Left (ProbeUnreadable "the sandbox helper's probe failed and said nothing")+      Left reason -> Left (ProbeUnreadable reason)++-- | Give the logger the fallback warning ('fallbackWarning'), the first+-- time this process falls back.+warnFallback :: Logger -> Unavailability -> IO ()+warnFallback logger cause = do+  first <- modifyMVar probeCache $ \state -> pure (state {psWarned = True}, not (psWarned state))+  when first (logMessage logger (fallbackWarning cause))++-- | Upstream's @isRootUser@ (users.cc at 2.24.9): whether the process+-- runs as uid 0, which is where @require-drop-supplementary-groups@+-- defaults on.  Never on Windows, which has no uid.+processIsRoot :: IO Bool+#if defined(mingw32_HOST_OS)+processIsRoot = pure False+#else+processIsRoot = (== 0) <$> getRealUserID+#endif++-- ---------------------------------------------------------------------------+-- Running the helper+-- ---------------------------------------------------------------------------++-- | What a run of the helper came to: whether the plan reached it, how it+-- exited, and what it wrote on its status output.+data HelperRun = HelperRun+  { hrDelivered :: !(Either Text ()),+    hrExit :: !ExitCode,+    hrStatus :: !ByteString+  }+  deriving (Eq, Show)++-- | Run the helper over a builder, given the logger, the helper, the+-- plan, the directory it starts in, and the program and arguments it+-- runs.  It is spawned as a builder is ("Nix.Builder"), with its+-- protocol around it ("Nix.Builder.Sandbox"): an empty environment, so the+-- loader reads no variable a derivation set; the plan on its standard+-- input, which stays open after it as the lifeline the helper kills the+-- build on the end of; its standard output the status channel; and+-- standard error the log.  On Linux the builder writes its own output to+-- the log as well; on macOS it writes to a pipe of the helper's, which+-- the helper copies into the log, so the log ends when the helper does.+-- The status is read once the log ends and the helper is gone, since it+-- holds at most one short record, which the pipe buffers.+--+-- Whatever ends the run early, an interrupt included, the end of the log+-- this reads is closed first, so that a helper or builder writing to the+-- log fails rather than waits on a reader that has stopped; then the+-- helper is terminated ('Proc.terminateProcess'), with @SIGTERM@, which it+-- answers by killing the builder, and waited for before this returns,+-- with asynchronous exceptions masked so a second one cannot cut the wait+-- short.  However the build ends, the helper ends its processes before it+-- exits.  On Linux the builder is PID 1 of its+-- namespace, which the kernel empties before PID 1 can be reaped, so no+-- process of the build is left.  On macOS the helper stops and kills+-- every process carrying the build's mark, which its profile alone+-- allows, including one that left the builder's group, and reports the+-- build as it ended only once a listing of the user's processes, taken+-- after every one of the build's it found had ended, finds none of the+-- build's left; where it cannot get there it fails the build, and a+-- process of the build may be left.  Neither holds if the helper is+-- killed by a signal no process can handle, though on Linux the builder+-- is set to die with the helper and takes its namespace with it, not+-- necessarily before this returns.+runHelper :: Logger -> FilePath -> ByteString -> FilePath -> [String] -> IO HelperRun+runHelper logger helper plan workDir command =+  bracket openLogPipe closePipe $ \(fromBuilder, toLog) ->+    E.mask $ \restore -> do+      (stdinEnd, stdoutEnd, _, process) <- Proc.createProcess (spawnWith toLog)+      let release = for_ stdinEnd hCloseQuietly *> for_ stdoutEnd hCloseQuietly+          stop = E.uninterruptibleMask_ (Proc.terminateProcess process *> void (Proc.waitForProcess process))+      outcome <-+        restore+          ( do+              delivered <- maybe (pure (Left "the sandbox helper has no standard input")) deliver stdinEnd+              streamBuildLog fromBuilder logger+              exitCode <- Proc.waitForProcess process+              status <- maybe (pure BS.empty) BS.hGetContents stdoutEnd+              pure (HelperRun delivered exitCode status)+          )+          `E.onException` (hCloseQuietly fromBuilder *> stop *> release)+      release+      pure outcome+  where+    spawnWith toLog =+      (Proc.proc helper (helperRunVerb : command))+        { Proc.cwd = Just workDir,+          Proc.env = Just [],+          Proc.std_in = Proc.CreatePipe,+          Proc.std_out = Proc.CreatePipe,+          Proc.std_err = Proc.UseHandle toLog,+          Proc.close_fds = closesInheritedDescriptors+        }+    closePipe (fromBuilder, toLog) = hClose fromBuilder *> hClose toLog+    -- A helper that ends before it reads the plan closes the pipe under+    -- the write; what it reported, if anything, says why.  The handle+    -- stays open: it is the lifeline.+    deliver planIn = do+      written <- try (BS.hPut planIn plan *> hFlush planIn)+      pure $ case written of+        Left (failure :: IOException) -> Left (T.pack (displayException failure))+        Right () -> Right ()+    -- Closing a pipe whose reader is gone can fail on the flush; the run+    -- is over either way.+    hCloseQuietly handle = hClose handle `E.catch` \(_ :: IOException) -> pure ()++-- | Whether the helper closes every descriptor past its standard ones as+-- it starts.  The builder it runs closes them before its exec, as+-- upstream's child does, but the helper itself runs for the whole build,+-- and a descriptor it held would keep what it names open: a daemon+-- client's socket, which its client would then not see closed when the+-- daemon closes its end, or another build's log, which would not end+-- when that build's builder does.  On Windows the process library+-- closes them only when the standard handles are inherited, which the+-- helper's are not.+closesInheritedDescriptors :: Bool+#if defined(mingw32_HOST_OS)+closesInheritedDescriptors = False+#else+closesInheritedDescriptors = True+#endif++-- | The helper's verbs: run a builder, and check that this system can+-- make the sandbox.+helperRunVerb, helperProbeVerb :: String+helperRunVerb = "run"+helperProbeVerb = "probe"++-- ---------------------------------------------------------------------------+-- The chroot+-- ---------------------------------------------------------------------------++-- | Where the chroot of a build whose directory is given lives: beside it,+-- in the store's state directory, so the outputs written inside move into+-- the store by a rename, as upstream's chroot sits in the store+-- (@startBuilder@ in local-derivation-goal.cc at 2.24.9).+chrootDirFor :: FilePath -> FilePath+chrootDirFor buildDir = buildDir <> ".chroot"++-- | The mount points at or beneath a directory, read from+-- @\/proc\/self\/mountinfo@'s text: the fifth field of each line, its+-- fields split at single spaces, as the kernel writes them, with the+-- kernel's octal escapes for a space, a tab, a newline and a backslash+-- undone.  The helper's walk of a bind's mounts reads the text the same+-- way (@sandbox\/mountinfo.c@).  A chroot's binds are mounts of the build's own namespace, gone+-- once the build is, so a mount point here means something was mounted+-- into the chroot from outside, and removing the chroot through it could+-- reach the store or the host.+mountPointsWithin :: ByteString -> ByteString -> [ByteString]+mountPointsWithin mountinfo dir =+  [point | line <- BS8.lines mountinfo, _ : _ : _ : _ : field : _ <- [BS8.split ' ' line], let point = unescape field, within point]+  where+    within point = point == dir || (dir <> "/") `BS.isPrefixOf` point+    unescape field = case BS8.break (== '\\') field of+      (plain, rest) -> case BS8.uncons rest of+        Nothing -> plain+        Just (_, afterSlash)+          | Just byte <- octal (BS.take 3 afterSlash) -> plain <> BS.singleton byte <> unescape (BS.drop 3 afterSlash)+          | otherwise -> plain <> "\\" <> unescape afterSlash+    octal digits+      | BS.length digits == 3, BS8.all (`elem` ['0' .. '7']) digits = Just (fromIntegral (BS.foldl' (\acc d -> acc * 8 + fromIntegral d - 48) (0 :: Int) digits))+      | otherwise = Nothing++-- | Close a sandboxed build's chroot to every other user, once its builder+-- has ended and no process is left in its PID namespace, and before+-- anything reads an output there.  A fixed-output build keeps the host's+-- network, so its builder can have opened a directory of the chroot to+-- everyone and passed another user a descriptor for it over an abstract+-- socket; with one, that user could rename entries while nova-nix walks,+-- copies and moves an output by path, and lead the walk out of the chroot.+--+-- From the root down to the store directory inside the chroot, each+-- directory has to be one of the invoking user's own, not a link, and is+-- made 0700.  Then every directory of the user's own in the store+-- directory's subtree, from the top down, is made 0700 too: no other+-- user can then write it, or reach through it a file the builder left+-- writable by everyone, and its owner can enter it, as the walk and what+-- reads the outputs after it need, if the builder closed it.  Nothing+-- needs another user to reach it before an output is made canonical and+-- moved into the store.  A directory is changed by its path, read without following a+-- link, and only once its parent is sealed, so no other user can point+-- that path elsewhere in between; the root's parent is no build's to+-- reach.  A directory another user owns is not entered: the build user's,+-- for a build that ran as one, whose processes are all killed before+-- anything reads an output, and any other's, which an output may not hold+-- ('Nix.Builder').  Nothing outside the store+-- directory's subtree is read, since registration reads nothing else and+-- the chroot's removal is descriptor-relative.+--+-- Answers the names of the store directory's entries the builder left+-- writable by others, read before the seal changes their modes, for the+-- refusal of an output others could have changed.+--+-- That closes the chroot to other users.  It does not close it to a+-- process of the same user, a concurrent build among them, which may+-- change anything there as the user may.+sealChroot :: FilePath -> FilePath -> IO (Either Text (Set FilePath))+#if defined(mingw32_HOST_OS)+sealChroot _ _ = pure (Left (unavailabilityCause PlatformUnsupported))+#else+sealChroot root storeDir = do+  user <- getEffectiveUserID+  let components = filter (`notElem` ["/", ""]) (splitDirectories storeDir)+      chain = scanl (</>) root components+      storeInChroot = foldl' (</>) root components+      ownDirectory status = isDirectory status && fileOwner status == user+      sealChain [] = pure (Right ())+      sealChain (path : rest) = do+        status <- E.try (getSymbolicLinkStatus path)+        case status of+          Right found | ownDirectory found -> setFileMode path privateMode *> sealChain rest+          Right _ -> pure (Left (replaced path))+          Left (_ :: IOException) -> pure (Left (replaced path))+      sealBelow path = do+        entries <- listDirectory path+        for_ entries $ \entry -> do+          let next = path </> entry+          status <- getSymbolicLinkStatus next+          when (ownDirectory status) $ do+            setFileMode next privateMode+            sealBelow next+      seal = do+        entries <- listDirectory storeInChroot+        marked <- traverse (\entry -> (,) entry <$> writableByOthers (storeInChroot </> entry)) entries+        sealBelow storeInChroot+        pure (Set.fromList [entry | (entry, True) <- marked])+  sealed <- E.try (sealChain chain >>= either (pure . Left) (const (Right <$> seal)))+  pure $ case sealed of+    Left (failure :: IOException) -> Left (T.pack ("cannot close the sandbox to other users: " <> displayException failure))+    Right result -> result+  where+    privateMode = 0o700+    replaced path = "the build replaced '" <> T.pack path <> "' in its sandbox, which holds its outputs, with something other than a directory of its own"+#endif++-- | Run a sandboxed build's action in its chroot, made empty and filled+-- with the skeleton: what an earlier build left at the name is removed+-- first, or moved aside where it cannot be ('clearLeftover'), and the+-- chroot is removed when the action ends, however it ends.  For a build+-- that runs as a build user, the group given is the build users': the+-- root and the store directory inside it are given to it, as upstream+-- gives them, so the builder can enter the one and write its outputs in+-- the other, while the directory holding the root stays closed to every+-- user but the one nova-nix runs as.+-- The action is given the chroot's root.  'Left' is why the chroot could+-- not be made.+--+-- Removal goes through @removePathForcibly@, which since directory 1.3.9+-- works relative to each directory's descriptor and never follows a link,+-- so a directory the build swapped for a link is unlinked, not entered.+-- It is refused while anything is mounted in the chroot+-- ('mountPointsWithin').+withChroot :: Logger -> FilePath -> Maybe Word32 -> [SkeletonEntry] -> (FilePath -> IO a) -> IO (Either Text a)+#if defined(mingw32_HOST_OS)+withChroot _ _ _ _ _ = pure (Left (unavailabilityCause PlatformUnsupported))+#else+withChroot logger buildDir buildGroup skeleton action = do+  leftover <- removeChroot (clearLeftover logger) parent+  case leftover of+    Left reason -> pure (Left reason)+    Right () -> do+      made <- try makeChroot+      case made of+        Left (failure :: IOException) -> do+          _ <- removeChroot removePathForcibly parent+          pure (Left ("cannot create the sandbox's root '" <> T.pack root <> "': " <> T.pack (show failure)))+        Right () -> Right <$> (action root `E.finally` removeQuietly)+  where+    parent = chrootDirFor buildDir+    root = parent </> "root"+    makeChroot = do+      createDirectory parent privateDir+      createDirectory root rootDir+      setFileMode root rootDir+      for_ buildGroup (toBuildGroup root)+      for_ skeleton (materialize root buildGroup)+    -- The removal runs as the build ends, where a chroot that will not+    -- go must not replace the build's own outcome; what it leaves is+    -- removed, or refused, by the next build of the derivation.+    removeQuietly = do+      outcome <- try (removeChroot removePathForcibly parent)+      case outcome of+        Left (_ :: IOException) -> pure ()+        Right _ -> pure ()+    privateDir = 0o700+    rootDir = 0o750++-- | Remove a chroot, unless something is mounted in it, by a removal of+-- the caller's: a leftover at the start of a build may be moved aside+-- ('clearLeftover').+removeChroot :: (FilePath -> IO ()) -> FilePath -> IO (Either Text ())+removeChroot remove parent = do+  parentBytes <- filePathBytes parent+  mountinfo <- E.try (BS.readFile "/proc/self/mountinfo")+  case either (\(_ :: IOException) -> []) (`mountPointsWithin` parentBytes) mountinfo of+    [] -> Right <$> remove parent+    point : _ -> pure (Left ("refusing to remove '" <> T.pack parent <> "', since '" <> TE.decodeUtf8Lenient point <> "' is mounted in it"))++-- | Make one skeleton entry beneath the root, given the build users'+-- group for a build that runs as a build user.+materialize :: FilePath -> Maybe Word32 -> SkeletonEntry -> IO ()+materialize root buildGroup entry = case entry of+  SkeletonDir path mode -> do+    at <- inRoot path+    createDirectoryIfMissing True at+    setFileMode at (fromIntegral mode :: FileMode)+  SkeletonStoreDir path -> do+    at <- inRoot path+    createDirectoryIfMissing True at+    setFileMode at storeDirMode+    for_ buildGroup (toBuildGroup at)+  SkeletonFile path contents -> do+    at <- inRoot path+    BS.writeFile at contents+  SkeletonLink path target -> do+    at <- inRoot path+    targetPath <- bytesFilePath target+    createSymbolicLink targetPath at+  where+    inRoot path = (root <>) <$> bytesFilePath path+    storeDirMode = 0o1775++-- | Give a directory nova-nix made to the build users' group, keeping its+-- owner.+toBuildGroup :: FilePath -> Word32 -> IO ()+toBuildGroup path group = do+  owner <- getEffectiveUserID+  setOwnerAndGroup path owner (fromIntegral group)+#endif++-- ---------------------------------------------------------------------------+-- The macOS profile's paths+-- ---------------------------------------------------------------------------++-- | What each of a macOS build's paths adds to its profile+-- ('profileFilter'), in order, each looked at with @lstat@ once its+-- target is known to be its source ('darwinPathTarget'): the first+-- refusal is the build's.+profileFilters :: [DarwinPath] -> IO (Either Text [ProfileFilter])+#if defined(mingw32_HOST_OS)+profileFilters _ = pure (Left (unavailabilityCause PlatformUnsupported))+#else+profileFilters paths = fmap catMaybes . sequence <$> traverse filterFor paths+  where+    filterFor path = case darwinPathTarget path of+      Left refusal -> pure (Left refusal)+      Right target -> profileFilter path <$> found target+    found target = do+      at <- bytesFilePath target+      status <- E.try (getSymbolicLinkStatus at)+      pure $ case status of+        Right present+          | isDirectory present -> FoundDirectory+          | otherwise -> FoundOther+        Left (failure :: IOException) -> LstatFailed (maybe 0 fromIntegral (ioe_errno failure))+#endif++-- | A path with its links, and its @.@ and @..@ components, resolved, as+-- a profile has to name it: macOS's sandbox matches the path a file+-- resolves to, not the one it was reached by.+resolvedPath :: ByteString -> IO ByteString+resolvedPath path = bytesFilePath path >>= canonicalizePath >>= filePathBytes++-- ---------------------------------------------------------------------------+-- Paths as bytes+-- ---------------------------------------------------------------------------++-- | A path's bytes: on POSIX what the file system encoding gives, which+-- returns a name read from the system to the bytes it was read from; on+-- Windows its UTF-8.+filePathBytes :: FilePath -> IO ByteString+#if defined(mingw32_HOST_OS)+filePathBytes = pure . TE.encodeUtf8 . T.pack+#else+filePathBytes path = do+  encoding <- getFileSystemEncoding+  GHC.withCStringLen encoding path BS.packCStringLen+#endif++-- | The path bytes name, the inverse of 'filePathBytes'.+bytesFilePath :: ByteString -> IO FilePath+#if defined(mingw32_HOST_OS)+bytesFilePath = pure . T.unpack . TE.decodeUtf8Lenient+#else+bytesFilePath bytes = do+  encoding <- getFileSystemEncoding+  BS.useAsCStringLen bytes (GHC.peekCStringLen encoding)+#endif
+ src/Nix/Builder/Settings.hs view
@@ -0,0 +1,283 @@+{-# LANGUAGE LambdaCase #-}++-- | The build configuration a store's settings give: the caches its+-- substituters and trusted keys name, what a failed substitute leads to,+-- whether a derivation's @allowSubstitutes@ is heeded, how many times a+-- download is tried, the cores a builder is told of, how builds are+-- sandboxed, whom they run as and what a failed build keeps, each with+-- upstream's default where no setting gives it.+--+-- The defaults that take the machine to find ('machineDefaults') are+-- found once, and what settings give is then pure+-- ('settingsBuildConfig'), so a daemon gives each operation the+-- configuration its connection's settings give without looking again.+-- The command line applies its flags to the settings first, as+-- upstream's flags set settings.+module Nix.Builder.Settings+  ( MachineDefaults (..),+    machineDefaults,+    settingsBuildConfig,+    configToCaches,+    settingsFallback,+    settingsSubstitutes,+    settingsFetchRetry,+  )+where++import Control.Applicative ((<|>))+import Control.Monad (filterM)+import qualified Data.ByteString as BS+import Data.Containers.ListUtils (nubOrd)+import Data.Maybe (fromMaybe, listToMaybe)+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Word (Word32)+import Nix.Builder (BuildConfig (..), defaultBuildConfig)+import Nix.Builder.BuildDir (FailedBuilds (..))+import Nix.Builder.BuildUser (ProcessPrivilege (..), buildUsersFor, defaultBuildUsersGroup, processPrivilege, userPoolDir)+import qualified Nix.Builder.Cores as Cores+import Nix.Builder.Sandbox (DropGroups (..), SandboxConfig (..), SandboxFallback (..), SandboxMode (..), ViolationLog (..), darwinImpureHostPrefixes, darwinSandboxPaths, parseSandboxPaths)+import Nix.Builder.Sandbox.Spawn (bytesFilePath, filePathBytes)+import Nix.Config (DefaultUse (..), NixConfig (..), PathSetValue (..))+import Nix.Environment (EnvLookup (..), lookupEnvBytes)+import Nix.Http (FetchRetryPolicy (..), defaultFetchRetryPolicy)+import Nix.Realise (Fallback (..), SubstitutesSetting (..))+import Nix.Store.Path (StoreDir)+import Nix.Substituter (CacheConfig (..), RequireSigs (..))+import Paths_nova_nix (getBinDir)+import System.Directory (doesFileExist)+import System.Environment (getExecutablePath)+import System.FilePath (takeDirectory, (</>))+import qualified System.Info++-- ---------------------------------------------------------------------------+-- The configuration+-- ---------------------------------------------------------------------------++-- | The defaults a build's settings fall back on that only the machine+-- can tell.+data MachineDefaults = MachineDefaults+  { -- | Upstream's default for @cores@, which a @cores@ of 0 gives as+    -- well: the limit of the process's cgroup, which upstream reads on+    -- Linux alone, else the hardware thread count.+    mdCores :: !Word32,+    -- | The sandbox helper: beside the executable, as a release archive+    -- and a @cabal install@ put it, or in Cabal's install directory.+    mdSandboxHelper :: !(Maybe FilePath),+    -- | The @sandbox-paths@ a release archive's bundled shell gives: the+    -- shell as @\/bin\/sh@ on Linux, where the archive carries one.+    mdSandboxShell :: !(Set BS.ByteString),+    -- | Whether the process runs as root, which builds as+    -- @build-users-group@'s members and turns+    -- @require-drop-supplementary-groups@ on by default.+    mdPrivilege :: !ProcessPrivilege,+    -- | The user pool's directory ('userPoolDir'), in @NIX_STATE_DIR@+    -- where that is set and not empty.+    mdUserPool :: !FilePath,+    -- | Upstream's @ssl-cert-file@ default: @NIX_SSL_CERT_FILE@, else+    -- @SSL_CERT_FILE@, when not empty, else the first of upstream's+    -- bundle paths that exists.+    mdCaFile :: !(Maybe BS.ByteString)+  }+  deriving (Eq, Show)++-- | Find the machine's defaults, its cgroup read through the reader+-- given.+machineDefaults :: Cores.ReadKernelFile IO -> IO MachineDefaults+machineDefaults readKernelFile = do+  exeDir <- takeDirectory <$> getExecutablePath+  binDir <- getBinDir+  MachineDefaults+    <$> (Cores.defaultCores <$> cgroupLimit <*> Cores.hardwareConcurrency)+    <*> (listToMaybe <$> filterM doesFileExist [exeDir </> sandboxHelperName, binDir </> sandboxHelperName])+    <*> bundledSandboxShell exeDir+    <*> processPrivilege+    <*> userPool+    <*> defaultSslCertFile+  where+    userPool =+      lookupEnvBytes "NIX_STATE_DIR" >>= \case+        EnvValue bytes | not (BS.null bytes) -> userPoolDir . Just <$> bytesFilePath bytes+        _ -> pure (userPoolDir Nothing)+    cgroupLimit+      | System.Info.os == "linux" = Cores.cgroupCoreLimit readKernelFile+      | otherwise = pure Nothing++-- | The build configuration settings give a store's builds on a machine.+settingsBuildConfig :: MachineDefaults -> NixConfig -> StoreDir -> BuildConfig+settingsBuildConfig defaults config storeDir =+  (defaultBuildConfig storeDir)+    { bcCaches = configToCaches config,+      bcFallback = settingsFallback config,+      bcSubstitutes = settingsSubstitutes config,+      bcFetchRetry = settingsFetchRetry config,+      bcCores = settingsCores defaults config,+      bcSandbox = sandboxConfig defaults config,+      bcBuildUsers = buildUsersFor privilege (mdUserPool defaults) (fromMaybe (defaultBuildUsersGroup privilege) (ncBuildUsersGroup config)),+      bcFailedBuilds = if ncKeepFailed config then KeepFailed else RemoveFailed+    }+  where+    privilege = mdPrivilege defaults++-- | The cores a builder is told of: the configured @cores@, or the+-- machine's default where it is 0 or nothing sets it, as upstream's+-- builder reads a 0 when it builds.+settingsCores :: MachineDefaults -> NixConfig -> Word32+settingsCores defaults config+  | Just count <- ncCores config, count > 0 = count+  | otherwise = mdCores defaults++-- | What a failed substitute leads to: a build from source under+-- @fallback@.+settingsFallback :: NixConfig -> Fallback+settingsFallback config+  | ncFallback config = BuildFromSource+  | otherwise = NoFallback++-- | Whether a derivation's @allowSubstitutes@ attribute is heeded: not+-- under @always-allow-substitutes@.+settingsSubstitutes :: NixConfig -> SubstitutesSetting+settingsSubstitutes config+  | ncAlwaysAllowSubstitutes config = AlwaysAllowSubstitutes+  | otherwise = HeedAllowSubstitutes++-- | How each download and upload is tried: the default policy with the+-- attempts @download-attempts@ gives, as upstream's one setting governs+-- every transfer.+settingsFetchRetry :: NixConfig -> FetchRetryPolicy+settingsFetchRetry config = defaultFetchRetryPolicy {frpAttempts = ncDownloadAttempts config}++-- ---------------------------------------------------------------------------+-- Caches+-- ---------------------------------------------------------------------------++-- | The priority a configured HTTP substituter is asked at+-- (cache.nixos.org is 40).  A @file:\/\/@ one is asked at the priority its+-- @nix-cache-info@ states ("Nix.Substituter").+substituterPriority :: Int+substituterPriority = 50++-- | The caches the settings name.  One t'CacheConfig' per substituter,+-- by its URL as configured, each carrying the whole trusted-key set, the+-- secret key files whose public keys are trusted too, and+-- @require-sigs@: upstream's keys are not bound to a substituter, so a+-- narinfo from any cache is accepted by any trusted key.  A substituter+-- with no trusted key anywhere is not refused here (it accepts nothing at+-- the signature gate), as upstream's @substituters@ and+-- @trusted-public-keys@ are independent.+--+-- A substituter listed again is dropped and the first listing keeps its+-- place, as upstream drops one it already has before it opens them, so a+-- cache is not asked a second time for a path it failed to deliver.  Two+-- listings are one when they are spelled alike.  Upstream compares them+-- once parsed, so spellings that differ only in percent-escapes, the+-- order of a query's parameters, a fragment or a port's leading zeros are+-- one substituter there and two here; one with a trailing slash and one+-- without are two in both.+configToCaches :: NixConfig -> [CacheConfig]+configToCaches config =+  [ CacheConfig+      { ccUrl = url,+        ccPublicKeys = ncTrustedPublicKeys config,+        ccSecretKeyFiles = ncSecretKeyFiles config,+        ccRequireSigs = if ncRequireSigs config then RequireSigs else AcceptUnsigned,+        ccPriority = substituterPriority+      }+  | url <- nubOrd (ncSubstituters config)+  ]++-- ---------------------------------------------------------------------------+-- The sandbox+-- ---------------------------------------------------------------------------++-- | How builds are sandboxed: the settings, with upstream's defaults+-- where one is unset.  @sandbox@ is on by default on Linux alone.+-- @sandbox-paths@ keeps a release archive's bundled shell, and macOS's+-- system paths ('darwinSandboxPaths'), unless a plain assignment replaces+-- it, as upstream's default names the shell a package was built with and+-- those paths; @allowed-impure-host-deps@ keeps upstream's macOS prefixes+-- the same way.  @require-drop-supplementary-groups@ is on for root.+sandboxConfig :: MachineDefaults -> NixConfig -> SandboxConfig+sandboxConfig defaults config =+  SandboxConfig+    { scMode = fromMaybe platformSandboxMode (ncSandbox config),+      scFallback = if ncSandboxFallback config then FallBackUnsandboxed else RefuseUnsandboxed,+      scPaths = parseSandboxPaths (withDefault (Set.union (mdSandboxShell defaults) platformSandboxPaths) (ncSandboxPaths config)),+      scBuildDir = ncSandboxBuildDir config,+      scDevShmSize = ncSandboxDevShmSize config,+      scDropGroups = if fromMaybe (mdPrivilege defaults == RunsAsRoot) (ncRequireDropSupplementaryGroups config) then RequireDropGroups else TolerateKeptGroups,+      scAllowedImpureHostDeps = withDefault platformImpureHostPrefixes (ncAllowedImpureHostDeps config),+      scViolationLog = if ncDarwinLogSandboxViolations config then ViolationsLogged else ViolationsUnlogged,+      scCaFile = ncSslCertFile config <|> mdCaFile defaults,+      scHelper = mdSandboxHelper defaults+    }+  where+    withDefault fallback setting = case psvDefault setting of+      KeepsDefault -> Set.union fallback (psvPaths setting)+      ReplacesDefault -> psvPaths setting++-- | Upstream's default for @sandbox@ on this platform.+platformSandboxMode :: SandboxMode+platformSandboxMode+  | System.Info.os == "linux" = SandboxEnabled+  | otherwise = SandboxDisabled++-- | The @sandbox-paths@ default beside a sandbox shell: on macOS the+-- system paths a build reads ('darwinSandboxPaths'), and elsewhere+-- nothing.+platformSandboxPaths :: Set BS.ByteString+platformSandboxPaths+  | System.Info.os == "darwin" = darwinSandboxPaths+  | otherwise = Set.empty++-- | Upstream's @allowed-impure-host-deps@ default: on macOS, the prefixes+-- a derivation's @__impureHostDeps@ may name a path beneath+-- ('darwinImpureHostPrefixes'), and elsewhere none.+platformImpureHostPrefixes :: Set BS.ByteString+platformImpureHostPrefixes+  | System.Info.os == "darwin" = darwinImpureHostPrefixes+  | otherwise = Set.empty++-- | The sandbox helper's file name.+sandboxHelperName :: FilePath+sandboxHelperName = "nova-nix-sandbox"++-- | Where a release archive keeps the shell a sandboxed build sees as+-- @\/bin\/sh@, relative to the directory holding @bin@.+bundledShellSubpath :: FilePath+bundledShellSubpath = "libexec" </> "nova-nix" </> "sh"++-- | The @sandbox-paths@ default: a release archive's bundled shell as+-- @\/bin\/sh@ on Linux, where the archive carries one, and otherwise+-- nothing, upstream's default for a Nix built without a sandbox shell.+bundledSandboxShell :: FilePath -> IO (Set BS.ByteString)+bundledSandboxShell exeDir+  | System.Info.os /= "linux" = pure Set.empty+  | otherwise = do+      let shell = takeDirectory exeDir </> bundledShellSubpath+      present <- doesFileExist shell+      Set.fromList <$> traverse (fmap ("/bin/sh=" <>) . filePathBytes) [shell | present]++-- | Upstream's @ssl-cert-file@ default: @NIX_SSL_CERT_FILE@ when it is+-- set, else @SSL_CERT_FILE@, when the value is not empty; else the first+-- of upstream's bundle paths that exists.+defaultSslCertFile :: IO (Maybe BS.ByteString)+defaultSslCertFile = do+  nixVariable <- lookupEnvBytes "NIX_SSL_CERT_FILE"+  plainVariable <- lookupEnvBytes "SSL_CERT_FILE"+  case (variableValue nixVariable, variableValue plainVariable) of+    (Just named, _) | not (BS.null named) -> pure (Just named)+    (Just _, _) -> firstBundle+    (Nothing, Just named) | not (BS.null named) -> pure (Just named)+    _ -> firstBundle+  where+    variableValue found = case found of+      EnvValue value -> Just value+      _ -> Nothing+    firstBundle = do+      present <- filterM doesFileExist sslCertFileDefaults+      traverse filePathBytes (listToMaybe present)++-- | Upstream's bundle paths, in the order it tries them.+sslCertFileDefaults :: [FilePath]+sslCertFileDefaults = ["/etc/ssl/certs/ca-certificates.crt", "/nix/var/nix/profiles/default/etc/ssl/certs/ca-bundle.crt"]
src/Nix/Builder/Unpack.hs view
@@ -1,15 +1,14 @@ {-# LANGUAGE ScopedTypeVariables #-} --- | __builtin:unpack__ - in-process archive extraction for the bootstrap seed.+-- | __builtin:unpack__ - in-process archive extraction for the Windows+-- bootstrap. -- -- == Why this is a builtin ----- The Windows bootstrap fetches archives into the store before any tool--- exists there: pre-built toolchain tarballs (MSYS2 @.pkg.tar.zst@--- packages) for the stdenv, and GitHub's @.tar.gz@ archives of the sources--- the full-source chain assembles.  Nothing in the store can unpack them ---- the unpacker is the thing being bootstrapped - and ambient @tar.exe@ is--- unpinned and may lack zstd support.  So, like+-- Before any tool exists in the store, the Windows bootstrap fetches+-- GitHub's @.tar.gz@ archives of the sources stage0-pe32's chain+-- assembles.  Nothing in the store can unpack them - the unpacker is the+-- thing being bootstrapped - and ambient @tar.exe@ is unpinned.  So, like -- 'Nix.Builder.runBuiltinFetchurl', extraction runs in-process: a -- derivation whose @builder@ is @builtin:unpack@ is handled by this module -- instead of being spawned as a subprocess.@@ -17,18 +16,18 @@ -- == Derivation interface -- -- * @srcs@ - whitespace-separated archive store paths, extracted in order---   into the single @out@ output.  MSYS2 packages share a top-level---   @mingw64\/@ prefix, so extracting a package set into one output yields a---   working toolchain root directly (no separate union step).+--   into the single @out@ output.+-- * @omit@ - optional, whitespace-separated paths of archive members left+--   out of the tree, each as an archive names its entries, from its root.+--   Each has to be in one of the archives: a path none holds fails the+--   build, so a list of members to leave out cannot go stale unnoticed. -- * @out@ - the merged tree. -- -- == Determinism -- -- Extraction is a pure function of the archive bytes: entries are written in--- archive order, a file appearing in two archives is an error (pacman--- enforces the same no-conflict invariant), and pacman's per-package--- metadata entries (@.PKGINFO@, @.MTREE@, ...) are skipped - they are not part--- of the installed tree and would otherwise collide across packages.+-- archive order, and a file appearing in two archives is an error, since+-- which one the tree kept would depend on their order in @srcs@. -- -- Symlink and hardlink entries are materialized by __copying__ their target: -- symlinks on Windows require elevation or Developer Mode, so a link in the@@ -40,6 +39,7 @@      -- * Derivation environment keys     envSrcs,+    envOmit,      -- * Extraction budget     UnpackLimits (..),@@ -57,16 +57,17 @@ import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Tar.Entry as TarEntry import qualified Codec.Compression.GZip as GZip-import qualified Codec.Compression.Zstd.Lazy as Zstd-import Control.Exception (ErrorCall, Handler (..), IOException, catches)+import Control.Exception (Handler (..), IOException, catches) import Control.Monad (when) import Data.Bits ((.&.)) import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BL import Data.Char (toLower) import Data.Int (Int64)-import Data.List (isPrefixOf, isSuffixOf)+import Data.List (intercalate, isSuffixOf) import qualified Data.Map.Strict as Map+import Data.Set (Set)+import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as TE@@ -101,13 +102,21 @@ envSrcs :: Text envSrcs = "srcs" +-- | Derivation environment key holding the whitespace-separated paths of+-- archive members to leave out of the tree.  A member's path holds no+-- whitespace where an archive this unpacks names it.+envOmit :: Text+envOmit = "omit"+ -- | Name of the output the merged tree is extracted into. unpackOutputName :: Text unpackOutputName = "out"  -- | Extraction budget for one @builtin:unpack@ build, across every--- archive in @srcs@: total bytes materialized and total filesystem--- entries created.  Archive bytes decompress and expand with no+-- archive in @srcs@: total bytes materialized and total entries made, one+-- per file, directory or link an archive lists and per entry a directory+-- link's copy makes; a parent directory only implied by an entry's path+-- is not counted.  Archive bytes decompress and expand with no -- relation to their compressed size, so extraction without a budget -- lets a small input produce an output with no upper bound. data UnpackLimits = UnpackLimits@@ -116,9 +125,8 @@   }   deriving (Eq, Show) --- | Default extraction budget: 4 GiB and one million entries.  The--- MSYS2 toolchain seed decompresses to well under half of either, and--- 4 GiB matches the largest NAR nova-cache's server accepts.+-- | Default extraction budget: 4 GiB, the largest NAR nova-cache's+-- server accepts, and one million entries. defaultUnpackLimits :: UnpackLimits defaultUnpackLimits =   UnpackLimits@@ -168,16 +176,17 @@ -- ---------------------------------------------------------------------------  -- | Run a @builtin:unpack@ derivation: extract every archive listed in its--- @srcs@ env into the @out@ output directory.  Returns the same--- @Either (exit, msg) ()@ shape as the process runner, so the shared--- output-validation and registration path in "Nix.Builder" is reused--- unchanged.+-- @srcs@ env into the @out@ output directory.  Returns+-- @Either (exit, msg) ()@, which "Nix.Builder" reports as a refused+-- builder, so the shared output-validation and registration path there is+-- reused unchanged. -- -- @srcs@ carries eval's canonical @\/nix\/store@ spelling, and the physical -- root may live elsewhere - @C:\\nix\\store@ on Windows, where a bare -- \/-rooted path resolves against the current DRIVE - so each entry is -- parsed as a store path and rendered through the store dir rather than--- opened verbatim (#101).  On Unix the rendering is the identity.+-- opened verbatim.  For a store at @\/nix\/store@ the rendering is the+-- identity. runBuiltinUnpack :: StoreDir -> UnpackLimits -> Derivation -> [(Text, FilePath)] -> IO (Either (Int, Text) ()) runBuiltinUnpack storeDir limits drv outputDirs =   case (Map.lookup envSrcs (drvEnv drv), lookup unpackOutputName outputDirs) of@@ -187,48 +196,65 @@       Left _ -> failure "'srcs' contains invalid UTF-8"       Right srcs         | null (T.words srcs) -> failure "'srcs' is empty"-        | otherwise -> case traverse resolveSrc (T.words srcs) of-            Left bad -> failure ("'srcs' entry is not a store path: " <> bad)-            Right archives -> case mOutDir of+        | otherwise -> case (traverse resolveSrc (T.words srcs), omitted) of+            (Left bad, _) -> failure ("'srcs' entry is not a store path: " <> bad)+            (_, Left msg) -> failure msg+            (Right archives, Right omit) -> case mOutDir of               Nothing -> failure "derivation defines no 'out' output"               Just outDir -> do                 createDirectoryIfMissing True outDir-                result <- unpackAll outDir limits archives+                result <- unpackAll outDir omit limits archives                 pure $ case result of                   Left msg -> Left (1, "builtin:unpack: " <> msg)-                  Right () -> Right ()+                  Right seen -> case Set.toList (Set.difference omit seen) of+                    [] -> Right ()+                    missing : _ -> Left (1, "builtin:unpack: 'omit' names " <> T.pack (joinMember missing) <> ", which no archive in 'srcs' holds")   where     failure msg = pure (Left (1, "builtin:unpack: " <> msg))     resolveSrc word = case parseStorePath defaultStoreDir word of       Just sp -> Right (storePathToFilePath storeDir sp)       Nothing -> Left word+    omitted = case Map.lookup envOmit (drvEnv drv) of+      Nothing -> Right Set.empty+      Just bytes -> case TE.decodeUtf8' bytes of+        Left _ -> Left "'omit' contains invalid UTF-8"+        Right paths -> Set.fromList <$> traverse omittedMember (T.words paths)+    omittedMember word = case entryComponents (T.unpack word) of+      Left err -> Left ("'omit': " <> err)+      Right [] -> Left ("'omit' names the archive root: " <> word)+      Right comps -> Right comps+    joinMember = intercalate "/" --- | Extract archives in order, stopping at the first failure.  One--- budget spans all of them: the caps bound the BUILD's output, not any--- single archive.-unpackAll :: FilePath -> UnpackLimits -> [FilePath] -> IO (Either Text ())-unpackAll _ _ [] = pure (Right ())-unpackAll outDir budget (archive : rest) = do-  result <- unpackArchive outDir budget archive+-- | Extract archives in order, stopping at the first failure, and return+-- the members of @omit@ they held and left out.  One budget spans all of+-- them: the caps bound the BUILD's output, not any single archive.+unpackAll :: FilePath -> Set [FilePath] -> UnpackLimits -> [FilePath] -> IO (Either Text (Set [FilePath]))+unpackAll outDir omit = go Set.empty+  where+    go seen _ [] = pure (Right seen)+    go seen budget (archive : rest) = do+      result <- unpackArchive outDir omit budget archive       case result of         Left err -> pure (Left err)-    Right remaining -> unpackAll outDir remaining rest+        Right (remaining, held) -> go (Set.union seen held) remaining rest --- | Unpack one archive into @outDir@, returning the budget left for the--- archives after it.  The decompressor is chosen by file extension; the--- tar stream is decoded (GNU + pax long names) and extracted entry by--- entry.  The archive is read lazily and decoded as the entries are--- forced, so a failure surfaces mid-extraction as an exception, and the--- whole extraction is wrapped to turn each kind into a clean failure: an--- 'IOException' reading the archive or writing the tree, the 'ErrorCall'--- the zstd decoder raises for a corrupt frame (its lazy API reports every--- decoding error with 'error'), or the 'GZip.DecompressError' the gzip--- decoder throws for a corrupt or truncated stream.-unpackArchive :: FilePath -> UnpackLimits -> FilePath -> IO (Either Text UnpackLimits)-unpackArchive outDir budget archivePath =+-- | Unpack one archive into @outDir@, leaving out the members @omit@+-- names, and return the budget left for the archives after it with the+-- members of @omit@ it held.  The decompressor is chosen by file+-- extension; the tar stream is decoded (GNU + pax long names) and+-- extracted entry by entry.  The archive is read whole, and its file+-- closed, before any of it is decoded, so no handle on it outlives the+-- extraction, whichever entry stops it: a lazy read would hold the file+-- open until a collection, and an open file on Windows cannot be deleted.+-- It is decompressed and decoded as the entries are forced, so a failure+-- surfaces mid-extraction as an exception, and the whole extraction is+-- wrapped to turn each kind into a clean failure: an 'IOException'+-- reading the archive or writing the tree, or the 'GZip.DecompressError'+-- the gzip decoder throws for a corrupt or truncated stream.+unpackArchive :: FilePath -> Set [FilePath] -> UnpackLimits -> FilePath -> IO (Either Text (UnpackLimits, Set [FilePath]))+unpackArchive outDir omit budget archivePath =   run     `catches` [ Handler (\(e :: IOException) -> failed e),-                Handler (\(e :: ErrorCall) -> failed e),                 Handler (\(e :: GZip.DecompressError) -> failed e)               ]   where@@ -236,17 +262,13 @@     run = case decoderFor archivePath of       Nothing -> pure (Left ("unsupported archive format: " <> T.pack archivePath))       Just decoder -> do-        raw <- BL.readFile archivePath-        extractEntries outDir budget (Tar.decodeLongNames (Tar.read (decoder raw)))+        raw <- BL.fromStrict <$> BS.readFile archivePath+        extractEntries outDir omit budget (Tar.decodeLongNames (Tar.read (decoder raw))) --- | Choose a decompressor from the archive file name.  @.tar.zst@ (MSYS2--- packages), @.tar.gz@ (GitHub's archive of a commit) and plain @.tar@ are--- supported.  MSYS2's zstd frames do not pledge a content size, so the lazy--- (streaming) zstd decoder is required - the strict single-shot API rejects--- them.+-- | Choose a decompressor from the archive file name: @.tar.gz@ (GitHub's+-- archive of a commit) and plain @.tar@ are supported. decoderFor :: FilePath -> Maybe (BL.ByteString -> BL.ByteString) decoderFor path-  | ".tar.zst" `isSuffixOf` lowered = Just Zstd.decompress   | ".tar.gz" `isSuffixOf` lowered = Just GZip.decompress   | ".tar" `isSuffixOf` lowered = Just id   | otherwise = Nothing@@ -257,31 +279,32 @@ -- Entry extraction -- --------------------------------------------------------------------------- --- | Walk the entry stream, extracting each entry under @outDir@ and--- threading the remaining extraction budget.-extractEntries :: FilePath -> UnpackLimits -> DecodedEntries -> IO (Either Text UnpackLimits)-extractEntries outDir = go+-- | Walk the entry stream, extracting each entry under @outDir@ but those+-- @omit@ names, threading the remaining extraction budget and the members+-- of @omit@ the stream held.  A member left out is not charged.+extractEntries :: FilePath -> Set [FilePath] -> UnpackLimits -> DecodedEntries -> IO (Either Text (UnpackLimits, Set [FilePath]))+extractEntries outDir omit = go Set.empty   where-    go budget stream = case stream of-      Tar.Done -> pure (Right budget)+    go seen budget stream = case stream of+      Tar.Done -> pure (Right (budget, seen))       Tar.Fail err -> pure (Left ("malformed archive: " <> T.pack (show err)))-      Tar.Next entry rest -> do+      Tar.Next entry rest -> case entryComponents (TarEntry.entryTarPath entry) of+        Right comps | Set.member comps omit -> go (Set.insert comps seen) budget rest+        _ -> do           result <- extractEntry outDir budget entry           case result of             Left err -> pure (Left err)-          Right remaining -> go remaining rest+            Right remaining -> go seen remaining rest  -- | Extract a single entry, after validating its path stays inside the--- archive root and skipping pacman package metadata.+-- archive root. extractEntry :: FilePath -> UnpackLimits -> DecodedEntry -> IO (Either Text UnpackLimits) extractEntry outDir budget entry =   case entryComponents (TarEntry.entryTarPath entry) of     Left err -> pure (Left err)     -- The archive root itself (an entry for "." or "./").     Right [] -> pure (Right budget)-    Right comps-      | isPackageMetadata comps -> pure (Right budget)-      | otherwise -> extractContent outDir budget comps entry+    Right comps -> extractContent outDir budget comps entry  -- | Extract a path-validated entry's content, charging every created -- entry and its bytes against the budget.  @comps@ is non-empty (the@@ -380,7 +403,7 @@ -- | Split a tar entry path into validated components: relative, no @..@, no -- @:@ (drive letters, NTFS alternate data streams).  Tar paths use @/@; -- 'splitDirectories' accepts both separators on Windows.  @.@ components are--- dropped, so @./mingw64@ and @mingw64@ agree.+-- dropped, so @./src@ and @src@ agree. entryComponents :: FilePath -> Either Text [FilePath] entryComponents raw   | isAbsolute raw = Left ("absolute entry path: " <> T.pack raw)@@ -423,22 +446,13 @@   (comp : _) -> not (null comp) && all isPathSeparator comp   [] -> False --- | pacman package metadata at the archive root (@.PKGINFO@, @.BUILDINFO@,--- @.MTREE@, @.INSTALL@): describes the package to pacman, is not part of the--- installed tree, and collides across packages when several archives merge--- into one output - so root-level dotfile entries are skipped.-isPackageMetadata :: [FilePath] -> Bool-isPackageMetadata comps = case comps of-  [name] -> "." `isPrefixOf` name-  _ -> False- -- --------------------------------------------------------------------------- -- Filesystem helpers -- --------------------------------------------------------------------------- --- | Guard that nothing was already extracted at @dest@.  Two archives in one--- seed providing the same file is a packaging error worth failing loudly on--- (pacman enforces the same no-conflict invariant between its packages).+-- | Guard that nothing was already extracted at @dest@: an entry whose+-- path another archive, or an earlier entry, already extracted fails the+-- build rather than leaving whichever came last. freshDestination :: FilePath -> IO (Either Text ()) freshDestination dest = do   exists <- doesPathExist dest
src/Nix/Builtins.hs view
@@ -1,8 +1,11 @@+{-# LANGUAGE LambdaCase #-}+ -- | Built-in function environment for the Nix evaluator. -- -- Every Nix expression has access to a @builtins@ attribute set containing -- ~100 functions.  This module assembles the initial t'Env' from the--- central registry in "Nix.Eval" and adds standard constants+-- builtins "Nix.Eval" defines ('Nix.Eval.listedBuiltins') and adds+-- standard constants -- (@true@, @false@, @null@, @storeDir@, @currentTime@, -- @currentSystem@, etc.), among them @derivation@: a Nix lambda over the -- @derivationStrict@ primop, evaluated from its source.@@ -11,10 +14,9 @@ -- (@addConstant@ skips an @impureOnly@ constant), so neither exists here -- then. ----- The environment is allocated in the C data layer, so 'builtinEnv' must--- be forced between 'Nix.Eval.Arena.arenaInit' and--- 'Nix.Eval.Arena.arenaDestroy'; outside that window forcing it raises--- 'Nix.Eval.CStatus.ArenaNotInitialized'.+-- The environment is allocated in the C data layer, so 'builtinEnv' runs+-- in an evaluation session ('Nix.Eval.IO.withEvalSession'); outside one+-- it raises 'Nix.Eval.CStatus.ArenaNotInitialized'. module Nix.Builtins   ( -- * Builtin registration     builtinEnv,@@ -36,17 +38,22 @@ import Data.Int (Int64) import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map-import Data.Maybe (fromMaybe, mapMaybe)+import Data.Maybe (catMaybes, fromMaybe) import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as TE-import Foreign.Ptr (nullPtr)-import Nix.Eval (Env (..), NixValue (..), Thunk (..), attrSetFromMap, attrSetLookup, builtinNames, currentSystemStr, deferApply, evaluated, readThunkValue)-import Nix.Eval.Types (AttrSet, EvalPolicy (..), cheapThunk, clistFromThunks, mkStr, mkStrBytes, newCEnv, thunkToCPtr)+import Nix.Eval (Env (..), NixValue (..), Thunk (..), attrSetFromMap, attrSetLookup, currentSystemStr, deferApply, evaluated, listedBuiltins, readThunkValue)+import Nix.Eval.AllocSite (EnvSite (EnvRoot), SetSite (SetRoot))+import Nix.Eval.Builtin (Builtin, builtinIndex, builtinName, builtinNamed)+import qualified Nix.Eval.Builtin as Builtin+import Nix.Eval.CData (MonadCData, cdataIO)+import Nix.Eval.CStatus (cInvariantViolated)+import Nix.Eval.CThunk (cthunkPrimop)+import Nix.Eval.Types (AttrSet, EvalPolicy (..), cheapThunk, clistFromThunks, mkStr, mkStrBytes, newScopeEnv) import Nix.Expr.Resolve (impureOnlyGlobalNames, staticGlobalNames)-import Nix.Parser (SourceOrigin (..), parseNixWithScope)+import Nix.Parser (SourceOrigin (..), parseNixWithScope, parsedExpr) import Nix.Store.Path (defaultStoreDirText)  -- | The initial environment: every name upstream's base environment binds@@ -55,6 +62,11 @@ -- @addConstant@ install one value under both (eval.cc at 2.24.9).  So -- @__typeOf@ is @builtins.typeOf@, and @map@ is @builtins.map@. --+-- An evaluation session builds it once ('Nix.Eval.IO.withEvalSession') and+-- evaluates every file it imports in it, as upstream's @createBaseEnv@+-- builds one base environment per @EvalState@; the @derivation@ wrapper+-- in it is the session's one.+-- -- @fetchMercurial@ is the one name upstream binds by default that nova-nix -- does not implement: it is bound as a builtin of that name, so binding -- accepts it and a call fails with the evaluator's unknown-builtin error.@@ -67,16 +79,19 @@ -- by 'parseNixPath'.  In tests, pass @[]@. -- -- The policy decides which constants exist: see 'standardEntries'.-builtinEnv :: EvalPolicy -> Int64 -> [Thunk] -> Env-builtinEnv policy timestamp searchPaths =-  let builtinsSet = builtinsAttrSet policy timestamp searchPaths-      bind name+builtinEnv :: (MonadCData m) => EvalPolicy -> Int64 -> [Thunk] -> m Env+builtinEnv policy timestamp searchPaths = do+  builtinsSet <- builtinsAttrSet policy timestamp searchPaths+  let bind name         | name == "builtins" = evaluated (VAttrs builtinsSet)-        | otherwise =+        | otherwise = do             let unprefixed = fromMaybe name (T.stripPrefix "__" name)-             in fromMaybe (evaluated (VBuiltin unprefixed [])) (attrSetLookup unprefixed builtinsSet)-      scope = attrSetFromMap (Map.fromSet bind (rootScopeNames policy))-   in newCEnv nullPtr 0 (Just scope) Nothing nullPtr 0+            attrSetLookup unprefixed builtinsSet >>= maybe (unlisted unprefixed) pure+      unlisted unprefixed = case builtinNamed unprefixed of+        Just builtin -> builtinFunction builtin+        Nothing -> cdataIO (cInvariantViolated "builtinEnv" ("the root name " ++ show unprefixed ++ " is neither in builtins nor a builtin"))+  scope <- sequenceA (Map.fromSet bind (rootScopeNames policy)) >>= attrSetFromMap SetRoot+  newScopeEnv EnvRoot Nothing scope  -- | The names the root environment binds under a policy: upstream's base -- environment, which leaves out its @impureOnly@ constants under@@ -86,35 +101,41 @@   | epPureEval policy = staticGlobalNames `Set.difference` impureOnlyGlobalNames   | otherwise = staticGlobalNames --- | Create a top-level binding for a builtin function.-topLevelBuiltin :: Text -> (Text, Thunk)-topLevelBuiltin name = (name, evaluated (VBuiltin name []))+-- | The value of a builtin function bound under its own name: the+-- builtin's shared cell, so every environment 'builtinEnv' builds binds+-- the same one, as upstream binds one value per primop in its base+-- environment (@EvalState::addPrimOp@, eval.cc at 2.24.9).  A builtin+-- read in one file is then the same value as the same builtin read in+-- another, which @==@ shows of sets copied out of @builtins@ in two+-- files.  The cell is a C static ('Nix.Eval.CThunk.cthunkPrimop'), so it+-- is the same in every arena window.+builtinFunction :: (MonadCData m) => Builtin -> m Thunk+builtinFunction = fmap Thunk . cthunkPrimop . builtinIndex --- | Like 'builtinEnv' but with additional scope bindings overlaid on--- the top-level environment.  Used by @scopedImport@.-builtinEnvWithScope :: EvalPolicy -> Int64 -> [Thunk] -> [(Text, Thunk)] -> Env-builtinEnvWithScope policy timestamp searchPaths scope =-  let base = builtinEnv policy timestamp searchPaths-      scopeMap = Map.fromList scope-   in newCEnv nullPtr 0 (Just (attrSetFromMap scopeMap)) (Just base) nullPtr 0+-- | A base environment with a set's names bound over it, each to its+-- value in the set, as @scopedImport@ binds its scope.  The set is the+-- environment's name table, as upstream binds the scope's own values in+-- the environment it evaluates the file in (@import@ in primops.cc at+-- 2.24.9, @scopedImport@ there at 2.36.0).+builtinEnvWithScope :: (MonadCData m) => Env -> AttrSet -> m Env+builtinEnvWithScope base = newScopeEnv EnvRoot (Just base) --- | The @builtins@ attribute set, derived from the central registry.-builtinsAttrSet :: EvalPolicy -> Int64 -> [Thunk] -> AttrSet-builtinsAttrSet policy timestamp searchPaths =-  attrSetFromMap $ Map.union builtinEntries (standardEntries policy timestamp searchPaths)-  where-    builtinEntries =-      Map.fromList [(name, evaluated (VBuiltin name [])) | name <- builtinNames]+-- | The @builtins@ attribute set: every builtin it lists and the constants.+builtinsAttrSet :: (MonadCData m) => EvalPolicy -> Int64 -> [Thunk] -> m AttrSet+builtinsAttrSet policy timestamp searchPaths = do+  standard <- standardEntries policy timestamp searchPaths+  functions <- sequenceA (Map.fromList [(builtinName builtin, builtinFunction builtin) | builtin <- listedBuiltins])+  attrSetFromMap SetRoot (Map.union functions standard) --- | The constants beside the registry.  @currentTime@ and @currentSystem@+-- | The constants beside the builtin functions.  @currentTime@ and @currentSystem@ -- are upstream's @impureOnly@ constants and are absent under @pure-eval@ -- (@builtins ? currentTime@ is @false@ there, observed from -- nix-instantiate 2.33.2); @nixPath@ stays, holding whatever search path -- the caller passed, which under @pure-eval@ is what upstream leaves of -- it.-standardEntries :: EvalPolicy -> Int64 -> [Thunk] -> Map.Map Text Thunk+standardEntries :: (MonadCData m) => EvalPolicy -> Int64 -> [Thunk] -> m (Map.Map Text Thunk) standardEntries policy timestamp searchPaths =-  Map.fromList $+  fmap Map.fromList . traverse sequenceA $     [ ("true", evaluated (VBool True)),       ("false", evaluated (VBool False)),       ("null", evaluated VNull),@@ -124,7 +145,7 @@       ("storeDir", evaluated (mkStr defaultStoreDirText)),       ("nixVersion", evaluated (mkStr targetNixVersion)),       ("langVersion", evaluated (VInt 6)),-      ("nixPath", evaluated (VList (clistFromThunks (map thunkToCPtr searchPaths)))),+      ("nixPath", clistFromThunks (map unThunk searchPaths) >>= evaluated . VList),       ("derivation", derivationWrapper)     ]       ++ [("currentTime", evaluated (VInt timestamp)) | not (epPureEval policy)]@@ -163,35 +184,34 @@ -- shares what upstream's does: an output's set is one value in @all@, -- under its name and as the result, and each output has a @drvPath@ of -- its own.  The attributes it defines are at this text's lines, which--- differ from upstream's.  Its identifiers differ too, and compiling it--- interns them before any file a program imports, as upstream's startup--- interns its wrapper's: an error that names attributes in interning order--- (an unexpected argument, the keys of a set missing an attribute) can--- name another first than upstream's identifiers would make it.+-- differ from upstream's.  Its identifiers are upstream's (@strict@,+-- @commonAttrs@, @outputsList@ and @x@), which the evaluator interns as+-- it starts ("Nix.Eval.StartupSymbols"), so compiling it interns no name,+-- wherever in an evaluation it compiles. derivationWrapperSource :: ByteString derivationWrapperSource =   BC.unlines     [ "{ outputs ? [ \"out\" ], ... }@drvAttrs:",       "let",-      "  paths = derivationStrict drvAttrs;",-      "  entries = map (outputName: {",+      "  strict = derivationStrict drvAttrs;",+      "  outputsList = map (outputName: {",       "    name = outputName;",-      "    value = shared // {",+      "    value = commonAttrs // {",       "      type = \"derivation\";",       "      inherit outputName;",-      "      drvPath = paths.drvPath;",-      "      outPath = builtins.getAttr outputName paths;",+      "      drvPath = strict.drvPath;",+      "      outPath = builtins.getAttr outputName strict;",       "    };",       "  }) outputs;",-      "  shared =",+      "  commonAttrs =",       "    drvAttrs",-      "    // builtins.listToAttrs entries",+      "    // builtins.listToAttrs outputsList",       "    // {",       "      inherit drvAttrs;",-      "      all = map (entry: entry.value) entries;",+      "      all = map (x: x.value) outputsList;",       "    };",       "in",-      "(builtins.head entries).value"+      "(builtins.head outputsList).value"     ]  -- | Where the wrapper's source is: upstream evaluates its wrapper as the@@ -206,41 +226,35 @@ -- the wrapper reads, so the constant needs no knot through 'builtinEnv'. -- The wrapper is bound against these names too, so it cannot read one the -- slice lacks.-derivationWrapperScope :: Map Text Thunk-derivationWrapperScope =-  let builtinsUsed = ["getAttr", "head", "listToAttrs"]-   in Map.fromList-        [ ("derivationStrict", evaluated (VBuiltin "derivationStrict" [])),-          ("map", evaluated (VBuiltin "map" [])),-          ("builtins", evaluated (VAttrs (attrSetFromMap (Map.fromList (map topLevelBuiltin builtinsUsed)))))+derivationWrapperScope :: (MonadCData m) => m (Map Text Thunk)+derivationWrapperScope = do+  builtinsUsed <- sequenceA (Map.fromList [(builtinName builtin, builtinFunction builtin) | builtin <- [Builtin.GetAttr, Builtin.Head, Builtin.ListToAttrs]])+  builtinsSet <- attrSetFromMap SetRoot builtinsUsed+  sequenceA $+    Map.fromList+      [ ("derivationStrict", builtinFunction Builtin.DerivationStrict),+        ("map", builtinFunction Builtin.Map),+        ("builtins", evaluated (VAttrs builtinsSet))       ]-{-# NOINLINE derivationWrapperScope #-} --- | 'derivationWrapperScope' as the wrapper's environment.-derivationWrapperEnv :: Env-derivationWrapperEnv =-  newCEnv nullPtr 0 (Just (attrSetFromMap derivationWrapperScope)) Nothing nullPtr 0-{-# NOINLINE derivationWrapperEnv #-}- -- | The @derivation@ constant: the wrapper lambda closed over--- 'derivationWrapperEnv'.  One value bound in both the root scope and--- @builtins@, as upstream's @addConstant@ binds it.  It is compiled once--- for the process rather than once per environment: 'builtinEnv' runs for--- every imported file, and the arena the lambda lives in is the process's--- ("Nix.Eval.Arena").  The source is a constant, so a parse failure is a--- defect in this module; it surfaces as an abort at the first use of+-- 'derivationWrapperScope'.  One value bound in both the root scope and+-- @builtins@ of the base environment it is made for, as upstream's+-- @addConstant@ binds it.  The source is a constant, so a parse failure+-- is a defect in this module; it surfaces as an abort at the first use of -- @derivation@ rather than as a crash while the environment is assembled.-derivationWrapper :: Thunk-derivationWrapper =-  case parseNixWithScope (Map.keysSet derivationWrapperScope) "/" derivationWrapperOrigin derivationWrapperSource of-    Right expr -> cheapThunk derivationWrapperEnv expr+derivationWrapper :: (MonadCData m) => m Thunk+derivationWrapper = do+  scope <- derivationWrapperScope+  env <- attrSetFromMap SetRoot scope >>= newScopeEnv EnvRoot Nothing+  case parseNixWithScope (Map.keysSet scope) "/" derivationWrapperOrigin derivationWrapperSource of+    Right parsed -> cheapThunk env (parsedExpr parsed)     Left err -> abortingThunk ("the derivation wrapper does not parse: " <> T.pack (show err))-{-# NOINLINE derivationWrapper #-}  -- | A thunk that aborts evaluation with the message when forced: @abort@ -- applied to it, deferred the way "Nix.Eval" defers any application.-abortingThunk :: Text -> Thunk-abortingThunk message = deferApply (VBuiltin "abort" []) (evaluated (mkStr message))+abortingThunk :: (MonadCData m) => Text -> m Thunk+abortingThunk message = evaluated (mkStr message) >>= deferApply (VBuiltin Builtin.Abort [])  -- --------------------------------------------------------------------------- -- NIX_PATH parsing@@ -252,30 +266,26 @@ -- Format: colon-separated entries, each either @name=path@ or plain @path@, -- split at the first @=@.  A plain path gets an empty prefix (matching -- real Nix behaviour).  The prefix and path keep the entry's bytes, as--- upstream's @LookupPath::Elem::parse@ keeps them--- (src/libexpr/search-path.cc at Nix 2.24.9).+-- upstream Nix keeps them. ----- >>> parseNixPath "nixpkgs=/home/user/nixpkgs:custom=/opt/custom"--- [Evaluated (VAttrs {"prefix": "nixpkgs", "path": "/home/user/nixpkgs"}), ...]-parseNixPath :: ByteString -> [Thunk]+-- @parseNixPath "nixpkgs=\/home\/user\/nixpkgs:custom=\/opt\/custom"@ gives+-- two evaluated thunks, @{ prefix = "nixpkgs"; path =+-- "\/home\/user\/nixpkgs"; }@ and @{ prefix = "custom"; path =+-- "\/opt\/custom"; }@.+parseNixPath :: (MonadCData m) => ByteString -> m [Thunk] parseNixPath raw-  | BS.null raw = []-  | otherwise = map parseEntry (splitNixPath raw)+  | BS.null raw = pure []+  | otherwise = mapM parseEntry (splitNixPath raw)   where-    parseEntry entry =+    parseEntry entry = do       let (prefix, path) = case BC.break (== '=') entry of             (before, after)               | BS.null after -> ("", before)               | otherwise -> (before, BS.drop 1 after)-       in evaluated-            ( VAttrs-                ( attrSetFromMap $-                    Map.fromList-                      [ ("prefix", evaluated (mkStrBytes prefix)),-                        ("path", evaluated (mkStrBytes path))-                      ]-                )-            )+      prefixThunk <- evaluated (mkStrBytes prefix)+      pathThunk <- evaluated (mkStrBytes path)+      attrs <- attrSetFromMap SetRoot (Map.fromList [("prefix", prefixThunk), ("path", pathThunk)])+      evaluated (VAttrs attrs)  -- | The @path@ of every search path entry 'parseNixPath' produced, for the -- restricted-mode allow list: upstream allows every lookup path root@@ -283,17 +293,19 @@ -- read back from the very list the evaluator will search.  A root is the -- bytes the entry holds.  An entry that is not an attribute set with a -- string or path @path@ contributes nothing.-searchPathRoots :: [Thunk] -> [ByteString]-searchPathRoots = mapMaybe entryRoot+searchPathRoots :: (MonadCData m) => [Thunk] -> m [ByteString]+searchPathRoots = fmap catMaybes . mapM entryRoot   where-    entryRoot thunk = do-      VAttrs attrs <- readThunkValue thunk-      pathThunk <- attrSetLookup "path" attrs-      pathVal <- readThunkValue pathThunk-      case pathVal of-        VStr bytes _ -> Just bytes-        VPath p -> Just (TE.encodeUtf8 p)-        _ -> Nothing+    entryRoot thunk =+      readThunkValue thunk >>= \case+        Just (VAttrs attrs) ->+          attrSetLookup "path" attrs >>= \case+            Just pathThunk -> (>>= rootBytes) <$> readThunkValue pathThunk+            Nothing -> pure Nothing+        _ -> pure Nothing+    rootBytes (VStr bytes _) = Just bytes+    rootBytes (VPath p) = Just (TE.encodeUtf8 p)+    rootBytes _ = Nothing  -- | URL schemes that keep a @NIX_PATH@ entry whole when @://@ follows -- them: the allowlist in @EvalSettings::isPseudoUrl@,
+ src/Nix/CacheDirectory.hs view
@@ -0,0 +1,335 @@+{-# LANGUAGE ScopedTypeVariables #-}++-- | A binary cache in a local directory, as upstream's @file:\/\/@ store+-- reads and writes one: the URL that names it, the @nix-cache-info@ at its+-- root, the directories it holds, and the files a narinfo may name in it.+-- A push writes such a cache ("Nix.Push.Directory") and a substitution+-- reads one ("Nix.Substituter"), and both open it the same way first, as+-- upstream opens its store the same way for either.+--+-- == Opening+--+-- Opening a cache makes its @nar@, @build-trace-v2@ and @log@ directories,+-- writes a @nix-cache-info@ holding @StoreDir: \/nix\/store@ alone where+-- the directory has none, and reads the one it has ('openCacheDirectory').+-- Upstream's store makes those directories whenever it opens a cache, to+-- read it as well as to write, and making a directory that is there needs+-- no write access.  A reader that cannot make a missing one drops the+-- cache with a warning, so a push makes them all for a reader without+-- write access to the directory, and also the @realisations@ directory+-- that older upstream releases name in place of @build-trace-v2@+-- ('realisationsDirName'), for a reader of either.+module Nix.CacheDirectory+  ( -- * Naming a cache+    fileUrlDirectory,+    directoryUrl,++    -- * Opening a cache+    CacheInfo (..),+    CacheOpenFailure (..),+    cacheOpenFailureMessage,+    openCacheDirectory,++    -- * Files in a cache+    realisationsDirName,+    cacheFilePath,+    writeCacheFile,++    -- * Pure pieces (exported for tests)+    cacheInfoFileName,+    cacheInfoText,+    readCacheInfo,+    parsePriority,+  )+where++import Control.Exception (IOException, bracketOnError, catch, displayException, handle, tryJust)+import Control.Monad (foldM, guard)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BC+import Data.Char (isAsciiLower, isAsciiUpper, isDigit)+import Data.Int (Int32)+import Data.List (stripPrefix)+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import qualified Data.Text.Encoding.Error as TE+import Nix.Push (narDirSegment)+import Nix.Store.Path (defaultStoreDirText)+import System.Directory (createDirectoryIfMissing, removeFile, renameFile)+import System.FilePath (dropTrailingPathSeparator, hasDrive, isAbsolute, isPathSeparator, splitDirectories, takeDirectory, takeFileName, (</>))+import System.IO (Handle, hClose, openBinaryTempFileWithDefaultPermissions)+import System.IO.Error (isDoesNotExistError)+import Text.Read (readMaybe)++-- ---------------------------------------------------------------------------+-- Naming a cache+-- ---------------------------------------------------------------------------++-- | The scheme of a URL that names a directory.+fileScheme :: String+fileScheme = "file://"++-- | The directory a @file:\/\/@ URL names, or why it names none, and+-- 'Nothing' for a URL of another scheme.  The URL names an absolute path+-- after an empty host, the form upstream's grammar gives a @file:\/\/@ URL,+-- which refuses any host; upstream reads @file:\/\/@ alone as the root+-- directory.  A URL naming a filesystem root, that one or @file:\/\/\/@ or a+-- drive's root, is refused here, as a cache in a root is a variable that+-- expanded to nothing.  A query, a fragment or a percent-escape is refused+-- rather than read: upstream takes the query as the store's settings and+-- decodes escapes, so each would name another cache there.  The refusal+-- ends with the given words, which say how the caller takes what a query+-- would set.  A URL without them that upstream parses names the same+-- directory in both.  A Windows drive path is written with a slash before+-- the drive, @file:\/\/\/C:\/cache@ (RFC 8089, appendix E.2), so where that+-- names no absolute path and the drive path does, on Windows, the slash is+-- dropped.+fileUrlDirectory :: Text -> String -> Maybe (Either Text FilePath)+fileUrlDirectory settingsHint url = named <$> stripPrefix fileScheme url+  where+    shown = T.pack url+    named path+      | any (`elem` unreadUrlCharacters) path =+          Left ("a file:// URL with a query, a fragment or a percent-escape is not read here; name the directory as it is spelled, and " <> settingsHint <> ": " <> shown)+      | otherwise = case absoluteAfterHost path of+          Nothing -> Left ("a file:// URL names an absolute path after an empty host, as file:///srv/cache does, or file:///C:/cache on Windows: " <> shown)+          Just found+            | isRoot found -> Left ("a file:// URL names a directory below a filesystem root, as a variable that expanded to nothing leaves the root: " <> shown)+            | otherwise -> Right found+    isRoot candidate = let trimmed = dropTrailingPathSeparator candidate in takeDirectory trimmed == trimmed+    -- The empty host is the slash that begins the path; without it the+    -- URL names a host, even where what follows is a drive path.+    absoluteAfterHost path = case path of+      '/' : drivePath@(letter : ':' : _)+        | isAsciiUpper letter || isAsciiLower letter,+          isAbsolute drivePath ->+            Just drivePath+      '/' : _ | isAbsolute path -> Just path+      _ -> Nothing++-- | The characters that begin a URL's query, fragment and percent-escapes.+unreadUrlCharacters :: String+unreadUrlCharacters = "?#%"++-- | The @file:\/\/@ URL of a directory 'fileUrlDirectory' accepts, spelled+-- as upstream spells one: with a slash before a Windows drive, and each+-- path separator a slash.+directoryUrl :: FilePath -> Text+directoryUrl dir = T.pack (fileScheme <> driveSlash <> map slashed dir)+  where+    driveSlash = case dir of+      letter : ':' : _ | isAsciiUpper letter || isAsciiLower letter -> "/"+      _ -> ""+    slashed c+      | isPathSeparator c = '/'+      | otherwise = c++-- ---------------------------------------------------------------------------+-- Opening a cache+-- ---------------------------------------------------------------------------++-- | What a cache's @nix-cache-info@ says that nova-nix reads.+newtype CacheInfo = CacheInfo+  { -- | Where a substitution asks the cache among the others, lower+    -- first, when the cache states it.+    ciPriority :: Maybe Int+  }+  deriving (Eq, Show)++-- | Why a cache could not be opened, told apart as upstream tells them+-- apart: a substitution passes over a cache it cannot open, with a+-- warning, while a @Priority@ upstream cannot read as a number fails the+-- command that opens the cache.+data CacheOpenFailure+  = -- | Its directories or its @nix-cache-info@ could not be made or+    -- read, or it is for another store directory.+    CacheUnopenable !Text+  | -- | Its @nix-cache-info@ states a @Priority@ that is not a number,+    -- said in nova-nix's words: upstream's command fails with only the+    -- C++ library's text for the failed conversion.+    CachePriorityInvalid !Text+  deriving (Eq, Show)++-- | What a t'CacheOpenFailure' says.+cacheOpenFailureMessage :: CacheOpenFailure -> Text+cacheOpenFailureMessage failure = case failure of+  CacheUnopenable message -> message+  CachePriorityInvalid message -> message++-- | Open the cache in a directory, named by its URL in what this says:+-- make its directories, write its @nix-cache-info@ where it has none, and+-- read the one it has ('readCacheInfo').  A directory or file that cannot+-- be made or read is a 'CacheUnopenable', which names the cache.+openCacheDirectory :: Text -> FilePath -> IO (Either CacheOpenFailure CacheInfo)+openCacheDirectory url dir = handle unopenable $ do+  mapM_ (createDirectoryIfMissing True . (dir </>)) cacheDirectories+  existing <- tryJust (guard . isDoesNotExistError) (BS.readFile file)+  case existing of+    Left () -> Right (CacheInfo Nothing) <$ writeCacheFile file cacheInfoText+    Right contents -> pure (readCacheInfo url contents)+  where+    file = dir </> cacheInfoFileName+    unopenable (err :: IOException) =+      pure (Left (CacheUnopenable ("cannot open binary cache '" <> url <> "': " <> T.pack (displayException err))))++-- | The directories upstream's @file:\/\/@ store makes in every cache it+-- opens: the NARs', and those a push leaves empty, the realisations+-- directory under the name the newest upstream release gives it.+cacheDirectories :: [FilePath]+cacheDirectories = [T.unpack narDirSegment, buildTraceDirName, logDirName]++-- | The directory of content-addressed derivations' realisations, as+-- older upstream releases name it, which a push makes beside+-- @build-trace-v2@ so a reader of an older release that cannot write+-- opens the cache.  A substitution makes only the newer name, as the+-- newest release does, so it opens a cache without this one that it+-- cannot write to.+realisationsDirName :: FilePath+realisationsDirName = "realisations"++-- | The directory of content-addressed derivations' realisations, as the+-- newest upstream release names it.+buildTraceDirName :: FilePath+buildTraceDirName = "build-trace-v2"++-- | The directory of build logs.+logDirName :: FilePath+logDirName = "log"++-- ---------------------------------------------------------------------------+-- nix-cache-info+-- ---------------------------------------------------------------------------++-- | The file at a binary cache's root that names the store directory its+-- paths are in.+cacheInfoFileName :: FilePath+cacheInfoFileName = "nix-cache-info"++-- | The field of @nix-cache-info@ naming the store directory.+storeDirField :: BS.ByteString+storeDirField = "StoreDir"++-- | The field of @nix-cache-info@ giving the cache's priority.+priorityField :: BS.ByteString+priorityField = "Priority"++-- | What opening a directory writes as @nix-cache-info@ where it has none:+-- the store directory alone, as upstream writes it.  The narinfos name+-- paths in the canonical store directory whatever directory the local+-- store is in, so this is @\/nix\/store@ on every host.+cacheInfoText :: BS.ByteString+cacheInfoText = storeDirField <> ": " <> TE.encodeUtf8 defaultStoreDirText <> "\n"++-- | Read a @nix-cache-info@ as upstream reads it, the cache named by its+-- URL in what a refusal says: each line with a colon is a field, its name+-- what comes before the first colon and its value the rest trimmed of+-- spaces, tabs, carriage returns and newlines, and the fields are read in+-- order, so the first one refused is the refusal.  A @StoreDir@ other than+-- @\/nix\/store@ refuses the cache in upstream's words.  The last+-- @Priority@ is the cache's priority, read as 'parsePriority' reads it,+-- and one that does not read is a 'CachePriorityInvalid'.  Upstream's+-- @WantMassQuery@ is not read: it says whether to ask the cache about many+-- paths at once, which nova-nix never does, and other fields upstream does+-- not read either.+readCacheInfo :: Text -> BS.ByteString -> Either CacheOpenFailure CacheInfo+readCacheInfo url contents = foldM field (CacheInfo Nothing) fields+  where+    fields =+      [ (name, trim (BS.drop 1 rest))+      | line <- BC.split '\n' contents,+        let (name, rest) = BC.break (== ':') line,+        not (BS.null rest)+      ]+    field info (name, value)+      | name == storeDirField && value /= canonical =+          Left+            ( CacheUnopenable+                ( "binary cache '"+                    <> url+                    <> "' is for Nix stores with prefix '"+                    <> lenient value+                    <> "', not '"+                    <> defaultStoreDirText+                    <> "'"+                )+            )+      | name == priorityField = case parsePriority value of+          Just priority -> Right info {ciPriority = Just priority}+          Nothing -> Left (CachePriorityInvalid ("binary cache '" <> url <> "' gives the Priority '" <> lenient value <> "' in its nix-cache-info, which is not a 32-bit integer"))+      | otherwise = Right info+    canonical = TE.encodeUtf8 defaultStoreDirText+    lenient = TE.decodeUtf8With TE.lenientDecode+    trim = BC.dropWhile isTrimmed . BC.dropWhileEnd isTrimmed+    isTrimmed c = c `elem` (" \t\r\n" :: String)++-- | A @Priority@ value as upstream reads it, which is how C reads an+-- @int@ from text: after any white space, an optional sign and at least+-- one decimal digit, with whatever follows them ignored, within the range+-- of a 32-bit @int@.+parsePriority :: BS.ByteString -> Maybe Int+parsePriority value = do+  let unspaced = BC.dropWhile (`elem` cWhiteSpace) value+      (signed, unsigned) = case BC.uncons unspaced of+        Just ('-', rest) -> (negate, rest)+        Just ('+', rest) -> (id, rest)+        _ -> (id, unspaced)+  magnitude <- readMaybe (BC.unpack (BC.takeWhile isDigit unsigned)) :: Maybe Integer+  let priority = signed magnitude+  guard (priority >= toInteger (minBound :: Int32) && priority <= toInteger (maxBound :: Int32))+  pure (fromInteger priority)++-- | The characters C counts as white space before a number.+cWhiteSpace :: String+cWhiteSpace = " \t\n\v\f\r"++-- ---------------------------------------------------------------------------+-- Files in a cache+-- ---------------------------------------------------------------------------++-- | The path of a file a narinfo names in the cache in a directory, held+-- below the directory as upstream holds it: a name that is empty, absolute+-- or holds a @.@ or @..@ segment is refused in upstream's words.  A name+-- with a drive, or one beginning with a separator, is refused as absolute+-- on Windows too, where upstream would read some of them below the cache.+cacheFilePath :: FilePath -> Text -> Either Text FilePath+cacheFilePath dir name+  | null relative = Left "local binary cache path must not be empty"+  | hasDrive relative || any isPathSeparator (take 1 relative) =+      Left ("local binary cache path '" <> name <> "' must not be absolute")+  | any (`elem` [".", ".."]) (splitDirectories relative) =+      Left ("local binary cache path '" <> name <> "' must not contain '..' or '.' segments")+  | otherwise = Right (dir </> relative)+  where+    relative = T.unpack name++-- | Write a file of a cache: whole, into a new file beside it, which is+-- then renamed onto it, as upstream writes one, so a reader never meets a+-- torn file.  The new file has the permissions the umask leaves, as+-- upstream's write creates one, where @openBinaryTempFile@ would leave it+-- readable by its owner alone and so unreadable to a web server running as+-- another user.  Its name starts with a dot, which static servers commonly+-- hide.+writeCacheFile :: FilePath -> BS.ByteString -> IO ()+writeCacheFile target bytes =+  bracketOnError+    (openBinaryTempFileWithDefaultPermissions (takeDirectory target) ('.' : takeFileName target <> tempSuffix))+    discardTemp+    ( \(temp, out) -> do+        BS.hPut out bytes+        hClose out+        renameFile temp target+    )++-- | The extension of a file being written, before its rename.+tempSuffix :: String+tempSuffix = ".tmp"++-- | Close and remove a file whose write failed.  An error doing so is+-- dropped, so it never replaces the failure that brought it here.+discardTemp :: (FilePath, Handle) -> IO ()+discardTemp (temp, opened) = do+  ignoringIOErrors (hClose opened)+  ignoringIOErrors (removeFile temp)+  where+    ignoringIOErrors action = action `catch` \(_ :: IOException) -> pure ()
src/Nix/Compression.hs view
@@ -1,6 +1,6 @@ -- | The narinfo compression register - one vocabulary for every--- consumer (the substituter's dispatch, and push once it writes--- compressed objects), so the accepted set exists exactly once and+-- consumer (the substituter's dispatch, and push, which writes zstd+-- objects), so the accepted set exists exactly once and -- cannot drift between encodings. -- -- Upstream note: C++ Nix decodes an absent or empty @Compression@
+ src/Nix/Compression/Stream.hs view
@@ -0,0 +1,168 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | The compressed streams nova-nix opens, told apart by their first+-- bytes, as libarchive's filters tell them apart, and decompressed as a+-- pull source so no stream is held whole.+module Nix.Compression.Stream+  ( -- * Formats+    Compression (..),+    compressionOf,+    compressionMagicBytes,++    -- * Streaming+    withDecompressed,+    decodingFailure,++    -- * Failures+    xzReason,+    bzip2Reason,+  )+where++import qualified Codec.Compression.Zlib.Internal as Zlib+import Control.Exception (Exception, Handler (..), catches, throwIO)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import Data.IORef (newIORef, readIORef, writeIORef)+import Data.Text (Text)+import qualified Data.Text as T+import qualified NovaCache.Bzip2 as Bzip2+import qualified NovaCache.Xz as Xz+import qualified NovaCache.Zstd as Zstd++-- ---------------------------------------------------------------------------+-- Formats+-- ---------------------------------------------------------------------------++-- | A compressed stream, or none.+data Compression = Gzip | Zstd | Xz | Bzip2 | Uncompressed+  deriving (Eq, Show)++-- | The stream a file's first bytes start, told by its magic.+compressionOf :: ByteString -> Compression+compressionOf bytes+  | gzipMagic `BS.isPrefixOf` bytes = Gzip+  | zstdMagic `BS.isPrefixOf` bytes || startsSkippableFrame bytes = Zstd+  | xzMagic `BS.isPrefixOf` bytes = Xz+  | startsBzip2 bytes = Bzip2+  | otherwise = Uncompressed++-- | The most bytes 'compressionOf' reads: an xz stream's magic.+compressionMagicBytes :: Int+compressionMagicBytes = BS.length xzMagic++-- | A gzip member's first bytes: the magic and the deflate method, the+-- only one gzip defines.+gzipMagic :: ByteString+gzipMagic = BS.pack [0x1F, 0x8B, 0x08]++-- | A zstd frame's magic number, as a file starts with it.+zstdMagic :: ByteString+zstdMagic = BS.pack [0x28, 0xB5, 0x2F, 0xFD]++-- | Whether bytes start a zstd skippable frame, as @pzstd@'s output does:+-- a magic number whose low four bits are free, then the rest of its+-- little-endian word.+startsSkippableFrame :: ByteString -> Bool+startsSkippableFrame bytes = case BS.uncons bytes of+  Just (lead, rest) -> lead >= skippableLow && lead <= skippableHigh && skippableTail `BS.isPrefixOf` rest+  Nothing -> False+  where+    skippableLow = 0x50+    skippableHigh = 0x5F+    skippableTail = BS.pack [0x2A, 0x4D, 0x18]++-- | An xz stream's header magic.+xzMagic :: ByteString+xzMagic = BS.pack [0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00]++-- | Whether bytes start a bzip2 stream: its magic, then the block size in+-- hundreds of kilobytes, a digit from one to nine.+startsBzip2 :: ByteString -> Bool+startsBzip2 bytes = case BS.stripPrefix bzip2Magic bytes >>= BS.uncons of+  Just (size, _) -> size >= smallestBlockSize && size <= largestBlockSize+  Nothing -> False+  where+    smallestBlockSize = 0x31+    largestBlockSize = 0x39++-- | A bzip2 stream's magic, which a block size digit follows.+bzip2Magic :: ByteString+bzip2Magic = "BZh"++-- ---------------------------------------------------------------------------+-- Streaming+-- ---------------------------------------------------------------------------++-- | A gzip stream the decoder refused, thrown from the decompressed+-- source as the other decoders throw theirs.+newtype GzipFailure = GzipFailure Zlib.DecompressError+  deriving (Show)++instance Exception GzipFailure++-- | A source's bytes decompressed as the compression says, as a source+-- whose empty chunk ends it.  A corrupt stream is thrown from the pull,+-- for 'decodingFailure' to read.  No bound is put on what a decoder+-- gives, since a caller reads the stream as it arrives and never holds+-- it whole; xz's decoder keeps nova-cache's bound on its own memory.+withDecompressed :: Compression -> IO ByteString -> (IO ByteString -> IO a) -> IO a+withDecompressed compression source consume = case compression of+  Uncompressed -> consume source+  Gzip -> withGzipSource source consume+  Xz -> Xz.withXzSource Xz.XzLimits {Xz.xzMaxOutputBytes = maxBound, Xz.xzMaxDecoderMemoryBytes = Xz.defaultXzDecoderMemoryBytes} source consume+  Zstd -> Zstd.withZstdSource Zstd.ZstdLimits {Zstd.zstdMaxOutputBytes = maxBound} source consume+  Bzip2 -> Bzip2.withBzip2Source Bzip2.Bzip2Limits {Bzip2.bzip2MaxOutputBytes = maxBound} source consume++-- | A gzip stream decompressed as a source, every member in turn, as+-- libarchive's gzip filter reads one.+withGzipSource :: IO ByteString -> (IO ByteString -> IO a) -> IO a+withGzipSource source consume = do+  state <- newIORef (Zlib.decompressIO Zlib.gzipFormat Zlib.defaultDecompressParams)+  let pull =+        readIORef state >>= \case+          Zlib.DecompressInputRequired supply -> do+            chunk <- source+            supply chunk >>= writeIORef state+            pull+          Zlib.DecompressOutputAvailable output next -> do+            next >>= writeIORef state+            pure output+          Zlib.DecompressStreamEnd _ -> pure BS.empty+          Zlib.DecompressStreamError err -> throwIO (GzipFailure err)+  consume pull++-- | Run a read of a decompressed source, a corrupt stream giving the+-- reason the decoder gives for it.+decodingFailure :: IO a -> IO (Either Text a)+decodingFailure action =+  (Right <$> action)+    `catches` [ Handler (\(GzipFailure err) -> pure (Left ("gzip stream error: " <> T.pack (show err)))),+                Handler (pure . Left . xzReason),+                Handler (pure . Left . zstdReason),+                Handler (pure . Left . bzip2Reason)+              ]++-- ---------------------------------------------------------------------------+-- Failures+-- ---------------------------------------------------------------------------++-- | An xz decoding failure, as a message gives it.+xzReason :: Xz.XzError -> Text+xzReason failure = case failure of+  Xz.XzStreamError message -> "xz stream error: " <> T.pack message+  Xz.XzOutputOverBound bound -> "xz stream decompresses to more than " <> T.pack (show bound) <> " bytes"+  Xz.XzMemoryOverBound bound -> "xz stream needs more than " <> T.pack (show bound) <> " bytes of decoder memory"++-- | A bzip2 decoding failure, as a message gives it.+bzip2Reason :: Bzip2.Bzip2Error -> Text+bzip2Reason failure = case failure of+  Bzip2.Bzip2StreamError message -> "bzip2 stream error: " <> T.pack message+  Bzip2.Bzip2OutputOverBound bound -> "bzip2 stream decompresses to more than " <> T.pack (show bound) <> " bytes"++-- | A zstd decoding failure, as a message gives it.+zstdReason :: Zstd.ZstdError -> Text+zstdReason failure = case failure of+  Zstd.ZstdStreamError message -> "zstd stream error: " <> T.pack message+  Zstd.ZstdOutputOverBound bound -> "zstd stream decompresses to more than " <> T.pack (show bound) <> " bytes"
src/Nix/Config.hs view
@@ -1,9 +1,27 @@+{-# LANGUAGE TupleSections #-}+ -- | Nix configuration: the @nix.conf@ / @NIX_CONFIG@ settings that decide -- which binary caches a machine substitutes from, which public keys it--- trusts, whether a failed substitute builds from source (@fallback@), how--- deep function calls may nest, how far an evaluation may reach--- (@restrict-eval@, @pure-eval@, @allowed-uris@), and whether--- @builtins.traceVerbose@ traces (@trace-verbose@).+-- trusts, whether a failed substitute builds from source (@fallback@),+-- whether a derivation may forbid substitutes+-- (@always-allow-substitutes@), how many cores a builder is told it may+-- use (@cores@), how deep function calls may nest, how far an evaluation+-- may reach (@restrict-eval@, @pure-eval@, @allowed-uris@), whether+-- @builtins.traceVerbose@ traces (@trace-verbose@), whether a path+-- reader may build what its argument's context names+-- (@allow-import-from-derivation@, @trace-import-from-derivation@), how+-- builds are sandboxed (@sandbox@ and the settings beside it, macOS's+-- @allowed-impure-host-deps@ and @darwin-log-sandbox-violations@ among+-- them), whom builds run as when nova-nix runs as root+-- (@build-users-group@), what a build that fails leaves (@keep-failed@),+-- where the link to the default profile is+-- (@use-xdg-base-directories@), the prompt of a @develop@ shell+-- (@bash-prompt@ and its prefix and suffix), which experimental features+-- are on (@experimental-features@), who may connect to the daemon and+-- what it lets them do (@trusted-users@, @allowed-users@,+-- @build-users-group@, @trusted-substituters@), and how many times a+-- download or upload is tried (@filetransfer-retry-attempts@, also+-- named @download-attempts@), and which store a command uses (@store@). -- -- == The format --@@ -37,6 +55,8 @@ -- against a narinfo's signatures, a URI prefix matched against the -- evaluator's URIs).  A token that is not UTF-8 is refused rather than -- spelled with U+FFFD, which would name a different cache, key or URI.+-- The daemon's lists of users stay bytes, as upstream keeps them, since+-- they are matched against the names the system gives in bytes. -- -- == Where the files are --@@ -50,20 +70,44 @@ -- @XDG_CONFIG_DIRS@ entry, applied back to front so the first listed wins; -- then @NIX_CONFIG@.  'configFilePaths' computes that order from the -- environment and the platform's directories, which the caller looks up--- (this module holds no platform literal), and 'loadConfig' reads and+-- (the one platform choice this module makes is the default of+-- @trusted-users@), and 'loadConfig' reads and -- folds it. -- -- == Precedence -- -- Sources are folded weakest first, so a later source overrides an earlier -- one.  A plain assignment REPLACES the accumulated value; an @extra-@--- prefixed assignment APPENDS to a list.  An @extra-@ on a Boolean or a+-- prefixed assignment APPENDS to a list or a set.  An @extra-@ on a Boolean or a -- scalar names no setting (upstream appends only to an appendable -- setting, so @extra-max-call-depth@ is an unknown name) and is ignored--- like any unknown name.  The caller supplies the sources in order--- (built-in default, then files, then @NIX_CONFIG@, then the command--- line), so the command line wins, exactly as upstream orders them.+-- like any unknown name.  'loadConfig' folds over the built-in default+-- the files, in the order the caller lists them, then @NIX_CONFIG@, so+-- @NIX_CONFIG@ overrides every file, as upstream Nix orders them.  The+-- command line is not a source here: the CLI applies its flags over the+-- resolved settings. --+-- == Settings a source set+--+-- A client of a daemon sends the daemon the store settings a source set+-- and none it left at their defaults.  Only the settings this module+-- reads can be sent: a store setting it does not read (@builders@ and+-- @connect-timeout@, for example) is not sent whatever a source says.+-- The fold records which settings an assignment named+-- ('assignedSettings', through 'loadConfigAssigned'), each by its own+-- name whatever alias or @extra-@ spelling set it, and whether a plain+-- assignment replaced the value it started from or only @extra-@+-- assignments added to it ('HowAssigned'); 'storeSettingOverrides'+-- writes those that belong to the store as @nix.conf@ spells them.  A+-- list that only @extra-@ assignments built is sent with the default+-- upstream's client would hold before the entries, since the default+-- here is empty and a daemon is sent what upstream's client sends.  A+-- command-line flag that sets a store setting is recorded as the+-- assignment it stands for, each setting's record joined to the sources'+-- ('Semigroup'): the flag that adds to a list is an @extra-@ assignment+-- and one that sets a mode a plain assignment, so a setting a source+-- replaced stays replaced when a flag only adds to it.+-- -- == Security -- -- @trusted-public-keys@ decides which signatures a substituted path is@@ -87,6 +131,8 @@   ( -- * Resolved settings     NixConfig (..),     defaultNixConfig,+    PathSetValue (..),+    DefaultUse (..),      -- * Where the files are     ConfigLocations (..),@@ -100,8 +146,15 @@     ConfigReadFailure (..),     ReadConfigFile,     loadConfig,+    loadConfigAssigned,     expandConfigSource, +    -- * Settings a source set+    AssignedSettings (..),+    HowAssigned (..),+    assignedSettings,+    storeSettingOverrides,+     -- * Parsing and folding     ConfigLine (..),     IncludeMode (..),@@ -125,12 +178,20 @@ import Data.List (dropWhileEnd, intercalate) import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.List.NonEmpty as NE-import Data.Maybe (catMaybes, fromMaybe, maybeToList)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (catMaybes, fromMaybe, mapMaybe, maybeToList)+import Data.Set (Set)+import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text.Encoding as TE import Data.Word (Word32)+import Nix.Builder.Sandbox (SandboxMode, parseSandboxMode, renderSandboxMode) import Nix.Eval.CallDepth (defaultMaxCallDepth)+import Nix.ExperimentalFeature (FeatureSet, addFeatures, noFeatures, parseFeatures, replaceFeatures) import Nix.HostPath (hostPathFromBytes, hostPathText)+import Nix.Http (defaultDownloadAttempts)+import qualified System.Info import System.OsPath (OsChar, OsPath, OsString, (</>)) import qualified System.OsPath as OP @@ -146,8 +207,22 @@ data NixConfig = NixConfig   { ncSubstituters :: ![Text],     ncTrustedPublicKeys :: ![Text],+    -- | Upstream's @secret-key-files@: files of secret keys, whose public+    -- halves are trusted beside @trusted-public-keys@, as bytes.+    ncSecretKeyFiles :: ![ByteString],+    -- | Upstream's @require-sigs@: a path copied into the store that is+    -- not content-addressed must be signed by a trusted key.+    ncRequireSigs :: !Bool,     -- | Upstream @fallback@: build from source when a substitute fails.     ncFallback :: !Bool,+    -- | Upstream @always-allow-substitutes@: substitute a derivation+    -- whatever its @allowSubstitutes@ attribute says.+    ncAlwaysAllowSubstitutes :: !Bool,+    -- | Upstream's @cores@, what a builder's @NIX_BUILD_CORES@ says, when+    -- a source sets it.  Its default, which a 0 gives as well, is the+    -- machine's ("Nix.Builder.Cores"), which only IO can find, so unset+    -- is 'Nothing' rather than a number.+    ncCores :: !(Maybe Word32),     -- | Upstream's @max-call-depth@: how many function calls may be     -- active around a new one before evaluation refuses it.     ncMaxCallDepth :: !Word32,@@ -158,16 +233,105 @@     -- | Upstream @pure-eval@.     ncPureEval :: !Bool,     -- | Upstream @trace-verbose@.-    ncTraceVerbose :: !Bool+    ncTraceVerbose :: !Bool,+    -- | Upstream @allow-import-from-derivation@.+    ncAllowImportFromDerivation :: !Bool,+    -- | Upstream @trace-import-from-derivation@.+    ncTraceImportFromDerivation :: !Bool,+    -- | Upstream's @sandbox@, when a source sets it.  Its default is+    -- @true@ on Linux and @false@ elsewhere, the caller's to apply.+    ncSandbox :: !(Maybe SandboxMode),+    -- | Upstream @sandbox-fallback@.+    ncSandboxFallback :: !Bool,+    -- | Upstream @sandbox-paths@, as bytes.+    ncSandboxPaths :: !PathSetValue,+    -- | Upstream @sandbox-build-dir@.+    ncSandboxBuildDir :: !ByteString,+    -- | Upstream @sandbox-dev-shm-size@.+    ncSandboxDevShmSize :: !ByteString,+    -- | Upstream's @require-drop-supplementary-groups@, when a source sets+    -- it.  Its default is whether the process runs as root, which only IO+    -- can find.+    ncRequireDropSupplementaryGroups :: !(Maybe Bool),+    -- | Upstream's @ssl-cert-file@, when a source sets it.  Its default+    -- comes from the environment and the files there are, which only IO+    -- can find.+    ncSslCertFile :: !(Maybe ByteString),+    -- | Upstream's @build-users-group@, when a source sets it: the group+    -- whose members builds run as, and whose members may not connect to+    -- the daemon.  Its default is @nixbld@ for root and empty otherwise,+    -- which only IO can tell apart ("Nix.Builder.BuildUser").+    ncBuildUsersGroup :: !(Maybe ByteString),+    -- | Upstream's @store@, as @--store@ spells it, when a source sets it:+    -- the store commands use.  Its default is @$NIX_REMOTE@ and then+    -- @auto@, which only the environment can tell.+    ncStore :: !(Maybe ByteString),+    -- | Upstream @use-xdg-base-directories@: the link to the default+    -- profile is in the state directory, not the home.+    ncUseXdgBaseDirectories :: !Bool,+    -- | Upstream's @bash-prompt@: a @develop@ shell's prompt in place of+    -- the user's, none when empty.+    ncBashPrompt :: !ByteString,+    -- | Upstream's @bash-prompt-prefix@: text before that prompt.+    ncBashPromptPrefix :: !ByteString,+    -- | Upstream's @bash-prompt-suffix@: text after it.+    ncBashPromptSuffix :: !ByteString,+    -- | Upstream's @allowed-impure-host-deps@, as bytes.  Its default is+    -- macOS's alone, the caller's to apply.+    ncAllowedImpureHostDeps :: !PathSetValue,+    -- | Upstream's @darwin-log-sandbox-violations@.+    ncDarwinLogSandboxViolations :: !Bool,+    -- | Upstream's @keep-failed@: a build that fails keeps its directory,+    -- and a check its rebuild of an output that differs.+    ncKeepFailed :: !Bool,+    -- | Upstream's @experimental-features@, with the warnings its values+    -- gave, which the caller reports.+    ncExperimentalFeatures :: !FeatureSet,+    -- | Upstream's @trusted-users@: the users, and with @\@@ the groups,+    -- the daemon trusts, as bytes, as the system names them.  Its default+    -- is upstream's @root@, and on Windows, which has no root, the+    -- machine's administrators.+    ncTrustedUsers :: ![ByteString],+    -- | Upstream's @allowed-users@: the users, and with @\@@ the groups,+    -- who may connect to the daemon, @*@ for everyone, as bytes.+    ncAllowedUsers :: ![ByteString],+    -- | Upstream's @trusted-substituters@: substituters a client the+    -- daemon does not trust may ask for.+    ncTrustedSubstituters :: ![Text],+    -- | Upstream's @filetransfer-retry-attempts@: how many times one+    -- download or upload is tried before it fails.+    ncDownloadAttempts :: !Word32   }   deriving (Eq, Show) +-- | A set of paths whose default is the caller's: upstream's+-- @sandbox-paths@ defaults to the sandbox shell a binary was built with,+-- which is where it was installed, and on macOS to system paths, as its+-- @allowed-impure-host-deps@ does.  An @extra-@ assignment adds to the+-- default, and a plain one replaces it.+data PathSetValue = PathSetValue+  { psvDefault :: !DefaultUse,+    psvPaths :: !(Set ByteString)+  }+  deriving (Eq, Show)++-- | Whether a t'PathSetValue' keeps its default beside its own paths.+data DefaultUse = KeepsDefault | ReplacesDefault+  deriving (Eq, Show)+ -- | The baseline the fold starts from: no substituters, no trusted keys,--- no fallback, upstream's call-depth ceiling, no allowed URIs, both--- evaluation modes off, and @trace-verbose@ off.  The empty substituter--- list is nova-nix's existing default (nothing is substituted unless--- configured), a deliberate divergence from upstream's cache.nixos.org--- default: turning a cache on for every machine is the operator's+-- no secret key files, signatures required, no fallback,+-- @allowSubstitutes@ heeded, @cores@ unset so that the+-- machine's default applies, upstream's call-depth ceiling, no allowed+-- URIs, both evaluation modes off, @trace-verbose@ off, an import from+-- derivation allowed and not traced, upstream's sandbox settings,+-- those whose defaults take the platform or IO unset or kept for the+-- caller, the default profile's link in the home, the three prompt+-- settings empty, as upstream's are, nothing kept of a build that+-- fails, and upstream's number of download attempts.  The empty+-- substituter list and the empty trusted-key list diverge from upstream,+-- whose defaults name cache.nixos.org and its key: turning a cache on for+-- every machine, and trusting what its key signed, is the operator's -- decision to make in a config file, not a built-in.  The other defaults -- are upstream's own. defaultNixConfig :: NixConfig@@ -175,23 +339,61 @@   NixConfig     { ncSubstituters = [],       ncTrustedPublicKeys = [],+      ncSecretKeyFiles = [],+      ncRequireSigs = True,       ncFallback = False,+      ncAlwaysAllowSubstitutes = False,+      ncCores = Nothing,       ncMaxCallDepth = defaultMaxCallDepth,       ncAllowedUris = [],       ncRestrictEval = False,       ncPureEval = False,-      ncTraceVerbose = False+      ncTraceVerbose = False,+      ncAllowImportFromDerivation = True,+      ncTraceImportFromDerivation = False,+      ncSandbox = Nothing,+      ncSandboxFallback = True,+      ncSandboxPaths = PathSetValue KeepsDefault Set.empty,+      ncSandboxBuildDir = "/build",+      ncSandboxDevShmSize = "50%",+      ncRequireDropSupplementaryGroups = Nothing,+      ncSslCertFile = Nothing,+      ncBuildUsersGroup = Nothing,+      ncStore = Nothing,+      ncUseXdgBaseDirectories = False,+      ncBashPrompt = "",+      ncBashPromptPrefix = "",+      ncBashPromptSuffix = "",+      ncAllowedImpureHostDeps = PathSetValue KeepsDefault Set.empty,+      ncDarwinLogSandboxViolations = False,+      ncKeepFailed = False,+      ncExperimentalFeatures = noFeatures,+      ncTrustedUsers = defaultTrustedUsers,+      ncAllowedUsers = ["*"],+      ncTrustedSubstituters = [],+      ncDownloadAttempts = defaultDownloadAttempts     } +-- | The default of @trusted-users@: upstream's @root@, and on Windows,+-- which has no root, the machine's administrators, the group of SID+-- @S-1-5-32-544@ that only an elevated administrator's token enables.+-- The group is named by its SID, which no name a domain or a user could+-- take stands in for.+defaultTrustedUsers :: [ByteString]+defaultTrustedUsers = case System.Info.os of+  "mingw32" -> ["@S-1-5-32-544"]+  _ -> ["root"]+ -- --------------------------------------------------------------------------- -- Where the files are -- --------------------------------------------------------------------------- --- | The environment that decides which files are read.  The two variables--- are carried raw, as the bytes 'Nix.Environment.lookupEnvBytes' returns,--- because upstream reads them differently: an empty @NIX_CONF_DIR@ is--- unset (@getEnvNonEmpty@), while an empty @NIX_USER_CONF_FILES@ is set--- and names no files at all.  The directories arrive resolved, since the+-- | The environment that decides which files are read.  The three+-- variables are carried raw, as the bytes 'Nix.Environment.lookupEnvBytes'+-- returns, because upstream reads them differently: an empty+-- @NIX_CONF_DIR@ is unset (@getEnvNonEmpty@), while an empty+-- @NIX_USER_CONF_FILES@ is set and names no files at all, and an empty+-- @NIX_CONFIG_HOME@ is set and names the working directory.  The directories arrive resolved, since the -- platform defaults behind them (where the machine-wide config directory -- is, what the XDG config home and dirs fall back to) are the caller's to -- look up.@@ -204,6 +406,8 @@     clSystemConfDir :: !(Maybe OsPath),     -- | @NIX_USER_CONF_FILES@.     clUserConfFiles :: !(Maybe ByteString),+    -- | @NIX_CONFIG_HOME@.+    clNixConfigHome :: !(Maybe ByteString),     -- | The XDG config home.     clConfigHome :: !OsPath,     -- | The XDG config dirs, first entry strongest.@@ -216,16 +420,20 @@ -- platform's machine-wide directory (no file at all when the platform has -- none); then the user files in reverse of the order upstream lists them, -- since @loadConfFile@ walks @nixUserConfFiles@ back to front--- (globals.cc:139) so that the first listed, the config home, wins.--- The system directory goes through 'canonicalAbsolutePath', as upstream's--- @Settings@ constructor runs it through @canonPath@ (globals.cc:65): a--- relative one is refused, and @.@ and @..@ in it collapse, so the file--- is named canonically wherever it is reported and its includes resolve--- against the collapsed directory.  The user files are read as named;--- upstream canonicalizes none of them.--- @NIX_USER_CONF_FILES@ replaces the XDG list outright, in its own order.--- It is split on the platform's list separator with empty entries dropped--- as upstream's tokenizer drops them; upstream splits on @:@ on every+-- (globals.cc) so that the first listed, the config home, wins.  The+-- config home's file is in @NIX_CONFIG_HOME@ itself when that is set,+-- as upstream 2.36.0's @getConfigDir@ reads it (users.cc), and otherwise+-- in @nix@ under the XDG config home; an empty @NIX_CONFIG_HOME@ is set,+-- since upstream reads it with @getEnvOs@, and names @nix.conf@ in the+-- working directory, as @std::filesystem@ joins an empty path.  The system+-- directory goes through 'canonicalAbsolutePath', as upstream's @Settings@+-- constructor runs it through @canonPath@ (globals.cc): a relative one is+-- refused, and @.@ and @..@ in it collapse, so the file is named canonically+-- wherever it is reported and its includes resolve against the collapsed+-- directory.  The user files are read as named; upstream canonicalizes none+-- of them.  @NIX_USER_CONF_FILES@ replaces the XDG list outright, in its own+-- order.  It is split on the platform's list separator with empty entries+-- dropped as upstream's tokenizer drops them; upstream splits on @:@ on every -- platform, which cannot carry a Windows drive letter, so @;@ is honoured -- there as it is for @PATH@ and @XDG_CONFIG_DIRS@. configFilePaths :: ConfigLocations -> Either Text [OsPath]@@ -234,10 +442,11 @@   systemDir <- traverse canonicalAbsolutePath (confDir <|> clSystemConfDir locations)   userFiles <- case clUserConfFiles locations of     Just listed -> splitListVar <$> variablePath listed-    Nothing -> pure (map underXdgDir (clConfigHome locations : clConfigDirs locations))+    Nothing -> do+      home <- maybe (pure (clConfigHome locations </> nixConfDirName)) variablePath (clNixConfigHome locations)+      pure (map (</> nixConfFileName) (home : map (</> nixConfDirName) (clConfigDirs locations)))   pure (maybeToList ((</> nixConfFileName) <$> systemDir) ++ reverse userFiles)   where-    underXdgDir dir = dir </> nixConfDirName </> nixConfFileName     variablePath bytes = maybe (Left (noHostSpelling bytes)) Right (hostPathFromBytes bytes)  -- | Split a path-list variable on the platform's list separator, dropping@@ -302,11 +511,16 @@ -- @NIX_CONFIG@ bytes when the variable is set.  A file that is read and -- does not expand is an error, never treated as absent. loadConfig :: (Monad m) => ReadConfigFile m -> [OsPath] -> Maybe ByteString -> m (Either Text NixConfig)-loadConfig readConfigFile paths nixConfigText = runExceptT $ do+loadConfig readConfigFile paths nixConfigText = fmap fst <$> loadConfigAssigned readConfigFile paths nixConfigText++-- | 'loadConfig', and which settings the sources set.+loadConfigAssigned :: (Monad m) => ReadConfigFile m -> [OsPath] -> Maybe ByteString -> m (Either Text (NixConfig, AssignedSettings))+loadConfigAssigned readConfigFile paths nixConfigText = runExceptT $ do   fileSources <- lift (rights <$> traverse readSource paths)   let sources = fileSources ++ maybeToList (ConfigSource nixConfigSourceName <$> nixConfigText)-  assignments <- traverse (ExceptT . expandConfigSource readConfigFile) sources-  liftEither (resolveConfig (concat assignments))+  assignments <- concat <$> traverse (ExceptT . expandConfigSource readConfigFile) sources+  config <- liftEither (resolveConfig assignments)+  pure (config, assignedSettings assignments)   where     readSource path = fmap (ConfigSource path) <$> readConfigFile path @@ -463,9 +677,9 @@   deriving (Eq, Show)  -- | Parse one source's bytes into its lines.  Comments and blank lines--- drop out; a malformed line (fewer than @name = value@, a missing @=@,+-- drop out; a malformed line (fewer than @name =@, a missing @=@, -- or an include with other than exactly one path) is a loud error rather--- than a silent skip, matching upstream's @UsageError@ - a typo in a+-- than a silent skip, as upstream Nix makes it - a typo in a -- security-relevant file must not pass for an empty setting.  The error -- quotes the line as upstream does, comment-truncated and otherwise -- verbatim, leading whitespace included.@@ -543,12 +757,17 @@ -- | Apply one assignment to the accumulated config.  The name is resolved -- through the aliases (@binary-caches@ -> @substituters@, -- @binary-cache-public-keys@ -> @trusted-public-keys@,--- @build-fallback@ -> @fallback@) and the @extra-@--- prefix (append rather than replace, list settings only).  A name+-- @trusted-binary-caches@ -> @trusted-substituters@,+-- @build-fallback@ -> @fallback@, @build-cores@ -> @cores@,+-- @build-use-chroot@ and @build-use-sandbox@ -> @sandbox@,+-- @build-chroot-dirs@ and @build-sandbox-paths@ -> @sandbox-paths@,+-- @download-attempts@ -> @filetransfer-retry-attempts@) and the+-- @extra-@ prefix (append rather than replace, list and path-set settings+-- only).  A name -- outside the known set is ignored, not an error: upstream warns and -- continues, and refusing every unknown key would reject a config that--- also carries settings this layer does not model yet.  A value that does--- not parse for its setting is an error, as upstream's @UsageError@ is:+-- also carries settings this layer does not model.  A value that does+-- not parse for its setting is an error, as it is in upstream Nix: -- @pure-eval = ture@ must not pass for off. applyAssignment :: NixConfig -> ConfigAssignment -> Either Text NixConfig applyAssignment config (ConfigAssignment name value) =@@ -556,13 +775,36 @@     Nothing -> Right config     Just (ListSetting field, mode) ->       (\items -> setList field (combine mode (getList field config) items) config) <$> listItems field value+    Just (WordsSetting field, mode) ->+      Right (setWords field (combine mode (getWords field config) (configTokens value)) config)+    -- Upstream's Boolean and integer errors name the setting by its own+    -- name, not the alias it was set through (@BaseSetting\<T\>::parse@+    -- throws with @name@, the setting's, which @Config::set@ reaches+    -- through an alias's entry, config.cc at 2.24.9).     Just (BoolSetting field, _) ->-      (\flag -> setBool field flag config) <$> parseBool name value-    Just (ScalarSetting MaxCallDepthField, _) ->-      (\limit -> config {ncMaxCallDepth = limit}) <$> parseUnsignedSetting name value+      (\flag -> setBool field flag config) <$> parseBool (boolFieldKey field) value+    Just (ScalarSetting field, _) ->+      (\number -> setScalar field number config) <$> parseUnsignedSetting (scalarFieldKey field) value+    Just (ModeSetting, _) ->+      (\mode -> config {ncSandbox = Just mode}) <$> parseSandboxMode value+    Just (BytesSetting field, _) -> Right (setBytes field value config)+    Just (PathSetSetting field, mode) ->+      Right (setPathSet field (combinePaths mode (getPathSet field config) (Set.fromList (configTokens value))) config)+    Just (FeaturesSetting, mode) ->+      Right (config {ncExperimentalFeatures = combineFeatures mode (ncExperimentalFeatures config) (parseFeatures value)})   where     combine ReplaceMode _ new = new     combine AppendMode old new = old ++ new+    -- Upstream's @StringSet@ setting: a plain assignment replaces the+    -- set, the default included, and @extra-@ adds to it+    -- (its @parse@ and @appendOrSet@ in config.cc at 2.24.9,+    -- configuration.cc at 2.36.0).+    combinePaths ReplaceMode _ new = PathSetValue ReplacesDefault new+    combinePaths AppendMode old new = old {psvPaths = Set.union (psvPaths old) new}+    -- Upstream's set of features: a plain assignment replaces it and+    -- @extra-@ adds to it (@appendOrSet@ in configuration.cc at 2.36.0).+    combineFeatures ReplaceMode = replaceFeatures+    combineFeatures AppendMode = addFeatures  -- | A list value's tokens as text, split as upstream's @Strings@ setting -- splits it, or the refusal of a token that is not UTF-8 (see the module@@ -577,13 +819,16 @@  -- | Which setting a name targets, once the @extra-@ prefix and the aliases -- are resolved, and whether it replaces or appends.  @extra-@ composes--- with a list only: upstream looks the base name up and appends when the--- setting is appendable, and a Boolean or a scalar is not.+-- with a list or a path set only: upstream looks the base name up and appends+-- when the setting is appendable, and a Boolean or a scalar is not. resolveName :: ByteString -> Maybe (Setting, ApplyMode) resolveName name =   case BS.stripPrefix extraPrefix name of     Just base -> case baseSetting base of       Just setting@(ListSetting _) -> Just (setting, AppendMode)+      Just setting@(WordsSetting _) -> Just (setting, AppendMode)+      Just setting@(PathSetSetting _) -> Just (setting, AppendMode)+      Just FeaturesSetting -> Just (FeaturesSetting, AppendMode)       _ -> Nothing     Nothing -> case baseSetting name of       Just setting -> Just (setting, ReplaceMode)@@ -592,28 +837,105 @@     baseSetting n       | n == substitutersKey || n == substitutersAlias = Just (ListSetting SubstitutersField)       | n == trustedKeysKey || n == trustedKeysAlias = Just (ListSetting TrustedKeysField)+      | n == secretKeyFilesKey = Just (WordsSetting SecretKeyFilesField)+      | n == requireSigsKey = Just (BoolSetting RequireSigsField)+      | n == trustedUsersKey = Just (WordsSetting TrustedUsersField)+      | n == allowedUsersKey = Just (WordsSetting AllowedUsersField)+      | n == trustedSubstitutersKey || n == trustedSubstitutersAlias = Just (ListSetting TrustedSubstitutersField)       | n == allowedUrisKey = Just (ListSetting AllowedUrisField)       | n == fallbackKey || n == fallbackAlias = Just (BoolSetting FallbackField)+      | n == alwaysAllowSubstitutesKey = Just (BoolSetting AlwaysAllowSubstitutesField)       | n == restrictEvalKey = Just (BoolSetting RestrictEvalField)       | n == pureEvalKey = Just (BoolSetting PureEvalField)       | n == traceVerboseKey = Just (BoolSetting TraceVerboseField)+      | n == allowImportFromDerivationKey = Just (BoolSetting AllowImportFromDerivationField)+      | n == traceImportFromDerivationKey = Just (BoolSetting TraceImportFromDerivationField)       | n == maxCallDepthKey = Just (ScalarSetting MaxCallDepthField)+      | n == coresKey || n == coresAlias = Just (ScalarSetting CoresField)+      | n == downloadAttemptsKey || n == downloadAttemptsAlias = Just (ScalarSetting DownloadAttemptsField)+      | n == sandboxKey || n `elem` sandboxAliases = Just ModeSetting+      | n == sandboxFallbackKey = Just (BoolSetting SandboxFallbackField)+      | n == sandboxPathsKey || n `elem` sandboxPathsAliases = Just (PathSetSetting SandboxPathsField)+      | n == allowedImpureHostDepsKey = Just (PathSetSetting AllowedImpureHostDepsField)+      | n == darwinLogSandboxViolationsKey = Just (BoolSetting DarwinLogSandboxViolationsField)+      | n == keepFailedKey = Just (BoolSetting KeepFailedField)+      | n == sandboxBuildDirKey = Just (BytesSetting SandboxBuildDirField)+      | n == sandboxDevShmSizeKey = Just (BytesSetting SandboxDevShmSizeField)+      | n == requireDropGroupsKey = Just (BoolSetting RequireDropGroupsField)+      | n == sslCertFileKey = Just (BytesSetting SslCertFileField)+      | n == buildUsersGroupKey = Just (BytesSetting BuildUsersGroupField)+      | n == storeKey = Just (BytesSetting StoreField)+      | n == useXdgBaseDirectoriesKey = Just (BoolSetting UseXdgBaseDirectoriesField)+      | n == bashPromptKey = Just (BytesSetting BashPromptField)+      | n == bashPromptPrefixKey = Just (BytesSetting BashPromptPrefixField)+      | n == bashPromptSuffixKey = Just (BytesSetting BashPromptSuffixField)+      | n == experimentalFeaturesKey = Just FeaturesSetting       | otherwise = Nothing --- | A setting this layer resolves, by the shape of its value.-data Setting = ListSetting !ListField | BoolSetting !BoolField | ScalarSetting !ScalarField+-- | A setting this layer resolves, by the shape of its value: a list of+-- text, a list of tokens kept as bytes, a Boolean, an unsigned integer,+-- @sandbox@'s mode, a string kept as bytes, a set of paths, or+-- @experimental-features@' set of features.+data Setting+  = ListSetting !ListField+  | WordsSetting !WordsField+  | BoolSetting !BoolField+  | ScalarSetting !ScalarField+  | ModeSetting+  | BytesSetting !BytesField+  | PathSetSetting !PathSetField+  | FeaturesSetting   deriving (Eq, Show) +-- | The settings whose value is a set of paths, kept as bytes.+data PathSetField = SandboxPathsField | AllowedImpureHostDepsField+  deriving (Eq, Show)+ -- | The list settings.-data ListField = SubstitutersField | TrustedKeysField | AllowedUrisField+data ListField+  = SubstitutersField+  | TrustedKeysField+  | AllowedUrisField+  | TrustedSubstitutersField   deriving (Eq, Show) +-- | The settings whose value is a list of tokens kept as bytes: user and+-- group names, which the system spells in bytes, and the files of secret+-- keys.+data WordsField = TrustedUsersField | AllowedUsersField | SecretKeyFilesField+  deriving (Eq, Show)+ -- | The Boolean settings.-data BoolField = FallbackField | RestrictEvalField | PureEvalField | TraceVerboseField+data BoolField+  = FallbackField+  | AlwaysAllowSubstitutesField+  | RestrictEvalField+  | PureEvalField+  | TraceVerboseField+  | AllowImportFromDerivationField+  | TraceImportFromDerivationField+  | SandboxFallbackField+  | RequireDropGroupsField+  | UseXdgBaseDirectoriesField+  | DarwinLogSandboxViolationsField+  | KeepFailedField+  | RequireSigsField   deriving (Eq, Show) +-- | The settings whose value is a string, kept as bytes.+data BytesField+  = SandboxBuildDirField+  | SandboxDevShmSizeField+  | SslCertFileField+  | BuildUsersGroupField+  | StoreField+  | BashPromptField+  | BashPromptPrefixField+  | BashPromptSuffixField+  deriving (Eq, Show)+ -- | The scalar settings, which only ever replace.-data ScalarField = MaxCallDepthField+data ScalarField = MaxCallDepthField | CoresField | DownloadAttemptsField   deriving (Eq, Show)  -- | Whether an assignment replaces the accumulated value or appends to it.@@ -624,23 +946,145 @@ getList SubstitutersField = ncSubstituters getList TrustedKeysField = ncTrustedPublicKeys getList AllowedUrisField = ncAllowedUris+getList TrustedSubstitutersField = ncTrustedSubstituters  setList :: ListField -> [Text] -> NixConfig -> NixConfig setList SubstitutersField v config = config {ncSubstituters = v} setList TrustedKeysField v config = config {ncTrustedPublicKeys = v} setList AllowedUrisField v config = config {ncAllowedUris = v}+setList TrustedSubstitutersField v config = config {ncTrustedSubstituters = v} +getWords :: WordsField -> NixConfig -> [ByteString]+getWords TrustedUsersField = ncTrustedUsers+getWords AllowedUsersField = ncAllowedUsers+getWords SecretKeyFilesField = ncSecretKeyFiles++setWords :: WordsField -> [ByteString] -> NixConfig -> NixConfig+setWords TrustedUsersField v config = config {ncTrustedUsers = v}+setWords AllowedUsersField v config = config {ncAllowedUsers = v}+setWords SecretKeyFilesField v config = config {ncSecretKeyFiles = v}++wordsFieldKey :: WordsField -> ByteString+wordsFieldKey TrustedUsersField = trustedUsersKey+wordsFieldKey AllowedUsersField = allowedUsersKey+wordsFieldKey SecretKeyFilesField = secretKeyFilesKey++bytesFieldKey :: BytesField -> ByteString+bytesFieldKey SandboxBuildDirField = sandboxBuildDirKey+bytesFieldKey SandboxDevShmSizeField = sandboxDevShmSizeKey+bytesFieldKey SslCertFileField = sslCertFileKey+bytesFieldKey BuildUsersGroupField = buildUsersGroupKey+bytesFieldKey StoreField = storeKey+bytesFieldKey BashPromptField = bashPromptKey+bytesFieldKey BashPromptPrefixField = bashPromptPrefixKey+bytesFieldKey BashPromptSuffixField = bashPromptSuffixKey++pathSetFieldKey :: PathSetField -> ByteString+pathSetFieldKey SandboxPathsField = sandboxPathsKey+pathSetFieldKey AllowedImpureHostDepsField = allowedImpureHostDepsKey+ listFieldKey :: ListField -> ByteString listFieldKey SubstitutersField = substitutersKey listFieldKey TrustedKeysField = trustedKeysKey listFieldKey AllowedUrisField = allowedUrisKey+listFieldKey TrustedSubstitutersField = trustedSubstitutersKey +-- | What a scalar setting holds, none for one no source has set whose+-- default only IO can find.+getScalar :: ScalarField -> NixConfig -> Maybe Word32+getScalar MaxCallDepthField = Just . ncMaxCallDepth+getScalar CoresField = ncCores+getScalar DownloadAttemptsField = Just . ncDownloadAttempts++setScalar :: ScalarField -> Word32 -> NixConfig -> NixConfig+setScalar MaxCallDepthField v config = config {ncMaxCallDepth = v}+setScalar CoresField v config = config {ncCores = Just v}+setScalar DownloadAttemptsField v config = config {ncDownloadAttempts = v}++scalarFieldKey :: ScalarField -> ByteString+scalarFieldKey MaxCallDepthField = maxCallDepthKey+scalarFieldKey CoresField = coresKey+scalarFieldKey DownloadAttemptsField = downloadAttemptsKey++boolFieldKey :: BoolField -> ByteString+boolFieldKey FallbackField = fallbackKey+boolFieldKey AlwaysAllowSubstitutesField = alwaysAllowSubstitutesKey+boolFieldKey RestrictEvalField = restrictEvalKey+boolFieldKey PureEvalField = pureEvalKey+boolFieldKey TraceVerboseField = traceVerboseKey+boolFieldKey AllowImportFromDerivationField = allowImportFromDerivationKey+boolFieldKey TraceImportFromDerivationField = traceImportFromDerivationKey+boolFieldKey SandboxFallbackField = sandboxFallbackKey+boolFieldKey RequireDropGroupsField = requireDropGroupsKey+boolFieldKey UseXdgBaseDirectoriesField = useXdgBaseDirectoriesKey+boolFieldKey DarwinLogSandboxViolationsField = darwinLogSandboxViolationsKey+boolFieldKey KeepFailedField = keepFailedKey+boolFieldKey RequireSigsField = requireSigsKey++-- | What a Boolean setting holds, none for one whose default only IO can+-- find while no source has set it.+getBool :: BoolField -> NixConfig -> Maybe Bool+getBool FallbackField = Just . ncFallback+getBool AlwaysAllowSubstitutesField = Just . ncAlwaysAllowSubstitutes+getBool RestrictEvalField = Just . ncRestrictEval+getBool PureEvalField = Just . ncPureEval+getBool TraceVerboseField = Just . ncTraceVerbose+getBool AllowImportFromDerivationField = Just . ncAllowImportFromDerivation+getBool TraceImportFromDerivationField = Just . ncTraceImportFromDerivation+getBool SandboxFallbackField = Just . ncSandboxFallback+getBool RequireDropGroupsField = ncRequireDropSupplementaryGroups+getBool UseXdgBaseDirectoriesField = Just . ncUseXdgBaseDirectories+getBool DarwinLogSandboxViolationsField = Just . ncDarwinLogSandboxViolations+getBool KeepFailedField = Just . ncKeepFailed+getBool RequireSigsField = Just . ncRequireSigs+ setBool :: BoolField -> Bool -> NixConfig -> NixConfig setBool FallbackField v config = config {ncFallback = v}+setBool AlwaysAllowSubstitutesField v config = config {ncAlwaysAllowSubstitutes = v} setBool RestrictEvalField v config = config {ncRestrictEval = v} setBool PureEvalField v config = config {ncPureEval = v} setBool TraceVerboseField v config = config {ncTraceVerbose = v}+setBool AllowImportFromDerivationField v config = config {ncAllowImportFromDerivation = v}+setBool TraceImportFromDerivationField v config = config {ncTraceImportFromDerivation = v}+setBool SandboxFallbackField v config = config {ncSandboxFallback = v}+setBool RequireDropGroupsField v config = config {ncRequireDropSupplementaryGroups = Just v}+setBool UseXdgBaseDirectoriesField v config = config {ncUseXdgBaseDirectories = v}+setBool DarwinLogSandboxViolationsField v config = config {ncDarwinLogSandboxViolations = v}+setBool KeepFailedField v config = config {ncKeepFailed = v}+setBool RequireSigsField v config = config {ncRequireSigs = v} +getPathSet :: PathSetField -> NixConfig -> PathSetValue+getPathSet SandboxPathsField = ncSandboxPaths+getPathSet AllowedImpureHostDepsField = ncAllowedImpureHostDeps++setPathSet :: PathSetField -> PathSetValue -> NixConfig -> NixConfig+setPathSet SandboxPathsField v config = config {ncSandboxPaths = v}+setPathSet AllowedImpureHostDepsField v config = config {ncAllowedImpureHostDeps = v}++-- | What a string setting holds, none for one no source has set whose+-- default only IO can find.+getBytes :: BytesField -> NixConfig -> Maybe ByteString+getBytes SandboxBuildDirField = Just . ncSandboxBuildDir+getBytes SandboxDevShmSizeField = Just . ncSandboxDevShmSize+getBytes SslCertFileField = ncSslCertFile+getBytes BuildUsersGroupField = ncBuildUsersGroup+getBytes StoreField = ncStore+getBytes BashPromptField = Just . ncBashPrompt+getBytes BashPromptPrefixField = Just . ncBashPromptPrefix+getBytes BashPromptSuffixField = Just . ncBashPromptSuffix++-- | Upstream's @Setting\<std::string\>@: the value as it reads, its tokens+-- joined by single spaces.+setBytes :: BytesField -> ByteString -> NixConfig -> NixConfig+setBytes SandboxBuildDirField v config = config {ncSandboxBuildDir = v}+setBytes SandboxDevShmSizeField v config = config {ncSandboxDevShmSize = v}+setBytes SslCertFileField v config = config {ncSslCertFile = Just v}+setBytes BuildUsersGroupField v config = config {ncBuildUsersGroup = Just v}+setBytes StoreField v config = config {ncStore = Just v}+setBytes BashPromptField v config = config {ncBashPrompt = v}+setBytes BashPromptPrefixField v config = config {ncBashPromptPrefix = v}+setBytes BashPromptSuffixField v config = config {ncBashPromptSuffix = v}+ -- | Upstream's Boolean spellings (@BaseSetting\<bool\>::parse@): anything -- else is an error with upstream's wording, which names the setting alone, -- as 'parseUnsignedSetting' does.@@ -651,9 +1095,14 @@   | otherwise = Left ("Boolean setting '" <> shownBytes name <> "' has invalid value '" <> shownBytes value <> "'")  trueSpellings, falseSpellings :: [ByteString]-trueSpellings = ["true", "yes", "1"]-falseSpellings = ["false", "no", "0"]+trueSpellings = [canonicalTrue, "yes", "1"]+falseSpellings = [canonicalFalse, "no", "0"] +-- | The spellings upstream writes a Boolean setting's value in.+canonicalTrue, canonicalFalse :: ByteString+canonicalTrue = "true"+canonicalFalse = "false"+ -- | Fold expanded assignments onto the default config, weakest first. -- The caller orders them so the strongest source's assignments are last -- (and so win).  A value a setting cannot take aborts the fold, as@@ -662,6 +1111,292 @@ resolveConfig = foldM applyAssignment defaultNixConfig  -- ---------------------------------------------------------------------------+-- Settings a source set+-- ---------------------------------------------------------------------------++-- | How the sources set a setting: by a plain assignment, which replaces+-- the value the setting started from (its built-in default, or what an+-- earlier source set), or by @extra-@ assignments alone, which add to it.+data HowAssigned+  = -- | Only @extra-@ assignments named the setting.+    ExtendedOnly+  | -- | A plain assignment named it, whatever @extra-@ assignments came+    -- before or after.+    Replaced+  deriving (Eq, Show)++-- | Two records of how a setting was set, as one: a plain assignment+-- anywhere makes the setting replaced, whatever @extra-@ assignments+-- came before it or after.+instance Semigroup HowAssigned where+  Replaced <> _ = Replaced+  ExtendedOnly <> how = how++-- | The settings any source set, each by its own name (the name an alias+-- or an @extra-@ spelling resolves to) with how the sources set it.+-- Upstream's client sends a daemon the settings that were set and none+-- left at their defaults, so this is what tells them apart.+newtype AssignedSettings = AssignedSettings (Map ByteString HowAssigned)+  deriving (Eq, Show)++-- | The records of two sets of assignments as the record of both, a+-- setting both name being replaced when either replaced it.+instance Semigroup AssignedSettings where+  AssignedSettings earlier <> AssignedSettings later = AssignedSettings (Map.unionWith (<>) earlier later)++-- | The settings a list of assignments sets.  An alias or an @extra-@+-- spelling counts as the setting itself, and a name this layer does not+-- know sets nothing.+assignedSettings :: [ConfigAssignment] -> AssignedSettings+assignedSettings assignments =+  AssignedSettings (Map.fromListWith (<>) [(settingKey setting, howAssigned mode) | ConfigAssignment name _ <- assignments, Just (setting, mode) <- [resolveName name]])+  where+    howAssigned ReplaceMode = Replaced+    howAssigned AppendMode = ExtendedOnly++-- | The overrides a client sends a daemon: each setting a source set that+-- upstream's client sends from its store library or its file transfer,+-- under its own name and written as @nix.conf@ spells its value, so that+-- a daemon reads it back as the assignment it came from.  Only the+-- settings this module reads are sent: a store setting it does not read+-- (@builders@ and @connect-timeout@, for example) is not, whatever a+-- source says.  Left out too are the settings the @SetOptions@ message+-- carries as fields of its own, the ones upstream's client does not send+-- from its other configuration objects (the evaluator's, a command's, the+-- daemon command's), a setting upstream declares only on other systems+-- than the one this runs on (@sandbox-dev-shm-size@ on Linux alone, for+-- example), and a setting whose value only IO can find that no source+-- gave one.+--+-- A list is sent in full under its own name.  The default of+-- @substituters@ and of @trusted-public-keys@ is empty here and names+-- cache.nixos.org and its key in upstream's client, which sends a daemon+-- the default and then the entries added to it, so a list that only+-- @extra-@ assignments built is sent with those two defaults before its+-- entries, none merged and none dropped, and so is one whose @extra-@+-- assignments added nothing.  A list a plain assignment replaced is sent+-- as it resolved.  A trusted client of nova-nix's own daemon that only+-- extends either list therefore turns on cache.nixos.org and its key+-- there, as upstream's client would.+--+-- A set of paths that keeps its default beside its own paths is sent as an+-- @extra-@ assignment of those paths alone, and not at all when it holds+-- none: its default (the sandbox shell the binary was built with, the+-- system paths of macOS) is not held here, so the default is the daemon's+-- to apply.+storeSettingOverrides :: AssignedSettings -> NixConfig -> Map ByteString ByteString+storeSettingOverrides (AssignedSettings assigned) config =+  Map.fromList (mapMaybe override (Map.toAscList assigned))+  where+    override (key, how) = do+      (setting, _) <- resolveName key+      case carriage setting of+        Sent declared+          | declaredOn System.Info.os declared -> overrideOf config how setting+          | otherwise -> Nothing+        InOptions -> Nothing+        ClientsOwn -> Nothing++-- | The name and value of a setting's override, if it has one.+overrideOf :: NixConfig -> HowAssigned -> Setting -> Maybe (ByteString, ByteString)+overrideOf config how setting = case setting of+  ListSetting field -> Just (key, listOverride (upstreamListDefault field) how (map TE.encodeUtf8 (getList field config)))+  WordsSetting field -> Just (key, joinTokens (getWords field config))+  BoolSetting field -> named (spellBool <$> getBool field config)+  ScalarSetting field -> named (spellNumber <$> getScalar field config)+  ModeSetting -> named (renderSandboxMode <$> ncSandbox config)+  BytesSetting field -> named (getBytes field config)+  PathSetSetting field -> pathSetOverride key (getPathSet field config)+  FeaturesSetting -> Nothing+  where+    key = settingKey setting+    named = fmap (key,)++-- | The entries of a list setting's default in upstream's client that the+-- default here lacks, spelled as that client sends them.  The defaults+-- here are empty, so a list that only @extra-@ assignments built holds+-- just the entries they added; a daemon is sent what upstream's client+-- sends, which is the default and then those entries.  A daemon at+-- upstream's defaults then keeps cache.nixos.org, and an untrusted+-- client's added cache that the daemon trusts passes the daemon's+-- filter, which takes the plain @substituters@ name from such a client+-- and refuses its @extra-@ spelling.+upstreamListDefault :: ListField -> [ByteString]+upstreamListDefault SubstitutersField = [upstreamSubstituter]+upstreamListDefault TrustedKeysField = [upstreamTrustedKey]+upstreamListDefault AllowedUrisField = []+upstreamListDefault TrustedSubstitutersField = []++-- | The one entry of upstream's default @substituters@, with the trailing+-- slash its client renders it with.+upstreamSubstituter :: ByteString+upstreamSubstituter = "https://cache.nixos.org/"++-- | The one entry of upstream's default @trusted-public-keys@.+upstreamTrustedKey :: ByteString+upstreamTrustedKey = "cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY="++-- | A list's value as an override: its tokens, with upstream's default+-- before them where only @extra-@ assignments built it, none merged and+-- none dropped.+listOverride :: [ByteString] -> HowAssigned -> [ByteString] -> ByteString+listOverride upstreamDefault how items = joinTokens (start ++ items)+  where+    start = case how of+      ExtendedOnly -> upstreamDefault+      Replaced -> []++-- | A set of paths as an override: replacing the default, under the+-- setting's own name, and adding to it, under its @extra-@ name.+pathSetOverride :: ByteString -> PathSetValue -> Maybe (ByteString, ByteString)+pathSetOverride key (PathSetValue use paths) = case use of+  ReplacesDefault -> Just (key, joinTokens (Set.toAscList paths))+  KeepsDefault+    | Set.null paths -> Nothing+    | otherwise -> Just (extraPrefix <> key, joinTokens (Set.toAscList paths))++-- | The tokens of a value as upstream's @Strings@ and @StringSet@ settings+-- write them.+joinTokens :: [ByteString] -> ByteString+joinTokens = BS.intercalate valueSeparator++spellBool :: Bool -> ByteString+spellBool True = canonicalTrue+spellBool False = canonicalFalse++spellNumber :: Word32 -> ByteString+spellNumber = BS8.pack . show++-- | How a setting reaches a daemon from a client.  Every setting this+-- module reads has one, so a setting added to it is classified before it+-- compiles ('carriage').+data Carriage+  = -- | As an override, from the systems upstream declares it on: a+    -- setting of upstream's store library or its file transfer.+    Sent !Declared+  | -- | As a field of the @SetOptions@ message, where upstream's client+    -- takes it out of its overrides: keep-failed, fallback and cores.+    InOptions+  | -- | Not at all: the client's own.  These are the settings of+    -- upstream's other configuration objects (the evaluator's, which says+    -- how deep calls nest, what an evaluation may reach and whether an+    -- import from a derivation builds and traces; the @develop@ command's+    -- prompt; the daemon command's, who it trusts and who may connect),+    -- and the two its client takes out of its overrides because they are+    -- its own: @experimental-features@, which a daemon ignores from a+    -- client, and @use-xdg-base-directories@, which places the client's+    -- default profile.  The @store@ setting is the client's own as well:+    -- what a daemon is sent for it depends on the command's flag and on+    -- @NIX_REMOTE@, which this module does not see, so the client sends it+    -- itself (@storeOverride@ in "Nix.Daemon.StoreChoice").+    ClientsOwn++-- | The systems upstream declares a setting on, by the names+-- 'System.Info.os' gives them.  Its client has the setting, and so sends+-- it, on those alone.+data Declared+  = -- | Every system.+    EverySystem+  | -- | Only these.+    OnlySystems ![String]+  | -- | Every system but these.+    EverySystemBut ![String]++-- | Whether a setting is declared on a system.+declaredOn :: String -> Declared -> Bool+declaredOn _ EverySystem = True+declaredOn os (OnlySystems systems) = os `elem` systems+declaredOn os (EverySystemBut systems) = os `notElem` systems++-- | The names 'System.Info.os' gives the systems a setting is declared+-- on or off.+linuxOs, freeBsdOs, darwinOs, windowsOs :: String+linuxOs = "linux"+freeBsdOs = "freebsd"+darwinOs = "darwin"+windowsOs = "mingw32"++-- | How a setting is carried, by an exhaustive match over each kind of+-- setting.+carriage :: Setting -> Carriage+carriage setting = case setting of+  ListSetting field -> listCarriage field+  WordsSetting field -> wordsCarriage field+  BoolSetting field -> boolCarriage field+  ScalarSetting field -> scalarCarriage field+  ModeSetting -> everySystem+  BytesSetting field -> bytesCarriage field+  PathSetSetting field -> pathSetCarriage field+  FeaturesSetting -> ClientsOwn++-- | A setting of the store library or the file transfer, declared on every+-- system.+everySystem :: Carriage+everySystem = Sent EverySystem++listCarriage :: ListField -> Carriage+listCarriage SubstitutersField = everySystem+listCarriage TrustedKeysField = everySystem+listCarriage AllowedUrisField = ClientsOwn+listCarriage TrustedSubstitutersField = everySystem++wordsCarriage :: WordsField -> Carriage+wordsCarriage TrustedUsersField = ClientsOwn+wordsCarriage AllowedUsersField = ClientsOwn+wordsCarriage SecretKeyFilesField = everySystem++-- | Upstream declares @require-drop-supplementary-groups@ on every system+-- but Windows and @darwin-log-sandbox-violations@ on macOS alone.+boolCarriage :: BoolField -> Carriage+boolCarriage FallbackField = InOptions+boolCarriage AlwaysAllowSubstitutesField = everySystem+boolCarriage RestrictEvalField = ClientsOwn+boolCarriage PureEvalField = ClientsOwn+boolCarriage TraceVerboseField = ClientsOwn+boolCarriage AllowImportFromDerivationField = ClientsOwn+boolCarriage TraceImportFromDerivationField = ClientsOwn+boolCarriage SandboxFallbackField = everySystem+boolCarriage RequireDropGroupsField = Sent (EverySystemBut [windowsOs])+boolCarriage UseXdgBaseDirectoriesField = ClientsOwn+boolCarriage DarwinLogSandboxViolationsField = Sent (OnlySystems [darwinOs])+boolCarriage KeepFailedField = InOptions+boolCarriage RequireSigsField = everySystem++scalarCarriage :: ScalarField -> Carriage+scalarCarriage MaxCallDepthField = ClientsOwn+scalarCarriage CoresField = InOptions+scalarCarriage DownloadAttemptsField = everySystem++-- | Upstream declares @sandbox-build-dir@ on Linux and FreeBSD and+-- @sandbox-dev-shm-size@ on Linux alone.+bytesCarriage :: BytesField -> Carriage+bytesCarriage SandboxBuildDirField = Sent (OnlySystems [linuxOs, freeBsdOs])+bytesCarriage SandboxDevShmSizeField = Sent (OnlySystems [linuxOs])+bytesCarriage SslCertFileField = everySystem+bytesCarriage BuildUsersGroupField = everySystem+bytesCarriage StoreField = ClientsOwn+bytesCarriage BashPromptField = ClientsOwn+bytesCarriage BashPromptPrefixField = ClientsOwn+bytesCarriage BashPromptSuffixField = ClientsOwn++pathSetCarriage :: PathSetField -> Carriage+pathSetCarriage SandboxPathsField = everySystem+pathSetCarriage AllowedImpureHostDepsField = everySystem++-- | The name a setting is known by, which an alias and an @extra-@+-- spelling both resolve to.+settingKey :: Setting -> ByteString+settingKey setting = case setting of+  ListSetting field -> listFieldKey field+  WordsSetting field -> wordsFieldKey field+  BoolSetting field -> boolFieldKey field+  ScalarSetting field -> scalarFieldKey field+  ModeSetting -> sandboxKey+  BytesSetting field -> bytesFieldKey field+  PathSetSetting field -> pathSetFieldKey field+  FeaturesSetting -> experimentalFeaturesKey++-- --------------------------------------------------------------------------- -- Messages -- --------------------------------------------------------------------------- @@ -689,16 +1424,88 @@ trustedKeysKey = "trusted-public-keys" trustedKeysAlias = "binary-cache-public-keys" +-- | The settings that decide what a path copied into the store must be+-- signed by, beside @trusted-public-keys@.+secretKeyFilesKey, requireSigsKey :: ByteString+secretKeyFilesKey = "secret-key-files"+requireSigsKey = "require-sigs"+ fallbackKey, fallbackAlias :: ByteString fallbackKey = "fallback" fallbackAlias = "build-fallback" -allowedUrisKey, maxCallDepthKey, pureEvalKey, restrictEvalKey, traceVerboseKey :: ByteString+coresKey, coresAlias :: ByteString+coresKey = "cores"+coresAlias = "build-cores"++downloadAttemptsKey, downloadAttemptsAlias :: ByteString+downloadAttemptsKey = "filetransfer-retry-attempts"+downloadAttemptsAlias = "download-attempts"++allowImportFromDerivationKey, allowedUrisKey, alwaysAllowSubstitutesKey, maxCallDepthKey, pureEvalKey, restrictEvalKey, traceImportFromDerivationKey, traceVerboseKey :: ByteString+allowImportFromDerivationKey = "allow-import-from-derivation" allowedUrisKey = "allowed-uris"+alwaysAllowSubstitutesKey = "always-allow-substitutes" maxCallDepthKey = "max-call-depth" pureEvalKey = "pure-eval" restrictEvalKey = "restrict-eval"+traceImportFromDerivationKey = "trace-import-from-derivation" traceVerboseKey = "trace-verbose"++sandboxKey, sandboxFallbackKey, sandboxPathsKey, sandboxBuildDirKey, sandboxDevShmSizeKey, requireDropGroupsKey, sslCertFileKey :: ByteString+sandboxKey = "sandbox"+sandboxFallbackKey = "sandbox-fallback"+sandboxPathsKey = "sandbox-paths"+sandboxBuildDirKey = "sandbox-build-dir"+sandboxDevShmSizeKey = "sandbox-dev-shm-size"+requireDropGroupsKey = "require-drop-supplementary-groups"+sslCertFileKey = "ssl-cert-file"++useXdgBaseDirectoriesKey :: ByteString+useXdgBaseDirectoriesKey = "use-xdg-base-directories"++-- | Upstream's name for the group whose members builds run as.+buildUsersGroupKey :: ByteString+buildUsersGroupKey = "build-users-group"++-- | Upstream's name for the setting that names the store commands use.+storeKey :: ByteString+storeKey = "store"++-- | The daemon's settings: who it trusts and who may connect, and the+-- substituters an untrusted client may ask for, with that setting's older+-- name.+trustedUsersKey, allowedUsersKey, trustedSubstitutersKey, trustedSubstitutersAlias :: ByteString+trustedUsersKey = "trusted-users"+allowedUsersKey = "allowed-users"+trustedSubstitutersKey = "trusted-substituters"+trustedSubstitutersAlias = "trusted-binary-caches"++-- | The settings of a @develop@ shell's prompt (@DevelopSettings@ in+-- develop.cc).+bashPromptKey, bashPromptPrefixKey, bashPromptSuffixKey :: ByteString+bashPromptKey = "bash-prompt"+bashPromptPrefixKey = "bash-prompt-prefix"+bashPromptSuffixKey = "bash-prompt-suffix"++allowedImpureHostDepsKey, darwinLogSandboxViolationsKey :: ByteString+allowedImpureHostDepsKey = "allowed-impure-host-deps"+darwinLogSandboxViolationsKey = "darwin-log-sandbox-violations"++experimentalFeaturesKey :: ByteString+experimentalFeaturesKey = "experimental-features"++-- | The setting for what a build that fails leaves, which upstream gives no+-- other name.+keepFailedKey :: ByteString+keepFailedKey = "keep-failed"++-- | Upstream's older names for @sandbox@ and @sandbox-paths@+-- (the aliases of @sandboxMode@ and @sandboxPaths@ in globals.hh at+-- 2.24.9, local-settings.hh from 2.34.9).+sandboxAliases, sandboxPathsAliases :: [ByteString]+sandboxAliases = ["build-use-chroot", "build-use-sandbox"]+sandboxPathsAliases = ["build-chroot-dirs", "build-sandbox-paths"]  extraPrefix :: ByteString extraPrefix = "extra-"
+ src/Nix/Daemon/Auth.hs view
@@ -0,0 +1,322 @@+{-# LANGUAGE LambdaCase #-}++-- | Who may connect to a daemon, and whom it trusts, as upstream's daemon+-- decides from what the operating system says of a connection's peer:+-- its user, matched against @trusted-users@ and @allowed-users@ by name,+-- by @*@, or by a group named with @\@@; and its group, a member of the+-- build users' group being refused.+--+-- On Windows a peer is an account, read from the token of a named pipe's+-- client ('admitAccount'): its user and the groups the token grants by,+-- each a SID.  An entry names an account as Windows resolves a name+-- (@NAME@, an account of this machine, or @DOMAIN\\NAME@ or+-- @NAME\@DOMAIN@) or by its SID (@S-1-5-...@), and matches by SID: a bare+-- entry the user, and an entry after @\@@ a group the token holds.  An+-- account whose name holds a space is named by its SID, since the+-- settings are lists split at whitespace.  A client is refused for the+-- build users' group by the groups Windows holds for its account, not by+-- those its token shows, which its holder can shape.+--+-- The decision is pure over the account database it is given, a+-- t'UserDatabase' or an t'AccountDatabase', so it runs in tests over+-- users that do not exist; "Nix.Daemon.Listen" gives it the system's, and+-- a peer's identity read from a Unix socket or a named pipe.+--+-- The other way round, a client of a daemon's named pipe on Windows+-- decides whether the pipe is the daemon's by the account that owns it+-- ('trustsPipeOwner').+module Nix.Daemon.Auth+  ( -- * Peers+    Peer (..),+    unknownPeer,++    -- * The user database+    UserDatabase (..),+    GroupEntry (..),++    -- * Windows accounts+    AccountPeer (..),+    AccountKind (..),+    AccountDatabase (..),++    -- * Admission+    AuthSettings (..),+    Admission (..),+    admitPeer,+    admitAccount,+    acceptedMessage,++    -- * Trusting a daemon+    trustsPipeOwner,+  )+where++import Data.Bifunctor (first)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BS8+import Data.Either (fromRight)+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Word (Word32)+import Nix.Builder.BuildUser (peerInBuildUsersGroup)+import Nix.Daemon.Protocol (Trust (..))+import Nix.Store.Access (Sid, administratorsSid, localSystemSid, novaNixServiceSid, sidFromText, sidText)++-- ---------------------------------------------------------------------------+-- Peers+-- ---------------------------------------------------------------------------++-- | What the operating system says of a connection's peer, as far as it+-- says: its process, its user and its group, each by number.+data Peer = Peer+  { peerProcess :: !(Maybe Word32),+    peerUser :: !(Maybe Word32),+    peerGroup :: !(Maybe Word32)+  }+  deriving (Eq, Show)++-- | A peer the daemon knows nothing of, as one whose trust is forced is+-- treated: its identity is not read.+unknownPeer :: Peer+unknownPeer = Peer Nothing Nothing Nothing++-- ---------------------------------------------------------------------------+-- The user database+-- ---------------------------------------------------------------------------++-- | A group as the user database records it: its number and the names+-- it lists as members.+data GroupEntry = GroupEntry+  { groupEntryId :: !Word32,+    groupEntryMembers :: ![ByteString]+  }+  deriving (Eq, Show)++-- | What the decision asks of the system's users and groups.+data UserDatabase m = UserDatabase+  { -- | A user's name, by number.+    udUserName :: !(Word32 -> m (Maybe ByteString)),+    -- | A group's name, by number.+    udGroupName :: !(Word32 -> m (Maybe ByteString)),+    -- | A group, by name.+    udGroup :: !(ByteString -> m (Maybe GroupEntry)),+    -- | Whether a user is a member of a group, by their numbers, where+    -- the system answers that apart from a group's member list, as+    -- macOS's directory does, and 'Nothing' where it does not or the+    -- question fails.+    udMembership :: !(Word32 -> Word32 -> m (Maybe Bool))+  }++-- ---------------------------------------------------------------------------+-- Windows accounts+-- ---------------------------------------------------------------------------++-- | What Windows says of a named pipe's client, read from its token: its+-- process, where known, its user, and the groups it grants by, each by+-- SID.+data AccountPeer = AccountPeer+  { accountProcess :: !(Maybe Word32),+    accountUser :: !Sid,+    -- | The token's groups that are enabled and not held for deny only,+    -- as an access check counts them: the ones that trust or admit it.+    accountGroups :: ![Sid]+  }+  deriving (Eq, Show)++-- | What an account name is to name.+data AccountKind+  = -- | A user, as a @trusted-users@ or @allowed-users@ entry with no+    -- @\@@ names one.  SYSTEM and a service's virtual account are users+    -- here, as processes run as them.+    UserAccount+  | -- | A group, as an entry after @\@@ or @build-users-group@ names one.+    GroupAccount+  deriving (Eq, Show)++-- | What the decision asks of Windows' accounts.+data AccountDatabase m = AccountDatabase+  { -- | The SID an account's name names, as Windows resolves one, where+    -- one of that kind has the name: 'Right' 'Nothing' where none does,+    -- and 'Left' why where the lookup could not be made, which is not an+    -- answer.+    adAccountSid :: !(AccountKind -> ByteString -> m (Either Text (Maybe Sid))),+    -- | An account's name, @DOMAIN\\NAME@, by its SID, or 'Nothing' where+    -- it has none.+    adAccountName :: !(Sid -> m (Maybe ByteString)),+    -- | Every group an account belongs to, as Windows computes them from+    -- the account, or why it cannot say.+    adAccountGroups :: !(Sid -> m (Either Text [Sid]))+  }++-- ---------------------------------------------------------------------------+-- Admission+-- ---------------------------------------------------------------------------++-- | The daemon's settings that decide admission, as bytes, matched+-- against the user database's.+data AuthSettings = AuthSettings+  { -- | @trusted-users@.+    asTrustedUsers :: ![ByteString],+    -- | @allowed-users@.+    asAllowedUsers :: ![ByteString],+    -- | @build-users-group@, empty for none.+    asBuildUsersGroup :: !ByteString+  }+  deriving (Eq, Show)++-- | What becomes of a peer.+data Admission+  = -- | It may connect, trusted or not, and is named so, where it has a+    -- name.+    Admitted !Trust !(Maybe ByteString)+  | -- | It may not, for this reason.+    Refused !Text+  deriving (Eq, Show)++-- | Decide a peer's admission as upstream's daemon does.  The peer is+-- named by its user's name, or its user's number where the user has no+-- entry, and its group likewise.  It is trusted when @trusted-users@+-- matches it, and a peer that is not is refused unless @allowed-users@+-- matches it; a peer whose group is the build users' is refused either+-- way.+admitPeer :: (Monad m) => UserDatabase m -> AuthSettings -> Peer -> m Admission+admitPeer db settings peer = do+  user <- traverse (\uid -> fromMaybe (decimal uid) <$> udUserName db uid) (peerUser peer)+  group <- traverse (\gid -> fromMaybe (decimal gid) <$> udGroupName db gid) (peerGroup peer)+  let matches = matchUser db peer user group+  trusted <- matches (asTrustedUsers settings)+  allowed <- if trusted then pure True else matches (asAllowedUsers settings)+  pure $+    if not allowed || peerInBuildUsersGroup (asBuildUsersGroup settings) group+      then refusal user+      else Admitted (if trusted then Trusted else NotTrusted) user++-- | Decide a Windows account's admission as 'admitPeer' decides a POSIX+-- peer's, by SID: an entry names the user, or after @\@@ a group the+-- token grants by, by SID or by a name Windows resolves to one, and @*@+-- everyone.  The account is named by its name, or its SID where it has+-- none.  An entry that cannot be looked up names no one, which only+-- withholds trust or admission.  An account that belongs to the build+-- users' group, by the groups Windows holds for it, is refused whatever+-- its token shows, and one whose membership cannot be told, or whose group+-- cannot be looked up, is refused too, where a mistaken answer would let+-- a build account in.+admitAccount :: (Monad m) => AccountDatabase m -> AuthSettings -> AccountPeer -> m Admission+admitAccount db settings peer = do+  name <- fromMaybe (TE.encodeUtf8 (sidText user)) <$> adAccountName db user+  trusted <- matches (asTrustedUsers settings)+  allowed <- if trusted then pure True else matches (asAllowedUsers settings)+  building <- inBuildUsersGroup (asBuildUsersGroup settings)+  pure $ case building of+    Left reason -> Refused (notAllowed (Just name) <> ": " <> reason)+    Right member+      | member || not allowed -> refusal (Just name)+      | otherwise -> Admitted (if trusted then Trusted else NotTrusted) (Just name)+  where+    user = accountUser peer+    matches = anyM entryMatches+    entryMatches entry+      | entry == everyone = pure True+      | Just group <- BS.stripPrefix groupMark entry = maybe False (`elem` accountGroups peer) . resolved <$> entrySid GroupAccount group+      | otherwise = (== Just user) . resolved <$> entrySid UserAccount entry+    resolved = fromRight Nothing+    inBuildUsersGroup group+      | BS.null group = pure (Right False)+      | otherwise =+          entrySid GroupAccount group >>= \case+            Left reason -> pure (Left ("cannot look up build-users-group '" <> TE.decodeUtf8Lenient group <> "': " <> reason))+            -- A group no account has holds no one.+            Right Nothing -> pure (Right False)+            Right (Just built) -> fmap (elem built) . first ("cannot tell the groups of the account: " <>) <$> adAccountGroups db user+    entrySid kind entry+      | BS.null entry = pure (Right Nothing)+      | Right text <- TE.decodeUtf8' entry, Just sid <- sidFromText text = pure (Right (Just sid))+      | otherwise = adAccountSid db kind entry++-- | Upstream's refusal of a peer, named by its user where it has one.+refusal :: Maybe ByteString -> Admission+refusal = Refused . notAllowed++-- | What upstream's daemon says of a peer it will not serve.+notAllowed :: Maybe ByteString -> Text+notAllowed user = "user '" <> maybe unknownName TE.decodeUtf8Lenient user <> "' is not allowed to connect to the Nix daemon"++-- | Whether a list of users matches the peer: @*@ matches everyone, a+-- name the peer's user's name, and @\@GROUP@ a peer whose group is+-- named so or whose user the group lists, or, where the system answers+-- membership itself, one it says is a member.+matchUser :: (Monad m) => UserDatabase m -> Peer -> Maybe ByteString -> Maybe ByteString -> [ByteString] -> m Bool+matchUser db peer user group users+  | everyone `elem` users = pure True+  | maybe False (`elem` users) user = pure True+  | otherwise = anyM groupMatches [name | entry <- users, Just name <- [BS.stripPrefix groupMark entry]]+  where+    groupMatches name+      | group == Just name = pure True+      | otherwise =+          udGroup db name >>= \case+            Nothing -> pure False+            Just entry -> maybe (pure False) (`listedIn` entry) user+    listedIn name entry+      | name `elem` groupEntryMembers entry = pure True+      | otherwise = maybe (pure False) (\uid -> fromMaybe False <$> udMembership db uid (groupEntryId entry)) (peerUser peer)++-- | Whether any of the tests passes, trying them in order until one does.+anyM :: (Monad m) => (a -> m Bool) -> [a] -> m Bool+anyM test = \case+  [] -> pure False+  item : rest -> test item >>= \passed -> if passed then pure True else anyM test rest++-- | The entry that matches every user, and the mark of a group.+everyone, groupMark :: ByteString+everyone = "*"+groupMark = "@"++-- | A number as upstream names a user or group without an entry.+decimal :: Word32 -> ByteString+decimal = BS8.pack . show++-- | How a peer with no user is named.+unknownName :: Text+unknownName = "<unknown>"++-- | The line upstream's daemon logs as it accepts a connection, given the+-- peer's process, where known.+acceptedMessage :: Maybe Word32 -> Admission -> Text+acceptedMessage process admission =+  "accepted connection from pid "+    <> maybe unknownName (T.pack . show) process+    <> ", user "+    <> named+  where+    named = case admission of+      Admitted Trusted user -> userText user <> " (trusted)"+      Admitted NotTrusted user -> userText user+      Refused _ -> unknownName+    userText = maybe unknownName TE.decodeUtf8Lenient++-- ---------------------------------------------------------------------------+-- Trusting a daemon+-- ---------------------------------------------------------------------------++-- | Whether a client trusts a named pipe to be a daemon's, given its own+-- account and the account that owns the pipe.  The process that makes a+-- pipe chooses its owner, and Windows lets it choose only its token's+-- user or a group its token holds enabled with the right to own objects+-- as it: an elevated administrator's token holds Administrators so, and a+-- filtered one, which holds the group for deny only, does not.  Only a+-- process holding the restore privilege, which an elevated+-- administrator's token has, can name another owner.  So the owner says+-- who made the pipe.  A client trusts a pipe owned by its own account, by+-- SYSTEM, by Administrators, or by the virtual account+-- @NT SERVICE\\nova-nix@ the daemon's Windows service is to run as.  Any+-- other user owns the pipes it makes as itself, an administrator who is+-- not elevated among them, and is not trusted, and neither are the other+-- accounts services run as, which other services share.+trustsPipeOwner :: Sid -> Sid -> Bool+trustsPipeOwner client owner = owner == client || owner `elem` trustedServers+  where+    trustedServers = [localSystemSid, administratorsSid, novaNixServiceSid]
+ src/Nix/Daemon/Client.hs view
@@ -0,0 +1,612 @@+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TupleSections #-}++-- | A client of a daemon that speaks upstream's worker protocol, as+-- upstream's remote store is one: the handshake as the client, then each+-- operation it asks, its request, any upload after it, the daemon's+-- messages while it works and the reply.+--+-- == The session+--+-- A t'ClientT' runs over a t'Transport', the daemon's side being the+-- other end, after the handshake 'runClient' makes: the client offers the+-- newest version it speaks and its features, and the session runs at the+-- lower of the two numbers, with the features both list, refusing a+-- daemon older than upstream's oldest.  The core is pure: everything the+-- client does to the world goes through the transport and the report the+-- daemon's messages are given to ('relayMessage' gives them to a+-- t'Logger').+--+-- A session need not run in one call.  'openSession' makes the handshake+-- and answers a t'ClientSession', which 'continueSession' runs steps+-- over, any number of times, one call after another: the bytes the daemon+-- sent that a step did not read stay with the session, and each call is+-- given the transport and the report afresh.  'runClient' is the two+-- together for a session that runs in one call.+--+-- == Failures+--+-- An operation the daemon fails is a 'DaemonFailed', which 'attempt'+-- turns into a value, the session going on as upstream's does after an+-- error its daemon sends; one the client will not send at the agreed+-- version is a 'NotSent', which leaves the session as it was; and a+-- connection that broke, or that the daemon sent bytes the protocol does+-- not allow, is a 'ConnectionLost', after which nothing more is read.+--+-- == Uploads+--+-- An upload is framed, as from the versions every daemon serving it+-- frames it.  The daemon's messages are read on a thread of their own+-- while the frames are written, so a daemon that says more during an add+-- than the connection holds does not stall the upload, whatever the+-- transport.  An exception of the transport, or of the chunk source (a+-- file that cannot be read), stops the reading and goes up out of the+-- operation, and the session is not to be used again, its framed stream+-- being cut short.  An upload runs in 'IO', which the threads need.+module Nix.Daemon.Client+  ( -- * The session+    ClientT,+    ClientFailure (..),+    runClient,+    ClientSession,+    openSession,+    continueSession,+    attempt,+    agreedVersion,+    daemonInfo,+    offeredVersion,++    -- * Operations+    setOptions,+    isValidPath,+    queryValidPaths,+    querySubstitutablePaths,+    queryReferrers,+    queryValidDerivers,+    queryDerivationOutputMap,+    queryAllValidPaths,+    queryPathInfo,+    queryMissing,+    addToStore,+    addToStoreNar,+    buildPaths,+    buildPathsWithResults,+    ensurePath,+    addTempRoot,+    addIndirectRoot,++    -- * The daemon's messages+    Relayed (..),+    relayed,+    Relay,+    newRelay,+    relayMessage,+    stopOpenActivities,+    disconnectedMessage,+  )+where++import Control.Concurrent (forkIOWithUnmask, killThread)+import Control.Concurrent.MVar (newEmptyMVar, putMVar, readMVar)+import Control.Exception (SomeException, mask, mask_, onException, throwIO, try)+import Control.Monad (void, when)+import Control.Monad.Except (ExceptT, MonadError, catchError, runExceptT, throwError)+import Control.Monad.Reader (MonadReader, ReaderT, asks, runReaderT)+import qualified Control.Monad.Reader as Reader+import Control.Monad.State.Strict (MonadState, StateT, get, gets, modify', put, runStateT)+import Control.Monad.Trans (lift)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import Data.ByteString.Builder (Builder)+import qualified Data.ByteString.Char8 as BS8+import Data.Foldable (traverse_)+import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Tuple (swap)+import Data.Word (Word64)+import Nix.Daemon.Connection (Transport (..))+import Nix.Daemon.Ops (AddToStoreRequest, CheckSigs, ClientSettings, Repair, Request (..), Substitute, activityStart, buildResultsSince, outputMapSince, putRequest, queryMissingSince)+import Nix.Daemon.Protocol+  ( Activity (..),+    ActivityId (..),+    BuildMode,+    DaemonError,+    DerivedPath,+    Field (..),+    HandshakeInfo,+    KeyedBuildResult,+    Missing,+    OutputName,+    StderrMessage (..),+    UnkeyedValidPathInfo,+    ValidPathInfo,+    Version (..),+    VersionNumber (..),+    featureDeleteDeadSpecificReferrers,+    featureDisableSetOptions,+    featureRealisationWithPath,+    getFeatures,+    getHandshakeInfo,+    getKeyedBuildResults,+    getMissing,+    getOutputMap,+    getServerMagic,+    getStderrMessage,+    getStorePathSet,+    getUnkeyedValidPathInfo,+    getValidPathInfo,+    getVersionNumber,+    latestVersionNumber,+    minimumVersionNumber,+    putClientMagic,+    putClientObsoleteFields,+    putFeatures,+    putVersionNumber,+    resBuildLogLine,+    resPostBuildLogLine,+  )+import Nix.Daemon.Wire (DecodeError (..), Decoder, Decoding (..), feedInput, getBool, getWord64, putFrame, putFrameEnd, startDecoding)+import Nix.Logger (ActivityStart, Level (..), Logger (..), logMessage)+import Nix.Store.Path (StoreDir, StorePath)++-- ---------------------------------------------------------------------------+-- The session+-- ---------------------------------------------------------------------------++-- | Why an operation, or the session, did not get its answer.+data ClientFailure+  = -- | The daemon failed the operation, with its error, which upstream's+    -- client throws as the daemon's.  The session goes on, unless the+    -- daemon closed the connection with it, which the next operation+    -- finds.+    DaemonFailed !DaemonError+  | -- | The client will not send the operation at the agreed version, for+    -- the reason given; nothing was sent.+    NotSent !Text+  | -- | The connection broke, or the daemon sent what the protocol does+    -- not allow, for the reason given.  Nothing more can be read.+    ConnectionLost !Text+  deriving (Eq, Show)++-- | What every step of a session reads.+data ClientEnv m = ClientEnv+  { ceStoreDir :: !StoreDir,+    ceTransport :: !(Transport m),+    ceReport :: !(StderrMessage -> m ())+  }++-- | What a session holds: the version agreed, what the daemon told the+-- client, and the bytes the daemon sent that have not been read.  It+-- belongs to the connection it was opened on, whose daemon its bytes are.+data ClientSession = ClientSession+  { sessVersion :: !Version,+    sessInfo :: !(Maybe HandshakeInfo),+    sessInput :: !ByteString+  }++-- | A session before its handshake: nothing agreed or heard.+unopenedSession :: ClientSession+unopenedSession = ClientSession (Version minimumVersionNumber Set.empty) Nothing BS.empty++-- | A session's steps over the monad its transport runs in.  A failure+-- ends the steps that follow it unless 'attempt' catches it, and leaves+-- what the session has read read, so a caught failure leaves the session+-- where the daemon's bytes put it.+newtype ClientT m a = ClientT (ReaderT (ClientEnv m) (ExceptT ClientFailure (StateT ClientSession m)) a)+  deriving (Functor, Applicative, Monad, MonadReader (ClientEnv m), MonadError ClientFailure, MonadState ClientSession)++-- | Run an action in the transport's monad.+inner :: (Monad m) => m a -> ClientT m a+inner = ClientT . lift . lift . lift++-- | The version this client offers: the newest number upstream speaks,+-- with the features the codec carries and 'featureDisableSetOptions', as+-- upstream's client offers it.+offeredVersion :: Version+offeredVersion = Version latestVersionNumber (Set.fromList [featureRealisationWithPath, featureDeleteDeadSpecificReferrers, featureDisableSetOptions])++-- | Make the handshake with a daemon over a transport, offering the+-- version given ('offeredVersion' as upstream's client offers its own),+-- naming paths under the store directory given, and giving what the+-- daemon says as it works to the report; then run the session's steps.+-- The session's input is the daemon's; nothing is closed here.+runClient :: (Monad m) => StoreDir -> Version -> Transport m -> (StderrMessage -> m ()) -> ClientT m a -> m (Either ClientFailure a)+runClient storeDir offered transport report steps =+  openSession storeDir offered transport report >>= \case+    Left failure -> pure (Left failure)+    Right session -> fst <$> continueSession storeDir transport report session steps++-- | Make the handshake with a daemon over a transport, as 'runClient'+-- does, and answer the session it made, for 'continueSession' to run+-- steps over.+openSession :: (Monad m) => StoreDir -> Version -> Transport m -> (StderrMessage -> m ()) -> m (Either ClientFailure ClientSession)+openSession storeDir offered transport report = do+  (outcome, session) <- continueSession storeDir transport report unopenedSession (handshake offered)+  pure (session <$ outcome)++-- | Run steps over a session opened earlier, over the transport it was+-- opened on, the daemon's messages given to the report, and answer what+-- the steps answer with the session as they leave it.  A failed step+-- leaves what it read read, and a 'ConnectionLost' leaves the session+-- unusable, as 'attempt' says.+continueSession :: StoreDir -> Transport m -> (StderrMessage -> m ()) -> ClientSession -> ClientT m a -> m (Either ClientFailure a, ClientSession)+continueSession storeDir transport report = runSteps (ClientEnv storeDir transport report)++-- | Run steps over what they read, given the session as it stands.+runSteps :: ClientEnv m -> ClientSession -> ClientT m a -> m (Either ClientFailure a, ClientSession)+runSteps env session (ClientT steps) = runStateT (runExceptT (runReaderT steps env)) session++-- | Run steps, a failure of theirs answered as a value: what was read+-- stays read, and a 'ConnectionLost' leaves the session unusable all the+-- same.+attempt :: (Monad m) => ClientT m a -> ClientT m (Either ClientFailure a)+attempt steps = (Right <$> steps) `catchError` (pure . Left)++-- | The version the session agreed.+agreedVersion :: (Monad m) => ClientT m Version+agreedVersion = gets sessVersion++-- | What the daemon told the client at the handshake.+daemonInfo :: (Monad m) => ClientT m (Maybe HandshakeInfo)+daemonInfo = gets sessInfo++-- | The version a daemon's features are exchanged from.+featureExchangeSince :: VersionNumber+featureExchangeSince = VersionNumber 1 38++-- | Agree a version with the daemon, as upstream's client does: send the+-- opening word and the version offered together, read the daemon's word+-- and number, refuse another major version or one older than upstream's+-- oldest, and from 1.38 send the features offered and read the daemon's.+-- Then send the obsolete fields, read what the daemon tells its client,+-- and read its startup work to its end.+handshake :: (Monad m) => Version -> ClientT m ()+handshake offered = do+  send (putClientMagic <> putVersionNumber (versionNumber offered))+  receive getServerMagic+  daemonNumber <- receive getVersionNumber+  when (vnMajor daemonNumber /= vnMajor latestVersionNumber) (throwError (ConnectionLost "Nix daemon protocol version not supported"))+  let agreed = min daemonNumber (versionNumber offered)+  when (agreed < minimumVersionNumber) (throwError (ConnectionLost "the Nix daemon version is too old"))+  daemonFeatures <-+    if agreed >= featureExchangeSince+      then send (putFeatures (versionFeatures offered)) *> receive getFeatures+      else pure Set.empty+  let version = Version agreed (Set.intersection daemonFeatures (versionFeatures offered))+  modify' (\session -> session {sessVersion = version})+  send (putClientObsoleteFields version)+  info <- receive (getHandshakeInfo version)+  modify' (\session -> session {sessInfo = Just info})+  awaitWork++-- | Upstream's words for a daemon that went away mid-session.+disconnectedMessage :: Text+disconnectedMessage = "Nix daemon disconnected unexpectedly (maybe it crashed?)"++-- | Read a value the daemon sends, the input after it kept.+receive :: (Monad m) => Decoder a -> ClientT m a+receive decoder = do+  held <- gets sessInput+  modify' (\session -> session {sessInput = BS.empty})+  settle (if BS.null held then startDecoding decoder else feedInput (Just held) (startDecoding decoder))+  where+    settle = \case+      Decoded value rest -> value <$ modify' (\session -> session {sessInput = rest})+      DecodeFailed failure rest -> do+        modify' (\session -> session {sessInput = rest})+        throwError (ConnectionLost (decodeFailure failure))+      NeedInput more -> do+        transport <- asks ceTransport+        inner (transportReceive transport) >>= settle . more+    decodeFailure = \case+      InputEnded -> disconnectedMessage+      Malformed message -> message++-- | Send bytes to the daemon.+send :: (Monad m) => Builder -> ClientT m ()+send bytes = do+  transport <- asks ceTransport+  inner (transportSend transport bytes)++-- | Read the daemon's messages until its work on an operation is done,+-- each given to the report, as upstream's client reads them: the end of+-- the work ends the reading, and the daemon's error fails the operation.+-- The client sends no upload unframed and has no sink, so a request for+-- either is the daemon's breach of the session, in upstream's words.+awaitWork :: (Monad m) => ClientT m ()+awaitWork = do+  version <- gets sessVersion+  receive (getStderrMessage version) >>= \case+    StderrLast -> pure ()+    StderrError failure -> throwError (DaemonFailed failure)+    StderrRead _ -> throwError (ConnectionLost "no source")+    StderrWrite _ -> throwError (ConnectionLost "no sink")+    message -> do+      report <- asks ceReport+      inner (report message)+      awaitWork++-- ---------------------------------------------------------------------------+-- Requests+-- ---------------------------------------------------------------------------++-- | A request as the client sends it at the agreed version, as+-- 'putRequest' writes it, or why it is not sent: what 'putRequest'+-- refuses, and an operation the version does not carry.  Upstream's+-- client works out a build's results, what is missing and a derivation's+-- outputs itself when its daemon is older than the operation; this one+-- does not send it.+clientRequest :: StoreDir -> Version -> Request -> Either Text Builder+clientRequest storeDir version request = maybe (putRequest storeDir version request) Left (notCarried request)+  where+    notCarried = \case+      QueryMissing _ -> needs "QueryMissing" queryMissingSince+      QueryDerivationOutputMap _ -> needs "QueryDerivationOutputMap" outputMapSince+      BuildPathsWithResults _ _ -> needs "BuildPathsWithResults" buildResultsSince+      _ -> Nothing+    needs operation gate+      | versionNumber version >= gate = Nothing+      | otherwise = Just (operation <> " needs protocol 1." <> T.pack (show (vnMinor gate)) <> ", which the daemon does not speak")++-- ---------------------------------------------------------------------------+-- Operations+-- ---------------------------------------------------------------------------++-- | Send a request, and read the daemon's work to its end.+perform :: (Monad m) => Request -> ClientT m ()+perform request = sendRequest request *> awaitWork++-- | Send a request as it is sent at the agreed version, or refuse it as+-- 'NotSent'.+sendRequest :: (Monad m) => Request -> ClientT m ()+sendRequest request = do+  storeDir <- asks ceStoreDir+  version <- gets sessVersion+  written <- either (throwError . NotSent) pure (clientRequest storeDir version request)+  send written++-- | Send a request, then an upload after it, framed from a chunk source+-- that gives an empty chunk at its end, while the daemon's messages are+-- read on a thread of their own, and read the daemon's work to its end.+-- A failure of the daemon's work is the operation's, as for 'perform'; an+-- exception of the transport or the chunk source stops the reading and+-- goes up.+performUploading :: Request -> IO ByteString -> ClientT IO ()+performUploading request source = do+  sendRequest request+  env <- Reader.ask+  session <- get+  (outcome, afterWork) <- inner (fst <$> overlapped (runSteps env session awaitWork) (sendFrames (ceTransport env) source))+  put afterWork+  either throwError pure outcome++-- | Send the chunks a source gives as frames, and the end of the frames+-- where it gives an empty one.+sendFrames :: Transport IO -> IO ByteString -> IO ()+sendFrames transport source = do+  chunk <- source+  if BS.null chunk+    then transportSend transport putFrameEnd+    else transportSend transport (putFrame chunk) *> sendFrames transport source++-- | Run an action on a thread of its own while another runs on this one,+-- and answer what both answered.  An exception of this thread's action,+-- or an interrupt of this thread, stops the other thread and waits for it+-- to end before it goes up.  An exception of the other thread's action is+-- handed to this thread, which raises it once its own action has ended.+overlapped :: IO a -> IO b -> IO (a, b)+overlapped background foreground = mask $ \restore -> do+  outcome <- newEmptyMVar+  thread <- forkIOWithUnmask (\unmask -> try (unmask background) >>= putMVar outcome)+  let stop = killThread thread *> void (readMVar outcome)+  written <- restore foreground `onException` stop+  heard <- restore (readMVar outcome) `onException` stop+  either (\(err :: SomeException) -> throwIO err) (\value -> pure (value, written)) heard++-- | Ask, then read the reply.+ask :: (Monad m) => Request -> Decoder a -> ClientT m a+ask request reply = perform request *> receive reply++-- | Ask, then read the word an operation with nothing else to say replies+-- with.+done :: (Monad m) => Request -> ClientT m ()+done request = void (ask request getWord64)++-- | The store directory paths are named under.+storeDirOf :: (Monad m) => ClientT m StoreDir+storeDirOf = asks ceStoreDir++-- | Send the client's settings for the rest of the session.+setOptions :: (Monad m) => ClientSettings -> ClientT m ()+setOptions settings = perform (SetOptions settings)++-- | Whether a path is valid.+isValidPath :: (Monad m) => StorePath -> ClientT m Bool+isValidPath path = ask (IsValidPath path) getBool++-- | Which of the paths are valid, having first substituted them where+-- asked to.+queryValidPaths :: (Monad m) => Set StorePath -> Substitute -> ClientT m (Set StorePath)+queryValidPaths paths substitute = storeDirOf >>= ask (QueryValidPaths paths substitute) . getStorePathSet++-- | Which of the paths a substituter offers.+querySubstitutablePaths :: (Monad m) => Set StorePath -> ClientT m (Set StorePath)+querySubstitutablePaths paths = storeDirOf >>= ask (QuerySubstitutablePaths paths) . getStorePathSet++-- | The valid paths that refer to a path.+queryReferrers :: (Monad m) => StorePath -> ClientT m (Set StorePath)+queryReferrers path = storeDirOf >>= ask (QueryReferrers path) . getStorePathSet++-- | The valid derivations that output a path.+queryValidDerivers :: (Monad m) => StorePath -> ClientT m (Set StorePath)+queryValidDerivers path = storeDirOf >>= ask (QueryValidDerivers path) . getStorePathSet++-- | A derivation's outputs and the paths they have, where known.+queryDerivationOutputMap :: (Monad m) => StorePath -> ClientT m (Map OutputName (Maybe StorePath))+queryDerivationOutputMap path = storeDirOf >>= ask (QueryDerivationOutputMap path) . getOutputMap++-- | Every valid path.+queryAllValidPaths :: (Monad m) => ClientT m (Set StorePath)+queryAllValidPaths = storeDirOf >>= ask QueryAllValidPaths . getStorePathSet++-- | What the store records of a path, or 'Nothing' for a path that is not+-- valid.+queryPathInfo :: (Monad m) => StorePath -> ClientT m (Maybe UnkeyedValidPathInfo)+queryPathInfo path = do+  storeDir <- storeDirOf+  version <- gets sessVersion+  ask (QueryPathInfo path) $ do+    valid <- getBool+    if valid then Just <$> getUnkeyedValidPathInfo storeDir version else pure Nothing++-- | What realising the paths would build, substitute or not find.+queryMissing :: (Monad m) => [DerivedPath] -> ClientT m Missing+queryMissing targets = storeDirOf >>= ask (QueryMissing targets) . getMissing++-- | Make a content-addressed path from a dump, given the request and the+-- dump as a chunk source that gives an empty chunk at its end, and answer+-- the path's info.+addToStore :: AddToStoreRequest -> IO ByteString -> ClientT IO ValidPathInfo+addToStore upload dump = do+  storeDir <- storeDirOf+  version <- gets sessVersion+  performUploading (AddToStore upload) dump+  receive (getValidPathInfo storeDir version)++-- | Import a path from its NAR, given its info, whether a valid path's+-- contents are replaced, whether its signatures are checked, and the NAR+-- as a chunk source that gives an empty chunk where the archive ends.+addToStoreNar :: ValidPathInfo -> Repair -> CheckSigs -> IO ByteString -> ClientT IO ()+addToStoreNar info repair checkSigs = performUploading (AddToStoreNar info repair checkSigs)++-- | Realise the paths.+buildPaths :: (Monad m) => [DerivedPath] -> BuildMode -> ClientT m ()+buildPaths targets mode = done (BuildPaths targets mode)++-- | Realise the paths, with each one's result, keyed by the path as it was+-- asked for.+buildPathsWithResults :: (Monad m) => [DerivedPath] -> BuildMode -> ClientT m [KeyedBuildResult]+buildPathsWithResults targets mode = do+  storeDir <- storeDirOf+  version <- gets sessVersion+  ask (BuildPathsWithResults targets mode) (getKeyedBuildResults storeDir version)++-- | Make a path valid, substituting it if need be.+ensurePath :: (Monad m) => StorePath -> ClientT m ()+ensurePath = done . EnsurePath++-- | Keep a path from collection while the session lasts.+addTempRoot :: (Monad m) => StorePath -> ClientT m ()+addTempRoot = done . AddTempRoot++-- | Keep what a link names from collection while the link exists, given+-- the bytes of the link's absolute path.+addIndirectRoot :: (Monad m) => ByteString -> ClientT m ()+addIndirectRoot = done . AddIndirectRoot++-- ---------------------------------------------------------------------------+-- The daemon's messages+-- ---------------------------------------------------------------------------++-- | What a message of the daemon's is to a logger.+data Relayed+  = -- | A line the daemon logged, its trailing whitespace taken off.+    RelayedMessage !Text+  | -- | The store's activity the daemon started, under the number it gave+    -- it.+    RelayedStart !Word64 !ActivityStart+  | -- | A line a build's builder wrote, for the activity of that number.+    RelayedLine !Word64 !ByteString+  | -- | A line a post-build hook wrote.+    RelayedHookLine !ByteString+  | -- | The activity of that number stopped.+    RelayedStop !Word64+  | -- | Nothing a logger takes: an activity that is not the store's, a+    -- result of another kind, a message about the connection itself.+    RelayedNothing+  deriving (Eq, Show)++-- | What a message of the daemon's is to a logger, given the directory its+-- paths are named under.  A line of text is shown with any byte that is not+-- UTF-8 replaced, since a logger takes text.+relayed :: StoreDir -> StderrMessage -> Relayed+relayed storeDir = \case+  StderrNext line -> RelayedMessage (shown (BS8.dropWhileEnd isTrailingSpace line))+  StderrStartActivity activity@Activity {actId = ActivityId number} -> maybe RelayedNothing (RelayedStart number) (activityStart storeDir activity)+  StderrResult (ActivityId number) kind (FieldString line : _)+    | kind == resBuildLogLine -> RelayedLine number line+    | kind == resPostBuildLogLine -> RelayedHookLine line+  StderrStopActivity (ActivityId number) -> RelayedStop number+  _ -> RelayedNothing+  where+    isTrailingSpace c = c `elem` [' ', '\n', '\r', '\t']++-- | What a logger has of the activities a daemon started: the sink for+-- each one's builder lines and the action that stops it, by the number the+-- daemon gave it, and the logger itself.+data Relay = Relay+  { relayStoreDir :: !StoreDir,+    relayLogger :: !Logger,+    relayOpen :: !(IORef (Map Word64 (ByteString -> IO (), IO ())))+  }++-- | A relay to a logger for the daemon of a store directory, with no+-- activity open.+newRelay :: StoreDir -> Logger -> IO Relay+newRelay storeDir logger = Relay storeDir logger <$> newIORef Map.empty++-- | Give a daemon's message to the logger as the same calls the store+-- makes for the same work: a line as a message at the error level, as+-- upstream's client reports one, a build's or a substitution's start as an+-- activity of the logger, its builder's lines as that activity's, and its+-- stop as the activity's.  A builder line of an activity that is not open+-- is a build line of the logger, and a post-build hook's line a message+-- after @post-build-hook: @.  An activity started under a number already+-- open stops the one it replaces.+--+-- An activity is started and kept in one step that asynchronous+-- exceptions do not interrupt, so one that stops the thread reading the+-- daemon's messages (an upload whose source fails) cannot leave an+-- activity started and not kept, which nothing would stop.  A blocking+-- call of the logger can still be interrupted.+relayMessage :: Relay -> StderrMessage -> IO ()+relayMessage relay message = case relayed (relayStoreDir relay) message of+  RelayedMessage text -> logAt logger LevelError text+  RelayedStart number start -> mask_ (logActivity logger start >>= openActivity relay number)+  RelayedLine number line -> readIORef (relayOpen relay) >>= \held -> maybe (logBuildLine logger line) (\(sink, _) -> sink line) (Map.lookup number held)+  RelayedHookLine line -> logMessage logger ("post-build-hook: " <> shown line)+  RelayedStop number -> closeActivity relay number+  RelayedNothing -> pure ()+  where+    logger = relayLogger relay++-- | Keep an activity under its number, stopping one already open under it.+openActivity :: Relay -> Word64 -> (ByteString -> IO (), IO ()) -> IO ()+openActivity relay number activity = do+  replaced <- atomicModifyIORef' (relayOpen relay) (swap . Map.insertLookupWithKey (\_ new _ -> new) number activity)+  traverse_ snd replaced++-- | Stop the activity open under a number and forget it.+closeActivity :: Relay -> Word64 -> IO ()+closeActivity relay number = do+  stopping <- atomicModifyIORef' (relayOpen relay) (\held -> (Map.delete number held, Map.lookup number held))+  traverse_ snd stopping++-- | Stop every activity still open, latest first, and forget them: the+-- ones an operation that failed left started.+stopOpenActivities :: Relay -> IO ()+stopOpenActivities relay = do+  open <- atomicModifyIORef' (relayOpen relay) (Map.empty,)+  traverse_ snd (reverse (Map.elems open))++-- | Bytes shown as text, any that are not UTF-8 replaced.+shown :: ByteString -> Text+shown = TE.decodeUtf8Lenient
+ src/Nix/Daemon/ClientStore.hs view
@@ -0,0 +1,857 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | A command's store reached through a daemon in upstream's worker+-- protocol: the operations of a t'Nix.Store.Ops.StoreOps' over a client+-- session ("Nix.Daemon.Client"), on a Unix socket or on Windows a named+-- pipe ("Nix.Daemon.Dial").  A command's connection is opened at the+-- first operation that needs one and closed when the command is done with+-- the store, and a command that asks nothing of the store never connects.+--+-- == Where paths live+--+-- Paths go on the wire under @\/nix\/store@, the directory every path is+-- computed under, while the files of the store are read from the+-- directory the command was given ('dscFileDir'): evaluation reads a+-- tree the daemon holds there, and a copy of a path evaluation named is+-- sent from there.  A command that evaluates over this store gives its+-- evaluation session the same directory.+--+-- == Adds+--+-- A daemon's client cannot write the store's directory, so evaluation+-- hands each tree it writes to the store as it makes it+-- ('Nix.Store.Ops.AddedAsMade'), sent as upstream's client sends it+-- ('evalWriteRequest').  What evaluation only named is sent when the+-- command adds what evaluation made ('soAddEvalObjects'): each copy of a+-- path, then each derivation after every derivation and source it refers+-- to ('derivationAddOrder'), a daemon needing each reference valid first.+-- A path the daemon answers is held to the path evaluation computed.+--+-- == Temporary roots+--+-- A connection's temporary roots end with it.  The daemon roots each path+-- it adds for the connection.  The client roots a path before it asks the+-- daemon whether it holds the path where it then relies on the answer+-- without sending the path, so a collection between the question and the+-- use cannot remove it: each source and derivation an add considers+-- ('soAddEvalObjects'), each fetched path evaluation adopts ('moHold'),+-- and each path whose record or files a push or trust relies on (see+-- below).  The other queries ('sqValidPaths', 'sqReferences') root+-- nothing, and the path a pinned fetch names is taken as held on an+-- unrooted answer of 'sqValidPaths', as upstream's early exit for a+-- pinned fetch takes it.+--+-- == Builds+--+-- A build asks the daemon to build each derivation's named outputs, and a+-- check to build every output of a derivation again under the check mode,+-- as upstream's client asks.  What the daemon says while it works reaches+-- the command's logger as the calls the local store makes for the same+-- work ('Nix.Daemon.Client.relayMessage'), and any activity a failed+-- operation leaves open is stopped when it ends.  A build the daemon fails+-- stops with the daemon's message and status; from protocol 1.26 on the+-- status is not sent and reads as 1, as upstream's client reads it.  A+-- read-only evaluation's realisation substitutes in the daemon, as+-- upstream's does through its daemon.+--+-- == Push and trust+--+-- A push ('withDaemonPushSource') asks the daemon what it records of each+-- path, its references, NAR hash and deriver, and reads the path's files+-- from 'dscFileDir', as upstream's client of a daemon on the same machine+-- reads them: the daemon is asked what it records of the path, never for+-- its NAR.  Trust ('withDaemonFixedOutputs') has the daemon fetch each+-- input a builtin fetches, by adding its derivation and building it, and+-- substitute every other input, with what it references, by building its+-- path; the files of an input the daemon holds are read from+-- 'dscFileDir'.  Each path whose record or files a push or trust relies+-- on is rooted for the connection before the daemon is asked about it, so+-- a collection cannot remove it between the answer and the read of its+-- files.  The list a push of every path starts from is not rooted, so a+-- path collected between the listing and its read fails the push.+--+-- A daemon's result for a substitution does not tell a download that+-- failed from a path no substituter offers, nor a reference whose download+-- failed from one no substituter offers.  Through a daemon an input whose+-- download failed, or whose references' download failed, is therefore left+-- unread and the report names it as not read, where a store opened+-- directly stops the command; every other outcome matches.+--+-- == Out-links+--+-- The client makes a build's result link itself, in the directory the+-- command runs in, and the daemon roots it: the path is rooted for the+-- connection before the link is looked at, and the link's absolute spelling+-- is recorded as an indirect root once it exists, as upstream's client+-- roots one.+--+-- == Settings+--+-- After the handshake the client sends the settings 'dscSettings' holds,+-- as upstream's client does, unless the daemon grants+-- 'Nix.Daemon.Protocol.featureDisableSetOptions'.  They carry the+-- configuration's keep-failed, fallback and cores, and as overrides the+-- store settings a source set that the configuration reads+-- ('clientSettings').+--+-- == Failures+--+-- An operation the daemon refuses fails with the daemon's message, as+-- upstream's client throws it, and the connection goes on.  A connection+-- that cannot be opened, in its connecting, its handshake or its+-- settings, fails the operation that tried with the reason, and every+-- operation after with upstream's words for it ('previouslyFailedText'),+-- without trying again.  A connection that breaks, or that an upload+-- breaks by failing to read a local file, fails the operation that found+-- it and is closed; the next operation opens a new one, which holds none+-- of the old one's temporary roots.+module Nix.Daemon.ClientStore+  ( -- * Where the daemon is+    DaemonAddress (..),+    daemonAddressPath,+    daemonStoreName,+    Connector,+    dialDaemon,++    -- * A connection's session+    DaemonSession,+    withDaemonSession,+    daemonOperation,+    DaemonOpFailure (..),+    opFailureText,++    -- * The store+    DaemonStoreConfig (..),+    withDaemonStore,+    withDaemonPushSource,+    withDaemonFixedOutputs,+    clientSettings,++    -- * What is sent+    evalWriteRequest,+    derivationAddOrder,+    textMethod,+    narMethod,+    flatMethod,++    -- * What is said of a failure+    connectFailureText,+    openFailureText,+    previouslyFailedText,+  )+where++import Control.Concurrent.MVar (MVar, newMVar, putMVar, swapMVar, takeMVar)+import Control.Exception (Handler (..), IOException, bracket, catches, displayException, finally, mask, onException, try)+import Control.Monad (unless, when)+import Control.Monad.Except (ExceptT (..), liftEither, runExceptT, throwError, withExceptT)+import Control.Monad.IO.Class (liftIO)+import Data.Bifunctor (bimap, first)+import Data.Bool (bool)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import Data.Foldable (for_, traverse_)+import Data.IORef (atomicModifyIORef', newIORef)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe)+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Word (Word32)+import Nix.Config (AssignedSettings, NixConfig (..), storeSettingOverrides)+import Nix.Daemon.Client+  ( ClientFailure (..),+    ClientSession,+    ClientT,+    Relay,+    addIndirectRoot,+    addTempRoot,+    addToStore,+    agreedVersion,+    buildPaths,+    buildPathsWithResults,+    continueSession,+    newRelay,+    offeredVersion,+    openSession,+    queryAllValidPaths,+    queryPathInfo,+    queryValidPaths,+    relayMessage,+    setOptions,+    stopOpenActivities,+  )+import Nix.Daemon.Connection (Transport)+import qualified Nix.Daemon.Dial as Dial+import Nix.Daemon.Ops (AddToStoreRequest (..), ClientSettings (..), Repair (..), Substitute (..), unsetCores)+import Nix.Daemon.Protocol (BuildOutcome (..), BuildResult (..), DaemonError (..), DerivedPath (..), Failure (..), FailureStatus (DependencyFailed, NoSubstituters), KeyedBuildResult (..), OutputName (..), OutputsSpec (..), StderrMessage, UnkeyedValidPathInfo (..), ValidPathInfo (..), Verbosity (..), Version (..), featureDisableSetOptions, namedOutputs, narHashDigest)+import qualified Nix.Daemon.Protocol as Proto+import Nix.DependencyGraph (DepNode (..))+import Nix.Derivation (Derivation, fromATerm)+import Nix.Eval.Policy (hostPathRules)+import Nix.Fetch.Url (encodeUrlPath, pathToUrlPath)+import Nix.Hash (makeSourcePath, sha256Digest)+import Nix.Http (catchSync)+import Nix.Logger (Logger)+import Nix.Push.Source (PushSource (..), PushedPath (..))+import Nix.Realise (ClosureOutcome (..))+import Nix.Store (drvReferences)+import Nix.Store.CaseSensitive (CaseSensitivity, pathCaseHack, probeCaseSensitivity, volumeCaseHack)+import qualified Nix.Store.ExecBit as ExecBit+import Nix.Store.GC (LinkRooting (..), makeOutLinkRoot)+import Nix.Store.Ops (BuildStop (..), EvalObjects (..), EvalWrite (..), EvalWrites (..), MadeOps (..), StoreOps (..), StoreQueries (..), evalWriteContents, madeAnotherPath, nothingToAdd)+import Nix.Store.Path (StoreDir (..), StorePath (spName), badStorePathText, defaultStoreDir, parseStorePath, storePathToFilePath, storePathToText, storeTextToFilePath)+import Nix.Trust.Fetch (FixedOutputStore (..))+import Nix.Trust.Scan (scanFetched)+import NovaCache.Hash (NixHash (..), formatNixHash)+import qualified NovaCache.NAR as NAR+import System.IO.Error (illegalOperationErrorType, ioeSetErrorString, mkIOError)++-- ---------------------------------------------------------------------------+-- Where the daemon is+-- ---------------------------------------------------------------------------++-- | The socket a daemon listens on, or on Windows the named pipe.+data DaemonAddress+  = -- | The address the daemon listens on unless it is told another+    -- ('Nix.Daemon.Listen.daemonSocketPath'), as the bytes of a socket's+    -- path or on Windows a named pipe's.+    DefaultSocket !ByteString+  | -- | The address a @unix:\/\/PATH@ store names, as the bytes of a+    -- socket's path or on Windows a named pipe's.  A path that is the+    -- default's is a 'DefaultSocket' instead, as upstream names a store+    -- at the default's path @daemon@.+    NamedSocket !ByteString+  deriving (Eq, Show)++-- | The bytes of the path of the socket.+daemonAddressPath :: DaemonAddress -> ByteString+daemonAddressPath = \case+  DefaultSocket path -> path+  NamedSocket path -> path++-- | What a store at the address is called in a message, as upstream's+-- store reference renders it: @daemon@ for the default address, and+-- @unix:\/\/@ and the path of any other, each segment of the path+-- percent-encoded keeping only the unreserved characters, @:@ and @\@@+-- (upstream's @encodeUrlPath@).+daemonStoreName :: DaemonAddress -> Text+daemonStoreName = \case+  DefaultSocket _ -> "daemon"+  NamedSocket path -> "unix://" <> shown (encodeUrlPath (pathToUrlPath hostPathRules path))++-- | How a connection to the daemon is made: a transport over it and the+-- action that closes it, or why none could be made.+type Connector = IO (Either Text (Transport IO, IO ()))++-- | Connect to the daemon at an address ("Nix.Daemon.Dial"); the reason+-- for a connection that cannot be made is the operating system's, or on+-- Windows the pipe client's.+dialDaemon :: DaemonAddress -> Connector+dialDaemon address = fmap (\connection -> (Dial.connectionTransport connection, Dial.closeDaemonConnection connection)) <$> Dial.connectDaemon (daemonAddressPath address)++-- ---------------------------------------------------------------------------+-- A connection's session+-- ---------------------------------------------------------------------------++-- | An open connection: the transport it runs over, the session its+-- handshake made, and what closes it.+data Link = Link+  { linkTransport :: !(Transport IO),+    linkSession :: !ClientSession,+    linkClose :: !(IO ())+  }++-- | Where a session's connection stands.+data LinkState+  = -- | None is open: none was needed yet, or the one that was open broke+    -- and was closed.  The next operation opens one.+    Unopened+  | -- | One is open.+    Open !Link+  | -- | An attempt to open one failed.  Every operation after fails+    -- without trying again.+    OpenFailed+  | -- | The session has ended.+    Closed++-- | A command's connection to a daemon, opened at its first operation.+-- The state is taken for the length of an operation, so one runs at a+-- time.+data DaemonSession = DaemonSession+  { sessionConnector :: !Connector,+    sessionAddress :: !DaemonAddress,+    sessionSettings :: !ClientSettings,+    sessionReport :: !(StderrMessage -> IO ()),+    sessionState :: !(MVar LinkState)+  }++-- | Why an operation through a daemon did not answer.+data DaemonOpFailure+  = -- | The daemon refused the operation, with its error, and the+    -- connection goes on.+    DaemonRefused !DaemonError+  | -- | The connection could not be opened or broke, or the client will+    -- not send the operation, for this reason.+    LinkFailed !Text+  deriving (Eq, Show)++-- | The words a failure is reported in: the daemon's message, as+-- upstream's client throws it, or the reason a connection failed.+opFailureText :: DaemonOpFailure -> Text+opFailureText = \case+  DaemonRefused refusal -> daemonErrorText refusal+  LinkFailed reason -> reason++-- | A daemon's error as text: its message, with any byte that is not+-- UTF-8 replaced.  The traces it carries are not shown.+daemonErrorText :: DaemonError -> Text+daemonErrorText = shown . errMessage++-- | The verbosity the daemon's messages are reported at, and the client+-- tells the daemon to send them at: info, upstream's default.+reportVerbosity :: Verbosity+reportVerbosity = Verbosity 3++-- | Run an action with a session to the daemon at an address, which sends+-- the settings given after each handshake, over connections the+-- connector makes as operations need them, and closes the one that is+-- open when the action ends, by returning or by an exception.  The+-- daemon's messages go to the report.  A connection that cannot be+-- opened fails every operation after the one that tried+-- ('previouslyFailedText'), and a connection that breaks is replaced by+-- the next operation's.+withDaemonSession :: Connector -> DaemonAddress -> ClientSettings -> (StderrMessage -> IO ()) -> (DaemonSession -> IO a) -> IO a+withDaemonSession connector address settings report action =+  bracket (newMVar Unopened) end (action . DaemonSession connector address settings report)+  where+    end state =+      swapMVar state Closed >>= \case+        Open link -> linkClose link+        _ -> pure ()++-- | Run steps over the session's connection, one operation at a time,+-- opening the connection when the session has none and its opening has+-- not failed.  A daemon's refusal is the operation's failure and the+-- connection goes on.  A connection that breaks, in the middle of an+-- operation or before it, fails the operation with the reason, as does+-- an 'IOException' of the transport or of a chunk source the steps read+-- from, and a failed access of the walk of a local tree+-- (t'NAR.NarWalkError', which a file that cannot be read raises): the+-- connection is closed, since a framed upload is cut short, and the next+-- operation opens another.  An exception of any other kind, and an+-- interrupt, closes the connection and goes on up.+--+-- The action given runs once the operation has ended, however it ended,+-- and before the next operation can start: the operation still holds the+-- session, so the action never meets another operation's work.+daemonOperation :: DaemonSession -> IO () -> ClientT IO a -> IO (Either DaemonOpFailure a)+daemonOperation session settle steps = mask $ \restore -> do+  state <- takeMVar var+  case state of+    Closed -> release state *> ioError sessionEnded+    OpenFailed -> Left (LinkFailed (previouslyFailedText (sessionAddress session))) <$ release state+    Open link -> runOn restore link+    Unopened -> do+      opened <- restore (openLink session) `onException` release Unopened+      case opened of+        Left reason -> Left (LinkFailed reason) <$ release OpenFailed+        Right link -> runOn restore link+  where+    var = sessionState session+    -- Hands the session on in a state, once the operation has settled.+    release next = settle `finally` putMVar var next+    sessionEnded = ioeSetErrorString (mkIOError illegalOperationErrorType "daemonOperation" Nothing Nothing) "used after the session ended"+    runOn restore link = do+      ran <-+        ( (Right <$> restore (continueSession defaultStoreDir (linkTransport link) (sessionReport session) (linkSession link) steps))+            `catches` [ Handler (\(err :: IOException) -> pure (Left (T.pack (displayException err)))),+                        Handler (\(err :: NAR.NarWalkError) -> pure (Left (walkFailureText err)))+                      ]+        )+          `onException` dropLink link+      case ran of+        Left reason -> lose link reason+        Right (Left (ConnectionLost reason), _) -> lose link reason+        Right (Left (DaemonFailed refusal), next) -> continuing link next (Left (DaemonRefused refusal))+        Right (Left (NotSent reason), next) -> continuing link next (Left (LinkFailed reason))+        Right (Right answer, next) -> continuing link next (Right answer)+    continuing link next outcome = outcome <$ release (Open link {linkSession = next})+    lose link reason = Left (LinkFailed reason) <$ dropLink link+    dropLink link = linkClose link `finally` release Unopened++-- | Make a connection, its handshake and its settings, or say why they+-- cannot be made.  The connector runs with asynchronous exceptions+-- masked, so what it returns is closed whatever arrives next, and so is+-- a connection whose handshake or settings fail, the close masked too.  A+-- failure to connect is reported as the connector gives it, a failure of+-- the handshake in upstream's words for one ('openFailureText'), which+-- wrap only the handshake's errors, and a failure of the settings as the+-- daemon says it.  A synchronous exception counts as a failure of the+-- step it is thrown in; an asynchronous one goes up.+openLink :: DaemonSession -> IO (Either Text Link)+openLink session = mask $ \restore ->+  connecting >>= \case+    Left reason -> pure (Left reason)+    Right (transport, close) -> do+      made <- restore (greeting transport >>= either (pure . Left) (settling transport close)) `onException` close+      either (\reason -> Left reason <$ close) (pure . Right) made+  where+    address = sessionAddress session+    report = sessionReport session+    connecting = (first (connectFailureText address) <$> sessionConnector session) `catchSync` (pure . Left . exceptionText)+    greeting transport = first (openFailureText address) <$> (openSession defaultStoreDir offeredVersion transport report `catchSync` (pure . Left . ConnectionLost . exceptionText))+    settling transport close fresh = settled `catchSync` (pure . Left . exceptionText)+      where+        settled = do+          (sent, next) <- continueSession defaultStoreDir transport report fresh (sendSettings (sessionSettings session))+          pure (either (Left . failureText) (\() -> Right (Link transport next close)) sent)+    exceptionText = T.pack . displayException++-- | Send the client's settings for the connection, as upstream's client+-- does once the handshake is made, unless the daemon grants+-- 'featureDisableSetOptions'.+sendSettings :: ClientSettings -> ClientT IO ()+sendSettings settings = do+  version <- agreedVersion+  unless (Set.member featureDisableSetOptions (versionFeatures version)) (setOptions settings)++-- ---------------------------------------------------------------------------+-- The store+-- ---------------------------------------------------------------------------++-- | Where a command's daemon store is, how it reads files, and what the+-- daemon is told.+data DaemonStoreConfig = DaemonStoreConfig+  { -- | The daemon.+    dscAddress :: !DaemonAddress,+    -- | The directory the command's store files are read from: the trees+    -- the daemon holds, which evaluation reads, and the copies of paths it+    -- named, which are sent from here.  Paths cross the wire under+    -- @\/nix\/store@ whatever it is.+    dscFileDir :: !StoreDir,+    -- | The settings sent after each handshake ('clientSettings').+    dscSettings :: !ClientSettings,+    -- | Where the daemon's messages are reported.+    dscLogger :: !Logger+  }++-- | The settings a client sends, from its configuration and the settings a+-- source set: keep-failed, fallback and cores as the configuration has+-- them, cores being 'unsetCores' where it sets none, as upstream's client+-- sends its own default for the daemon to read as its machine's, the+-- verbosity the daemon's messages are reported at, and as overrides the+-- store settings a source set that the configuration reads+-- ('storeSettingOverrides'): a store setting it does not read, such as+-- @builders@ or @connect-timeout@, is not sent whatever a source says.+-- Each setting the configuration does not model takes the default+-- upstream's client sends.+clientSettings :: AssignedSettings -> NixConfig -> ClientSettings+clientSettings assigned config =+  ClientSettings+    { csKeepFailed = ncKeepFailed config,+      csKeepGoing = False,+      csTryFallback = ncFallback config,+      csVerbosity = reportVerbosity,+      csMaxBuildJobs = defaultMaxBuildJobs,+      csMaxSilentTime = noSilentTimeLimit,+      csVerboseBuild = True,+      csBuildCores = fromMaybe unsetCores (ncCores config),+      csUseSubstitutes = True,+      csOverrides = storeSettingOverrides assigned config+    }++-- | Upstream's default for @max-jobs@: one build at a time.+defaultMaxBuildJobs :: Word32+defaultMaxBuildJobs = 1++-- | Upstream's default for @max-silent-time@: a build is never stopped for+-- its silence.+noSilentTimeLimit :: Word32+noSilentTimeLimit = 0++-- | Run an action with a command's store operations through a daemon,+-- over a session ('withDaemonSession') that connects only when an+-- operation first asks the daemon something.+--+-- The queries ask the daemon: 'sqValidPaths' fails with an 'IOError' on a+-- failure, as a local store's database does, the type having no other+-- channel for one.  An add sends each source and derivation the+-- evaluation named that the daemon does not hold, holding the path the+-- daemon makes to the one evaluation computed.  A build or a check asks+-- the daemon to build, and stops with the daemon's message and status,+-- which from protocol 1.26 on reads as 1, as upstream's client reads it;+-- what the daemon says meanwhile reaches 'dscLogger' as the local store's+-- own calls do.  An out-link is made by the client and rooted by the+-- daemon.  A read-only evaluation's realisation substitutes in the daemon,+-- as upstream's does through its daemon.+withDaemonStore :: DaemonStoreConfig -> Connector -> (StoreOps IO -> IO a) -> IO a+withDaemonStore config connector action = withStoreSession config connector (action . daemonOps config)++-- | Run an action over a session to the daemon ('withDaemonSession') and+-- the relay its messages go to ('dscLogger'), which every operation of a+-- command's store runs over ('operate').+withStoreSession :: DaemonStoreConfig -> Connector -> (StoreSession -> IO a) -> IO a+withStoreSession config connector action = do+  relay <- newRelay defaultStoreDir (dscLogger config)+  withDaemonSession connector (dscAddress config) (dscSettings config) (relayMessage relay) (action . StoreSession relay)++-- | Run an action with what a push reads, a t'PushSource', through a+-- daemon, over a session that connects when it first asks the daemon+-- something.  Each path's references, NAR hash and deriver are asked of+-- the daemon, and the files of the path are read from 'dscFileDir', as+-- upstream's client of a daemon on the same machine reads them.  Each+-- path whose record is asked, which a push then reads the files of, is+-- rooted for the connection first, so a collection cannot remove it+-- between the answer and the read of its files.  The list of every path+-- ('psAllValid') is not rooted, so a path collected between the listing+-- and its read fails the push.  The volume's case sensitivity is probed+-- once, when the action starts.+withDaemonPushSource :: DaemonStoreConfig -> Connector -> (PushSource -> IO a) -> IO a+withDaemonPushSource config connector action = withStoreSession config connector $ \session -> do+  sensitivity <- probeCaseSensitivity (unStoreDir (dscFileDir config))+  action+    PushSource+      { psStoreDir = dscFileDir config,+        psCaseHack = volumeCaseHack sensitivity,+        psLogger = dscLogger config,+        psReferences = referencesOfRecord session,+        psPathInfo = pathInfoOf session,+        psAllValid = bimap opFailureText Set.toAscList <$> operate session queryAllValidPaths+      }++-- | A path rooted for the connection, then its record: 'Nothing' for a+-- path the daemon does not hold.+pathInfoOf :: StoreSession -> StorePath -> IO (Either Text (Maybe PushedPath))+pathInfoOf session path = bimap opFailureText (fmap pushedPath) <$> operate session (addTempRoot path *> queryPathInfo path)++-- | The references of a path's record, as 'pathInfoOf' gives it: none for+-- a path the daemon does not hold.+referencesOfRecord :: StoreSession -> StorePath -> IO (Either Text [StorePath])+referencesOfRecord session path = fmap (maybe [] ppReferences) <$> pathInfoOf session path++-- | What a push reads of a daemon's record of a path, its NAR hash spelled+-- as a store's database spells it.+pushedPath :: UnkeyedValidPathInfo -> PushedPath+pushedPath info =+  PushedPath+    { ppNarHash = formatNixHash (NixHash (narHashDigest (upiNarHash info))),+      ppReferences = Set.toAscList (upiReferences info),+      ppDeriver = upiDeriver info+    }++-- | Run an action with what trust asks of a store, a t'FixedOutputStore',+-- through a daemon, over a session that connects when it first asks the+-- daemon something.  The function gives the ATerm recorded for a+-- derivation.+--+-- A fetch adds the input's derivation, which nothing else refers to, as+-- 'soAddEvalObjects' adds one, unless the daemon holds it, and has the+-- daemon build every output of it.  A substitution roots the path, asks+-- the daemon whether it holds it, and if not has the daemon realise it as+-- an opaque path, which substitutes it with what it references, under the+-- fallback setting the session sent.  A path the daemon holds asks no+-- substituter anything.  A realisation that succeeds is complete; one the+-- daemon fails because no substituter offers the path is unavailable, and+-- because a dependency failed, incomplete: a path left unread, the run+-- going on, as for a store opened directly.  Any other failure, or no+-- result for the path, is a failed substitution, which stops the run.  A+-- daemon's result does not tell a download that failed from a path no+-- substituter offers, so a path whose download failed, or whose+-- references' download failed, is unavailable or incomplete too, where a+-- store opened directly fails it.  A daemon older than protocol 1.34+-- cannot say how a realisation ended, so the substitution of a path it+-- does not hold fails with the client's reason.  Each path whose files+-- are read is rooted before the daemon is asked whether it holds it, and+-- the files are read from 'dscFileDir'.+withDaemonFixedOutputs :: DaemonStoreConfig -> Connector -> (StorePath -> Either Text ByteString) -> (FixedOutputStore IO -> IO a) -> IO a+withDaemonFixedOutputs config connector recordedAterm action = withStoreSession config connector $ \session ->+  action+    FixedOutputStore+      { fosFetch = fetchThrough config session recordedAterm,+        fosSubstitute = \path -> first opFailureText <$> operate session (substituteOpaque path),+        fosHeld = \path -> first opFailureText <$> operate session (rootedValid path),+        fosScan = scanFetched . storePathToFilePath (dscFileDir config)+      }++-- | Have the daemon fetch an input: its derivation added as a text with no+-- references, since a derivation a builtin fetches names no input, then+-- built for every output.+fetchThrough :: DaemonStoreConfig -> StoreSession -> (StorePath -> Either Text ByteString) -> DepNode -> IO (Either Text ())+fetchThrough config session recordedAterm node = runExceptT $ do+  aterm <- liftEither (recordedAterm path)+  ExceptT (addEvalObjects config session EvalObjects {eoSources = Map.empty, eoStoreWrites = Map.empty, eoDerivations = Map.singleton (storePathToText defaultStoreDir path) aterm})+  withExceptT opFailureText (ExceptT (operate session (buildPaths [DerivedBuilt path AllOutputs] Proto.BuildNormal)))+  where+    path = dnDrvPath node++-- | A path rooted for the connection, then whether the daemon holds it,+-- without substituting it.+rootedValid :: StorePath -> ClientT IO Bool+rootedValid path = addTempRoot path *> (Set.member path <$> queryValidPaths (Set.singleton path) NoSubstitute)++-- | Make a path valid through the daemon, as a substitution in a store+-- opened directly does ('ClosureOutcome'): the path is rooted, and one the+-- daemon holds is complete.  Any other is realised as an opaque path,+-- which has the daemon's substituters offer it with what it references,+-- and ends as the daemon's result for it says ('substitutionOutcome').+-- The daemon's substituters are not asked first which of them offer the+-- path: a daemon asks only those that declare they take such a question,+-- and one that does not would be taken for not offering a path it holds.+substituteOpaque :: StorePath -> ClientT IO ClosureOutcome+substituteOpaque path = rootedValid path >>= bool (substitutionOutcome path <$> buildPathsWithResults [DerivedOpaque path] Proto.BuildNormal) (pure ClosureComplete)++-- | The outcome of a path's realisation from the result the daemon gave+-- it: success is complete; no substituter offering the path is+-- unavailable; a reference that could not be substituted, because no+-- substituter offers it or its download failed, is incomplete; any other+-- failure, or no result for the path, is a failed substitution.+substitutionOutcome :: StorePath -> [KeyedBuildResult] -> ClosureOutcome+substitutionOutcome path results = case lookup (DerivedOpaque path) [(kbrPath keyed, brOutcome (kbrResult keyed)) | keyed <- results] of+  Just (Succeeded _) -> ClosureComplete+  Just (Failed failure) -> case failureStatus failure of+    NoSubstituters -> ClosureUnavailable+    DependencyFailed -> ClosureIncomplete+    _ -> ClosureFailed+  Nothing -> ClosureFailed++-- | A command's session with the relay the daemon's messages go to, which+-- every operation of the store runs over ('operate').+data StoreSession = StoreSession+  { ssRelay :: !Relay,+    ssSession :: !DaemonSession+  }++-- | Run steps over the session as 'daemonOperation' does, then stop any+-- activity the daemon started and did not stop, however the operation+-- ended: a failed build's activity has no stop of its own.  The stop is+-- made while the operation holds the session, so it never stops an+-- activity of another operation on the same store.+operate :: StoreSession -> ClientT IO a -> IO (Either DaemonOpFailure a)+operate session = daemonOperation (ssSession session) (stopOpenActivities (ssRelay session))++-- | The operations of a store through a session.+daemonOps :: DaemonStoreConfig -> StoreSession -> StoreOps IO+daemonOps config session =+  StoreOps+    { soQueries = StoreQueries {sqValidPaths = validAmong session, sqReferences = referencesOf session},+      soAddEvalObjects = addEvalObjects config session,+      soAddSourceTree = addSourceTree session,+      soBuild = buildRequested session,+      soCheck = \drv -> buildThrough session [DerivedBuilt drv AllOutputs] Proto.BuildCheck,+      soAddOutLinkRoot = makeOutLinkRoot (dscFileDir config) (outLinkRooting session),+      soEvalWrites = AddedAsMade (MadeOps {moAdd = addEvalWrite session, moHold = holdPath session})+    }++-- | Build the outputs each request names, none being asked of the daemon+-- for a request that names none.+buildRequested :: StoreSession -> [(StorePath, Set Text)] -> IO (Either BuildStop ())+buildRequested session requests = case targets of+  [] -> pure (Right ())+  _ -> buildThrough session targets Proto.BuildNormal+  where+    targets = [DerivedBuilt drv spec | (drv, names) <- requests, Just spec <- [namedOutputs (Set.map OutputName names)]]++-- | Ask the daemon to build, in a mode: the stop a failure is.+buildThrough :: StoreSession -> [DerivedPath] -> Proto.BuildMode -> IO (Either BuildStop ())+buildThrough session targets mode = first buildStop <$> operate session (buildPaths targets mode)++-- | A failed operation as the stop a build reports: the daemon's message+-- and status, or the reason the connection failed with the status of+-- every other stop.+buildStop :: DaemonOpFailure -> BuildStop+buildStop = \case+  DaemonRefused refusal -> BuildStop (daemonErrorText refusal) (fromIntegral (errExitStatus refusal))+  LinkFailed reason -> BuildStop reason connectionFailedStatus++-- | The status a build that could not ask the daemon reports.+connectionFailedStatus :: Int+connectionFailedStatus = 1++-- | How an out-link is rooted through the daemon: its path rooted for the+-- connection while the link is made, and the link's absolute spelling+-- recorded as an indirect root.+outLinkRooting :: StoreSession -> LinkRooting+outLinkRooting session =+  LinkRooting+    { lrHold = holdPath session,+      lrRecord = \bytes -> first opFailureText <$> operate session (addIndirectRoot bytes)+    }++-- | Which of the paths the daemon holds, asking it nothing when there are+-- none.+validAmong :: StoreSession -> Set StorePath -> IO (Set StorePath)+validAmong session paths+  | Set.null paths = pure Set.empty+  | otherwise = operate session (queryValidPaths paths NoSubstitute) >>= either (ioError . userError . T.unpack . opFailureText) pure++-- | The references the daemon records for a path, none for one it does+-- not hold.+referencesOf :: StoreSession -> StorePath -> IO (Either Text (Set StorePath))+referencesOf session path = either (Left . opFailureText) (Right . maybe Set.empty upiReferences) <$> operate session (queryPathInfo path)++-- | Keep a path from collection for the connection's life.+holdPath :: StoreSession -> StorePath -> IO (Either Text ())+holdPath session path = first opFailureText <$> operate session (addTempRoot path)++-- | An operation's answer, or the text of why it failed.+viaDaemon :: StoreSession -> ClientT IO a -> ExceptT Text IO a+viaDaemon session = withExceptT opFailureText . ExceptT . operate session++-- | Add what evaluation made and named, as 'soAddEvalObjects' says:+-- nothing at all asks nothing of the daemon, and neither do the trees+-- evaluation wrote, which the daemon took as they were made.  Each source+-- and derivation is held before the daemon is asked which it has, since+-- those it has are not sent.  The sources are sent, then the derivations+-- in 'derivationAddOrder', each one the daemon does not hold, until the+-- first fails.+addEvalObjects :: DaemonStoreConfig -> StoreSession -> EvalObjects -> IO (Either Text ())+addEvalObjects config session objects+  | nothingToAdd objects = pure (Right ())+  | otherwise = runExceptT $ do+      derivations <- liftEither (derivationAddOrder (eoDerivations objects))+      let sources = Map.toAscList (eoSources objects)+          candidates = map fst sources <> [path | (path, _, _) <- derivations]+      unless (null candidates) $ do+        valid <- viaDaemon session (traverse_ addTempRoot candidates *> queryValidPaths (Set.fromList candidates) NoSubstitute)+        sensitivity <- liftIO (probeCaseSensitivity (unStoreDir (dscFileDir config)))+        for_ sources $ \(path, srcText) -> unless (Set.member path valid) (addSource config session sensitivity path srcText)+        for_ derivations $ \(path, drv, aterm) -> unless (Set.member path valid) (addDerivation session path drv aterm)++-- | Send the copy of a path evaluation named, as a NAR of the tree its+-- text names, under the case-hack evaluation read it with.  A tree that+-- cannot be read fails the add with the failed access's words, whether+-- it fails as the walk plans the archive or as the upload pulls a file.+addSource :: DaemonStoreConfig -> StoreSession -> CaseSensitivity -> StorePath -> Text -> ExceptT Text IO ()+addSource config session sensitivity path srcText = do+  let request = AddToStoreRequest (TE.encodeUtf8 (spName path)) narMethod Set.empty NoRepair+      source = storeTextToFilePath (dscFileDir config) srcText+  added <- liftIO (try (ExecBit.withNarSource (pathCaseHack sensitivity srcText) source (operate session . addToStore request)))+  info <- liftEither (either (Left . walkFailureText) (first opFailureText) added)+  when (vpiPath info /= path) $+    throwError ("refusing to register " <> storePathToText defaultStoreDir path <> ": " <> srcText <> " changed after evaluation hashed it, so it no longer reproduces its store path; re-evaluate")++-- | Send a derivation's ATerm as a text that refers to what the+-- derivation refers to.+addDerivation :: StoreSession -> StorePath -> Derivation -> ByteString -> ExceptT Text IO ()+addDerivation session path drv aterm = do+  let request = AddToStoreRequest (TE.encodeUtf8 (spName path)) textMethod (Set.fromList (drvReferences drv)) NoRepair+  source <- liftIO (chunkSource [aterm])+  info <- viaDaemon session (addToStore request source)+  when (vpiPath info /= path) $ throwError (madeAnotherPath (vpiPath info) path)++-- | Add a tree, given as its NAR, as the path its SHA-256, the name and+-- the references make.+addSourceTree :: StoreSession -> Text -> Set StorePath -> NAR.NarEntry -> IO (Either Text StorePath)+addSourceTree session name refs entry = runExceptT $ do+  let nar = NAR.serialise entry+  expected <- liftEither (first badStorePathText (makeSourcePath name (sha256Digest nar) refs))+  source <- liftIO (chunkSource [nar])+  info <- viaDaemon session (addToStore (AddToStoreRequest (TE.encodeUtf8 name) narMethod refs NoRepair) source)+  expected <$ when (vpiPath info /= expected) (throwError (madeAnotherPath (vpiPath info) expected))++-- | Add a tree as evaluation makes it, answering the path the daemon+-- made.+addEvalWrite :: StoreSession -> EvalWrite -> IO (Either Text StorePath)+addEvalWrite session write = do+  source <- chunkSource [evalWriteContents write]+  bimap opFailureText vpiPath <$> operate session (addToStore (evalWriteRequest write) source)++-- | A chunk source over chunks, as an upload is given: each call answers+-- the next chunk, and then an empty one, for ever.+chunkSource :: [ByteString] -> IO (IO ByteString)+chunkSource chunks = do+  remaining <- newIORef chunks+  pure (atomicModifyIORef' remaining (\case [] -> ([], BS.empty); next : rest -> (rest, next)))++-- ---------------------------------------------------------------------------+-- What is sent+-- ---------------------------------------------------------------------------++-- | The spellings upstream's client sends an add's method in: a text+-- hashed with SHA-256, a NAR hashed with it, and a file's bytes hashed+-- with it.+textMethod, narMethod, flatMethod :: ByteString+textMethod = "text:sha256"+narMethod = "fixed:r:sha256"+flatMethod = "fixed:sha256"++-- | The add that sends a tree evaluation made: its name, the method its+-- kind names, and the references a text has.  Nothing is repaired.+evalWriteRequest :: EvalWrite -> AddToStoreRequest+evalWriteRequest = \case+  TextWrite name refs _ -> request name textMethod refs+  FlatWrite name _ -> request name flatMethod Set.empty+  NarWrite name _ -> request name narMethod Set.empty+  where+    request name method refs = AddToStoreRequest (TE.encodeUtf8 name) method refs NoRepair++-- | The derivations an evaluation recorded, parsed and in the order to+-- add them: each after every derivation of the map that it refers to, as+-- a daemon needs each reference valid first.  A derivation visits what+-- it refers to, sources and input derivations, before itself, the keys+-- and references in ascending order, and each is placed once, so a cycle,+-- which no evaluation makes, ends.  A key that names no store path, and+-- an ATerm that does not parse, are the reason it is refused.+derivationAddOrder :: Map Text ByteString -> Either Text [(StorePath, Derivation, ByteString)]+derivationAddOrder recorded = do+  parsed <- traverse parseRecorded (Map.toAscList recorded)+  let known = Map.fromList [(path, (drv, aterm)) | (path, drv, aterm) <- parsed]+  pure (reverse (snd (foldl' (visit known) (Set.empty, []) (Map.keys known))))+  where+    parseRecorded (key, aterm) = case parseStorePath defaultStoreDir key of+      Nothing -> Left ("no store path: " <> key)+      Just path -> either (\err -> Left ("the recorded .drv for " <> key <> " does not parse: " <> err)) (\drv -> Right (path, drv, aterm)) (fromATerm aterm)++-- | Place a derivation after what it refers to, given the derivations+-- known and the paths placed so far with the order they were placed in,+-- latest first.+visit :: Map StorePath (Derivation, ByteString) -> (Set StorePath, [(StorePath, Derivation, ByteString)]) -> StorePath -> (Set StorePath, [(StorePath, Derivation, ByteString)])+visit known (placed, order) path+  | Set.member path placed = (placed, order)+  | Just (drv, aterm) <- Map.lookup path known =+      let (placedAfter, orderAfter) = foldl' (visit known) (Set.insert path placed, order) (Set.toAscList (Set.fromList (drvReferences drv)))+       in (placedAfter, (path, drv, aterm) : orderAfter)+  | otherwise = (placed, order)++-- ---------------------------------------------------------------------------+-- What is said of a failure+-- ---------------------------------------------------------------------------++-- | A connection that cannot be made, given the reason the operating+-- system gives, as upstream words it ('Nix.Daemon.Dial.connectFailureText').+connectFailureText :: DaemonAddress -> Text -> Text+connectFailureText address = Dial.connectFailureText (shown (daemonAddressPath address))++-- | A handshake that fails, as upstream words it: the store's name and+-- the daemon's message, or the reason the connection failed or the client+-- refused to go on.+openFailureText :: DaemonAddress -> ClientFailure -> Text+openFailureText address failure = "cannot open connection to remote store '" <> daemonStoreName address <> "': error: " <> failureText failure++-- | What every operation after a connection failed to open fails with, as+-- upstream words it.+previouslyFailedText :: DaemonAddress -> Text+previouslyFailedText address = "opening a connection to remote store '" <> daemonStoreName address <> "' previously failed"++-- | Why a step of the client failed: the daemon's message, or the reason+-- the connection failed or the client refused to go on.+failureText :: ClientFailure -> Text+failureText = \case+  DaemonFailed refusal -> daemonErrorText refusal+  NotSent why -> why+  ConnectionLost why -> why++-- | A failed access of the walk of a local tree as the words of the+-- access that failed: the entry, what was done to it and the operating+-- system's reason.+walkFailureText :: NAR.NarWalkError -> Text+walkFailureText = T.pack . displayException++-- | Bytes shown in a message, any that are not UTF-8 replaced.+shown :: ByteString -> Text+shown = TE.decodeUtf8Lenient
+ src/Nix/Daemon/Connection.hs view
@@ -0,0 +1,553 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE TupleSections #-}++-- | A daemon's side of one connection, as upstream's daemon serves one:+-- the handshake, then each operation the client asks, run over the store+-- the connection is given ("Nix.Daemon.Ops"), until the client's input+-- ends or an error closes the connection.+--+-- An operation's request is read, and judged by the client's trust,+-- before its work begins.  A failure there is sent to the client and+-- closes the connection, the error going out twice, as upstream's+-- connection loop sends it once for the operation and again as it gives+-- up.  Once the work has begun, what the store reports goes to the client+-- as it happens (t'LogEvent'), and a failure is sent once and the+-- connection goes on with the next operation.  The end of the work is+-- @STDERR_LAST@, then the reply.+--+-- An upload follows its request as a framed stream.  The store is fed its+-- bytes, an archive's only up to the archive's end ('NarBoundary'), and+-- whatever of the stream it does not take is read past before the+-- operation's result is sent, as upstream drains a framed upload, so the+-- next operation starts at its first byte.  A refused frame leaves the+-- stream where upstream's does, and the draining goes on from there.+--+-- The core is pure: everything a connection does to the world goes+-- through its t'Transport' and its t'DaemonStore'.+module Nix.Daemon.Connection+  ( Transport (..),+    ServerConfig (..),+    ConnectionEnd (..),+    serveConnection,+  )+where++import Control.Monad (unless, when)+import Control.Monad.Except (ExceptT (..), runExceptT)+import Control.Monad.State.Strict (StateT, evalStateT, get, gets, modify', put, runStateT)+import Control.Monad.Trans (lift)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import Data.ByteString.Builder (Builder)+import qualified Data.ByteString.Builder as BB+import Data.Foldable (traverse_)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import Data.Word (Word64)+import Nix.Config (NixConfig)+import Nix.Daemon.Ops+  ( AddToStoreRequest (..),+    Authorization (..),+    CheckSigs,+    ConnectionSettings (..),+    DaemonStore (..),+    DumpUpload (..),+    Intake (..),+    LogEvent (..),+    NarBoundary (..),+    Repair,+    Request (..),+    Work (..),+    applyClientSettings,+    authorize,+    daemonError,+    getRequest,+    getUploadPathInfo,+    narSizeBoundary,+    rootCensoring,+  )+import Nix.Daemon.Protocol+  ( Activity (..),+    DaemonError,+    StderrMessage (..),+    Trust,+    UnkeyedValidPathInfo (..),+    ValidPathInfo (..),+    Verbosity (..),+    Version (..),+    VersionNumber (..),+    getClientMagic,+    getClientObsoleteFields,+    getFeatures,+    getVersionNumber,+    minimumVersionNumber,+    parseContentAddressMethod,+    putFeatures,+    putGCResult,+    putHandshakeInfo,+    putKeyedBuildResults,+    putMissing,+    putOutputMap,+    putRoots,+    putServerMagic,+    putStderrMessage,+    putStorePathSet,+    putUnkeyedValidPathInfo,+    putValidPathInfo,+    putVersionNumber,+  )+import Nix.Daemon.Wire (DecodeError (..), Decoder, Decoding (..), feedInput, getFrame, getWord32, getWord64, putBool, putNum, startDecoding)+import Nix.Store.Path (StoreDir)++-- ---------------------------------------------------------------------------+-- Configuration+-- ---------------------------------------------------------------------------++-- | How a connection reaches its client.+data Transport m = Transport+  { -- | The next bytes the client sent, never empty, or 'Nothing' once its+    -- input has ended, and at every call after.+    transportReceive :: !(m (Maybe ByteString)),+    -- | Send bytes to the client, all of them, before returning.+    transportSend :: !(Builder -> m ())+  }++-- | What a daemon tells and gives every connection.+data ServerConfig = ServerConfig+  { -- | The store directory paths are named under on the wire: the one+    -- they are computed under, which need not be where the store keeps+    -- its files.+    scStoreDir :: !StoreDir,+    -- | The protocol version this daemon offers: its number, and the+    -- features it lists for a client to share.+    scVersion :: !Version,+    -- | The Nix version this daemon names itself by, from 1.33.+    scNixVersion :: !ByteString,+    -- | How much a client is told until it sets its own verbosity.+    scVerbosity :: !Verbosity,+    -- | The daemon's settings, which each connection starts from.+    scConfig :: !NixConfig+  }++-- | Why a connection ended.+data ConnectionEnd+  = -- | The client's input ended between operations.+    ClientClosed+  | -- | The handshake failed, for this reason, and the client was sent+    -- nothing about it.+    HandshakeFailed !Text+  | -- | An error closed the connection, and the client was sent it.+    ClosedOnError !DaemonError+  deriving (Eq, Show)++-- ---------------------------------------------------------------------------+-- The connection+-- ---------------------------------------------------------------------------++-- | What a connection holds while it runs: the input that has arrived and+-- not been read, and its settings.+data Session = Session+  { sessInput :: !ByteString,+    sessSettings :: !ConnectionSettings+  }++-- | A connection's steps, over the monad its transport and store run in.+type Conn m = StateT Session m++-- | What every operation of an agreed connection reads.+data Env m = Env+  { envConfig :: !ServerConfig,+    envTrust :: !Trust,+    envStore :: !(DaemonStore m),+    envTransport :: !(Transport m),+    envVersion :: !Version+  }++-- | How an operation left its connection.+data OpEnd+  = -- | It ended, served or failed, and the next operation may follow.+    OpServed+  | -- | It failed where the connection cannot go on, and the client was+    -- sent the error.+    OpClosed !DaemonError++-- | Serve a client, the daemon trusting it or not, over a store and a+-- transport of the connection's own, until the connection ends.+serveConnection :: (Monad m) => ServerConfig -> Trust -> DaemonStore m -> Transport m -> m ConnectionEnd+serveConnection config trust store transport = evalStateT connection (Session BS.empty initialSettings)+  where+    initialSettings = ConnectionSettings (scVerbosity config) (scConfig config) Nothing+    connection =+      handshake config trust transport >>= \case+        Left reason -> pure (HandshakeFailed reason)+        Right version -> serveOperations (Env config trust store transport version)++-- | The version a client's features are exchanged from.+featureExchangeSince :: VersionNumber+featureExchangeSince = VersionNumber 1 38++-- | Agree a version with a client, as upstream's daemon does: read its+-- opening word, offer this daemon's version number, read the client's,+-- and from 1.38 read its features and offer this daemon's.  The version+-- is the lower number and the features both list.  A client below the+-- oldest version served is refused, and so is one whose handshake cannot+-- be read; neither is sent a reason.  Then the client's obsolete fields+-- are read, the daemon's Nix version and its trust in the client are+-- sent where the version carries them, and its startup work is reported+-- done.+handshake :: (Monad m) => ServerConfig -> Trust -> Transport m -> Conn m (Either Text Version)+handshake config trust transport = runExceptT $ do+  receive getClientMagic+  lift (send transport (putServerMagic <> putVersionNumber offered))+  clientNumber <- receive getVersionNumber+  let agreed = min clientNumber offered+  clientFeatures <-+    if agreed >= featureExchangeSince+      then receive getFeatures <* lift (send transport (putFeatures offeredFeatures))+      else pure Set.empty+  when (agreed < minimumVersionNumber) (ExceptT (pure (Left "the Nix client version is too old")))+  let version = Version agreed (Set.intersection clientFeatures offeredFeatures)+  receive (getClientObsoleteFields version)+  lift (send transport (putHandshakeInfo version (scNixVersion config) (Just trust) <> putStderrMessage version StderrLast))+  pure version+  where+    offered = versionNumber (scVersion config)+    offeredFeatures = versionFeatures (scVersion config)+    receive decoder = ExceptT (either (Left . decodeErrorText) Right <$> receiveValue transport decoder)++-- | Serve operations until the client's input ends or an error closes the+-- connection.  The input ending before an operation's code has been read+-- whole is the client closing it; a code too large to read is an error+-- sent once, as upstream sends it.+serveOperations :: (Monad m) => Env m -> Conn m ConnectionEnd+serveOperations env =+  receiveValue (envTransport env) getWord32 >>= \case+    Left InputEnded -> pure ClientClosed+    Left (Malformed message) -> ClosedOnError (daemonError message) <$ sendError env (daemonError message)+    Right code -> case getRequest (scStoreDir (envConfig env)) (envVersion env) code of+      Nothing -> refusedBeforeWork (daemonError ("invalid operation " <> T.pack (show code)))+      Just decoder ->+        receiveValue (envTransport env) decoder >>= \case+          Left err -> refusedBeforeWork (daemonError (decodeErrorText err))+          Right request -> case authorize (envTrust env) request of+            RefusedBeforeWork message -> refusedBeforeWork (daemonError message)+            RefusedInWork message -> sendError env (daemonError message) >> serveOperations env+            Permitted permitted ->+              perform env permitted >>= \case+                OpServed -> serveOperations env+                OpClosed err -> pure (ClosedOnError err)+  where+    refusedBeforeWork err = ClosedOnError err <$ closingError env err++-- | Perform a permitted request, its work begun.+perform :: (Monad m) => Env m -> Request -> Conn m OpEnd+perform env = \case+  SetOptions client -> do+    settings <- gets sessSettings+    let (updated, warnings) = applyClientSettings (envTrust env) client settings+    modify' (\session -> session {sessSettings = updated})+    traverse_ (warn (connVerbosity updated)) warnings+    finish mempty+  IsValidPath path -> answered (\w -> dsIsValidPath store w path) putBool+  QueryValidPaths paths substitute -> answered (\w -> dsQueryValidPaths store w substitute paths) pathSet+  QuerySubstitutablePaths paths -> answered (\w -> dsQuerySubstitutablePaths store w paths) pathSet+  QueryReferrers path -> answered (\w -> dsQueryReferrers store w path) pathSet+  QueryValidDerivers path -> answered (\w -> dsQueryValidDerivers store w path) pathSet+  QueryDerivationOutputMap path -> answered (\w -> dsQueryDerivationOutputMap store w path) (putOutputMap storeDir)+  QueryAllValidPaths -> answered (dsQueryAllValidPaths store) pathSet+  QueryPathInfo path ->+    answered (\w -> dsQueryPathInfo store w path) (maybe (putNum invalidFlag) (\info -> putNum validFlag <> putUnkeyedValidPathInfo storeDir version info))+  QueryMissing targets -> answered (\w -> dsQueryMissing store w targets) (putMissing storeDir)+  AddToStore upload ->+    -- The method is parsed before the dump is read, so a method refused+    -- leaves the dump unread, as upstream leaves it.+    case parseContentAddressMethod (atsMethod upload) of+      Left refusal -> failed (daemonError refusal)+      Right (method, algo) -> do+        w <- work env+        intake <- lift (dsAddToStore store w (DumpUpload (atsName upload) method algo (atsReferences upload) (atsRepair upload)))+        result <- framed transport (feedToEnd transport intake)+        either failed (finish . putValidPathInfo storeDir version) result+  AddToStoreNar info repair checkSigs -> do+    w <- work env+    intake <- lift (dsAddToStoreNar store w info repair checkSigs)+    result <- framed transport (fst <$> feedArchive transport (narSizeBoundary (upiNarSize (vpiInfo info))) intake)+    either failed (const (finish mempty)) result+  AddMultipleToStore repair checkSigs ->+    framed transport (importPaths env repair checkSigs) >>= either failed (const (finish mempty))+  BuildPaths targets mode -> answered (\w -> dsBuildPaths store w targets mode) (const done)+  BuildPathsWithResults targets mode -> do+    w <- work env+    lift (dsBuildPathsWithResults store w targets mode) >>= \case+      Left err -> failed err+      Right results -> case putKeyedBuildResults storeDir version results of+        (reply, Nothing) -> finish reply+        -- Upstream writes each result as it goes, so a client is sent+        -- the ones before the result it cannot write, then the error.+        (written, Just refusal) -> do+          send transport (putStderrMessage version StderrLast <> written)+          OpClosed (daemonError refusal) <$ closingError env (daemonError refusal)+  EnsurePath path -> answered (\w -> dsEnsurePath store w path) (const done)+  AddTempRoot path -> answered (\w -> dsAddTempRoot store w path) (const done)+  AddIndirectRoot link -> answered (\w -> dsAddIndirectRoot store w link) (const done)+  FindRoots -> answered (\w -> dsFindRoots store w (rootCensoring (envTrust env))) (putRoots storeDir)+  -- 'authorize' has refused a collection that ignores liveness.+  CollectGarbage request _ -> answered (\w -> dsCollectGarbage store w request) putGCResult+  OptimiseStore -> answered (dsOptimiseStore store) (const done)+  VerifyStore contents repair -> answered (\w -> dsVerifyStore store w contents repair) putBool+  AddSignatures path sigs -> answered (\w -> dsAddSignatures store w path sigs) (const done)+  -- The NAR follows the end of the work, so a failure writing it can no+  -- longer be told apart from the NAR and closes the connection.+  NarFromPath path -> do+    send transport (putStderrMessage version StderrLast)+    lift (dsNarFromPath store path (transportSend transport . BB.byteString)) >>= \case+      Left err -> OpClosed err <$ closingError env err+      Right () -> pure OpServed+  where+    config = envConfig env+    storeDir = scStoreDir config+    version = envVersion env+    store = envStore env+    transport = envTransport env+    pathSet = putStorePathSet storeDir+    done = putNum doneWord+    finish reply = OpServed <$ send transport (putStderrMessage version StderrLast <> reply)+    failed err = OpServed <$ sendError env err+    answered call reply = do+      w <- work env+      lift (call w) >>= either failed (finish . reply)+    warn verbosity message =+      when (heard warningVerbosity verbosity) (send transport (putStderrMessage version (StderrNext message)))++-- | The word an operation with nothing else to say replies with.+doneWord :: Word64+doneWord = 1++-- | The flags a path's info is sent after, or in place of.+validFlag, invalidFlag :: Word64+validFlag = 1+invalidFlag = 0++-- | The level of a warning (@lvlWarn@).+warningVerbosity :: Verbosity+warningVerbosity = Verbosity 1++-- | Whether a client at a verbosity hears a message at a level.+heard :: Verbosity -> Verbosity -> Bool+heard (Verbosity level) (Verbosity verbosity) = level <= verbosity++-- | The store's view of an operation's work: its report goes to the+-- client, and it runs under the connection's settings.+work :: (Monad m) => Env m -> Conn m (Work m)+work env = do+  settings <- gets sessSettings+  pure (Work (report (envTransport env) (envVersion env) (connVerbosity settings)) settings)++-- | Send what the store reports to the client, as upstream's daemon+-- forwards its logger's calls.+report :: (Monad m) => Transport m -> Version -> Verbosity -> LogEvent -> m ()+report transport version verbosity event =+  maybe (pure ()) (transportSend transport . putStderrMessage version) (forwarded version verbosity event)++-- | Activities go to the client as their own messages from this version.+activitiesSince :: VersionNumber+activitiesSince = VersionNumber 1 20++-- | The message a report goes to the client as, if any.  A line goes if+-- the client's verbosity reaches its level, with a line feed after it.+-- Before 1.20 an activity's start goes as its text, if it has any, with+-- an ellipsis, a line at the activity's level, and the rest of what an+-- activity reports does not go at all.+forwarded :: Version -> Verbosity -> LogEvent -> Maybe StderrMessage+forwarded version verbosity = \case+  LogLine level line -> logged level line+  ActivityStarted activity+    | activities -> Just (StderrStartActivity activity)+    | BS.null (actText activity) -> Nothing+    | otherwise -> logged (actLevel activity) (actText activity <> "...")+  ActivityStopped act -> onlyWithActivities (StderrStopActivity act)+  ActivityResult act kind fields -> onlyWithActivities (StderrResult act kind fields)+  where+    activities = versionNumber version >= activitiesSince+    onlyWithActivities message = if activities then Just message else Nothing+    logged level line+      | heard level verbosity = Just (StderrNext (line <> "\n"))+      | otherwise = Nothing++-- ---------------------------------------------------------------------------+-- Uploads+-- ---------------------------------------------------------------------------++-- | Where a framed upload's reading stands: the bytes of a chunk received+-- and not yet taken, and whether the chunk that ends the stream has been+-- read.+data Frames = Frames+  { framesHeld :: !ByteString,+    framesEnded :: !Bool+  }++-- | An operation's steps while it reads a framed upload.+type Upload m = StateT Frames (Conn m)++-- | Read an upload, and then read past what of it was left, as upstream's+-- framed source does as it goes out of scope, a failure to read past it+-- going unreported as it goes there.+framed :: (Monad m) => Transport m -> Upload m a -> Conn m a+framed transport upload = do+  (result, frames) <- runStateT upload (Frames BS.empty False)+  unless (framesEnded frames) drain+  pure result+  where+    drain =+      receiveValue transport getFrame >>= \case+        Right (Just _) -> drain+        _ -> pure ()++-- | The next bytes of an upload, or 'Nothing' at its end.+nextChunk :: (Monad m) => Transport m -> Upload m (Either DaemonError (Maybe ByteString))+nextChunk transport =+  get >>= \case+    Frames held ended+      | not (BS.null held) -> Right (Just held) <$ put (Frames BS.empty ended)+      | ended -> pure (Right Nothing)+      | otherwise ->+          lift (receiveValue transport getFrame) >>= \case+            Left err -> pure (Left (daemonError (decodeErrorText err)))+            Right Nothing -> Right Nothing <$ put (Frames BS.empty True)+            Right (Just chunk) -> pure (Right (Just chunk))++-- | Give back bytes an upload's reader took and did not use.+unread :: (Monad m) => ByteString -> Upload m ()+unread bytes = modify' (\frames -> frames {framesHeld = bytes <> framesHeld frames})++-- | Upstream's refusal of a read past the end of an upload.+uploadEnded :: DaemonError+uploadEnded = daemonError "reached end of FramedSource"++-- | A value read from an upload.+uploadValue :: (Monad m) => Transport m -> Decoder a -> Upload m (Either DaemonError a)+uploadValue transport decoder = settle (startDecoding decoder)+  where+    settle = \case+      Decoded value rest -> Right value <$ unread rest+      DecodeFailed InputEnded _ -> pure (Left uploadEnded)+      DecodeFailed (Malformed message) rest -> Left (daemonError message) <$ unread rest+      NeedInput more -> nextChunk transport >>= either (pure . Left) (settle . more)++-- | Feed the store the rest of an upload.+feedToEnd :: (Monad m) => Transport m -> Intake m a -> Upload m (Either DaemonError a)+feedToEnd transport = \case+  Taken result -> pure result+  Taking onChunk onEnd onBroken ->+    nextChunk transport >>= \case+      Left err -> Left err <$ lift (lift onBroken)+      Right Nothing -> lift (lift onEnd)+      Right (Just chunk) -> lift (lift (onChunk chunk)) >>= feedToEnd transport++-- | How much of an archive the store left.+data ArchiveLeft+  = -- | None: the upload stands at the archive's end.+    ArchiveRead+  | -- | Some, which this boundary still finds the end of.+    ArchiveUnread !NarBoundary++-- | Feed the store an archive from an upload, up to the archive's end,+-- and say where that leaves the upload.  The store hears that its bytes+-- have ended where the archive ends, or where the upload does before it,+-- and that they broke off where the upload cannot be read.+feedArchive :: (Monad m) => Transport m -> NarBoundary -> Intake m a -> Upload m (Either DaemonError a, ArchiveLeft)+feedArchive transport boundary intake = case boundary of+  BoundaryReached rest -> do+    unread rest+    result <- lift (lift (intakeEnd intake))+    pure (result, ArchiveRead)+  BoundaryAhead step -> case intake of+    Taken result -> pure (result, ArchiveUnread boundary)+    Taking onChunk onEnd onBroken ->+      nextChunk transport >>= \case+        Left err -> (Left err, ArchiveUnread boundary) <$ lift (lift onBroken)+        Right Nothing -> (,ArchiveUnread boundary) <$> lift (lift onEnd)+        Right (Just chunk) -> case step chunk of+          BoundaryReached rest -> do+            let archived = BS.take (BS.length chunk - BS.length rest) chunk+            fed <- if BS.null archived then pure intake else lift (lift (onChunk archived))+            feedArchive transport (BoundaryReached rest) fed+          ahead -> lift (lift (onChunk chunk)) >>= feedArchive transport ahead++-- | What the store makes of its bytes ending, if it still takes them.+intakeEnd :: (Applicative m) => Intake m a -> m (Either DaemonError a)+intakeEnd = \case+  Taken result -> pure result+  Taking _ onEnd _ -> onEnd++-- | Read past the rest of an archive the store did not take, which must+-- be there, as upstream reads its declared size whatever its store read.+skipArchive :: (Monad m) => Transport m -> NarBoundary -> Upload m (Either DaemonError ())+skipArchive transport = \case+  BoundaryReached rest -> Right () <$ unread rest+  BoundaryAhead step ->+    nextChunk transport >>= \case+      Left err -> pure (Left err)+      Right Nothing -> pure (Left uploadEnded)+      Right (Just chunk) -> skipArchive transport (step chunk)++-- | Import the paths an upload holds: their count, then each path's info+-- and its NAR.  No path imported this way is ultimate, whoever sends it.+importPaths :: (Monad m) => Env m -> Repair -> CheckSigs -> Upload m (Either DaemonError ())+importPaths env repair checkSigs = runExceptT $ do+  count <- ExceptT (uploadValue transport getWord64)+  traverse_ (const importOne) [1 .. count]+  where+    transport = envTransport env+    importOne = do+      uploaded <- ExceptT (uploadValue transport (getUploadPathInfo (scStoreDir (envConfig env))))+      let info = (vpiInfo uploaded) {upiUltimate = False}+      w <- lift (lift (work env))+      intake <- lift (lift (lift (dsAddToStoreNar (envStore env) w uploaded {vpiInfo = info} repair checkSigs)))+      (result, left) <- lift (feedArchive transport (narSizeBoundary (upiNarSize info)) intake)+      ExceptT (pure result)+      case left of+        ArchiveRead -> pure ()+        ArchiveUnread boundary -> ExceptT (skipArchive transport boundary)++-- ---------------------------------------------------------------------------+-- Input and output+-- ---------------------------------------------------------------------------++-- | Read a value from the client, the input after it kept for what is+-- read next.  A refused value keeps the input after the bytes it took.+receiveValue :: (Monad m) => Transport m -> Decoder a -> Conn m (Either DecodeError a)+receiveValue transport decoder = do+  held <- gets sessInput+  keepInput BS.empty+  settle (if BS.null held then startDecoding decoder else feedInput (Just held) (startDecoding decoder))+  where+    settle = \case+      Decoded value rest -> Right value <$ keepInput rest+      DecodeFailed err rest -> Left err <$ keepInput rest+      NeedInput more -> lift (transportReceive transport) >>= settle . more++-- | Keep input for what is read next.+keepInput :: (Monad m) => ByteString -> Conn m ()+keepInput rest = modify' (\session -> session {sessInput = rest})++-- | Upstream's message for a value that could not be read: its refusal,+-- or the end of the input before the value's end.+decodeErrorText :: DecodeError -> Text+decodeErrorText = \case+  InputEnded -> "unexpected end-of-file"+  Malformed message -> message++-- | Send bytes to the client.+send :: (Monad m) => Transport m -> Builder -> Conn m ()+send transport = lift . transportSend transport++-- | Send the client an error.+sendError :: (Monad m) => Env m -> DaemonError -> Conn m ()+sendError env err = send (envTransport env) (putStderrMessage (envVersion env) (StderrError err))++-- | Send the client an error that closes the connection: once for the+-- operation and once more as the connection ends, as upstream sends it.+closingError :: (Monad m) => Env m -> DaemonError -> Conn m ()+closingError env err = sendError env err >> sendError env err
+ src/Nix/Daemon/Dial.hs view
@@ -0,0 +1,159 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | The client's end of a daemon's address: a Unix socket on a POSIX+-- system and a named pipe on Windows ("Nix.Daemon.Pipe"), which+-- 'connectDaemon' connects to and 'connectionTransport' reads and writes+-- as the t'Transport' a client session runs over ("Nix.Daemon.Client").+-- On Windows the connection is the pipe client's, which refuses a pipe no+-- trusted account made before it sends a byte.  'addressPresence' asks+-- whether anything is at an address without connecting to it.+module Nix.Daemon.Dial+  ( DaemonConnection,+    connectDaemon,+    connectionTransport,+    closeDaemonConnection,+    connectFailureText,+    sunPathSize,+    AddressPresence (..),+    addressPresence,+  )+where++import Data.ByteString (ByteString)+import Data.Text (Text)+import Nix.Daemon.Connection (Transport (..))+#if !defined(mingw32_HOST_OS)+import Control.Exception (bracketOnError, try)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Builder as BB+import qualified Data.ByteString.Char8 as BS8+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Foreign.C.Error (Errno (..), eNOENT, eNOTDIR)+import GHC.IO.Exception (IOException (ioe_description, ioe_errno))+import Network.Socket (Family (AF_UNIX), SockAddr (SockAddrUnix), Socket, SocketType (Stream), close, connect, defaultProtocol, socket)+import Network.Socket.ByteString (recv)+import qualified Network.Socket.ByteString.Lazy as SocketLazy+import System.Posix.Files.ByteString (getSymbolicLinkStatus)+#endif+#if defined(mingw32_HOST_OS)+import qualified Nix.Daemon.Pipe as Pipe+#endif++-- | A connection to a daemon, which 'closeDaemonConnection' closes.+#if defined(mingw32_HOST_OS)+newtype DaemonConnection = DaemonConnection Pipe.PipeConnection+#else+newtype DaemonConnection = DaemonConnection Socket+#endif++-- | Connect to the daemon listening at an address, or say why it cannot+-- be reached.  On a POSIX system the address is a socket's path and the+-- reason is the operating system's, as @No such file or directory@ or+-- @Connection refused@; on Windows it is a named pipe's path+-- (@\\\\.\\pipe\\NAME@) and the reason is the pipe client's+-- ("Nix.Daemon.Pipe").+connectDaemon :: ByteString -> IO (Either Text DaemonConnection)+#if defined(mingw32_HOST_OS)+connectDaemon address = case Pipe.pipePath address of+  Left reason -> pure (Left reason)+  Right path -> fmap DaemonConnection <$> Pipe.connectPipe path+#else+connectDaemon path+  | BS.length path >= sunPathSize = pure (Left "path is too long")+  | otherwise = bracketOnError (socket AF_UNIX Stream defaultProtocol) close $ \sock ->+      try (connect sock (SockAddrUnix (BS8.unpack path))) >>= \case+        Left (err :: IOException) -> Left (T.pack (ioe_description err)) <$ close sock+        Right () -> pure (Right (DaemonConnection sock))+#endif++-- | The size of a Unix socket address's path on this system, its+-- terminating NUL included: 104 bytes on macOS, 108 elsewhere.  A path of+-- this length or longer does not fit.  Only the POSIX connection and the+-- daemon's listener use it.+sunPathSize :: Int+#if defined(darwin_HOST_OS)+sunPathSize = 104+#else+sunPathSize = 108+#endif++#if !defined(mingw32_HOST_OS)+-- | How much a read from the daemon asks for.+receiveChunkSize :: Int+receiveChunkSize = 65536+#endif++-- | A connection's transport.  A read of nothing is the end of the+-- daemon's output, which every read after it gives too.+connectionTransport :: DaemonConnection -> Transport IO+#if defined(mingw32_HOST_OS)+connectionTransport (DaemonConnection conn) = Pipe.connectionTransport conn+#else+connectionTransport (DaemonConnection conn) =+  Transport+    { transportReceive = (\chunk -> if BS.null chunk then Nothing else Just chunk) <$> recv conn receiveChunkSize,+      transportSend = SocketLazy.sendAll conn . BB.toLazyByteString+    }+#endif++-- | Close the connection.+closeDaemonConnection :: DaemonConnection -> IO ()+#if defined(mingw32_HOST_OS)+closeDaemonConnection (DaemonConnection conn) = Pipe.closeConnection conn+#else+closeDaemonConnection (DaemonConnection sock) = close sock+#endif++-- | Whether anything is at an address, which a client asks to decide+-- whether to go through a daemon.+data AddressPresence+  = -- | Something is there: a socket's path names an entry, a pipe's+    -- name is in the machine's pipes.  Whether a daemon answers is not+    -- known.+    AddressPresent+  | -- | Nothing is.+    AddressAbsent+  deriving (Eq, Show)++-- | Whether anything is at the address, without connecting to it, as+-- upstream's @auto@ store looks for the daemon's socket: the address+-- itself, a link not followed, on a POSIX system, and on Windows the+-- list of the machine's pipes ("Nix.Daemon.Pipe.pipePresent"), since+-- opening a pipe takes one of its instances.  An address that names a+-- missing entry, or one below something that is not a directory, is+-- absent; so is a pipe's path that is not one.  Any other failure to+-- look, such as a directory the process may not search, is thrown as+-- upstream words it: @getting status of "PATH": REASON@, the path as it is+-- given, shown as UTF-8 where it is, and the operating system's reason.+addressPresence :: ByteString -> IO AddressPresence+#if defined(mingw32_HOST_OS)+addressPresence address = case Pipe.pipePath address of+  Left _ -> pure AddressAbsent+  Right path ->+    Pipe.pipePresent path >>= \case+      True -> pure AddressPresent+      False -> pure AddressAbsent+#else+addressPresence path =+  try (getSymbolicLinkStatus path) >>= \case+    Right _ -> pure AddressPresent+    Left failure+      | fmap Errno (ioe_errno failure) `elem` [Just eNOENT, Just eNOTDIR] -> pure AddressAbsent+      | otherwise -> ioError (userError ("getting status of \"" <> T.unpack (TE.decodeUtf8Lenient path) <> "\": " <> ioe_description failure))+#endif++-- | A connection that cannot be made, given the address as it is shown+-- and the reason, as upstream's client words it for a socket: the socket+-- named in double quotes, then the reason.  On Windows the address is a+-- named pipe's and the message says so.+connectFailureText :: Text -> Text -> Text+connectFailureText shownAddress reason = "cannot connect to " <> endpoint <> " at \"" <> shownAddress <> "\": " <> reason+  where+#if defined(mingw32_HOST_OS)+    endpoint = "named pipe"+#else+    endpoint = "socket"+#endif
+ src/Nix/Daemon/Listen.hs view
@@ -0,0 +1,437 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | Where a daemon listens for clients, as upstream's daemon does on a+-- POSIX system: a Unix socket at upstream's path, created with the+-- directories above it and made writable by every user, so the+-- directory's own mode decides who reaches it.  Each connection is+-- served on a thread of its own, its peer's identity read from the+-- socket and judged by "Nix.Daemon.Auth" unless the daemon was told to+-- trust or not trust every client.  The listener stops the connections it+-- serves as it stops, and waits for them.+--+-- On Windows the daemon listens on a named pipe ("Nix.Daemon.Pipe"),+-- each client connecting to an instance of its own, and the next+-- instance made as one connects.  The client is named by the account it+-- connected as, which the pipe gives as the client connects, so a client+-- is judged before anything is read from it, and one the daemon refuses+-- holds neither its instance nor its thread.  The daemon does not watch a+-- Windows client for its hangup: the work for a client that has gone+-- stops when the daemon next fails to send to it.+module Nix.Daemon.Listen+  ( TrustOverride (..),+    DaemonOptions (..),+    daemonSocketPath,+    authSettingsFor,+    Listener,+    openListener,+    closeListener,+    serveListener,+  )+where++import Control.Concurrent.MVar (MVar, modifyMVar_, newEmptyMVar, newMVar, putMVar, readMVar, takeMVar)+import Data.ByteString (ByteString)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Nix.Builder.BuildUser (defaultBuildUsersGroup, processPrivilege)+import Nix.Config (NixConfig (..))+import Nix.Daemon.Auth (AuthSettings (..))+import qualified Nix.Daemon.Auth as Auth+import Nix.Daemon.Connection (ConnectionEnd (..), Transport (..))+import Nix.Daemon.Protocol (Trust (..))+import Nix.Environment (EnvLookup (..), lookupEnvBytes)+import Nix.Logger (Logger, logMessage)+#if !defined(mingw32_HOST_OS)+import Control.Concurrent (ThreadId, forkIO, forkIOWithUnmask, killThread, myThreadId, throwTo)+import Control.Exception (Exception (..), IOException, asyncExceptionFromException, asyncExceptionToException, bracket, catch, displayException, finally, mask, mask_, onException, try)+import Control.Monad (forever, unless, when)+import Foreign.C.Types (CInt (..))+import qualified Data.ByteString as BS+import qualified Data.ByteString.Builder as BB+import qualified Data.ByteString.Char8 as BS8+import Data.Word (Word32)+import Network.Socket (Family (AF_UNIX), SockAddr (SockAddrUnix), Socket, SocketType (Stream), accept, bind, close, defaultProtocol, getPeerCredential, listen, socket, withFdSocket)+import Network.Socket.ByteString (recv)+import qualified Network.Socket.ByteString.Lazy as SocketLazy+import Nix.Daemon.Dial (sunPathSize)+import Nix.HostPath (hostPathFromBytes)+import qualified System.Directory.OsPath as OsDir+import System.IO.Error (isDoesNotExistError)+import qualified System.OsPath as OP+import System.Posix.Files.ByteString (removeLink, setFileMode)+import System.Posix.IO (FdOption (CloseOnExec), closeFd, createPipe, setFdOption)+import qualified System.Posix.User.ByteString as Posix+#endif+#if defined(mingw32_HOST_OS)+import Control.Concurrent (ThreadId, forkIOWithUnmask, killThread, myThreadId, threadDelay)+import Control.Exception (IOException, displayException, finally, mask_, onException, try)+import Data.Foldable (traverse_)+import qualified Nix.Daemon.Pipe as Pipe+#endif+#if defined(darwin_HOST_OS)+import Foreign.C.Types (CUInt (..))+import Foreign.Marshal.Alloc (alloca, allocaBytes)+import Foreign.Ptr (Ptr)+import Foreign.Storable (peek)+import Data.Word (Word8)+#endif++-- ---------------------------------------------------------------------------+-- Options+-- ---------------------------------------------------------------------------++-- | Whether the daemon trusts its clients by who they are or by what it+-- was told.+data TrustOverride+  = -- | Trust every client, without reading who it is.+    ForceTrusted+  | -- | Trust no client, without reading who it is.+    ForceUntrusted+  | -- | Admit and trust each client as @trusted-users@ and+    -- @allowed-users@ say.+    DefaultTrust+  deriving (Eq, Show)++-- | How a daemon admits each client and what it does with one it admits.+data DaemonOptions = DaemonOptions+  { doTrust :: !TrustOverride,+    doAuth :: !AuthSettings,+    -- | Serve one admitted client, trusted or not, over its connection.+    doServe :: !(Trust -> Transport IO -> IO ConnectionEnd)+  }++-- | The socket a daemon listens on unless it is told another, as+-- upstream's names it for the local store: @NIX_DAEMON_SOCKET_PATH@ when+-- it is set and not empty, and otherwise @daemon-socket\/socket@ in the+-- state directory, @NIX_STATE_DIR@ when that is set and not empty and+-- @\/nix\/var\/nix@ otherwise.  On Windows it is a named pipe:+-- @NIX_DAEMON_SOCKET_PATH@ when it is set and not empty, and otherwise+-- @\\\\.\\pipe\\nova-nix-daemon@.+daemonSocketPath :: IO ByteString+daemonSocketPath =+  lookupEnvBytes "NIX_DAEMON_SOCKET_PATH" >>= \case+    EnvValue path | path /= "" -> pure path+#if defined(mingw32_HOST_OS)+    _ -> pure Pipe.defaultPipePath+#else+    _ ->+      lookupEnvBytes "NIX_STATE_DIR" >>= \case+        EnvValue dir | dir /= "" -> pure (dir <> "/" <> socketBelowStateDir)+        _ -> pure (defaultStateDir <> "/" <> socketBelowStateDir)+#endif++-- | The admission settings a daemon's configuration gives, the build+-- users' group, where none is set, @nixbld@ for a daemon run as root and+-- none otherwise, as upstream's defaults it ("Nix.Builder.BuildUser").+authSettingsFor :: NixConfig -> IO AuthSettings+authSettingsFor config = AuthSettings (ncTrustedUsers config) (ncAllowedUsers config) . buildUsersGroup <$> processPrivilege+  where+    buildUsersGroup privilege = fromMaybe (defaultBuildUsersGroup privilege) (ncBuildUsersGroup config)++#if !defined(mingw32_HOST_OS)+-- | Upstream's state directory, and where the socket is beneath it.+defaultStateDir, socketBelowStateDir :: ByteString+defaultStateDir = "/nix/var/nix"+socketBelowStateDir = "daemon-socket/socket"+#endif++-- ---------------------------------------------------------------------------+-- Serving+-- ---------------------------------------------------------------------------++-- | A socket a daemon listens on, or on Windows a named pipe: the+-- instance waiting for the next client, until the listener is closed.+#if defined(mingw32_HOST_OS)+newtype Listener = Listener (MVar (Maybe Pipe.PipeInstance))+#else+newtype Listener = Listener Socket+#endif++-- | Make the socket at a path and listen on it, or say why it cannot be+-- made.  On Windows the path is a named pipe's, @\\\\.\\pipe\\NAME@,+-- and a pipe some process already has is refused.+openListener :: ByteString -> IO (Either Text Listener)+#if defined(mingw32_HOST_OS)+openListener path = case Pipe.pipePath path of+  Left reason -> pure (Left (refused reason))+  Right pipe -> Pipe.listenPipe pipe >>= either (pure . Left . refused) (fmap (Right . Listener) . newMVar . Just)+  where+    refused reason = "cannot listen on '" <> TE.decodeUtf8Lenient path <> "': " <> reason+#else+openListener path = fmap Listener <$> listenAt path+#endif++-- | Stop listening, once the thread serving the listener has stopped.  The+-- socket's file stays, as upstream's daemon leaves it.  On Windows the+-- pipe's waiting instance is closed, and the pipe goes once its last+-- connection does.+closeListener :: Listener -> IO ()+#if defined(mingw32_HOST_OS)+closeListener (Listener waiting) = modifyMVar_ waiting (\held -> Nothing <$ traverse_ Pipe.closeInstance held)+#else+closeListener (Listener sock) = close sock+#endif++-- | Serve each client that connects, until the thread running this is+-- stopped, which stops every connection it is serving and waits for each+-- to end.  The line each connection is accepted with, and the reason one+-- is refused or fails its handshake, go to the logger.+serveListener :: Logger -> DaemonOptions -> Listener -> IO a+#if defined(mingw32_HOST_OS)+serveListener logger options (Listener waiting) = withConnections (`acceptFrom` 0)+  where+    -- A closed listener has no instance to wait on, which ends the loop.+    -- A failure to take one client is said and the loop waits, so a pipe+    -- that keeps failing is not spun on, and goes on; one that fails+    -- 'acceptFailureLimit' times in a row has failed for good, which ends+    -- the loop.+    acceptFrom spawn failures =+      readMVar waiting >>= \case+        Nothing -> ioError (userError "the listener is closed")+        Just inst ->+          try (Pipe.awaitClient inst >> handOver spawn inst) >>= \case+            Right () -> acceptFrom spawn (0 :: Int)+            Left (err :: IOException) -> do+              logMessage logger ("error: while processing connection: accepting connection: " <> T.pack (displayException err))+              if failures + 1 >= acceptFailureLimit+                then ioError (userError ("accepting connections failed " <> show acceptFailureLimit <> " times in a row, the last with: " <> displayException err))+                else threadDelay acceptRetryMicros >> acceptFrom spawn (failures + 1)+    -- The next instance is made before the connected one is handed to+    -- its thread, so the pipe always has an instance of the daemon's and+    -- no other process can make it anew.  Where none can be made, the+    -- client is let go and its instance waits again.+    handOver spawn connected =+      mask_ $+        Pipe.nextInstance connected >>= \case+          Left reason -> do+            Pipe.dropClient connected+            logMessage logger ("error: while processing connection: accepting connection: " <> reason)+          Right fresh -> do+            modifyMVar_ waiting (\_ -> pure (Just fresh))+            spawn (serveClient logger options connected `finally` Pipe.closeInstance connected) `onException` Pipe.closeInstance connected+#else+serveListener logger options (Listener sock) = withConnections (forever . acceptOne)+  where+    -- Masked from the accept to the thread's start, so a connection the+    -- loop accepts as it is stopped is still closed; the wait in accept+    -- stays interruptible.+    acceptOne spawn =+      mask_ (accept sock >>= \(conn, _) -> spawn (serveClient logger options conn `finally` close conn) `onException` close conn)+        `catch` \(err :: IOException) -> logMessage logger ("error: while processing connection: accepting connection: " <> T.pack (displayException err))+#endif++-- | Run the accept loop with what it spawns each connection's thread by,+-- and on the way out stop every connection still being served and wait+-- for each to finish.+withConnections :: ((IO () -> IO ()) -> IO a) -> IO a+withConnections body = do+  live <- newMVar Map.empty+  body (spawn live) `finally` stopAll live+  where+    spawn :: MVar (Map ThreadId (MVar ())) -> IO () -> IO ()+    spawn live action = mask_ $ modifyMVar_ live $ \running -> do+      done <- newEmptyMVar+      thread <- forkIOWithUnmask (\unmask -> unmask action `finally` finished live done)+      pure (Map.insert thread done running)+    finished live done = do+      me <- myThreadId+      modifyMVar_ live (pure . Map.delete me)+      putMVar done ()+    stopAll live = do+      running <- readMVar live+      mapM_ killThread (Map.keys running)+      mapM_ takeMVar (Map.elems running)++#if defined(mingw32_HOST_OS)+-- | Serve one client of the pipe: read who it is, which the pipe gives as+-- the client connects, admit the client, say so, and serve it, or say why+-- not.  A client that is refused is closed without a byte read from it.+serveClient :: Logger -> DaemonOptions -> Pipe.PipeInstance -> IO ()+serveClient logger options conn = case doTrust options of+  ForceTrusted -> serveAdmitted Nothing (Auth.Admitted Trusted Nothing)+  ForceUntrusted -> serveAdmitted Nothing (Auth.Admitted NotTrusted Nothing)+  DefaultTrust ->+    Pipe.clientAccount conn >>= \case+      Left reason -> logMessage logger ("error: while processing connection: " <> reason)+      Right peer -> Auth.admitAccount Pipe.systemAccounts (doAuth options) peer >>= serveAdmitted (Auth.accountProcess peer)+  where+    serveAdmitted process admission = case admission of+      Auth.Refused reason -> logMessage logger ("error: while processing connection: " <> reason)+      Auth.Admitted trust _ -> do+        logMessage logger (Auth.acceptedMessage process admission)+        try (doServe options trust (Pipe.instanceTransport conn)) >>= \case+          Left (err :: IOException) -> logMessage logger ("error: " <> T.pack (displayException err))+          Right (HandshakeFailed reason) -> logMessage logger ("error: " <> reason)+          Right _ -> pure ()++-- | How many accepts that fail in a row end the daemon's accept loop, and+-- how long, in microseconds, it waits after each one that fails.+acceptFailureLimit, acceptRetryMicros :: Int+acceptFailureLimit = 10+acceptRetryMicros = 500 * 1000+#else+-- | How many connections may wait to be accepted, as upstream's daemon+-- lets them.+listenBacklog :: Int+listenBacklog = 100++-- | The mode the socket gets, every user's read and write, so the+-- directory around it decides who can reach it.+socketMode :: Word32+socketMode = 0o666++-- | Make the socket as upstream's daemon makes it: the directories above+-- it, any file in its place removed, bound, given 'socketMode', and+-- listening.  A path longer than a socket address holds is refused,+-- where upstream binds it from its directory.+listenAt :: ByteString -> IO (Either Text Socket)+listenAt path+  | BS.length path >= sunPathSize = pure (Left ("cannot bind to socket at '" <> shown <> "': path is too long"))+  | otherwise = case hostPathFromBytes path of+      Nothing -> pure (Left ("cannot bind to socket at '" <> shown <> "': not a path"))+      Just osPath ->+        stepping ("creating directory '" <> shown <> "'") (OsDir.createDirectoryIfMissing True (OP.takeDirectory osPath)) `andThen` \() ->+          stepping ("removing '" <> shown <> "'") (removeLink path `catch` \(err :: IOException) -> unless (isDoesNotExistError err) (ioError err)) `andThen` \() ->+            stepping "creating a Unix socket" (socket AF_UNIX Stream defaultProtocol) `andThen` \sock ->+              let bound = do+                    bind sock (SockAddrUnix (BS8.unpack path))+                    setFileMode path (fromIntegral socketMode)+                    listen sock listenBacklog+               in stepping ("cannot bind to socket at '" <> shown <> "'") (bound `onException` close sock) `andThen` \() ->+                    pure (Right sock)+  where+    shown = TE.decodeUtf8Lenient path+    andThen step next = step >>= either (pure . Left) next+    stepping what action = either (\(err :: IOException) -> Left (what <> ": " <> T.pack (displayException err))) Right <$> try action++-- | Serve one client: admit it, say so, and serve it, or say why not.+serveClient :: Logger -> DaemonOptions -> Socket -> IO ()+serveClient logger options conn = do+  (peer, admission) <- case doTrust options of+    ForceTrusted -> pure (Auth.unknownPeer, Auth.Admitted Trusted Nothing)+    ForceUntrusted -> pure (Auth.unknownPeer, Auth.Admitted NotTrusted Nothing)+    DefaultTrust -> do+      peer <- peerOf conn+      (,) peer <$> Auth.admitPeer systemUsers (doAuth options) peer+  case admission of+    Auth.Refused reason -> logMessage logger ("error: while processing connection: " <> reason)+    Auth.Admitted trust _ -> do+      logMessage logger (Auth.acceptedMessage (Auth.peerProcess peer) admission)+      ended <- try (try (watchingHangup conn (doServe options trust (socketTransport conn))))+      case ended of+        Left (err :: IOException) -> logMessage logger ("error: " <> T.pack (displayException err))+        Right (Left ClientHungUp) -> pure ()+        Right (Right (HandshakeFailed reason)) -> logMessage logger ("error: " <> reason)+        Right (Right _) -> pure ()++-- | The client of the connection being served hung up.  It is thrown to+-- the connection's thread as an interrupt is, so the work it was doing+-- for the client stops and every resource it held is released, as+-- upstream's daemon stops a client's work when the client goes.+data ClientHungUp = ClientHungUp+  deriving (Show)++instance Exception ClientHungUp where+  toException = asyncExceptionToException+  fromException = asyncExceptionFromException++-- | Run an action while a thread watches the socket for its client to+-- hang up ("nn_hangup.h"), which stops the action with t'ClientHungUp'.+-- The watch ends as the action does: closing the pipe's write end wakes+-- the watcher, which is waited for, so no hangup is thrown once this+-- returns.  Both ends of the pipe are closed on exec, so a builder does+-- not hold the end whose closing stops the watch.+watchingHangup :: Socket -> IO a -> IO a+watchingHangup conn action = do+  serving <- myThreadId+  watched <- newEmptyMVar+  bracket createPipe (closeFd . fst) $ \(notifyEnd, stopEnd) ->+    mask $ \restore -> do+      let started = do+            setFdOption notifyEnd CloseOnExec True+            setFdOption stopEnd CloseOnExec True+            forkIO (watch serving notifyEnd `finally` putMVar watched ())+      _ <- started `onException` closeFd stopEnd+      restore action `finally` (closeFd stopEnd *> awaitWatch watched)+  where+    watch serving notifyEnd = do+      outcome <- withFdSocket conn (\fd -> c_wait_hangup fd (fromIntegral notifyEnd))+      when (outcome == hungUp) (throwTo serving ClientHungUp)+    -- A hangup the watcher saw as the action ended arrives here, and the+    -- connection is ending anyway.+    awaitWatch watched = takeMVar watched `catch` \ClientHungUp -> awaitWatch watched++-- | What 'c_wait_hangup' answers for a hangup.+hungUp :: CInt+hungUp = 1++foreign import ccall safe "nn_hangup.h nn_wait_hangup" c_wait_hangup :: CInt -> CInt -> IO CInt++-- | What the socket says of its peer.+peerOf :: Socket -> IO Auth.Peer+peerOf conn = do+  (pid, uid, gid) <- getPeerCredential conn+  pure (Auth.Peer (fromIntegral <$> pid) (fromIntegral <$> uid) (fromIntegral <$> gid))++-- | How much a read from a client asks for.+receiveChunkSize :: Int+receiveChunkSize = 65536++-- | A connection's transport over its socket.  A read of nothing is the+-- end of the client's input, which every read after it gives too.+socketTransport :: Socket -> Transport IO+socketTransport conn =+  Transport+    { transportReceive = (\chunk -> if BS.null chunk then Nothing else Just chunk) <$> recv conn receiveChunkSize,+      transportSend = SocketLazy.sendAll conn . BB.toLazyByteString+    }++-- | The system's users and groups, an entry that is not there and one+-- that cannot be read alike missing.+systemUsers :: Auth.UserDatabase IO+systemUsers =+  Auth.UserDatabase+    { Auth.udUserName = \uid -> entry (Posix.userName <$> Posix.getUserEntryForID (fromIntegral uid)),+      Auth.udGroupName = \gid -> entry (Posix.groupName <$> Posix.getGroupEntryForID (fromIntegral gid)),+      Auth.udGroup = \name -> entry ((\group -> Auth.GroupEntry (fromIntegral (Posix.groupID group)) (Posix.groupMembers group)) <$> Posix.getGroupEntryForName name),+      Auth.udMembership = membership+    }+  where+    entry query = either (\(_ :: IOException) -> Nothing) Just <$> try query++-- | Whether the directory counts a user a member of a group, as macOS+-- answers apart from a group's member list; elsewhere there is no such+-- answer.+membership :: Word32 -> Word32 -> IO (Maybe Bool)+#if defined(darwin_HOST_OS)+membership uid gid =+  allocaBytes uuidSize $ \userUuid ->+    allocaBytes uuidSize $ \groupUuid ->+      alloca $ \isMember -> do+        userMapped <- c_mbr_uid_to_uuid (fromIntegral uid) userUuid+        groupMapped <- c_mbr_gid_to_uuid (fromIntegral gid) groupUuid+        if userMapped /= 0 || groupMapped /= 0+          then pure Nothing+          else do+            checked <- c_mbr_check_membership userUuid groupUuid isMember+            if checked /= 0 then pure Nothing else Just . (/= 0) <$> peek isMember++-- | The size of a @uuid_t@.+uuidSize :: Int+uuidSize = 16++foreign import ccall safe "membership.h mbr_uid_to_uuid" c_mbr_uid_to_uuid :: CUInt -> Ptr Word8 -> IO CInt++foreign import ccall safe "membership.h mbr_gid_to_uuid" c_mbr_gid_to_uuid :: CUInt -> Ptr Word8 -> IO CInt++foreign import ccall safe "membership.h mbr_check_membership" c_mbr_check_membership :: Ptr Word8 -> Ptr Word8 -> Ptr CInt -> IO CInt+#else+membership _ _ = pure Nothing+#endif+#endif
+ src/Nix/Daemon/LocalStore.hs view
@@ -0,0 +1,672 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TupleSections #-}++-- | The local store as a daemon serves it: each connection's+-- t'DaemonStore' over the daemon's one open t'Store'.+--+-- The daemon holds the store's lease for as long as it runs, so no+-- collection starts while it serves ("Nix.Store.Handle").  Each+-- connection reads the store's database through a connection of its+-- own, which it closes as it ends, and keeps its own temporary roots,+-- which a listing of roots shows with every other connection's and which+-- go with it.+--+-- Each operation builds and substitutes under the configuration its+-- connection's settings give ("Nix.Builder.Settings"), on the defaults+-- the daemon found for the machine as it started, and its store reports+-- to the client: each message as a line at its level, and each build,+-- check and substitution as an activity, as upstream's derivation and+-- substitution goals start theirs ('storeActivity'), each line its+-- builder writes a result of it.+--+-- A client adds paths as upstream's daemon adds them for its clients: a+-- dump made into the path its content address makes, and a NAR with what+-- its path claims of itself, held to the signatures of the keys the+-- connection trusts where the client's trust and @require-sigs@ say so+-- ("Nix.Store.Import").  An upload is written to a staging directory as+-- it arrives and moved to its path once it has been checked; what one+-- holds between two of its chunks is released when it ends, or when the+-- connection does.  Each path added, or found valid, is a temporary root+-- of the connection, as upstream's store roots the paths it adds.+--+-- What the store does not do through a daemon yet is refused, with the+-- client told so: adding signatures, collecting garbage and repairing,+-- and optimising and verifying the store, which nova-nix does not do at+-- all.+--+-- What the daemon tells a client names a path under @\/nix\/store@, the+-- directory every store path is computed under, as the wire does,+-- wherever the store keeps its files.+module Nix.Daemon.LocalStore+  ( ServedStore,+    newServedStore,+    serveLocal,+  )+where++import Control.Concurrent.MVar (MVar, modifyMVar, modifyMVar_, newMVar, readMVar)+import Control.Exception (Handler (..), IOException, bracket, catch, catches, displayException, finally, mask_, uninterruptibleMask_)+import Control.Monad (filterM, join)+import Data.Bifunctor (bimap, first)+import Data.Bits (toIntegralSized)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import Data.Foldable (foldlM, traverse_)+import Data.Functor ((<&>))+import Data.IORef (IORef, atomicModifyIORef', newIORef)+import Data.Int (Int64)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (catMaybes)+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Word (Word64)+import Database.SQLite.Simple (SQLError)+import Nix.Builder (BuildConfig (..), BuildStop, buildRequests, buildRequestsEach, checkStored, planMissingPaths, readDrvFromStore, stopReported, substitutablePaths, substituteFromCaches)+import Nix.Builder.Settings (MachineDefaults, settingsBuildConfig)+import Nix.Config (NixConfig (..))+import Nix.Daemon.Connection (ConnectionEnd, ServerConfig (..), Transport, serveConnection)+import Nix.Daemon.Ops (CheckSigs (..), ClientSettings (..), ConnectionSettings (..), DaemonStore (..), DumpUpload (..), Intake (..), LogEvent (..), Repair (..), RootCensoring (..), Substitute (..), Work (..), daemonError, logVerbosity, storeActivity)+import Nix.Daemon.Protocol+  ( DaemonError,+    OutputName (..),+    Trust,+    UnkeyedValidPathInfo (..),+    ValidPathInfo (..),+    grammarText,+    narHashDigest,+    narHashFromDigest,+  )+import qualified Nix.Daemon.Protocol as Proto+import Nix.Derivation (Derivation, DerivationOutput (..), drvOutputs, fromATerm)+import Nix.HostPath (hostPathBytes)+import Nix.Key (KeyRefusal (..), keyRefusalReason, parsePublicKey, trustedKeys, verifyingKey)+import Nix.Logger (Level (..), Logger (..), logWarning)+import Nix.Realise (ClosureOutcome (..), MissingPaths (..), OutputSelection (..), RequestOutcome (..), Wanted (..), realiseFailureMessage)+import qualified Nix.Realise as Realise+import Nix.Store (SignatureRequirement (..), Store (..), isValid)+import Nix.Store.CaseSensitive (volumeCaseHack)+import Nix.Store.DB (PathInfo (..), PathRegistration (..), Ultimate (..), closeStoreDB, openStoreDB, queryAllValidPaths, queryPathInfo, queryReferences, queryReferrers, queryValidDerivers, statedRegistrationTime)+import qualified Nix.Store.ExecBit as ExecBit+import Nix.Store.GC (GcRoot (..), addIndirectRoot, findRoots)+import Nix.Store.Import (NarImportStart (..), NarImportStep (..), abandonDumpAdd, abandonNarImport, admitNar, beginDumpAdd, beginNarImport, endDumpAdd, endNarImport, endedDumpPath, feedDumpAdd, feedNarImport, placeDump)+import Nix.Store.Path (StorePath (spName), defaultStoreDir, parseStorePath, storePathToFilePath, storePathToText)+import NovaCache.Hash (NixHash (..), formatNixHash, parseNixHash)+import qualified System.OsPath as OP++-- ---------------------------------------------------------------------------+-- The store+-- ---------------------------------------------------------------------------++-- | The store a daemon serves, the machine's defaults its builds fall+-- back on, every connection's temporary roots, by the connection's+-- number, and the number the next activity of any connection takes.+data ServedStore = ServedStore+  { ssStore :: !Store,+    ssDefaults :: !MachineDefaults,+    ssTempRoots :: !(MVar (Map Int (Set StorePath))),+    ssNextConnection :: !(MVar Int),+    ssNextActivity :: !(IORef Word64)+  }++-- | Serve an open store, which the caller keeps open for as long as it+-- serves, its builds on the machine defaults given.+newServedStore :: MachineDefaults -> Store -> IO ServedStore+newServedStore defaults store = ServedStore store defaults <$> newMVar Map.empty <*> newMVar 0 <*> newIORef firstActivity++-- | The number of the daemon's first activity: 0 is an activity's parent+-- when it has none.+firstActivity :: Word64+firstActivity = 1++-- | Serve one connection over the store, its temporary roots dropped and+-- its database connection closed as it ends.+serveLocal :: ServedStore -> ServerConfig -> Trust -> Transport IO -> IO ConnectionEnd+serveLocal served config trust transport =+  bracket (openStoreDB (stDir (ssStore served))) closeStoreDB $ \db ->+    bracket register release $ \(number, hold) ->+      serveConnection config trust (connectionStore served (scConfig config) (ssStore served) {stDB = db} number hold) transport+  where+    register = do+      number <- modifyMVar (ssNextConnection served) (\next -> pure (next + 1, next))+      hold <- UploadHold <$> newIORef (pure ())+      (number, hold) <$ modifyMVar_ (ssTempRoots served) (pure . Map.insert number Set.empty)+    -- The release cannot be cut short: a hangup the watcher sees as the+    -- connection ends would otherwise leave the connection's roots held,+    -- or an upload's staging behind.+    release (number, hold) = uninterruptibleMask_ (releaseUpload hold `finally` modifyMVar_ (ssTempRoots served) (pure . Map.delete number))++-- ---------------------------------------------------------------------------+-- Uploads+-- ---------------------------------------------------------------------------++-- | What the upload a connection is taking in holds between two of its+-- chunks, as the action that releases it.  The store gives an upload up+-- itself when it fails or ends; the connection, which can be stopped+-- between two chunks, as a client that hangs up stops it, releases what+-- is held as it ends.  Releasing twice is harmless, since giving up an+-- upload never touches a store path ("Nix.Store.Import").+newtype UploadHold = UploadHold (IORef (IO ()))++-- | Hold what an upload begun holds, given what releases it, releasing+-- what an earlier upload still held.  It is called with asynchronous+-- exceptions masked around the upload's beginning, so nothing begun goes+-- unheld.+holdUpload :: UploadHold -> IO () -> IO ()+holdUpload (UploadHold cell) release = uninterruptibleMask_ (join (atomicModifyIORef' cell (release,)))++-- | Release what the connection's upload holds, if anything, and hold+-- nothing after.  The release is taken and run with asynchronous+-- exceptions held off, so none comes between the two or cuts the release+-- short, leaving what it removes behind.+releaseUpload :: UploadHold -> IO ()+releaseUpload (UploadHold cell) = uninterruptibleMask_ (join (atomicModifyIORef' cell (pure (),)))++-- ---------------------------------------------------------------------------+-- One connection's view+-- ---------------------------------------------------------------------------++-- | The store as one connection sees it, under the daemon's settings+-- given, reading through its own handle on the database.+connectionStore :: ServedStore -> NixConfig -> Store -> Int -> UploadHold -> DaemonStore IO+connectionStore served daemonConfig store number hold =+  DaemonStore+    { dsIsValidPath = \_ path -> reading (isValid store path),+      dsQueryValidPaths = queryValid . working,+      dsQuerySubstitutablePaths = \w paths -> let Working config opStore = working w in (>>= first daemonError) <$> reading (substitutablePaths config opStore (Set.toAscList paths)),+      dsQueryReferrers = \_ path -> (>>= storePaths) <$> reading (queryReferrers (stDB store) path),+      dsQueryValidDerivers = \_ path -> (>>= storePaths) <$> reading (queryValidDerivers (stDB store) path),+      dsQueryDerivationOutputMap = \_ path -> outputMap path,+      dsQueryAllValidPaths = \_ -> (>>= storePaths) <$> reading (queryAllValidPaths (stDB store)),+      dsQueryPathInfo = \_ path -> pathInfo path,+      dsQueryMissing = \w targets -> let Working config opStore = working w in (>>= bimap daemonError protocolMissing) <$> reading (planMissingPaths config opStore (map wantedFor targets)),+      dsAddToStore = addDump . reporting,+      dsAddToStoreNar = \w -> addNar (storeSettings daemonConfig (workSettings w)) (reporting w),+      dsBuildPaths = buildPaths . working,+      dsBuildPathsWithResults = buildPathsWithResults . working,+      dsEnsurePath = \w path -> addTempRoot path >>= either (pure . Left) (const (ensurePath (working w) path)),+      dsAddTempRoot = \_ path -> addTempRoot path,+      dsAddIndirectRoot = \_ link -> reading (addIndirectRoot store link),+      dsFindRoots = \_ censoring -> roots censoring,+      dsCollectGarbage = \_ _ -> pure (Left (daemonError "the nova-nix daemon does not collect garbage yet")),+      dsOptimiseStore = \_ -> pure (Left (daemonError "optimising the store is not available in nova-nix")),+      dsVerifyStore = \_ _ _ -> pure (Left (daemonError "verifying the store is not available in nova-nix")),+      dsAddSignatures = \_ _ _ -> pure (Left (daemonError "the nova-nix daemon does not add signatures yet")),+      dsNarFromPath = narFromPath+    }+  where+    addTempRoot path = reading (modifyMVar_ (ssTempRoots served) (pure . Map.adjust (Set.insert path) number))+    working = operationStore served daemonConfig store+    pathInfo path =+      reading ((,) <$> queryPathInfo (stDB store) path <*> queryReferences (stDB store) path) >>= \case+        Left err -> pure (Left err)+        Right (Nothing, _) -> pure (Right Nothing)+        Right (Just info, references) -> pure (Just <$> protocolInfo store info references)+    outputMap drvPath =+      reading (isValid store drvPath) >>= \case+        Left err -> pure (Left err)+        Right False -> pure (Left (notValid drvPath))+        Right True ->+          reading (BS.readFile (storePathToFilePath (stDir store) drvPath)) >>= \case+            Left err -> pure (Left err)+            Right aterm -> pure $ case fromATerm aterm of+              Left refusal -> Left (daemonError refusal)+              Right drv -> Right (Map.fromList [(OutputName (doName output), Just (doPath output)) | output <- drvOutputs drv])+    roots censoring =+      reading (findRoots store >>= traverse rootLink) >>= \case+        Left err -> pure (Left err)+        Right links -> do+          held <- readMVar (ssTempRoots served)+          let temporary = [Right (path, tempRootName censoring holder) | (holder, paths) <- Map.toList held, path <- Set.toList paths]+          pure ((\pairs -> Map.fromListWith Set.union [(path, Set.singleton link) | (path, link) <- pairs]) <$> sequence (links ++ temporary))+    rootLink root = do+      spelled <- hostPathBytes <$> OP.encodeFS (grLink root)+      pure ((,) <$> storePath (grPath root) <*> maybe (Left (daemonError ("cannot spell the root '" <> T.pack (grLink root) <> "' as bytes"))) Right spelled)+    narFromPath path sink =+      reading (isValid store path) >>= \case+        Left err -> pure (Left err)+        Right False -> pure (Left (notValid path))+        Right True -> reading (ExecBit.withNarSource (volumeCaseHack (stCaseSensitivity store)) (storePathToFilePath (stDir store) path) (pump sink))+    pump sink pull =+      pull >>= \chunk ->+        if BS.null chunk then pure () else sink chunk >> pump sink pull+    storePaths = fmap Set.fromList . traverse storePath+    storePath spelled = maybe (Left (daemonError ("the store's database names '" <> spelled <> "', which is not a path in it"))) Right (parseStorePath (stDir store) spelled)+    -- Upstream's refusal of a path that is not valid.+    notValid path = daemonError ("path '" <> storePathToText defaultStoreDir path <> "' is not valid")+    -- The store as an add uses it, telling the client what it says.+    reporting w = let Working _ opStore = working w in opStore+    -- A NAR with what its path claims of itself, as upstream's store adds+    -- one: admitted by its signatures or its content address, its path a+    -- temporary root, a path already valid not read, and another+    -- imported from its NAR as it arrives.+    addNar config opStore (ValidPathInfo path info) repair checkSigs = case repair of+      Repair -> pure (Taken (Left repairingRefusal))+      NoRepair ->+        signatureRequirement config checkSigs >>= \required -> case (,) <$> required <*> registrationClaim store path info of+          Left err -> pure (Taken (Left err))+          Right (requirement, claim) ->+            refusedOr (admitNar opStore requirement claim) $ \admitted ->+              addTempRoot path >>= \case+                Left err -> pure (Taken (Left err))+                Right () ->+                  beginHeld (beginNarImport admitted) heldImport >>= \case+                    Left err -> pure (Taken (Left err))+                    Right NarAlreadyValid -> pure (Taken (Right ()))+                    Right (NarImportBegun begun) -> pure (importing begun)+    heldImport = \case+      NarImportBegun begun -> holdUpload hold (abandonNarImport begun)+      NarAlreadyValid -> pure ()+    importing begun = Taking (feedImport begun) (ending (refusedValue (endNarImport begun) (pure . Right))) (abandoning (abandonNarImport begun))+    feedImport begun chunk =+      reading (feedNarImport begun chunk) >>= \case+        Left err -> settled (Left err)+        Right (Left refusal) -> settled (Left (daemonError refusal))+        Right (Right (NarImportGoesOn next)) -> pure (importing next)+        Right (Right NarImported) -> settled (Right ())+    -- A dump made into the path its content address makes, as upstream's+    -- store adds one: written as it arrives, then, once it ends, its path+    -- a temporary root and the path made valid from it unless it is+    -- already, and the path's info answered.+    addDump opStore upload = case duRepair upload of+      Repair -> pure (Taken (Left repairingRefusal))+      NoRepair ->+        beginHeld (beginDumpAdd opStore (grammarText (duName upload)) (duMethod upload) (duAlgo upload) (duReferences upload)) (traverse_ (holdUpload hold . abandonDumpAdd)) >>= \case+          Left err -> pure (Taken (Left err))+          Right (Left refusal) -> pure (Taken (Left (daemonError refusal)))+          Right (Right add) -> pure (dumping add)+    dumping add = Taking (feedDump add) (ending (endDump add)) (abandoning (abandonDumpAdd add))+    feedDump add chunk =+      reading (feedDumpAdd add chunk) >>= \case+        Left err -> settled (Left err)+        Right (Left refusal) -> settled (Left (daemonError refusal))+        Right (Right next) -> pure (dumping next)+    endDump add =+      refusedValue (endDumpAdd add) $ \ended ->+        let path = endedDumpPath ended+         in addTempRoot path >>= \case+              Left err -> pure (Left err)+              Right () -> refusedValue (placeDump ended) $ \() -> fmap (ValidPathInfo path) <$> (pathInfo path <&> (>>= maybe (Left (notValid path)) Right))+    -- A store call's refusal as the client is sent it, or what follows+    -- from its value; a failure to read the disk or the database is sent+    -- as the error it is.+    refusedOr call continue =+      reading call >>= \case+        Left err -> pure (Taken (Left err))+        Right (Left refusal) -> pure (Taken (Left (daemonError refusal)))+        Right (Right value) -> continue value+    refusedValue call continue =+      reading call >>= \case+        Left err -> pure (Left err)+        Right (Left refusal) -> pure (Left (daemonError refusal))+        Right (Right value) -> continue value+    -- Begin an upload with what it then holds held, no exception coming+    -- between the two.+    beginHeld begin holding = mask_ (reading begin >>= \begun -> begun <$ traverse_ holding begun)+    -- An upload that has ended, its store having given up what it held.+    settled outcome = Taken outcome <$ releaseUpload hold+    ending end = end <* releaseUpload hold+    abandoning abandon = abandon >> releaseUpload hold++-- ---------------------------------------------------------------------------+-- An operation's store+-- ---------------------------------------------------------------------------++-- | What an operation builds and substitutes under, and the store it does+-- so in.+data Working = Working !BuildConfig !Store++-- | The store as an operation uses it: reporting to the client, and+-- building under the configuration the connection's settings give+-- ('storeSettings'), with no cache when the client said not to+-- substitute, as upstream's worker has none then.+operationStore :: ServedStore -> NixConfig -> Store -> Work IO -> Working+operationStore served daemonConfig store w = Working config store {stLogger = tunnelLogger served (workReport w)}+  where+    settings = workSettings w+    configured = settingsBuildConfig (ssDefaults served) (storeSettings daemonConfig settings) (stDir store)+    config+      | maybe True csUseSubstitutes (connClient settings) = configured+      | otherwise = configured {bcCaches = []}++-- | The settings a connection's store works under, given the daemon's:+-- the connection's, with the daemon's own @require-sigs@.  Upstream's+-- store reads that setting as it opens, before a client's settings+-- arrive, so a trusted client that sets it changes nothing.+storeSettings :: NixConfig -> ConnectionSettings -> NixConfig+storeSettings daemonConfig settings = (connConfig settings) {ncRequireSigs = ncRequireSigs daemonConfig}++-- | A logger that reports to a client: a message as a line at its level,+-- and an activity under a number no other activity of the daemon has,+-- each line its builder writes a result of it.  A line outside any+-- activity goes as an info-level line.  A report the client cannot be+-- sent is dropped, as a logger drops a line it cannot deliver and as+-- upstream's daemon stops sending to a client that has gone, so the work+-- for a client that hung up stops for the hangup rather than going on+-- past a failed write.+tunnelLogger :: ServedStore -> (LogEvent -> IO ()) -> Logger+tunnelLogger served send =+  Logger+    { logAt = \level -> report . LogLine (logVerbosity level) . TE.encodeUtf8,+      logBuildLine = report . LogLine (logVerbosity LevelInfo),+      logActivity = \start -> do+        activity <- atomicModifyIORef' (ssNextActivity served) (\next -> (next + 1, Proto.ActivityId next))+        report (ActivityStarted (storeActivity defaultStoreDir activity start))+        pure (report . ActivityResult activity Proto.resBuildLogLine . pure . Proto.FieldString, report (ActivityStopped activity))+    }+  where+    report event = send event `catch` \(_ :: IOException) -> pure ()++-- ---------------------------------------------------------------------------+-- Building and substituting+-- ---------------------------------------------------------------------------++-- | The valid paths among those asked, after substituting those a cache+-- offers when asked to, as upstream's daemon substitutes them: what+-- realising them would take is worked out first, a derivation's own+-- path left out, and a substitution that fails is a warning.+queryValid :: Working -> Substitute -> Set StorePath -> IO (Either DaemonError (Set StorePath))+queryValid (Working config store) substitute paths = case substitute of+  NoSubstitute -> valid+  Substitute ->+    reading (planMissingPaths config store [WantedPath path | path <- Set.toAscList paths, not (".drv" `T.isSuffixOf` spName path)]) >>= \case+      Left err -> pure (Left err)+      Right (Left why) -> pure (Left (daemonError why))+      Right (Right plan) -> traverse_ substituteOne (Set.toAscList (mpSubstitute plan)) *> valid+  where+    valid = fmap Set.fromList <$> reading (filterM (isValid store) (Set.toAscList paths))+    substituteOne path =+      reading (substituteFromCaches config store [path]) >>= \case+        Right ClosureComplete -> pure ()+        _ -> logWarning (stLogger store) (requiredMessage path)++-- | Make a path valid: one that is already valid is, and another is+-- substituted with what it references, or fails in upstream's words.+ensurePath :: Working -> StorePath -> IO (Either DaemonError ())+ensurePath working path = (>>= either (Left . daemonError . snd) (const (Right ()))) <$> pathOutcome working path++-- | How making a path valid ends, as upstream's goal for substituting it+-- ends: valid already, or substituted; or failed, with the kind of+-- failure and upstream's message, no cache holding the path or something+-- it references.  A cache that cannot be asked ends the whole call, as+-- upstream's goal throws then.+pathOutcome :: Working -> StorePath -> IO (Either DaemonError (Either (Proto.FailureStatus, Text) Proto.SuccessStatus))+pathOutcome (Working config store) path =+  reading (isValid store path) >>= \case+    Left err -> pure (Left err)+    Right True -> pure (Right (Right Proto.AlreadyValid))+    Right False ->+      reading (substituteFromCaches config store [path]) <&> \case+        Left err -> Left err+        Right ClosureComplete -> Right (Right Proto.Substituted)+        Right (ClosureQueryFailed why) -> Left (daemonError why)+        Right ClosureIncomplete -> Right (Left (Proto.DependencyFailed, "some references of path '" <> spelled <> "' could not be realised"))+        Right ClosureUnavailable -> Right (Left (Proto.NoSubstituters, requiredMessage path))+        Right ClosureFailed -> Right (Left (Proto.NoSubstituters, requiredMessage path))+  where+    spelled = storePathToText defaultStoreDir path++-- | Upstream's report of a path no cache could substitute.+requiredMessage :: StorePath -> Text+requiredMessage path = "path '" <> storePathToText defaultStoreDir path <> "' is required, but there is no substituter that can build it"++-- | Realise derived paths as upstream's daemon builds them: each store+-- path as it is made valid ('ensurePath'), and the outputs of each+-- derivation asked for built, or under 'Proto.BuildCheck' checked.  The+-- first failure stops the call with the status the build gives, and a+-- derivation that cannot be obtained stops it before anything is done.+buildPaths :: Working -> [Proto.DerivedPath] -> Proto.BuildMode -> IO (Either DaemonError ())+buildPaths working@(Working config store) targets = \case+  Proto.BuildRepair -> pure (Left repairingRefusal)+  Proto.BuildNormal -> realised (\requests -> (>>= stopped) <$> reading (buildRequests config store requests))+  Proto.BuildCheck -> realised (foldlM (\done (drvPath, _) -> either (pure . Left) (const ((>>= stopped) <$> reading (checkStored config store drvPath))) done) (Right ()))+  where+    realised build =+      requestsFor working targets >>= \case+        Left err -> pure (Left err)+        Right (Requested _ _ _ (unobtained : _)) -> pure (Left (daemonError (unobtainedMessage unobtained)))+        Right (Requested opaque requests _ []) ->+          foldlM (\done path -> either (pure . Left) (const (ensurePath working path)) done) (Right ()) opaque >>= either (pure . Left) (const (build requests))+    stopped = \case+      Left stop -> Left (stoppedWith stop)+      Right () -> Right ()++-- | Realise derived paths as 'buildPaths' does, and say how each ended,+-- in the order asked, leaving out one left unrealised when another failed+-- as upstream leaves out a goal that never finished.  A derivation that+-- cannot be obtained fails its request, and nothing else is realised, as+-- upstream's worker stops once a requested goal fails.+buildPathsWithResults :: Working -> [Proto.DerivedPath] -> Proto.BuildMode -> IO (Either DaemonError [Proto.KeyedBuildResult])+buildPathsWithResults working@(Working config store) targets mode = case mode of+  Proto.BuildRepair -> pure (Left repairingRefusal)+  Proto.BuildNormal -> realised Realise.BuildNormal+  Proto.BuildCheck -> realised Realise.BuildCheck+  where+    realised realiseMode =+      requestsFor working targets >>= \case+        Left err -> pure (Left err)+        Right (Requested _ _ _ unobtained@(_ : _)) ->+          pure (Right [Proto.KeyedBuildResult target (failedAs Proto.DependencyFailed (TE.encodeUtf8 (unobtainedMessage drvPath))) | target@(Proto.DerivedBuilt drvPath _) <- targets, drvPath `elem` unobtained])+        Right (Requested opaque requests derivations []) -> do+          ensuring <- traverse (\path -> fmap (path,) <$> pathOutcome working path) opaque+          case Map.fromList <$> sequence ensuring of+            Left err -> pure (Left err)+            Right ensured -> (>>= either stoppedCall (Right . keyedResults derivations ensured)) <$> reading (buildRequestsEach config realiseMode store requests)+    stoppedCall = Left . stoppedWith+    keyedResults derivations ensured outcomes = [Proto.KeyedBuildResult target result | target <- targets, Just result <- [resultFor derivations ensured outcomes target]]+    resultFor derivations ensured outcomes = \case+      Proto.DerivedOpaque path -> either (\(status, message) -> failedAs status (TE.encodeUtf8 message)) (`succeededWith` Map.empty) <$> Map.lookup path ensured+      Proto.DerivedBuilt drvPath spec -> outcomeResult drvPath (Map.lookup drvPath derivations) spec <$> Map.lookup drvPath outcomes+    outcomeResult drvPath drv spec = \case+      RequestRealised Realise.AlreadyValid -> succeededWith Proto.AlreadyValid outputs+      RequestRealised Realise.Substituted -> succeededWith Proto.Substituted outputs+      RequestRealised Realise.Built -> (succeededWith Proto.Built outputs) {Proto.brTimesBuilt = 1}+      RequestRealised Realise.Checked -> (succeededWith Proto.Built outputs) {Proto.brTimesBuilt = 1}+      RequestFailed failure -> failedAs (failureKind failure) (TE.encodeUtf8 (realiseFailureMessage (stDir store) failure))+      RequestDependencyFailed _ _ -> failedAs Proto.DependencyFailed (TE.encodeUtf8 (dependencyFailedMessage drvPath drv))+      where+        outputs = foldMap (realisations spec) drv+    failedAs status message = noTimes (Proto.Failed (Proto.Failure status message False))+    succeededWith status outputs = noTimes (Proto.Succeeded (Proto.Success status outputs))+    noTimes outcome = Proto.BuildResult outcome 0 0 0 Nothing Nothing+    -- The outputs a target asks of a derivation, each where the+    -- derivation puts it.+    realisations spec drv =+      Map.fromList+        [ (OutputName (doName output), Proto.UnkeyedRealisation (doPath output) Set.empty)+        | output <- drvOutputs drv,+          maybe True (Set.member (OutputName (doName output))) (Proto.outputsSpecNames spec)+        ]++-- | Upstream's report of a derivation not built because one it needs+-- failed, with the paths of its outputs.+dependencyFailedMessage :: StorePath -> Maybe Derivation -> Text+dependencyFailedMessage drvPath drv =+  "Cannot build '" <> spelled drvPath <> "'.\nReason: 1 dependency failed." <> foldMap outputPaths drv+  where+    spelled = storePathToText defaultStoreDir+    outputPaths built = case Set.toAscList (Set.fromList (map doPath (drvOutputs built))) of+      [] -> ""+      paths -> "\nOutput paths:" <> foldMap (("\n  " <>) . spelled) paths++-- | The error a stopped build is sent as, with the status it exits with.+stoppedWith :: BuildStop -> DaemonError+stoppedWith stop = (daemonError message) {Proto.errExitStatus = fromIntegral status}+  where+    (message, status) = stopReported stop++-- | Which of upstream's kinds of failure a realisation's failure is.+failureKind :: Realise.RealiseFailure -> Proto.FailureStatus+failureKind = \case+  Realise.BuildFailed _ -> Proto.PermanentFailure+  Realise.FixedOutputRejected _ -> Proto.OutputRejected+  Realise.NotDeterministic {} -> Proto.NotDeterministic+  Realise.SubstitutesFailed _ -> Proto.TransientFailure+  Realise.CacheQueryFailed _ -> Proto.MiscFailure+  Realise.InvalidDerivation _ -> Proto.MiscFailure+  Realise.OutputsNotValid _ -> Proto.MiscFailure+  Realise.MissingDerivation _ -> Proto.MiscFailure+  Realise.MissingOutputs _ _ -> Proto.MiscFailure++-- | What realising some derived paths asks for: the store paths to make+-- valid, each derivation with the outputs asked of it, each derivation as+-- the store holds it, and the derivations that could not be obtained.+data Requested = Requested ![StorePath] ![(StorePath, Set Text)] !(Map StorePath Derivation) ![StorePath]++-- | One derived path as realising it asks for it.+data RequestedPath+  = OpaqueTarget !StorePath+  | DerivationTarget !StorePath !(Set Text) !Derivation+  | UnobtainedTarget !StorePath++-- | The derived paths as what realising them asks for.  A derivation the+-- store does not hold is substituted first, as upstream's goal obtains+-- one before it builds it, and one no cache gives is not obtained; one+-- it holds is read, which names every output where all are asked for.+requestsFor :: Working -> [Proto.DerivedPath] -> IO (Either DaemonError Requested)+requestsFor working@(Working config _) targets = fmap gather . sequence <$> traverse request targets+  where+    request = \case+      Proto.DerivedOpaque path -> pure (Right (OpaqueTarget path))+      Proto.DerivedBuilt drvPath spec ->+        pathOutcome working drvPath >>= \case+          Left err -> pure (Left err)+          Right (Left _) -> pure (Right (UnobtainedTarget drvPath))+          Right (Right _) -> bimap daemonError (\drv -> DerivationTarget drvPath (outputsAsked spec drv) drv) <$> readDrvFromStore config drvPath+    outputsAsked spec drv = maybe (Set.fromList (map doName (drvOutputs drv))) (Set.map outputNameText) (Proto.outputsSpecNames spec)+    gather chosen =+      Requested+        [path | OpaqueTarget path <- chosen]+        [(drvPath, names) | DerivationTarget drvPath names _ <- chosen]+        (Map.fromList [(drvPath, drv) | DerivationTarget drvPath _ drv <- chosen])+        [drvPath | UnobtainedTarget drvPath <- chosen]++-- | Upstream's report of a derivation it could not obtain to build.+unobtainedMessage :: StorePath -> Text+unobtainedMessage drvPath = "failed to obtain derivation of '" <> storePathToText defaultStoreDir drvPath <> "'"++-- | What realising a derived path asks for, as the planner takes it.+wantedFor :: Proto.DerivedPath -> Wanted+wantedFor = \case+  Proto.DerivedOpaque path -> WantedPath path+  Proto.DerivedBuilt drvPath spec -> WantedOutputs drvPath (maybe EveryOutput (TheseOutputs . Set.map outputNameText) (Proto.outputsSpecNames spec))++-- | An output's name as text.+outputNameText :: OutputName -> Text+outputNameText (OutputName name) = name++-- | What realising some paths would take, as the protocol says it.+protocolMissing :: MissingPaths -> Proto.Missing+protocolMissing plan = Proto.Missing (mpBuild plan) (mpSubstitute plan) (mpUnknown plan) (mpDownloadSize plan) (mpNarSize plan)++-- | How a connection's temporary root is listed: by the connection that+-- holds it, where upstream names the process that holds one, which for+-- its daemon is the connection's worker.+tempRootName :: RootCensoring -> Int -> ByteString+tempRootName censoring holder = case censoring of+  CensorRoots -> "{censored}"+  ShowRoots -> "{temp:" <> TE.encodeUtf8 (T.pack (show holder)) <> "}"++-- | A path's info from the store's database, in the protocol's terms.+protocolInfo :: Store -> PathInfo -> [Text] -> Either DaemonError UnkeyedValidPathInfo+protocolInfo store info references = do+  deriver <- traverse spelledPath (piDeriver info)+  refs <- traverse spelledPath references+  narHash <- either (const (Left (corrupt "its NAR hash"))) Right (parseNixHash (piNarHash info)) >>= \(NixHash digest) -> maybe (Left (corrupt "its NAR hash")) Right (narHashFromDigest digest)+  pure+    UnkeyedValidPathInfo+      { upiDeriver = deriver,+        upiNarHash = narHash,+        upiReferences = Set.fromList refs,+        upiRegistrationTime = fromIntegral (piRegTime info) :: Int64,+        upiNarSize = fromIntegral (piNarSize info),+        upiUltimate = piUltimate info == Ultimate,+        upiSignatures = piSignatures info,+        upiContentAddress = piContentAddress info+      }+  where+    spelledPath spelled = maybe (Left (corrupt ("'" <> spelled <> "'"))) Right (parseStorePath (stDir store) spelled)+    corrupt what = daemonError ("the store's database holds an entry for '" <> piPath info <> "' whose " <> what <> " cannot be read")++-- ---------------------------------------------------------------------------+-- Failures+-- ---------------------------------------------------------------------------++-- | Run a read of the store, its failure to read the disk or the+-- database an error the client is sent.+reading :: IO a -> IO (Either DaemonError a)+reading action =+  (Right <$> action)+    `catches` [ Handler (\(err :: IOException) -> pure (Left (daemonError (T.pack (displayException err))))),+                Handler (\(err :: SQLError) -> pure (Left (daemonError (T.pack (displayException err)))))+              ]++-- | What the daemon does not do yet.+repairingRefusal :: DaemonError+repairingRefusal = daemonError "repairing is not available in nova-nix"++-- ---------------------------------------------------------------------------+-- Adding paths+-- ---------------------------------------------------------------------------++-- | What an import holds its path to, as upstream's store holds a path it+-- is handed a NAR for: the signatures of the keys the connection trusts+-- ('trustedKeys'), unless the client may and does ask that they not be+-- checked ('Nix.Daemon.Ops.authorize' has held an untrusted client to+-- them) or @require-sigs@ is off, when no key is read.  A key that does+-- not read is refused in upstream's words, whatever the path, as+-- upstream reads every trusted key before it counts a path's+-- signatures.+signatureRequirement :: NixConfig -> CheckSigs -> IO (Either DaemonError SignatureRequirement)+signatureRequirement config = \case+  NoCheckSigs -> pure (Right SignaturesNotRequired)+  CheckSigs+    | not (ncRequireSigs config) -> pure (Right SignaturesNotRequired)+    | otherwise -> case traverse trustedKey (ncTrustedPublicKeys config) of+        Left err -> pure (Left err)+        Right given -> bimap (keyRefusal SecretKeyFile) RequireSignature <$> trustedKeys (catMaybes given) (ncSecretKeyFiles config)+  where+    trustedKey spelled = bimap (keyRefusal (TrustedKeySpelled spelled)) verifyingKey (parsePublicKey (TE.encodeUtf8 spelled))++-- | Where a key that does not read was found: spelled in+-- @trusted-public-keys@, or in a file @secret-key-files@ names.+data KeySource = TrustedKeySpelled !Text | SecretKeyFile++-- | Upstream's refusal of a key that does not read: one that is not a+-- name, a colon and base64 with the trace upstream adds as it decodes a+-- key, which names the key it has not yet read, so the name is always+-- empty, and shows a public key's spelling but never a secret one's; and+-- one of the wrong size on its own.+keyRefusal :: KeySource -> KeyRefusal -> DaemonError+keyRefusal source refusal = case refusal of+  KeyUnreadable _ -> (daemonError (keyRefusalReason refusal)) {Proto.errTraces = ["while decoding key named ''" <> rawValue]}+  SecretKeyNotValid -> daemonError (keyRefusalReason refusal)+  PublicKeyNotValid -> daemonError (keyRefusalReason refusal)+  where+    rawValue = case source of+      TrustedKeySpelled spelled -> " with raw value '" <> TE.encodeUtf8 spelled <> "'"+      SecretKeyFile -> ""++-- | What a path an upload names claims of itself, as the store registers+-- it: its deriver spelled as the database spells a path.  A NAR size this+-- platform cannot count to is refused before anything is read.+registrationClaim :: Store -> StorePath -> UnkeyedValidPathInfo -> Either DaemonError PathRegistration+registrationClaim store path info = case toIntegralSized (upiNarSize info) of+  Nothing -> Left (daemonError ("cannot add path '" <> storePathToText defaultStoreDir path <> "': its NAR size " <> T.pack (show (upiNarSize info)) <> " is more than this platform can count"))+  Just size ->+    Right+      PathRegistration+        { prPath = path,+          prNarHash = formatNixHash (NixHash (narHashDigest (upiNarHash info))),+          prNarSize = size,+          prDeriver = T.pack . storePathToFilePath (stDir store) <$> upiDeriver info,+          prReferences = Set.toAscList (upiReferences info),+          prUltimate = if upiUltimate info then Ultimate else NotUltimate,+          prSignatures = upiSignatures info,+          prContentAddress = upiContentAddress info,+          prRegistrationTime = statedRegistrationTime (upiRegistrationTime info)+        }
+ src/Nix/Daemon/Ops.hs view
@@ -0,0 +1,1050 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE TupleSections #-}++-- | The operations a daemon serves, as upstream's daemon reads and judges+-- them: what each one reads before its work begins ('getRequest'), what a+-- client the daemon does not trust may not ask ('authorize'), what a+-- client's settings change for its connection ('applyClientSettings'),+-- and what the store must provide to serve them, a t'DaemonStore' in the+-- protocol's own terms.  "Nix.Daemon.Connection" runs them on a+-- connection.+--+-- The operations served are the ones upstream's clients send for+-- building, substituting, copying, querying and collecting with a+-- daemon as their store.  Any other operation code is refused as+-- upstream refuses one it does not know.+--+-- Upstream's messages are kept without the colours its formatter puts+-- around the values it interpolates.+module Nix.Daemon.Ops+  ( -- * Requests+    Request (..),+    getRequest,+    putRequest,+    getUploadPathInfo,+    putUploadPathInfo,+    Substitute (..),+    Repair (..),+    CheckSigs (..),+    CheckContents (..),+    Liveness (..),+    RootCensoring (..),+    AddToStoreRequest (..),+    GCRequest (..),++    -- ** The versions requests change at+    substituteFlagSince,+    framedAddToStoreSince,+    framedAddToStoreNarSince,+    queryMissingSince,+    outputMapSince,+    buildResultsSince,++    -- * Trust+    Authorization (..),+    authorize,+    rootCensoring,++    -- * Client settings+    ClientSettings (..),+    unsetCores,+    getClientSettings,+    putClientSettings,+    ConnectionSettings (..),+    applyClientSettings,++    -- * The store+    DaemonStore (..),+    Work (..),+    LogEvent (..),+    logVerbosity,+    storeActivity,+    activityStart,+    Intake (..),+    DumpUpload (..),+    daemonError,++    -- * Archives in uploads+    NarBoundary (..),+    narSizeBoundary,+  )+where++import Control.Monad (replicateM, replicateM_, when)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import Data.ByteString.Builder (Builder)+import qualified Data.ByteString.Char8 as BS8+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (mapMaybe)+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Word (Word32, Word64)+import Nix.Config (ConfigAssignment (..), NixConfig (..), applyAssignment)+import Nix.Daemon.Protocol+  ( Activity (..),+    ActivityId (..),+    BuildMode (..),+    ContentAddressMethod,+    DaemonError (..),+    DerivedPath,+    Field (..),+    GCAction (..),+    GCPaths (..),+    GCResult,+    KeyedBuildResult,+    Missing,+    OutputName,+    ResultType,+    Signature,+    Trust (..),+    UnkeyedValidPathInfo (..),+    ValidPathInfo (..),+    Verbosity (..),+    Version (..),+    VersionNumber (..),+    actBuild,+    actSubstitute,+    defaultExitStatus,+    errorVerbosity,+    featureDeleteDeadSpecificReferrers,+    getBuildMode,+    getDerivedPath,+    getGCAction,+    getGCPaths,+    getSignatureSet,+    getStorePath,+    getStorePathSet,+    getValidPathInfo,+    putBuildMode,+    putDerivedPath,+    putGCAction,+    putGCPaths,+    putSignatureSet,+    putStorePath,+    putStorePathSet,+    putValidPathInfo,+  )+import Nix.Daemon.Wire (Decoder, getBool, getBytes, getList, getWord32, getWord64, malformed, putBool, putBytes, putNum)+import Nix.Logger (ActivityStart (..), Level (..))+import Nix.Store.Path (StoreDir, StorePath, parseStorePath, storePathToText)+#if defined(mingw32_HOST_OS)+import Nix.HostPath (absolutePath, hostPathBytes, hostPathFromBytes)+import qualified System.OsPath as OP+#endif++-- ---------------------------------------------------------------------------+-- Requests+-- ---------------------------------------------------------------------------++-- | Whether a query first substitutes the paths it asks about.+data Substitute = NoSubstitute | Substitute+  deriving (Eq, Show)++-- | Whether an import replaces the contents of a path that is valid.+data Repair = NoRepair | Repair+  deriving (Eq, Show)++-- | Whether an import holds a path to the signatures the store trusts.+data CheckSigs = CheckSigs | NoCheckSigs+  deriving (Eq, Show)++-- | Whether a verification of the store reads each path's contents.+data CheckContents = SkipContents | CheckContents+  deriving (Eq, Show)++-- | Whether a collection takes live paths for dead ones, which upstream's+-- daemon refuses every client.+data Liveness = KeepLiveness | IgnoreLiveness+  deriving (Eq, Show)++-- | Whether the roots a client is shown name what holds them, or hide+-- the names upstream calls privacy-sensitive (a temporary root's owner,+-- a process's open file).+data RootCensoring = ShowRoots | CensorRoots+  deriving (Eq, Show)++-- | An upload of a dump to make a content-addressed path from, as far as+-- it is read before its work begins.  Its method is parsed once that work+-- has begun, as upstream parses it.+data AddToStoreRequest = AddToStoreRequest+  { -- | The name of the path to make, as the client sent it.+    atsName :: !ByteString,+    -- | The method and algorithm, spelled as the client sent them.+    atsMethod :: !ByteString,+    -- | The paths the dump refers to.+    atsReferences :: !(Set StorePath),+    -- | Whether a valid path's contents are replaced.+    atsRepair :: !Repair+  }+  deriving (Eq, Show)++-- | A collection, as far as the store performs it.+data GCRequest = GCRequest+  { -- | What it does.+    gcAction :: !GCAction,+    -- | Which paths it considers.+    gcPaths :: !GCPaths,+    -- | How many bytes it may free before it stops, 0 for no limit.+    gcMaxFreed :: !Word64+  }+  deriving (Eq, Show)++-- | An operation a client asks of the daemon, with what it sends before+-- the daemon begins its work.  An upload's bytes follow its request.+data Request+  = -- | Settings for the rest of the connection.+    SetOptions !ClientSettings+  | -- | Whether a path is valid.+    IsValidPath !StorePath+  | -- | Which of the paths are valid.+    QueryValidPaths !(Set StorePath) !Substitute+  | -- | Which of the paths a substituter offers.+    QuerySubstitutablePaths !(Set StorePath)+  | -- | The valid paths that refer to a path.+    QueryReferrers !StorePath+  | -- | The valid derivations that output a path.+    QueryValidDerivers !StorePath+  | -- | A derivation's outputs and the paths they have, where known.+    QueryDerivationOutputMap !StorePath+  | -- | Every valid path.+    QueryAllValidPaths+  | -- | What the store records of a path.+    QueryPathInfo !StorePath+  | -- | What realising the paths would build, substitute or not find.+    QueryMissing ![DerivedPath]+  | -- | Make a content-addressed path from a dump that follows.+    AddToStore !AddToStoreRequest+  | -- | Import a path from the NAR that follows.+    AddToStoreNar !ValidPathInfo !Repair !CheckSigs+  | -- | Import the paths that follow, each its info and its NAR.+    AddMultipleToStore !Repair !CheckSigs+  | -- | Realise the paths.+    BuildPaths ![DerivedPath] !BuildMode+  | -- | Realise the paths, with each one's result.+    BuildPathsWithResults ![DerivedPath] !BuildMode+  | -- | Make a path valid, substituting it if need be.+    EnsurePath !StorePath+  | -- | Keep a path from collection while the connection lasts.+    AddTempRoot !StorePath+  | -- | Keep what a link names from collection while the link exists.+    AddIndirectRoot !ByteString+  | -- | The roots that keep paths from collection.+    FindRoots+  | -- | Collect garbage.+    CollectGarbage !GCRequest !Liveness+  | -- | Share identical files in the store.+    OptimiseStore+  | -- | Check the store's consistency.+    VerifyStore !CheckContents !Repair+  | -- | Add signatures to a path's info.+    AddSignatures !StorePath !(Set Signature)+  | -- | A path's NAR serialisation.+    NarFromPath !StorePath+  deriving (Eq, Show)++-- | The operations served, each with its code on the wire.+data Op+  = OpIsValidPath+  | OpQueryReferrers+  | OpAddToStore+  | OpBuildPaths+  | OpEnsurePath+  | OpAddTempRoot+  | OpAddIndirectRoot+  | OpFindRoots+  | OpSetOptions+  | OpCollectGarbage+  | OpQueryAllValidPaths+  | OpQueryPathInfo+  | OpQueryValidPaths+  | OpQuerySubstitutablePaths+  | OpQueryValidDerivers+  | OpOptimiseStore+  | OpVerifyStore+  | OpAddSignatures+  | OpNarFromPath+  | OpAddToStoreNar+  | OpQueryMissing+  | OpQueryDerivationOutputMap+  | OpAddMultipleToStore+  | OpBuildPathsWithResults+  deriving (Eq, Show, Enum, Bounded)++-- | An operation's code.+opCode :: Op -> Word32+opCode = \case+  OpIsValidPath -> 1+  OpQueryReferrers -> 6+  OpAddToStore -> 7+  OpBuildPaths -> 9+  OpEnsurePath -> 10+  OpAddTempRoot -> 11+  OpAddIndirectRoot -> 12+  OpFindRoots -> 14+  OpSetOptions -> 19+  OpCollectGarbage -> 20+  OpQueryAllValidPaths -> 23+  OpQueryPathInfo -> 26+  OpQueryValidPaths -> 31+  OpQuerySubstitutablePaths -> 32+  OpQueryValidDerivers -> 33+  OpOptimiseStore -> 34+  OpVerifyStore -> 35+  OpAddSignatures -> 37+  OpNarFromPath -> 38+  OpAddToStoreNar -> 39+  OpQueryMissing -> 40+  OpQueryDerivationOutputMap -> 41+  OpAddMultipleToStore -> 44+  OpBuildPathsWithResults -> 46++-- | The operations served, by code.+opsByCode :: Map Word32 Op+opsByCode = Map.fromList [(opCode op, op) | op <- [minBound .. maxBound]]++-- | The version an upload's path info is read and written at, whatever+-- version was agreed: the one that carries it whole.+uploadInfoVersion :: Version+uploadInfoVersion = Version (VersionNumber 1 16) Set.empty++-- | The info an upload sends for a path, which upstream reads as the+-- version that carries it whole sends it, whatever version was agreed.+getUploadPathInfo :: StoreDir -> Decoder ValidPathInfo+getUploadPathInfo storeDir = getValidPathInfo storeDir uploadInfoVersion++-- | Write the info an upload sends for a path.+putUploadPathInfo :: StoreDir -> ValidPathInfo -> Builder+putUploadPathInfo storeDir = putValidPathInfo storeDir uploadInfoVersion++-- | A query's substitute flag is sent from this version.+substituteFlagSince :: VersionNumber+substituteFlagSince = VersionNumber 1 27++-- | AddToStore sends a method and a framed dump from this version, and an+-- unframed NAR before it.+framedAddToStoreSince :: VersionNumber+framedAddToStoreSince = VersionNumber 1 25++-- | AddToStoreNar sends its NAR framed from this version, and before it+-- either unframed or on the daemon's request.+framedAddToStoreNarSince :: VersionNumber+framedAddToStoreNarSince = VersionNumber 1 23++-- | The versions from which upstream's client asks a daemon what+-- realising some paths would take (QueryMissing), a derivation's outputs+-- and their paths (QueryDerivationOutputMap), and each path's build+-- result (BuildPathsWithResults).  Below each, it works the answer out+-- from other operations itself.+queryMissingSince, outputMapSince, buildResultsSince :: VersionNumber+queryMissingSince = VersionNumber 1 19+outputMapSince = VersionNumber 1 22+buildResultsSince = VersionNumber 1 34++-- | Upstream's refusal of a form older than this daemon reads, in which+-- an upload is not framed.+unframedRefusal :: Text -> VersionNumber -> Text+unframedRefusal name gate = name <> " before protocol 1." <> T.pack (show (vnMinor gate)) <> " is not supported by this daemon"++-- | The request an operation code names, read as upstream's daemon reads+-- it before the operation's work begins, or 'Nothing' for a code this+-- daemon does not serve.  A form older than this daemon reads, in which+-- an upload is not framed, is refused as the request begins.+getRequest :: StoreDir -> Version -> Word32 -> Maybe (Decoder Request)+getRequest storeDir version code = requestFor <$> Map.lookup code opsByCode+  where+    path = getStorePath storeDir+    paths = getStorePathSet storeDir+    derivedPaths = getList (getDerivedPath storeDir version)+    since gate = versionNumber version >= gate+    requestFor = \case+      OpSetOptions -> SetOptions <$> getClientSettings+      OpIsValidPath -> IsValidPath <$> path+      OpQueryValidPaths ->+        QueryValidPaths <$> paths <*> (if since substituteFlagSince then substituteFrom <$> intFlag else pure NoSubstitute)+      OpQuerySubstitutablePaths -> QuerySubstitutablePaths <$> paths+      OpQueryReferrers -> QueryReferrers <$> path+      OpQueryValidDerivers -> QueryValidDerivers <$> path+      OpQueryDerivationOutputMap -> QueryDerivationOutputMap <$> path+      OpQueryAllValidPaths -> pure QueryAllValidPaths+      OpQueryPathInfo -> QueryPathInfo <$> path+      OpQueryMissing -> QueryMissing <$> derivedPaths+      OpAddToStore+        | since framedAddToStoreSince ->+            fmap AddToStore $+              AddToStoreRequest <$> getBytes <*> getBytes <*> paths <*> (repairFrom <$> getBool)+        | otherwise -> unframedForm "AddToStore" framedAddToStoreSince+      OpAddToStoreNar+        | since framedAddToStoreNarSince ->+            AddToStoreNar <$> getUploadPathInfo storeDir <*> (repairFrom <$> getBool) <*> (checkSigsFrom <$> getBool)+        | otherwise -> unframedForm "AddToStoreNar" framedAddToStoreNarSince+      OpAddMultipleToStore -> AddMultipleToStore . repairFrom <$> getBool <*> (checkSigsFrom <$> getBool)+      OpBuildPaths -> BuildPaths <$> derivedPaths <*> getBuildMode+      OpBuildPathsWithResults -> BuildPathsWithResults <$> derivedPaths <*> getBuildMode+      OpEnsurePath -> EnsurePath <$> path+      OpAddTempRoot -> AddTempRoot <$> path+      OpAddIndirectRoot -> getBytes >>= either malformed (pure . AddIndirectRoot) . absoluteLink+      OpFindRoots -> pure FindRoots+      OpCollectGarbage -> getCollectGarbage storeDir version+      OpOptimiseStore -> pure OptimiseStore+      OpVerifyStore -> VerifyStore . checkContentsFrom <$> getBool <*> (repairFrom <$> getBool)+      OpAddSignatures -> AddSignatures <$> path <*> getSignatureSet+      OpNarFromPath -> NarFromPath <$> path+    unframedForm name gate = malformed (unframedRefusal name gate)++-- | The operation a request is.+requestOp :: Request -> Op+requestOp = \case+  SetOptions _ -> OpSetOptions+  IsValidPath _ -> OpIsValidPath+  QueryValidPaths _ _ -> OpQueryValidPaths+  QuerySubstitutablePaths _ -> OpQuerySubstitutablePaths+  QueryReferrers _ -> OpQueryReferrers+  QueryValidDerivers _ -> OpQueryValidDerivers+  QueryDerivationOutputMap _ -> OpQueryDerivationOutputMap+  QueryAllValidPaths -> OpQueryAllValidPaths+  QueryPathInfo _ -> OpQueryPathInfo+  QueryMissing _ -> OpQueryMissing+  AddToStore _ -> OpAddToStore+  AddToStoreNar {} -> OpAddToStoreNar+  AddMultipleToStore _ _ -> OpAddMultipleToStore+  BuildPaths _ _ -> OpBuildPaths+  BuildPathsWithResults _ _ -> OpBuildPathsWithResults+  EnsurePath _ -> OpEnsurePath+  AddTempRoot _ -> OpAddTempRoot+  AddIndirectRoot _ -> OpAddIndirectRoot+  FindRoots -> OpFindRoots+  CollectGarbage _ _ -> OpCollectGarbage+  OptimiseStore -> OpOptimiseStore+  VerifyStore _ _ -> OpVerifyStore+  AddSignatures _ _ -> OpAddSignatures+  NarFromPath _ -> OpNarFromPath++-- | A request as upstream's client writes it: its operation's code, then+-- what 'getRequest' reads before the operation's work begins.  A version+-- that cannot carry the request is refused in upstream's words: an+-- upload whose form is older than a framed one, a derived path the+-- version cannot spell, and, without+-- 'featureDeleteDeadSpecificReferrers', a collection of some paths that+-- deletes other than those, or their referrers.  Below 1.27 a query's+-- substitute flag is not sent, as upstream's client does not send it.+putRequest :: StoreDir -> Version -> Request -> Either Text Builder+putRequest storeDir version request = (putNum (opCode (requestOp request)) <>) <$> body+  where+    since gate = versionNumber version >= gate+    path = putStorePath storeDir+    paths = putStorePathSet storeDir+    derivedPaths targets = (\spelled -> putNum (length targets) <> mconcat spelled) <$> traverse (putDerivedPath storeDir version) targets+    body = case request of+      SetOptions settings -> Right (putClientSettings settings)+      IsValidPath p -> Right (path p)+      QueryValidPaths ps substitute ->+        Right (paths ps <> (if since substituteFlagSince then putBool (substitute == Substitute) else mempty))+      QuerySubstitutablePaths ps -> Right (paths ps)+      QueryReferrers p -> Right (path p)+      QueryValidDerivers p -> Right (path p)+      QueryDerivationOutputMap p -> Right (path p)+      QueryAllValidPaths -> Right mempty+      QueryPathInfo p -> Right (path p)+      QueryMissing targets -> derivedPaths targets+      AddToStore upload+        | since framedAddToStoreSince ->+            Right (putBytes (atsName upload) <> putBytes (atsMethod upload) <> paths (atsReferences upload) <> putBool (atsRepair upload == Repair))+        | otherwise -> Left (unframedRefusal "AddToStore" framedAddToStoreSince)+      AddToStoreNar info repair checkSigs+        | since framedAddToStoreNarSince ->+            Right (putUploadPathInfo storeDir info <> putBool (repair == Repair) <> putBool (checkSigs == NoCheckSigs))+        | otherwise -> Left (unframedRefusal "AddToStoreNar" framedAddToStoreNarSince)+      AddMultipleToStore repair checkSigs -> Right (putBool (repair == Repair) <> putBool (checkSigs == NoCheckSigs))+      BuildPaths targets mode -> (<> putBuildMode mode) <$> derivedPaths targets+      BuildPathsWithResults targets mode -> (<> putBuildMode mode) <$> derivedPaths targets+      EnsurePath p -> Right (path p)+      AddTempRoot p -> Right (path p)+      AddIndirectRoot link -> Right (putBytes link)+      FindRoots -> Right mempty+      CollectGarbage (GCRequest action considered maxFreed) liveness ->+        (\pathsSent -> putGCAction action <> pathsSent <> putBool (liveness == IgnoreLiveness) <> putNum maxFreed <> obsoleteFields)+          <$> collectedPaths action considered+      OptimiseStore -> Right mempty+      VerifyStore contents repair -> Right (putBool (contents == CheckContents) <> putBool (repair == Repair))+      AddSignatures p sigs -> Right (path p <> putSignatureSet sigs)+      NarFromPath p -> Right (path p)+    obsoleteFields = mconcat (replicate obsoleteCollectionFields (putNum obsoleteWord))+    collectedPaths action considered+      | Set.member featureDeleteDeadSpecificReferrers (versionFeatures version) = Right (putGCPaths storeDir considered)+      | otherwise = case considered of+          WholeStore -> Right (paths Set.empty)+          SpecificPaths specific referrers+            | action /= DeleteSpecific -> Left "Your daemon version is too old to support garbage collecting a specific set of paths"+            | referrers -> Left "Your daemon version is too old to support deleting referrers."+            | otherwise -> Right (paths specific)++-- | The value upstream's client sends in each obsolete field.+obsoleteWord :: Word64+obsoleteWord = 0++-- | A flag upstream reads as an @unsigned int@ and takes as set when it is+-- not 0.+intFlag :: Decoder Bool+intFlag = (/= 0) <$> getWord32++substituteFrom :: Bool -> Substitute+substituteFrom set = if set then Substitute else NoSubstitute++repairFrom :: Bool -> Repair+repairFrom set = if set then Repair else NoRepair++-- | A client's flag that the signatures need not be checked.+checkSigsFrom :: Bool -> CheckSigs+checkSigsFrom dontCheck = if dontCheck then NoCheckSigs else CheckSigs++checkContentsFrom :: Bool -> CheckContents+checkContentsFrom set = if set then CheckContents else SkipContents++-- | A collection's request.  Without 'featureDeleteDeadSpecificReferrers'+-- its paths are a bare set: none means the whole store, unless the action+-- is to delete the paths given, and a collection of the dead limited to+-- some paths is refused once everything is read.  The three numbers after+-- the limit are obsolete.+getCollectGarbage :: StoreDir -> Version -> Decoder Request+getCollectGarbage storeDir version = do+  action <- getGCAction+  considered <-+    if withFeature+      then getGCPaths storeDir+      else bareSet action <$> getStorePathSet storeDir+  liveness <- (\ignore -> if ignore then IgnoreLiveness else KeepLiveness) <$> getBool+  maxFreed <- getWord64+  replicateM_ obsoleteCollectionFields getWord32+  when (action == DeleteDead && specific considered && not withFeature) $+    malformed "Garbage collecting specific paths requested but it is not supported by the negotiated protocol"+  pure (CollectGarbage (GCRequest action considered maxFreed) liveness)+  where+    withFeature = Set.member featureDeleteDeadSpecificReferrers (versionFeatures version)+    bareSet action given+      | action /= DeleteSpecific && Set.null given = WholeStore+      | otherwise = SpecificPaths given False+    specific = \case+      SpecificPaths _ _ -> True+      WholeStore -> False++-- | How many obsolete numbers follow a collection's limit.+obsoleteCollectionFields :: Int+obsoleteCollectionFields = 3++-- | A link's path made absolute and collapsed lexically, no link followed,+-- or the reason the daemon refuses it.  The refusal fails the request's+-- decoding, so it ends the connection before any work begins, as an+-- argument the daemon cannot read does.+--+-- On POSIX the link is made as upstream's daemon makes it, in the+-- directory its workers run in, @/@: a relative path is taken from @/@.+-- No link is refused.+--+-- On Windows the link is made as a client makes its out-link: read as+-- UTF-8, then collapsed over the host's own separators and roots, @.@+-- dropped and @..@ taking off what precedes it, a drive or a share staying+-- as it is.  A link that is not absolute (without a drive and a+-- separator, or a share; a drive alone as in @C:foo@; or rooted without a+-- drive) is refused: upstream builds no daemon for Windows, so no+-- behaviour is there to match, and the directory a link is relative to+-- would be a guess, since a client's directory is not the daemon's.+absoluteLink :: ByteString -> Either Text ByteString+#if defined(mingw32_HOST_OS)+-- An absolute path takes no base, so 'absolutePath' is given none.+absoluteLink link = case hostPathFromBytes link of+  Just path+    | OP.isAbsolute path,+      Just spelled <- hostPathBytes (absolutePath mempty path) ->+        Right spelled+  _ -> Left ("the link '" <> TE.decodeUtf8Lenient link <> "' is not an absolute Windows path: it needs a drive and a backslash, as in C:\\result, or a UNC share")+#else+absoluteLink link = Right (BS.cons slash (BS.intercalate (BS.singleton slash) (reverse (foldl' step [] (BS.split slash link)))))+  where+    slash = 0x2f+    step kept component+      | BS.null component || component == "." = kept+      | component == ".." = drop 1 kept+      | otherwise = component : kept+#endif++-- ---------------------------------------------------------------------------+-- Trust+-- ---------------------------------------------------------------------------++-- | What becomes of a request.+data Authorization+  = -- | The request, as the daemon performs it for this client.+    Permitted !Request+  | -- | Refused before the request's work begins, which ends the+    -- connection.+    RefusedBeforeWork !Text+  | -- | Refused once its work has begun: the client is told, and the+    -- connection goes on.+    RefusedInWork !Text+  deriving (Eq, Show)++-- | Upstream's rules for what a client may ask.  A client the daemon+-- does not trust may not repair (an import's or a build's repair is not+-- atomic), its imports are always held to the signatures the store+-- trusts and are never ultimate, and the roots it is shown are censored+-- ('rootCensoring').  No client may have a collection ignore liveness.+-- A refusal before work and one in work differ only in that the second+-- leaves the connection open, which is where upstream checks each.+authorize :: Trust -> Request -> Authorization+authorize trust request = case request of+  AddToStore upload+    | untrusted && atsRepair upload == Repair -> RefusedBeforeWork repairPathsRefusal+  AddToStoreNar (ValidPathInfo path info) repair _+    | untrusted && repair == Repair -> RefusedBeforeWork repairStorePathsRefusal+    | untrusted -> Permitted (AddToStoreNar (ValidPathInfo path info {upiUltimate = False}) repair CheckSigs)+  AddMultipleToStore repair _+    | untrusted && repair == Repair -> RefusedBeforeWork repairStorePathsRefusal+    | untrusted -> Permitted (AddMultipleToStore repair CheckSigs)+  BuildPaths _ BuildRepair+    | untrusted -> RefusedBeforeWork repairBuildRefusal+  BuildPathsWithResults _ BuildRepair+    | untrusted -> RefusedBeforeWork repairBuildRefusal+  VerifyStore _ Repair+    | untrusted -> RefusedInWork repairPathsRefusal+  CollectGarbage _ IgnoreLiveness -> RefusedInWork "you are not allowed to ignore liveness"+  _ -> Permitted request+  where+    untrusted = trust == NotTrusted++-- | Upstream's refusals of a repair to a client it does not trust, each+-- worded as the operations that raise it word it.+repairPathsRefusal, repairStorePathsRefusal, repairBuildRefusal :: Text+repairPathsRefusal = "you are not privileged to repair paths"+repairStorePathsRefusal = "you are not privileged to repair store paths"+repairBuildRefusal = "repairing is not allowed because you are not in 'trusted-users'"++-- | Whether a client is shown what holds each root.+rootCensoring :: Trust -> RootCensoring+rootCensoring = \case+  Trusted -> ShowRoots+  NotTrusted -> CensorRoots++-- ---------------------------------------------------------------------------+-- Client settings+-- ---------------------------------------------------------------------------++-- | The settings a client sends, as upstream's daemon reads them.+data ClientSettings = ClientSettings+  { csKeepFailed :: !Bool,+    csKeepGoing :: !Bool,+    csTryFallback :: !Bool,+    -- | How much the client is told, at most upstream's loudest level, 7:+    -- a louder one is taken as that.+    csVerbosity :: !Verbosity,+    csMaxBuildJobs :: !Word32,+    csMaxSilentTime :: !Word32,+    csVerboseBuild :: !Bool,+    -- | The cores a builder may use, 'unsetCores' for the machine's own+    -- default.+    csBuildCores :: !Word32,+    csUseSubstitutes :: !Bool,+    -- | Other settings by name, the first a name is sent with winning, as+    -- upstream keeps them.+    csOverrides :: !(Map ByteString ByteString)+  }+  deriving (Eq, Show)++-- | The cores setting where nothing sets it: upstream's @cores@ defaults to+-- 0, which its builder reads as the default count of the machine it runs+-- on.+unsetCores :: Word32+unsetCores = 0++-- | Upstream's loudest verbosity (@lvlVomit@).+loudestVerbosity :: Word32+loudestVerbosity = 7++-- | A client's settings, as upstream's daemon reads them: three flags,+-- its verbosity, its build limits, an obsolete build-hook flag, its+-- build-log verbosity (verbose when it is the error level), two obsolete+-- logging numbers, its cores and substitution flag, and the other+-- settings as name and value pairs.  Each number is an @unsigned int@.+getClientSettings :: Decoder ClientSettings+getClientSettings = do+  keepFailed <- intFlag+  keepGoing <- intFlag+  tryFallback <- intFlag+  verbosity <- Verbosity . min loudestVerbosity <$> getWord32+  maxBuildJobs <- getWord32+  maxSilentTime <- getWord32+  _useBuildHook <- getWord32+  verboseBuild <- (== errorVerbosity) . Verbosity <$> getWord32+  _logType <- getWord32+  _printBuildTrace <- getWord32+  buildCores <- getWord32+  useSubstitutes <- intFlag+  count <- getWord32+  overrides <- replicateM (fromIntegral count) ((,) <$> getBytes <*> getBytes)+  pure+    ClientSettings+      { csKeepFailed = keepFailed,+        csKeepGoing = keepGoing,+        csTryFallback = tryFallback,+        csVerbosity = verbosity,+        csMaxBuildJobs = maxBuildJobs,+        csMaxSilentTime = maxSilentTime,+        csVerboseBuild = verboseBuild,+        csBuildCores = buildCores,+        csUseSubstitutes = useSubstitutes,+        csOverrides = Map.fromListWith (\_later earlier -> earlier) overrides+      }++-- | Write a client's settings as upstream's client writes them: the+-- obsolete build-hook flag set, the build log's verbosity the error+-- level for a verbose build and the loudest otherwise, and the obsolete+-- logging numbers 0, then the other settings in name order.+putClientSettings :: ClientSettings -> Builder+putClientSettings settings =+  putBool (csKeepFailed settings)+    <> putBool (csKeepGoing settings)+    <> putBool (csTryFallback settings)+    <> putNum verbosity+    <> putNum (csMaxBuildJobs settings)+    <> putNum (csMaxSilentTime settings)+    <> putBool obsoleteBuildHook+    <> putNum (if csVerboseBuild settings then errorLevel else loudestVerbosity)+    <> putNum obsoleteWord+    <> putNum obsoleteWord+    <> putNum (csBuildCores settings)+    <> putBool (csUseSubstitutes settings)+    <> putNum (Map.size (csOverrides settings))+    <> foldMap (\(name, value) -> putBytes name <> putBytes value) (Map.toAscList (csOverrides settings))+  where+    Verbosity verbosity = csVerbosity settings+    Verbosity errorLevel = errorVerbosity++-- | The obsolete build-hook flag, which upstream's client still sends+-- set.+obsoleteBuildHook :: Bool+obsoleteBuildHook = True++-- | What a connection's operations run under: the daemon's own until the+-- client sends settings, and then those its trust lets it change.+data ConnectionSettings = ConnectionSettings+  { -- | How much the client is told.+    connVerbosity :: !Verbosity,+    -- | The daemon's settings, as the client changed them.+    connConfig :: !NixConfig,+    -- | What the client last sent, where it has.+    connClient :: !(Maybe ClientSettings)+  }+  deriving (Eq, Show)++-- | A client's settings applied to its connection, as upstream's daemon+-- applies them, with the warnings it gives on the way, each the message a+-- warning-level line carries.+--+-- The client's verbosity, keep-failed, fallback and cores apply+-- whatever its trust.  The client's cores replace the daemon's own, a 0+-- included: a build reads a 0 as the default count of the machine it+-- runs on, whatever the daemon's own @cores@ says.  Then each other+-- setting, in name order: an obsolete one is ignored, as are experimental features+-- (nova-nix knows none, so a client's list always reads as the daemon's+-- own, and upstream's note that it differs never fires), and @plugin-files@ is+-- ignored with upstream's warning.  A trusted client's setting applies as+-- a @nix.conf@ line would ('applyAssignment'), one nova-nix does not+-- model being ignored as upstream ignores an unknown one; so does an+-- untrusted client's @timeout@, @max-silent-time@, @build-poll-interval@,+-- @connect-timeout@ or empty @builders@.  An untrusted client's+-- substituters keep only those the connection trusts (its+-- @trusted-substituters@ and the substituters it already uses), each+-- other one warned of, and its other settings are refused with upstream's+-- warning.  A value a+-- setting cannot take is warned of as upstream warns of a value it+-- refuses, and the setting keeps its value.+--+-- One divergence: upstream compares substituters as parsed store+-- references, and these are compared by their spelling, a URL that has+-- no slash ending what precedes its query also matching one that has, as+-- upstream's comparison allows.  Two spellings of one reference's+-- parameters in different orders match there and not here.+applyClientSettings :: Trust -> ClientSettings -> ConnectionSettings -> (ConnectionSettings, [ByteString])+applyClientSettings trust client current =+  ( current {connVerbosity = csVerbosity client, connConfig = configured, connClient = Just client},+    reverse warnings+  )+  where+    fixed =+      (connConfig current)+        { ncKeepFailed = csKeepFailed client,+          ncFallback = csTryFallback client,+          ncCores = Just (csBuildCores client)+        }+    (configured, warnings) = foldl' override (fixed, []) (Map.toAscList (csOverrides client))+    override (config, said) (name, value)+      | name `elem` ignoredSettings = (config, said)+      | name == pluginFilesSetting = (config, warningLine pluginFilesWarning : said)+      | trust == Trusted || name `elem` unrestrictedSettings || (name == buildersSetting && BS.null value) =+          either (\refusal -> (config, usageWarning refusal : said)) (,said) (applyAssignment config (ConfigAssignment name value))+      | name `elem` substituterSettings =+          let (kept, refused) = trustedOnly (ncTrustedSubstituters config ++ ncSubstituters config) value+           in (config {ncSubstituters = kept}, reverse (map (warningLine . untrustedSubstituterWarning) refused) ++ said)+      | otherwise = (config, warningLine (restrictedWarning name) : said)++-- | Settings upstream's daemon ignores from a client: an obsolete one,+-- and the experimental features.+ignoredSettings :: [ByteString]+ignoredSettings = ["ssh-auth-sock", "experimental-features"]++-- | The setting a client may not set, with a warning of its own.+pluginFilesSetting :: ByteString+pluginFilesSetting = "plugin-files"++-- | The settings an untrusted client may set (each upstream setting's own+-- name, not an alias).+unrestrictedSettings :: [ByteString]+unrestrictedSettings = ["timeout", "max-silent-time", "build-poll-interval", "connect-timeout"]++-- | The setting an untrusted client may set only to nothing.+buildersSetting :: ByteString+buildersSetting = "builders"++-- | The names of the substituters setting.+substituterSettings :: [ByteString]+substituterSettings = ["substituters", "binary-caches"]++-- | The substituters a list names that are trusted, as the trusted+-- spelling, and the ones that are not, as sent.+trustedOnly :: [Text] -> ByteString -> ([Text], [ByteString])+trustedOnly trusted value = (mapMaybe snd matched, [token | (token, Nothing) <- matched])+  where+    known = Map.fromList [(TE.encodeUtf8 name, name) | name <- trusted]+    matched = [(token, trustedSpelling token) | token <- BS8.splitWith (`BS8.elem` " \t\n\r") value, not (BS.null token)]+    trustedSpelling token = case Map.lookup token known of+      Just name -> Just name+      Nothing+        | "://" `BS.isInfixOf` token,+          (base, query) <- BS8.break (== '?') token,+          not ("/" `BS.isSuffixOf` base) ->+            Map.lookup (base <> "/" <> query) known+        | otherwise -> Nothing++-- | A warning as upstream logs one it raises itself: its prefix, the+-- message, and the line feed every logged line ends with.+warningLine :: ByteString -> ByteString+warningLine message = warningPrefix <> message <> "\n"++-- | A refused value as upstream shows the error that refuses it, at the+-- warning level: its prefix, then the message with each line after the+-- first indented to the prefix's width and each line's trailing space+-- dropped.+usageWarning :: Text -> ByteString+usageWarning refusal = BS.intercalate "\n" (zipWith indented (warningPrefix : repeat indent) (BS8.lines (chomp (TE.encodeUtf8 refusal))))+  where+    indent = BS8.replicate (BS.length warningPrefix) ' '+    indented prefix line = chomp (prefix <> line)++-- | Bytes without their trailing whitespace, as upstream trims a line.+chomp :: ByteString -> ByteString+chomp = BS8.dropWhileEnd (`BS8.elem` " \n\r\t")++warningPrefix :: ByteString+warningPrefix = "warning: "++pluginFilesWarning :: ByteString+pluginFilesWarning =+  "Ignoring the client-specified plugin-files.\nThe client specifying plugins to the daemon never made sense, and was removed in Nix >=2.14."++untrustedSubstituterWarning :: ByteString -> ByteString+untrustedSubstituterWarning substituter =+  "ignoring untrusted substituter '"+    <> substituter+    <> "', you are not a trusted user.\nRun `man nix.conf` for more information on the `substituters` configuration option."++restrictedWarning :: ByteString -> ByteString+restrictedWarning name =+  "ignoring the client-specified setting '" <> name <> "', because it is a restricted setting and you are not a trusted user"++-- ---------------------------------------------------------------------------+-- The store+-- ---------------------------------------------------------------------------++-- | What an operation reports while it works, which the daemon forwards+-- to the client as upstream's daemon forwards its logger's calls.+data LogEvent+  = -- | A message at a level, without its line feed.  The client is sent+    -- it if its verbosity reaches that level.+    LogLine !Verbosity !ByteString+  | -- | An activity started.+    ActivityStarted !Activity+  | -- | An activity stopped.+    ActivityStopped !ActivityId+  | -- | An activity reported a result of a type, with fields: a build's+    -- log line, for one, is a result of its build's activity.+    ActivityResult !ActivityId !ResultType ![Field]+  deriving (Eq, Show)++-- | The verbosity upstream gives a message of a level.+logVerbosity :: Level -> Verbosity+logVerbosity = \case+  LevelError -> errorVerbosity+  LevelWarn -> Verbosity 1+  LevelInfo -> Verbosity 3++-- | The activity upstream's daemon sends its client for one of the+-- store's, by its number: a build or a check as upstream's derivation+-- goal starts one, at the info level, naming the derivation, no machine+-- and round 1 of 1, and a substitution as its substitution goal starts+-- one, at the error level with no text, naming the path and the cache.+storeActivity :: StoreDir -> ActivityId -> ActivityStart -> Activity+storeActivity storeDir number = \case+  Building drv -> derivationActivity buildingVerb drv+  Checking drv -> derivationActivity checkingVerb drv+  Substituting path cache -> Activity number errorVerbosity actSubstitute BS.empty [FieldString (spelled path), FieldString (TE.encodeUtf8 cache)] noParent+  where+    spelled = TE.encodeUtf8 . storePathToText storeDir+    derivationActivity verb drv =+      Activity number (logVerbosity LevelInfo) actBuild (verb <> spelled drv <> "'") [FieldString (spelled drv), FieldString BS.empty, FieldInt 1, FieldInt 1] noParent+    noParent = ActivityId 0++-- | What a build's text says before the derivation it names, and what a+-- check's does.+buildingVerb, checkingVerb :: ByteString+buildingVerb = "building '"+checkingVerb = "checking outputs of '"++-- | The store's activity an activity a daemon started is, if it is one:+-- what 'storeActivity' makes, and what upstream's daemon sends of the same+-- work.  A build is an activity of the build type whose first field names+-- the derivation, a check when its text says it checks outputs and a build+-- otherwise, so a build on a machine, which says where in its text and+-- fields, and a repair, whose text says it repairs, read as builds.  A+-- substitution is an activity of the substitution type whose first two+-- fields name the path and the cache, the cache read as UTF-8.  Any other+-- activity, and one whose fields do not read so, is none.+activityStart :: StoreDir -> Activity -> Maybe ActivityStart+activityStart storeDir activity = case actFields activity of+  FieldString named : rest+    | actType activity == actBuild -> derivationStart <$> path named+    | actType activity == actSubstitute,+      FieldString cache : _ <- rest ->+        Substituting <$> path named <*> either (const Nothing) Just (TE.decodeUtf8' cache)+  _ -> Nothing+  where+    path = either (const Nothing) (parseStorePath storeDir) . TE.decodeUtf8'+    derivationStart+      | checkingVerb `BS.isPrefixOf` actText activity = Checking+      | otherwise = Building++-- | What the store is given for an operation's work: where it reports,+-- and the connection's settings.  The report is the operation's for as+-- long as the call runs.+data Work m = Work+  { workReport :: !(LogEvent -> m ()),+    workSettings :: !ConnectionSettings+  }++-- | The store taking in the bytes of an upload as the daemon receives+-- them.  It may stop before they end, having what it needs or having+-- failed; the daemon then reads past the rest itself.+data Intake m a+  = -- | It takes the next bytes, hears that they have ended, or hears+    -- that the upload broke off before its end could be read, the+    -- operation failing with the reason the daemon has, so it releases+    -- what it holds for the upload.+    Taking !(ByteString -> m (Intake m a)) !(m (Either DaemonError a)) !(m ())+  | -- | It needs nothing more.+    Taken !(Either DaemonError a)++-- | A dump to make a content-addressed path from: the name, the method+-- and the algorithm it is hashed with, the paths it refers to, and+-- whether a valid path's contents are replaced.  A flat dump is a file's+-- contents and a recursive one a NAR.+data DumpUpload = DumpUpload+  { duName :: !ByteString,+    duMethod :: !ContentAddressMethod,+    duAlgo :: !Text,+    duReferences :: !(Set StorePath),+    duRepair :: !Repair+  }+  deriving (Eq, Show)++-- | The store a daemon serves, as one connection sees it: each of+-- upstream's store calls an operation makes, given the operation's+-- t'Work', in the protocol's own terms.  An expected failure is a+-- t'DaemonError', which the client is sent as upstream's daemon sends+-- the error its store throws.  A connection's temporary roots are the+-- ones its record adds, so each connection is given a record of its own.+data DaemonStore m = DaemonStore+  { dsIsValidPath :: !(Work m -> StorePath -> m (Either DaemonError Bool)),+    -- | The valid paths among those given, having first substituted them+    -- where asked to.+    dsQueryValidPaths :: !(Work m -> Substitute -> Set StorePath -> m (Either DaemonError (Set StorePath))),+    dsQuerySubstitutablePaths :: !(Work m -> Set StorePath -> m (Either DaemonError (Set StorePath))),+    dsQueryReferrers :: !(Work m -> StorePath -> m (Either DaemonError (Set StorePath))),+    dsQueryValidDerivers :: !(Work m -> StorePath -> m (Either DaemonError (Set StorePath))),+    -- | Each output of the derivation, and its path where it is known.+    dsQueryDerivationOutputMap :: !(Work m -> StorePath -> m (Either DaemonError (Map OutputName (Maybe StorePath)))),+    dsQueryAllValidPaths :: !(Work m -> m (Either DaemonError (Set StorePath))),+    -- | A valid path's info, or 'Nothing' for a path that is not valid.+    dsQueryPathInfo :: !(Work m -> StorePath -> m (Either DaemonError (Maybe UnkeyedValidPathInfo))),+    dsQueryMissing :: !(Work m -> [DerivedPath] -> m (Either DaemonError Missing)),+    -- | Make a path from a dump, and give its info.+    dsAddToStore :: !(Work m -> DumpUpload -> m (Intake m ValidPathInfo)),+    -- | Import a path from its NAR.+    dsAddToStoreNar :: !(Work m -> ValidPathInfo -> Repair -> CheckSigs -> m (Intake m ())),+    dsBuildPaths :: !(Work m -> [DerivedPath] -> BuildMode -> m (Either DaemonError ())),+    -- | Each path's result, keyed by the path as it was asked for.+    dsBuildPathsWithResults :: !(Work m -> [DerivedPath] -> BuildMode -> m (Either DaemonError [KeyedBuildResult])),+    dsEnsurePath :: !(Work m -> StorePath -> m (Either DaemonError ())),+    dsAddTempRoot :: !(Work m -> StorePath -> m (Either DaemonError ())),+    -- | Record a link, as the bytes of its absolute path, as a root.+    dsAddIndirectRoot :: !(Work m -> ByteString -> m (Either DaemonError ())),+    -- | Each rooted path and what holds it.+    dsFindRoots :: !(Work m -> RootCensoring -> m (Either DaemonError (Map StorePath (Set ByteString)))),+    dsCollectGarbage :: !(Work m -> GCRequest -> m (Either DaemonError GCResult)),+    dsOptimiseStore :: !(Work m -> m (Either DaemonError ())),+    -- | Whether the check found errors.+    dsVerifyStore :: !(Work m -> CheckContents -> Repair -> m (Either DaemonError Bool)),+    dsAddSignatures :: !(Work m -> StorePath -> Set Signature -> m (Either DaemonError ())),+    -- | Write a path's NAR, a chunk at a time, to what is given.  It runs+    -- after the operation's work is reported done, where upstream's+    -- daemon writes the NAR, so it has nothing to report through.+    dsNarFromPath :: !(StorePath -> (ByteString -> m ()) -> m (Either DaemonError ()))+  }++-- | An error with upstream's defaults for one its daemon raises itself:+-- the error level, no traces, and exit status 1.+daemonError :: Text -> DaemonError+daemonError message = DaemonError errorVerbosity (TE.encodeUtf8 message) [] defaultExitStatus++-- ---------------------------------------------------------------------------+-- Archives in uploads+-- ---------------------------------------------------------------------------++-- | Where an archive ends in the bytes of an upload, told a chunk at a+-- time from the archive's first byte.  The daemon gives the store an+-- archive's bytes up to its end and reads what follows itself, so the+-- store's reader sees exactly one archive.+data NarBoundary+  = -- | The archive goes on past what has been fed: every byte so far is+    -- its, and the next chunk is fed here.+    BoundaryAhead !(ByteString -> NarBoundary)+  | -- | The archive ended, followed by these bytes of the last chunk fed.+    BoundaryReached !ByteString++-- | An archive's end as the size its path's info declares: the boundary+-- an upload's NAR has here.  Upstream instead parses the NAR to its root+-- node's close, and then skips to the declared size where its store read+-- less, which words its refusal of a declared size that does not match+-- the archive differently; a store that holds the archive to its info's+-- size and hash accepts the same uploads either way.+narSizeBoundary :: Word64 -> NarBoundary+narSizeBoundary remaining+  | remaining == 0 = BoundaryReached BS.empty+  | otherwise = BoundaryAhead $ \chunk ->+      let size = fromIntegral (BS.length chunk)+       in if size <= remaining+            then narSizeBoundary (remaining - size)+            else BoundaryReached (BS.drop (fromIntegral remaining) chunk)
+ src/Nix/Daemon/Pipe.hs view
@@ -0,0 +1,695 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | The daemon's named pipe on Windows, and the accounts its clients are+-- named by.  Windows has no Unix socket that names its peer, so the daemon+-- listens on a named pipe, @\\\\.\\pipe\\nova-nix-daemon@ unless it is told+-- another, and names each client by the token it connected with.  Built+-- on Windows alone, through @cbits\/nn_winfs.c@.+--+-- == The pipe+--+-- The pipe's first instance is created with+-- @FILE_FLAG_FIRST_PIPE_INSTANCE@, so a daemon refuses to start where any+-- process already has the pipe, rather than adding instances to a pipe+-- another account made and controls.  Every instance refuses clients on+-- other machines (@PIPE_REJECT_REMOTE_CLIENTS@) and carries the security+-- descriptor 'pipeSddl' describes: an owner ('processPipeOwner'), and a+-- protected DACL that gives SYSTEM and Administrators full control and+-- Users the right to read and write data and nothing more+-- ('clientPipeAccess'), so while the daemon has the pipe no other user+-- can create an instance of it and take a client in the daemon's place.+-- An elevated daemon, which owns the pipe as Administrators, gives its own+-- account no entry: the processes of that account that are not elevated+-- hold Administrators for deny only and would otherwise create instances+-- and rewrite the DACL.  A daemon that does not hold Administrators owns+-- the pipe as its account and gives that account the access that creating+-- the next instance takes ('daemonPipeAccess'), which leaves out the+-- rights to change the DACL and the owner.  The pipe carries no mandatory+-- label when a process at Medium integrity or above makes it, which+-- Windows reads as Medium, so a Medium client can write it, and a process+-- at Low integrity cannot.+--+-- == Who serves the pipe+--+-- Where no daemon has the pipe, any user can make it, so a client of the+-- pipe checks who did before it sends anything ('connectPipe').  It reads+-- the pipe's owner and integrity label from the handle it opened, with+-- the read access it already holds, which any user may do against a pipe+-- an elevated process or a service made.  The owner of a pipe is chosen by+-- the process that makes it, from the accounts Windows lets that process+-- own objects as, so it names who made the pipe+-- ('Nix.Daemon.Auth.trustsPipeOwner' says which owners a client trusts).+-- The daemon sets it explicitly, to Administrators where its token holds+-- that group enabled and to its own account otherwise, rather than leave+-- it to the default, which a security policy decides.  A process at Low+-- integrity makes a pipe with the Low label, which a client refuses+-- whoever owns it, since the daemon runs at Medium or above.  A client+-- refuses a pipe no trusted account made, as it refuses one it cannot+-- read the owner of.  A nova-nix command that reaches the store through a+-- daemon connects with 'connectPipe'.+--+-- == Who a client is+--+-- The daemon impersonates a client as soon as it connects, before the+-- client has sent anything, and reads its token's user and groups, in one+-- C call, so the thread runs nothing else as the client ('clientAccount').+-- A client the daemon refuses has sent nothing and holds nothing: its+-- instance is closed and its thread ends.  The library's client opens the+-- pipe letting the daemon identify it but not act as it ('connectPipe').+-- A restricted token is not taken as its user's.  Which groups a client+-- belongs to for @build-users-group@ is read from its account+-- ('systemAccounts'), not from the token it presents, which it shapes.+-- Whether the pipe is there is read without connecting to it+-- ('pipePresent').+--+-- == Waiting+--+-- Every handle is opened for overlapped I/O, so a connection can be read+-- and written at once.  Each call that waits, for a client, for bytes or+-- for the pipe to take them, runs on a thread of its own with an event+-- that ends its wait, and the thread that asks waits for it where an+-- exception can interrupt the wait, as stopping a daemon or one of its+-- connections does: a thread blocked in a foreign call could not be.  The+-- interrupt sets the event and waits for the call to give up before it+-- goes on.  The call runs beside the asking thread only under GHC's+-- threaded runtime, which nova-nix is built with.+module Nix.Daemon.Pipe+  ( -- * The pipe's path+    PipePath,+    pipePath,+    pipePathText,+    defaultPipePath,+    pipePresent,++    -- * Who may use the pipe+    PipeOwner (..),+    pipeOwnerOf,+    pipeSddl,+    clientPipeAccess,+    daemonPipeAccess,+    processPipeOwner,++    -- * The daemon's end+    PipeInstance,+    listenPipe,+    nextInstance,+    awaitClient,+    dropClient,+    clientAccount,+    instanceTransport,+    closeInstance,++    -- * A client's end+    PipeConnection,+    connectPipe,+    connectionTransport,+    closeConnection,++    -- * Accounts+    systemAccounts,+  )+where++import Control.Concurrent (forkIO)+import Control.Concurrent.MVar (newEmptyMVar, putMVar, readMVar)+import Control.Exception (SomeException, bracket, finally, mask, onException, throwIO, try, uninterruptibleMask_)+import Control.Monad (unless, void)+import Control.Monad.Except (ExceptT (..), runExceptT, throwError)+import Data.Bits ((.|.))+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Builder as BB+import qualified Data.ByteString.Lazy as BL+import Data.Char (ord)+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Word (Word32)+import Foreign.C.String (CString, CWString, peekCString, peekCWString, peekCWStringLen, withCWString)+import Foreign.C.Types (CInt (..), CULong (..))+import Foreign.Marshal.Alloc (alloca, allocaBytes)+import Foreign.Marshal.Utils (maybePeek)+import Foreign.Ptr (Ptr, castPtr, nullPtr)+import Foreign.Storable (peek)+import Nix.Daemon.Auth (AccountDatabase (..), AccountKind (..), AccountPeer (..), trustsPipeOwner)+import Nix.Daemon.Connection (Transport (..))+import Nix.Store.Access (Sid, administratorsSid, sidFromText, sidText)+import Numeric (showHex)+import System.Win32.Event (setEvent)+import System.Win32.File (closeHandle)+import System.Win32.Types (BOOL, ErrCode, HANDLE, failIfFalse_, failIfNull, failWith, getErrorMessage, localFree, peekTString)++-- ---------------------------------------------------------------------------+-- The pipe's path+-- ---------------------------------------------------------------------------++-- | The path of a named pipe on this machine, @\\\\.\\pipe\\NAME@.+-- 'pipePath' is the one way to make one.+newtype PipePath = PipePath Text+  deriving (Eq, Show)++-- | A pipe's path from its bytes, UTF-8 as nova-nix holds a Windows path,+-- or why they are not one: @\\\\.\\pipe\\@, its @pipe@ in either case,+-- then a name of at least one character, at most 256 UTF-16 units in all,+-- as Windows takes a pipe's name.  The name holds no separator of either+-- kind and is not @.@ or @..@, which Windows would read as steps out of+-- the pipes' namespace.+pipePath :: ByteString -> Either Text PipePath+pipePath bytes = case TE.decodeUtf8' bytes of+  Left _ -> Left notAPipe+  Right path+    | let (prefix, name) = T.splitAt (T.length pipePrefix) path,+      T.toLower prefix == pipePrefix,+      name `notElem` ["", ".", ".."],+      T.all (`notElem` ['\\', '/', '\0']) name,+      utf16Length path <= maxPipePathUnits ->+        Right (PipePath path)+    | otherwise -> Left notAPipe+  where+    notAPipe = "not a named pipe's path, which is \\\\.\\pipe\\ and a name"+    utf16Length = sum . map (\c -> if ord c > 0xFFFF then 2 else 1) . T.unpack++-- | Where a pipe's path starts, as Windows spells the local machine's+-- pipes, in lower case.+pipePrefix :: Text+pipePrefix = "\\\\.\\pipe\\"++-- | The most UTF-16 units Windows takes in a pipe's whole path.+maxPipePathUnits :: Int+maxPipePathUnits = 256++-- | A pipe's path as text.+pipePathText :: PipePath -> Text+pipePathText (PipePath path) = path++-- | The pipe a daemon listens on unless it is told another.+defaultPipePath :: ByteString+defaultPipePath = "\\\\.\\pipe\\nova-nix-daemon"++-- | Whether a pipe exists at the path, as the pipe a daemon listens on+-- does, read from the listing of the machine's pipes: nothing connects to+-- it, so a daemon sees no client and loses no instance, and nothing+-- waits.  A failure to list the pipes throws.+pipePresent :: PipePath -> IO Bool+pipePresent (PipePath path) =+  withCWString (T.unpack path) $ \cPath ->+    withCWString (T.unpack (T.drop (T.length pipePrefix) path)) $ \cName ->+      alloca $ \presentOut -> alloca $ \failedOut -> do+        code <- c_nn_pipe_present cPath cName presentOut failedOut+        unless (code == 0) (throwFailure failedOut "nn_pipe_present" code)+        (/= 0) <$> peek presentOut++-- ---------------------------------------------------------------------------+-- Who may use the pipe+-- ---------------------------------------------------------------------------++-- | Who owns the daemon's pipe, which decides who else the pipe's DACL+-- names.+data PipeOwner+  = -- | Administrators, where the daemon's token holds the group enabled+    -- and with the right to own objects as it, as an elevated+    -- administrator's does.+    OwnedByAdministrators+  | -- | The daemon's own account, where its token does not.+    OwnedByAccount !Sid+  deriving (Eq, Show)++-- | The owner a daemon makes of its pipe, given the SID its token lets it+-- give one: Administrators, or its user.+pipeOwnerOf :: Sid -> PipeOwner+pipeOwnerOf sid+  | sid == administratorsSid = OwnedByAdministrators+  | otherwise = OwnedByAccount sid++-- | The SID of an owner.+ownerSid :: PipeOwner -> Sid+ownerSid = \case+  OwnedByAdministrators -> administratorsSid+  OwnedByAccount account -> account++-- | The security descriptor every instance of the daemon's pipe is+-- created with, given its owner: that owner, and a protected DACL that+-- grants full control to SYSTEM and Administrators and 'clientPipeAccess'+-- to Users, and, where the owner is the daemon's account and not+-- Administrators, 'daemonPipeAccess' to that account.+pipeSddl :: PipeOwner -> Text+pipeSddl owner =+  "O:"+    <> sidText (ownerSid owner)+    <> "D:P(A;;FA;;;SY)(A;;FA;;;BA)"+    <> daemonEntry+    <> "(A;;"+    <> accessMask clientPipeAccess+    <> ";;;BU)"+  where+    daemonEntry = case owner of+      OwnedByAdministrators -> ""+      OwnedByAccount account -> "(A;;" <> accessMask daemonPipeAccess <> ";;;" <> sidText account <> ")"+    accessMask rights = "0x" <> T.pack (showHex rights "")++-- | What the pipe grants Users, and the access the library's client opens+-- it with: @FILE_GENERIC_READ@ and @FILE_WRITE_DATA@.  It leaves out+-- @FILE_CREATE_PIPE_INSTANCE@, the bit @FILE_APPEND_DATA@ shares, which+-- would let a user create an instance of the pipe; @GENERIC_WRITE@ asks+-- for it, so a client asking for that is refused.  @FILE_GENERIC_READ@+-- includes @READ_CONTROL@, the right a client reads the pipe's owner and+-- label with.+clientPipeAccess :: Word32+clientPipeAccess = fileGenericRead .|. fileWriteData++-- | What the pipe grants the daemon's own account, where it owns the pipe+-- as that account: @FILE_GENERIC_READ@ and @FILE_GENERIC_WRITE@, which+-- creating a further instance asks for (measured: leaving out+-- @FILE_APPEND_DATA@, @FILE_WRITE_EA@ or @FILE_WRITE_ATTRIBUTES@ refuses+-- it).  It has neither @WRITE_DAC@ nor @WRITE_OWNER@ nor @DELETE@.+daemonPipeAccess :: Word32+daemonPipeAccess = fileGenericRead .|. fileGenericWrite++-- | @FILE_GENERIC_READ@, @FILE_GENERIC_WRITE@ and @FILE_WRITE_DATA@+-- (winnt.h).+fileGenericRead, fileGenericWrite, fileWriteData :: Word32+fileGenericRead = 0x120089+fileGenericWrite = 0x120116+fileWriteData = 0x2++-- | The owner the daemon makes of its pipe: Administrators where this+-- process's token holds that group enabled, not for deny only, and with+-- the right to own objects as it, as an elevated administrator's token+-- does, and the token's user otherwise.  Windows lets a process give what+-- it makes no other owner without the restore privilege, so a client that+-- reads the owner ('connectPipe') learns who made the pipe.+processPipeOwner :: IO PipeOwner+processPipeOwner = pipeOwnerOf <$> readSid "nn_token_pipe_owner" (c_nn_token_pipe_owner nullPtr)++-- ---------------------------------------------------------------------------+-- The daemon's end+-- ---------------------------------------------------------------------------++-- | An instance of the daemon's pipe: waiting for a client, or connected+-- to one, with what the next instance is created with.+data PipeInstance = PipeInstance+  { instancePath :: !PipePath,+    instanceSddl :: !Text,+    instanceHandle :: !HANDLE+  }++-- | Which instance of a pipe is being created.+data InstanceOrder+  = -- | The first, which fails where the pipe already exists.+    FirstInstance+  | -- | Another of a pipe this daemon made.+    LaterInstance++-- | Create the pipe at the path, its first instance, owned by+-- 'processPipeOwner' and open to whom 'pipeSddl' says, or say why it+-- cannot be: among the reasons, that a process already has the pipe.+listenPipe :: PipePath -> IO (Either Text PipeInstance)+listenPipe path = do+  owner <- processPipeOwner+  createInstance FirstInstance path (pipeSddl owner)++-- | Another instance of the pipe an instance is of, for the next client,+-- or why it cannot be made.+nextInstance :: PipeInstance -> IO (Either Text PipeInstance)+nextInstance previous = createInstance LaterInstance (instancePath previous) (instanceSddl previous)++-- | Create an instance of a pipe with a security descriptor.+createInstance :: InstanceOrder -> PipePath -> Text -> IO (Either Text PipeInstance)+createInstance order path sddl =+  withCWString (T.unpack (pipePathText path)) $ \cPath ->+    withCWString (T.unpack sddl) $ \cSddl ->+      alloca $ \pipeOut -> alloca $ \failedOut -> do+        code <- c_nn_pipe_create cPath firstFlag cSddl pipeOut failedOut+        case (code, order) of+          (0, _) -> Right . PipeInstance path sddl <$> peek pipeOut+          (_, FirstInstance) | code == errorAccessDenied -> pure (Left "a process already has the pipe open")+          _ -> Left <$> failureMessage failedOut "nn_pipe_create" code+  where+    firstFlag = case order of+      FirstInstance -> 1+      LaterInstance -> 0++-- | Wait for a client to connect to the instance.  A failure throws, as a+-- socket's accept does.+awaitClient :: PipeInstance -> IO ()+awaitClient inst =+  alloca $ \failedOut -> do+    code <- interruptibly (\stop -> c_nn_pipe_accept (instanceHandle inst) stop failedOut)+    unless (code == 0) (throwFailure failedOut "nn_pipe_accept" code)++-- | Disconnect the client of an instance, which then waits for another.+dropClient :: PipeInstance -> IO ()+dropClient inst = failIfFalse_ "DisconnectNamedPipe" (c_DisconnectNamedPipe (instanceHandle inst))++-- | Who the client connected to the instance is, read from its token, or+-- why that cannot be read or is not taken.  The client need not have sent+-- anything.  A restricted token is not taken as its user's: it may hold+-- the user's SID and still be kept from what the user may do.+clientAccount :: PipeInstance -> IO (Either Text AccountPeer)+clientAccount inst =+  alloca $ \processOut -> alloca $ \restrictedOut -> alloca $ \sidsOut -> alloca $ \charsOut -> alloca $ \failedOut -> do+    code <- c_nn_pipe_client (instanceHandle inst) processOut restrictedOut sidsOut charsOut failedOut+    if code /= 0+      then Left . ("cannot read who the client is: " <>) <$> failureMessage failedOut "nn_pipe_client" code+      else do+        process <- peek processOut+        restricted <- peek restrictedOut+        sids <- peek sidsOut+        chars <- peek charsOut+        spelled <- (T.pack <$> peekCWStringLen (sids, fromIntegral chars)) `finally` localFree sids+        pure $+          if restricted /= 0+            then Left "the client's token is restricted, so it is not taken as its user's"+            else maybe (Left ("cannot read who the client is: its token gave " <> T.pack (show spelled))) Right (accountFrom (Just (fromIntegral process)) spelled)++-- | A client's account from the SIDs its token gave, as 'clientAccount'+-- reads them: its user and then the groups it grants by, each ended by a+-- NUL.+accountFrom :: Maybe Word32 -> Text -> Maybe AccountPeer+accountFrom process spelled = case T.splitOn "\0" spelled of+  userText : groupTexts -> do+    user <- sidFromText userText+    -- The last SID's NUL leaves an empty piece at the end.+    groups <- traverse sidFromText (filter (not . T.null) groupTexts)+    Just (AccountPeer process user groups)+  [] -> Nothing++-- | The connection to the client of an instance.+instanceTransport :: PipeInstance -> Transport IO+instanceTransport = handleTransport . instanceHandle++-- | Close an instance, and with it any connection to its client.  What+-- it wrote and the client has not read stays for the client to read.+closeInstance :: PipeInstance -> IO ()+closeInstance = closeHandle . instanceHandle++-- ---------------------------------------------------------------------------+-- A client's end+-- ---------------------------------------------------------------------------++-- | A client's connection to a daemon's pipe.+newtype PipeConnection = PipeConnection HANDLE++-- | Connect to the daemon at a pipe, letting it identify this process's+-- account but not act as it, or say why not: among the reasons, that no+-- process has the pipe, as when no daemon runs, that no trusted account+-- made it ('Nix.Daemon.Auth.trustsPipeOwner'), and that a process below+-- Medium integrity did.  The pipe's owner and integrity are read before+-- anything is sent, and a pipe whose owner is not trusted, or whose owner+-- or integrity cannot be read, is closed unused.  While every instance is+-- busy it waits a bounded while for one.+connectPipe :: PipePath -> IO (Either Text PipeConnection)+connectPipe path =+  withCWString (T.unpack (pipePathText path)) $ \cPath ->+    alloca $ \pipeOut -> alloca $ \failedOut -> do+      code <- c_nn_pipe_open cPath (fromIntegral clientPipeAccess) pipeOut failedOut+      if code == 0+        then peek pipeOut >>= \handle -> vetServer path handle `onException` closeHandle handle+        else Left <$> failureMessage failedOut "nn_pipe_open" code++-- | Keep an opened pipe as the connection if a trusted account owns it+-- and it is at least Medium integrity, and close it, saying why, if not.+vetServer :: PipePath -> HANDLE -> IO (Either Text PipeConnection)+vetServer path handle = do+  client <- processAccount+  verdict <- runExceptT $ do+    owner <- ExceptT (handleOwner handle)+    unless (trustsPipeOwner client owner) (throwError ("it belongs to " <> sidText owner <> ", not to you, SYSTEM, Administrators or the nova-nix service"))+    level <- ExceptT (handleIntegrity handle)+    unless (level >= mediumIntegrity) (throwError ("it was made by a process below Medium integrity (level 0x" <> T.pack (showHex level "") <> ")"))+  case verdict of+    Right () -> pure (Right (PipeConnection handle))+    Left reason -> Left (notTrusted <> reason) <$ closeHandle handle+  where+    notTrusted = "the pipe '" <> pipePathText path <> "' is not served by a trusted account: "++-- | The mandatory label RID of Medium integrity (winnt.h's+-- @SECURITY_MANDATORY_MEDIUM_RID@): the lowest level a daemon runs at.+mediumIntegrity :: Word32+mediumIntegrity = 0x2000++-- | The account that owns the pipe a handle is open to, or why that is+-- not known.+handleOwner :: HANDLE -> IO (Either Text Sid)+handleOwner handle =+  alloca $ \sidOut -> alloca $ \failedOut -> do+    code <- c_nn_pipe_owner handle sidOut failedOut+    if code /= 0+      then Left . ("its owner cannot be read: " <>) <$> failureMessage failedOut "nn_pipe_owner" code+      else do+        found <- peek sidOut+        if found == nullPtr+          then pure (Left "it has no owner")+          else either (Left . ("its owner is not a SID: " <>)) Right <$> takeSid found++-- | The integrity level of the pipe a handle is open to, its mandatory+-- label's RID, Medium where it has no label, or why that is not known.+handleIntegrity :: HANDLE -> IO (Either Text Word32)+handleIntegrity handle =+  alloca $ \levelOut -> alloca $ \failedOut -> do+    code <- c_nn_pipe_integrity handle levelOut failedOut+    if code /= 0+      then Left . ("its integrity level cannot be read: " <>) <$> failureMessage failedOut "nn_pipe_integrity" code+      else Right . fromIntegral <$> peek levelOut++-- | The connection to the daemon.+connectionTransport :: PipeConnection -> Transport IO+connectionTransport (PipeConnection handle) = handleTransport handle++-- | Close the connection.+closeConnection :: PipeConnection -> IO ()+closeConnection (PipeConnection handle) = closeHandle handle++-- ---------------------------------------------------------------------------+-- Reading and writing+-- ---------------------------------------------------------------------------++-- | How much a read from the pipe asks for.+receiveChunkSize :: Int+receiveChunkSize = 65536++-- | A connection's transport over its end of the pipe.  The other end's+-- close is the end of input, which every read after it gives too; any+-- other failure throws.+handleTransport :: HANDLE -> Transport IO+handleTransport handle =+  Transport+    { transportReceive = receive,+      transportSend = mapM_ (sendChunk handle) . concatMap writable . BL.toChunks . BB.toLazyByteString+    }+  where+    receive =+      allocaBytes receiveChunkSize $ \buffer -> alloca $ \gotOut -> alloca $ \failedOut -> do+        code <- interruptibly (\stop -> c_nn_pipe_read handle buffer (fromIntegral receiveChunkSize) stop gotOut failedOut)+        got <- peek gotOut+        case code of+          0+            -- A write of nothing at the other end arrives as a read of+            -- nothing, which is not the end of input.+            | got == 0 -> receive+            | otherwise -> Just <$> BS.packCStringLen (castPtr buffer, fromIntegral got)+          _+            | code `elem` [errorBrokenPipe, errorPipeNotConnected] -> pure Nothing+            | otherwise -> throwFailure failedOut "nn_pipe_read" code++-- | A chunk in pieces a write can take, a write's size being a DWORD.+writable :: ByteString -> [ByteString]+writable chunk+  | BS.length chunk <= maxWriteBytes = [chunk]+  | otherwise = let (piece, rest) = BS.splitAt maxWriteBytes chunk in piece : writable rest++-- | The most bytes one write to the pipe takes.+maxWriteBytes :: Int+maxWriteBytes = fromIntegral (maxBound :: Word32)++-- | Write a chunk to the pipe, all of it, before returning.+sendChunk :: HANDLE -> ByteString -> IO ()+sendChunk handle chunk =+  BS.useAsCStringLen chunk $ \(bytes, size) -> alloca $ \failedOut -> do+    code <- interruptibly (\stop -> c_nn_pipe_write handle (castPtr bytes) (fromIntegral size) stop failedOut)+    unless (code == 0) (throwFailure failedOut "nn_pipe_write" code)++-- | Run a call that waits until it is done or the event it is given is+-- set, on a thread of its own, and wait for it here, where an exception+-- can interrupt the wait.  The exception sets the event, waits for the+-- call to give up, so nothing the call uses is released under it, and+-- goes on.  The call's outcome is read and left in place rather than+-- taken, so an exception that arrives as the call ends still finds it.+-- The call's own failure, which it cannot raise on the thread that asked,+-- is carried to that thread and raised there.+interruptibly :: (HANDLE -> IO a) -> IO a+interruptibly call =+  bracket newStopEvent closeHandle $ \stop -> mask $ \restore -> do+    outcome <- newEmptyMVar+    _ <- forkIO (try (call stop) >>= putMVar outcome)+    finished <- restore (readMVar outcome) `onException` (setEvent stop `finally` uninterruptibleMask_ (readMVar outcome))+    either (\(failure :: SomeException) -> throwIO failure) pure finished++-- | A manual-reset event, not set, with no name, for 'interruptibly'.+newStopEvent :: IO HANDLE+newStopEvent = failIfNull "CreateEventW" (c_CreateEventW nullPtr True False nullPtr)++-- ---------------------------------------------------------------------------+-- Accounts+-- ---------------------------------------------------------------------------++-- | This machine's accounts as Windows resolves them: a name or a SID it+-- finds no account for is not found, and one it fails to look up is a+-- failure, which is not an answer.+systemAccounts :: AccountDatabase IO+systemAccounts = AccountDatabase {adAccountSid = accountSid, adAccountName = accountName, adAccountGroups = groupsOf}++-- | The SID an account's name, UTF-8, names, as LookupAccountNameW finds+-- one of the kind: an account of this machine where the name names no+-- domain.  A name with no UTF-8 reading, or holding a NUL, names no+-- account.+accountSid :: AccountKind -> ByteString -> IO (Either Text (Maybe Sid))+accountSid kind bytes = case TE.decodeUtf8' bytes of+  Right name+    | not (T.any (== '\0') name) ->+        withCWString (T.unpack name) $ \cName -> alloca $ \sidOut -> alloca $ \failedOut -> do+          code <- c_nn_account_sid cName kindCode sidOut failedOut+          if code /= 0+            then Left <$> failureMessage failedOut "nn_account_sid" code+            else do+              found <- peek sidOut+              if found == nullPtr+                then pure (Right Nothing)+                else either (Left . ("an account's SID is not one: " <>)) (Right . Just) <$> takeSid found+  _ -> pure (Right Nothing)+  where+    -- NN_ACCOUNT_USER and NN_ACCOUNT_GROUP (cbits/nn_winfs.h).+    kindCode = case kind of+      UserAccount -> 0+      GroupAccount -> 1++-- | Every group an account belongs to, as Windows computes them from the+-- account, or why it cannot say.+groupsOf :: Sid -> IO (Either Text [Sid])+groupsOf sid =+  withCWString (T.unpack (sidText sid)) $ \cSid -> alloca $ \sidsOut -> alloca $ \charsOut -> alloca $ \failedOut -> do+    code <- c_nn_account_groups cSid sidsOut charsOut failedOut+    if code /= 0+      then Left <$> failureMessage failedOut "nn_account_groups" code+      else do+        sids <- peek sidsOut+        chars <- peek charsOut+        spelled <- (T.pack <$> peekCWStringLen (sids, fromIntegral chars)) `finally` localFree sids+        pure (maybe (Left ("the groups Windows gave are not SIDs: " <> T.pack (show spelled))) Right (traverse sidFromText (filter (not . T.null) (T.splitOn "\0" spelled))))++-- | An account's name, @DOMAIN\\NAME@, UTF-8, as LookupAccountSidW finds+-- it.+accountName :: Sid -> IO (Maybe ByteString)+accountName sid =+  withCWString (T.unpack (sidText sid)) $ \cSid -> alloca $ \nameOut -> alloca $ \failedOut -> do+    code <- c_nn_account_name cSid nameOut failedOut+    found <- peek nameOut+    if code /= 0 || found == nullPtr+      then pure Nothing+      else (Just . TE.encodeUtf8 . T.pack <$> peekCWString found) `finally` localFree found++-- | The account this process runs as, its token's user.+processAccount :: IO Sid+processAccount = readSid "nn_token_user_sid" c_nn_token_user_sid++-- | The SID a call writes as a string, or the failure of the call, thrown.+readSid :: String -> (Ptr CWString -> Ptr CString -> IO ErrCode) -> IO Sid+readSid shim call =+  alloca $ \sidOut -> alloca $ \failedOut -> do+    code <- call sidOut failedOut+    unless (code == 0) (throwFailure failedOut shim code)+    peek sidOut >>= takeSid >>= either (\spelled -> ioError (userError (shim <> " gave " <> show spelled <> ", which is not a SID"))) pure++-- | A SID a call wrote as a string for the caller to release, read and+-- released, or the text where it is not a SID.+takeSid :: CWString -> IO (Either Text Sid)+takeSid found = do+  spelled <- (T.pack <$> peekCWString found) `finally` localFree found+  pure (maybe (Left spelled) Right (sidFromText spelled))++-- ---------------------------------------------------------------------------+-- Failures+-- ---------------------------------------------------------------------------++-- | Win32 errors the pipe's callers tell apart (winerror.h): a pipe that+-- already exists, as a first instance finds it, and the other end gone.+errorAccessDenied, errorBrokenPipe, errorPipeNotConnected :: ErrCode+errorAccessDenied = 5+errorBrokenPipe = 109+errorPipeNotConnected = 233++-- | The call a shim names as the one that failed, or the shim's own name+-- where it names none.+failedCall :: Ptr CString -> String -> IO String+failedCall failedOut shim = fromMaybe shim <$> (maybePeek peekCString =<< peek failedOut)++-- | Throw a Win32 failure as the 'IOError' Win32 raises for one, naming+-- the call that failed.+throwFailure :: Ptr CString -> String -> ErrCode -> IO a+throwFailure failedOut shim code = failedCall failedOut shim >>= \call -> failWith call code++-- | A Win32 failure as a message: the call that failed and Windows' words+-- for the error.+failureMessage :: Ptr CString -> String -> ErrCode -> IO Text+failureMessage failedOut shim code = do+  call <- failedCall failedOut shim+  described <- bracket (getErrorMessage code) (void . localFree) $ \message ->+    if message == nullPtr then pure ("Win32 error " <> show code) else peekTString message+  pure (T.pack call <> ": " <> T.strip (T.pack described))++-- ---------------------------------------------------------------------------+-- Foreign calls+-- ---------------------------------------------------------------------------++-- The calls that wait are safe, so they block only the thread+-- 'interruptibly' runs them on.++foreign import ccall unsafe "nn_winfs.h nn_pipe_create"+  c_nn_pipe_create :: CWString -> CInt -> CWString -> Ptr HANDLE -> Ptr CString -> IO ErrCode++foreign import ccall safe "nn_winfs.h nn_pipe_accept"+  c_nn_pipe_accept :: HANDLE -> HANDLE -> Ptr CString -> IO ErrCode++foreign import ccall safe "nn_winfs.h nn_pipe_read"+  c_nn_pipe_read :: HANDLE -> Ptr () -> CULong -> HANDLE -> Ptr CULong -> Ptr CString -> IO ErrCode++foreign import ccall safe "nn_winfs.h nn_pipe_write"+  c_nn_pipe_write :: HANDLE -> Ptr () -> CULong -> HANDLE -> Ptr CString -> IO ErrCode++foreign import ccall unsafe "nn_winfs.h nn_pipe_client"+  c_nn_pipe_client :: HANDLE -> Ptr CULong -> Ptr CInt -> Ptr CWString -> Ptr CULong -> Ptr CString -> IO ErrCode++foreign import ccall unsafe "nn_winfs.h nn_pipe_present"+  c_nn_pipe_present :: CWString -> CWString -> Ptr CInt -> Ptr CString -> IO ErrCode++foreign import ccall safe "nn_winfs.h nn_pipe_open"+  c_nn_pipe_open :: CWString -> CULong -> Ptr HANDLE -> Ptr CString -> IO ErrCode++foreign import ccall unsafe "nn_winfs.h nn_pipe_owner"+  c_nn_pipe_owner :: HANDLE -> Ptr CWString -> Ptr CString -> IO ErrCode++foreign import ccall unsafe "nn_winfs.h nn_token_pipe_owner"+  c_nn_token_pipe_owner :: HANDLE -> Ptr CWString -> Ptr CString -> IO ErrCode++foreign import ccall unsafe "nn_winfs.h nn_pipe_integrity"+  c_nn_pipe_integrity :: HANDLE -> Ptr CULong -> Ptr CString -> IO ErrCode++foreign import ccall safe "nn_winfs.h nn_account_sid"+  c_nn_account_sid :: CWString -> CInt -> Ptr CWString -> Ptr CString -> IO ErrCode++foreign import ccall safe "nn_winfs.h nn_account_groups"+  c_nn_account_groups :: CWString -> Ptr CWString -> Ptr CULong -> Ptr CString -> IO ErrCode++foreign import ccall safe "nn_winfs.h nn_account_name"+  c_nn_account_name :: CWString -> Ptr CWString -> Ptr CString -> IO ErrCode++foreign import ccall unsafe "nn_winfs.h nn_token_user_sid"+  c_nn_token_user_sid :: Ptr CWString -> Ptr CString -> IO ErrCode++foreign import ccall unsafe "windows.h CreateEventW"+  c_CreateEventW :: Ptr () -> BOOL -> BOOL -> CWString -> IO HANDLE++foreign import ccall unsafe "windows.h DisconnectNamedPipe"+  c_DisconnectNamedPipe :: HANDLE -> IO BOOL
+ src/Nix/Daemon/Protocol.hs view
@@ -0,0 +1,1670 @@+{-# LANGUAGE LambdaCase #-}++-- | The values upstream's worker protocol carries, and how each is read and+-- written at every protocol version, as upstream 2.35.4 reads and writes+-- them: @worker-protocol.cc@, @common-protocol.cc@, @serialise.cc@ and+-- @worker-protocol-connection.cc@.  Every gate upstream's serialisers+-- have is kept, the one at 1.16 below the 1.18 floor included: upstream's+-- daemon reads the path info in an upload at 1.16 whatever version was+-- agreed.  A daemon refuses clients below 'minimumVersionNumber' at its+-- handshake, not here.+--+-- A reader takes the store directory paths are named under and the+-- t'Version' both sides agreed, where it needs them, and refuses bytes+-- upstream refuses with upstream's message (without its colours), but for+-- a malformed hash, which is worded as "Nix.Hash" words it, after 2.24.9.+-- A writer is total where upstream's is; one that refuses a value at some+-- versions returns upstream's message for it instead.+--+-- Wire strings are bytes.  The ones whose grammar is ASCII (store paths,+-- hashes, content addresses, checked output names) are read as text, each+-- byte that is not part of valid UTF-8 becoming a NUL: one byte for one,+-- so a hash's spelling keeps the length in bytes upstream picks its+-- decoder by, and a character every such grammar refuses where upstream+-- refuses the byte.  Base64 ends at its padding, and what follows it is+-- ignored there as upstream ignores it.+module Nix.Daemon.Protocol+  ( -- * Versions+    VersionNumber (..),+    Version (..),+    Feature (..),+    latestVersionNumber,+    minimumVersionNumber,+    featureRealisationWithPath,+    featureDeleteDeadSpecificReferrers,+    featureDisableSetOptions,+    getVersionNumber,+    putVersionNumber,+    getFeatures,+    putFeatures,++    -- * Handshake+    getClientMagic,+    putClientMagic,+    getServerMagic,+    putServerMagic,+    getClientObsoleteFields,+    putClientObsoleteFields,+    Trust (..),+    getTrust,+    putTrust,+    HandshakeInfo (..),+    getHandshakeInfo,+    putHandshakeInfo,++    -- * Store paths+    grammarText,+    getStorePath,+    putStorePath,+    getOptionalStorePath,+    putOptionalStorePath,+    getStorePathSet,+    putStorePathSet,++    -- * Path info+    NarHash,+    narHashFromDigest,+    narHashDigest,+    getNarHash,+    putNarHash,+    Signature,+    signatureFromParts,+    sigKeyName,+    sigBytes,+    parseSignature,+    renderSignature,+    getSignatureSet,+    putSignatureSet,+    ContentAddressMethod (..),+    ContentAddress,+    contentAddressFromParts,+    caMethod,+    caAlgo,+    caDigest,+    parseContentAddress,+    parseContentAddressMethod,+    renderContentAddress,+    getContentAddress,+    putContentAddress,+    getOptionalContentAddress,+    putOptionalContentAddress,+    UnkeyedValidPathInfo (..),+    getUnkeyedValidPathInfo,+    putUnkeyedValidPathInfo,+    ValidPathInfo (..),+    getValidPathInfo,+    putValidPathInfo,++    -- * Derived paths+    OutputName (..),+    getOutputName,+    putOutputName,+    OutputsSpec (AllOutputs),+    namedOutputs,+    outputsSpecNames,+    DerivedPath (..),+    getDerivedPath,+    putDerivedPath,++    -- * Realisations+    UnkeyedRealisation (..),+    getUnkeyedRealisation,+    putUnkeyedRealisation,+    getOptionalUnkeyedRealisation,+    putOptionalUnkeyedRealisation,+    DrvOutput (..),+    getDrvOutput,+    putDrvOutput,+    Realisation (..),+    getRealisation,+    putRealisation,++    -- * Builds+    BuildMode (..),+    getBuildMode,+    putBuildMode,+    SuccessStatus (..),+    FailureStatus (..),+    Success (..),+    Failure (..),+    BuildOutcome (..),+    BuildResult (..),+    getBuildResult,+    putBuildResult,+    KeyedBuildResult (..),+    getKeyedBuildResult,+    putKeyedBuildResult,++    -- * Garbage collection+    GCAction (..),+    getGCAction,+    putGCAction,+    GCPaths (..),+    getGCPaths,+    putGCPaths,++    -- * Replies+    Missing (..),+    getMissing,+    putMissing,+    GCResult (..),+    getGCResult,+    putGCResult,+    getOutputMap,+    putOutputMap,+    getRoots,+    putRoots,+    getKeyedBuildResults,+    putKeyedBuildResults,++    -- * Messages to the client+    Verbosity (..),+    errorVerbosity,+    ActivityId (..),+    ActivityType (..),+    actBuild,+    actSubstitute,+    ResultType (..),+    resBuildLogLine,+    resPostBuildLogLine,+    Field (..),+    Activity (..),+    DaemonError (..),+    defaultExitStatus,+    StderrMessage (..),+    getStderrMessage,+    putStderrMessage,+  )+where++import Control.Applicative ((<|>))+import Control.Monad (foldM, replicateM, unless, void, when)+import Data.Bits (shiftL, shiftR, (.&.), (.|.))+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import Data.ByteString.Builder (Builder)+import Data.Int (Int64)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe)+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Word (Word32, Word64, Word8)+import Nix.Daemon.Wire (Decoder, getBool, getBytes, getCount, getInt64, getList, getWord32, getWord64, getWord8, malformed, putBool, putBytes, putList, putNum)+import Nix.Hash (FileIngestionMethod (..), bytesToHexText, digestByLength, hashAlgoBytes, parseAnyHash, parseHashAlgo)+import Nix.Json (Json (..), expectJson, jsonText, parseJson, renderJson)+import Nix.Key (colonBase64Message, parseColonBase64, renderColonBase64)+import Nix.Store.Path (StoreDir (..), StorePath, checkStorePathName, parseStorePathBaseName, spName, storePathBaseNameError, storePathBasename, storePathHashLen, storePathNameUpstreamText, storePathToText)+import qualified NovaCache.Base32 as Nix32+import Numeric (showHex)++-- ---------------------------------------------------------------------------+-- Versions+-- ---------------------------------------------------------------------------++-- | A protocol version number.  Upstream compares numbers major first.+data VersionNumber = VersionNumber+  { -- | The major number, 1 for every version upstream has spoken.+    vnMajor :: !Word8,+    -- | The minor number, which every gate compares.+    vnMinor :: !Word8+  }+  deriving (Eq, Ord, Show)++-- | A protocol feature: a name both sides list at the handshake from 1.38,+-- enabling what neither version number promises.+newtype Feature = Feature ByteString+  deriving (Eq, Ord, Show)++-- | The version a connection agreed: the lower of the two numbers, and+-- the features both sides listed.+data Version = Version+  { -- | The lower of the two sides' numbers.+    versionNumber :: !VersionNumber,+    -- | The features both sides listed.+    versionFeatures :: !(Set Feature)+  }+  deriving (Eq, Show)++-- | The newest version number upstream speaks (@WorkerProto::latest@).+latestVersionNumber :: VersionNumber+latestVersionNumber = VersionNumber 1 38++-- | The oldest version number upstream's daemon serves+-- (@WorkerProto::minimum@).+minimumVersionNumber :: VersionNumber+minimumVersionNumber = VersionNumber 1 18++-- | Realisations named by their derivation's path rather than by its hash,+-- each carrying its output path and signatures.  Without it, realisations+-- cannot cross the wire, and a build result carries its outputs in the+-- older JSON form.+featureRealisationWithPath :: Feature+featureRealisationWithPath = Feature "realisation-with-path-not-hash"++-- | A collection's paths sent as a set with a flag that takes their+-- referrers too.  Without it, a collection's paths are a bare set, and a+-- collection of the dead limited to some paths cannot be asked for.+featureDeleteDeadSpecificReferrers :: Feature+featureDeleteDeadSpecificReferrers = Feature "delete-dead-specific-referrers"++-- | The client sends no settings after the handshake, so the connection+-- keeps the ones the daemon began it with.  Upstream's daemon grants it+-- only on the connections it serves to a build that runs Nix recursively.+featureDisableSetOptions :: Feature+featureDisableSetOptions = Feature "disable-set-options"++-- | Whether a version's number is at least the given one.+atLeast :: Version -> VersionNumber -> Bool+atLeast version gate = versionNumber version >= gate++-- | Whether a version carries a feature.+hasFeature :: Feature -> Version -> Bool+hasFeature feature version = Set.member feature (versionFeatures version)++-- | Read what a version carries, or take what it does not.+since :: Version -> VersionNumber -> a -> Decoder a -> Decoder a+since version gate absent present+  | atLeast version gate = present+  | otherwise = pure absent++-- | Write what a version carries, and nothing where it does not.+whenAtLeast :: Version -> VersionNumber -> Builder -> Builder+whenAtLeast version gate present+  | atLeast version gate = present+  | otherwise = mempty++-- The version gates, each named for what it adds.++-- | A path's info carries its ultimate flag, signatures and content+-- address.+pathInfoTrustSince :: VersionNumber+pathInfoTrustSince = VersionNumber 1 16++-- | The client sends its obsolete reserve-space flag after the handshake.+reserveSpaceSince :: VersionNumber+reserveSpaceSince = VersionNumber 1 11++-- | The client sends its obsolete CPU affinity after the handshake.+cpuAffinitySince :: VersionNumber+cpuAffinitySince = VersionNumber 1 14++-- | An error goes to the client as a record rather than a message and an+-- exit status.+errorRecordSince :: VersionNumber+errorRecordSince = VersionNumber 1 26++-- | A build result carries the outputs it built.+builtOutputsSince :: VersionNumber+builtOutputsSince = VersionNumber 1 28++-- | A build result carries how often it built, its determinism and its+-- start and stop times.+buildTimesSince :: VersionNumber+buildTimesSince = VersionNumber 1 29++-- | A derived path asks for all outputs with @*@, names a derivation file+-- itself by its bare path, and has its output names checked.+derivedPathOutputsSince :: VersionNumber+derivedPathOutputsSince = VersionNumber 1 30++-- | The daemon tells the client its Nix version after the handshake.+daemonVersionSince :: VersionNumber+daemonVersionSince = VersionNumber 1 33++-- | The daemon tells the client whether it trusts it.+trustSince :: VersionNumber+trustSince = VersionNumber 1 35++-- | A build result carries the CPU time its build took.+cpuTimesSince :: VersionNumber+cpuTimesSince = VersionNumber 1 37++-- | A version number as upstream sends it, the major number in the second+-- byte of an @unsigned int@ and the minor in the first; bits above those+-- are dropped, as upstream's @Number::fromWire@ drops them.+getVersionNumber :: Decoder VersionNumber+getVersionNumber = fromWire <$> getWord32+  where+    fromWire word = VersionNumber (fromIntegral (shiftR word 8 .&. 0xff)) (fromIntegral (word .&. 0xff))++-- | Write a version number.+putVersionNumber :: VersionNumber -> Builder+putVersionNumber (VersionNumber major minor) =+  putNum (shiftL (fromIntegral major :: Word32) 8 .|. fromIntegral minor)++-- | A side's feature list, read as upstream's @readStrings@ reads it into+-- a set.+getFeatures :: Decoder (Set Feature)+getFeatures = Set.fromList . map Feature <$> getList getBytes++-- | Write a feature list, in order.+putFeatures :: Set Feature -> Builder+putFeatures features = putList (\(Feature name) -> putBytes name) (Set.toAscList features)++-- ---------------------------------------------------------------------------+-- Handshake+-- ---------------------------------------------------------------------------++-- | The word a client opens a connection with (@WORKER_MAGIC_1@).+clientMagic :: Word32+clientMagic = 0x6e697863++-- | The word a daemon answers with (@WORKER_MAGIC_2@).+serverMagic :: Word32+serverMagic = 0x6478696f++-- | A client's opening word, which a daemon reads before it answers.+getClientMagic :: Decoder ()+getClientMagic = getWord32 >>= \word -> unless (word == clientMagic) (malformed "protocol mismatch")++-- | Write a client's opening word.+putClientMagic :: Builder+putClientMagic = putNum clientMagic++-- | A daemon's answering word, which a client reads before the daemon's+-- version.+getServerMagic :: Decoder ()+getServerMagic = getWord32 >>= \word -> unless (word == serverMagic) (malformed "nix-daemon protocol mismatch from")++-- | Write a daemon's answering word.+putServerMagic :: Builder+putServerMagic = putNum serverMagic++-- | The obsolete fields a client sends once the version is agreed: a CPU+-- affinity, a flag followed by a number when the flag is set, and a+-- reserve-space flag.  Their values mean nothing.+getClientObsoleteFields :: Version -> Decoder ()+getClientObsoleteFields version = do+  when (atLeast version cpuAffinitySince) $ do+    affinity <- getWord32+    when (affinity /= 0) (void getWord32)+  when (atLeast version reserveSpaceSince) (void getWord32)++-- | Write the obsolete fields as upstream's client does: no affinity, and+-- no reserved space.+putClientObsoleteFields :: Version -> Builder+putClientObsoleteFields version =+  whenAtLeast version cpuAffinitySince (putNum (0 :: Word32))+    <> whenAtLeast version reserveSpaceSince (putBool False)++-- | Whether the daemon trusts a client.+data Trust+  = -- | It does: the client may do what the daemon's own user may.+    Trusted+  | -- | It does not.+    NotTrusted+  deriving (Eq, Show)++-- | Whether a daemon trusts its client, or 'Nothing' where it does not+-- say.+getTrust :: Decoder (Maybe Trust)+getTrust =+  getWord8 >>= \case+    0 -> pure Nothing+    1 -> pure (Just Trusted)+    2 -> pure (Just NotTrusted)+    _ -> malformed "Invalid trusted status from remote"++-- | Write whether a daemon trusts its client.+putTrust :: Maybe Trust -> Builder+putTrust trust = putNum $ case trust of+  Nothing -> 0 :: Word8+  Just Trusted -> 1+  Just NotTrusted -> 2++-- | What a daemon tells its client once the handshake is done, as far as+-- the version carries it.+data HandshakeInfo = HandshakeInfo+  { -- | The daemon's Nix version, from 1.33.+    hiDaemonVersion :: !(Maybe ByteString),+    -- | Whether the daemon trusts the client, from 1.35.+    hiTrust :: !(Maybe Trust)+  }+  deriving (Eq, Show)++-- | Read what a daemon tells its client.+getHandshakeInfo :: Version -> Decoder HandshakeInfo+getHandshakeInfo version =+  HandshakeInfo+    <$> since version daemonVersionSince Nothing (Just <$> getBytes)+    <*> since version trustSince Nothing getTrust++-- | Write what a daemon tells its client: its Nix version and whether it+-- trusts it, each where the version carries it.+putHandshakeInfo :: Version -> ByteString -> Maybe Trust -> Builder+putHandshakeInfo version daemonVersion trust =+  whenAtLeast version daemonVersionSince (putBytes daemonVersion)+    <> whenAtLeast version trustSince (putTrust trust)++-- ---------------------------------------------------------------------------+-- Store paths+-- ---------------------------------------------------------------------------++-- | Wire bytes as text, for the ASCII grammars the module header names,+-- each byte that is not part of valid UTF-8 a NUL.  @text@ calls the+-- handler once for each such byte.+grammarText :: ByteString -> Text+grammarText = TE.decodeUtf8With (\_ _ -> Just '\0')++-- | A store path, as upstream's @parseStorePath@ reads one on POSIX: the+-- path is made canonical, its parent must be the store directory, and its+-- last component must be a store path's base name.+getStorePath :: StoreDir -> Decoder StorePath+getStorePath storeDir = getBytes >>= either malformed pure . parseWireStorePath storeDir . grammarText++-- | Write a store path under the store directory.+putStorePath :: StoreDir -> StorePath -> Builder+putStorePath storeDir path = putBytes (TE.encodeUtf8 (storePathToText storeDir path))++-- | Upstream's @StoreDirConfig::parseStorePath@ (store-dir-config.cc at+-- 2.35.4), whose @canonPath@ is lexical: no link is followed.+parseWireStorePath :: StoreDir -> Text -> Either Text StorePath+parseWireStorePath (StoreDir dir) path+  | T.null path = Left "empty path is not a valid store path"+  | not ("/" `T.isPrefixOf` path) = Left ("not an absolute path: \"" <> path <> "\"")+  | Just base <- T.stripPrefix (T.pack dir <> "/") canonical,+    not (T.any (== '/') base) =+      storePathFromBaseName base+  | otherwise = Left ("path \"" <> canonical <> "\" is not in the Nix store")+  where+    canonical = canonicalAbsolute path++-- | An absolute path with its empty and @.@ components dropped, each @..@+-- taking away the component before it, and no trailing separator, as+-- upstream's @canonPath@ makes one on POSIX.+canonicalAbsolute :: Text -> Text+canonicalAbsolute = ("/" <>) . T.intercalate "/" . reverse . foldl' step [] . T.split (== '/')+  where+    step kept component = case component of+      "" -> kept+      "." -> kept+      ".." -> drop 1 kept+      _ -> component : kept++-- | A store path from its base name, refused in the words of upstream's+-- @StorePath@ constructor (path.cc at 2.35.4): it is too short, the hash+-- is not followed by a dash, the hash has a character outside nix-base32,+-- or the name breaks a rule.+storePathFromBaseName :: Text -> Either Text StorePath+storePathFromBaseName base = maybe (Left refusal) Right (parseStorePathBaseName base)+  where+    refusal = fromMaybe ("'" <> base <> "' is not a valid store path") (noDash <|> storePathBaseNameError base)+    noDash = case T.uncons (T.drop storePathHashLen base) of+      Just (c, _) | c /= '-' -> Just ("'" <> base <> "' can't name a store path because the hash part is not followed by a '-'")+      _ -> Nothing++-- | A store path, or 'Nothing' for the empty string.+getOptionalStorePath :: StoreDir -> Decoder (Maybe StorePath)+getOptionalStorePath storeDir = getBytes >>= parsed+  where+    parsed bytes+      | BS.null bytes = pure Nothing+      | otherwise = either malformed (pure . Just) (parseWireStorePath storeDir (grammarText bytes))++-- | Write a store path, or the empty string for none.+putOptionalStorePath :: StoreDir -> Maybe StorePath -> Builder+putOptionalStorePath storeDir = maybe (putBytes BS.empty) (putStorePath storeDir)++-- | A set of store paths.+getStorePathSet :: StoreDir -> Decoder (Set StorePath)+getStorePathSet storeDir = Set.fromList <$> getList (getStorePath storeDir)++-- | Write a set of store paths, in order.+putStorePathSet :: StoreDir -> Set StorePath -> Builder+putStorePathSet storeDir paths = putList (putStorePath storeDir) (Set.toAscList paths)++-- ---------------------------------------------------------------------------+-- Path info+-- ---------------------------------------------------------------------------++-- | The name of the algorithm a NAR hash is taken with.+narHashAlgo :: Text+narHashAlgo = "sha256"++-- | The SHA-256 digest of a path's NAR serialisation.+newtype NarHash = NarHash ByteString+  deriving (Eq, Show)++-- | A NAR hash from its digest, which must be a SHA-256 digest's length.+narHashFromDigest :: ByteString -> Maybe NarHash+narHashFromDigest digest+  | Just (BS.length digest) == hashAlgoBytes narHashAlgo = Just (NarHash digest)+  | otherwise = Nothing++-- | A NAR hash's digest.+narHashDigest :: NarHash -> ByteString+narHashDigest (NarHash digest) = digest++-- | A NAR hash, read as upstream's @Hash::parseAny@ reads it with SHA-256+-- for the algorithm: any spelling of a SHA-256 hash.+getNarHash :: Decoder NarHash+getNarHash = getBytes >>= either malformed (pure . NarHash . snd) . parseAnyHash (Just narHashAlgo) . grammarText++-- | Write a NAR hash in base16, with no algorithm, as upstream does.+putNarHash :: NarHash -> Builder+putNarHash (NarHash digest) = putBytes (TE.encodeUtf8 (bytesToHexText digest))++-- | A signature: the name of the key that made it and its bytes, spelled+-- @name:base64@ on the wire.  It is built only by 'signatureFromParts' and+-- by reading, so every one reads back from its spelling.+data Signature = Signature !ByteString !ByteString+  deriving (Eq, Ord, Show)++-- | The name of the key that made a signature.+sigKeyName :: Signature -> ByteString+sigKeyName (Signature name _) = name++-- | A signature's bytes.+sigBytes :: Signature -> ByteString+sigBytes (Signature _ bytes) = bytes++-- | A signature from its key's name and its bytes: a name that is not+-- empty and has no colon, and bytes that are not empty, which is every+-- signature that reads back from its spelling.+signatureFromParts :: ByteString -> ByteString -> Maybe Signature+signatureFromParts name bytes+  | BS.null name || BS.elem colon name || BS.null bytes = Nothing+  | otherwise = Just (Signature name bytes)++-- | A signature from its spelling, as upstream reads one+-- ('parseColonBase64'): the name before the first colon, and the base64+-- after it, neither empty.+parseSignature :: ByteString -> Either Text Signature+parseSignature = either (Left . colonBase64Message "signature") (Right . uncurry Signature) . parseColonBase64++-- | The byte that ends a signature's key name.+colon :: Word8+colon = 0x3a++-- | A signature as upstream spells it, its bytes in padded base64.+renderSignature :: Signature -> ByteString+renderSignature (Signature name bytes) = renderColonBase64 name bytes++-- | A set of signatures.+getSignatureSet :: Decoder (Set Signature)+getSignatureSet = Set.fromList <$> getList (getBytes >>= either malformed pure . parseSignature)++-- | Write a set of signatures, in order.+putSignatureSet :: Set Signature -> Builder+putSignatureSet sigs = putList (putBytes . renderSignature) (Set.toAscList sigs)++-- | How a content address hashes a path.+data ContentAddressMethod+  = -- | The bytes of a file whose references are listed, as a @.drv@ or+    -- @builtins.toFile@ is (@text@).+    TextMethod+  | -- | A fixed output's contents, by the ingestion method (@fixed@).+    FixedMethod !FileIngestionMethod+  deriving (Eq, Show)++-- | A content address: the method, the algorithm and the digest.  It is+-- built only by 'contentAddressFromParts' and by reading, so its+-- algorithm is one 'hashAlgoBytes' knows and its digest that algorithm's+-- length.+data ContentAddress = ContentAddress !ContentAddressMethod !Text !ByteString+  deriving (Eq, Show)++-- | How a content-addressed path's contents were hashed.+caMethod :: ContentAddress -> ContentAddressMethod+caMethod (ContentAddress method _ _) = method++-- | The name of a content address's algorithm.+caAlgo :: ContentAddress -> Text+caAlgo (ContentAddress _ algo _) = algo++-- | A content address's digest.+caDigest :: ContentAddress -> ByteString+caDigest (ContentAddress _ _ digest) = digest++-- | A content address from its parts: an algorithm 'hashAlgoBytes' knows,+-- and a digest of its length.+contentAddressFromParts :: ContentAddressMethod -> Text -> ByteString -> Maybe ContentAddress+contentAddressFromParts method algo digest+  | hashAlgoBytes algo == Just (BS.length digest) = Just (ContentAddress method algo digest)+  | otherwise = Nothing++-- | A content address from its spelling, as upstream's+-- @ContentAddress::parse@ reads it (content-address.cc at 2.35.4): @text:@+-- or @fixed:@ with @r:@ for a NAR, the algorithm, and the digest in any+-- unprefixed spelling but SRI.  The @git:@ method needs upstream's+-- @git-hashing@ experimental feature, which nova-nix does not have.+parseContentAddress :: Text -> Either Text ContentAddress+parseContentAddress spelled = do+  (method, algo, digest) <- contentAddressPrefix spelled+  ContentAddress method algo <$> digestByLength algo digest++-- | The method and the algorithm an upload names for the path it makes+-- (@text:sha256@, @fixed:r:sha256@), as upstream reads them: the spelling+-- of a content address up to its digest, read with a colon after it, so+-- a refusal quotes that colon.  What follows the algorithm is ignored, as+-- upstream ignores it.+parseContentAddressMethod :: ByteString -> Either Text (ContentAddressMethod, Text)+parseContentAddressMethod spelled = do+  (method, algo, _) <- contentAddressPrefix (grammarText spelled <> ":")+  (method, algo) <$ parseHashAlgo algo++-- | A content address's method and algorithm, and the text after the+-- algorithm's colon, as upstream reads them, its refusals quoting the+-- whole of what it was given.+contentAddressPrefix :: Text -> Either Text (ContentAddressMethod, Text, Text)+contentAddressPrefix spelled = case T.breakOn ":" spelled of+  (prefix, rest)+    | Just afterPrefix <- T.stripPrefix ":" rest -> case prefix of+        "text" -> hashed TextMethod afterPrefix+        "fixed"+          | Just afterMethod <- T.stripPrefix "r:" afterPrefix -> hashed (FixedMethod NarIngestion) afterMethod+          | "git:" `T.isPrefixOf` afterPrefix -> Left (missingExperimentalFeature "git-hashing" Nothing)+          | otherwise -> hashed (FixedMethod FlatIngestion) afterPrefix+        _ -> Left ("content address prefix '" <> prefix <> "' is unrecognized. Recogonized prefixes are 'text' or 'fixed'")+  _ -> Left ("not a content address because it is not in the form '<prefix>:<rest>': " <> spelled)+  where+    hashed method afterMethod = case T.breakOn ":" afterMethod of+      (algo, rest)+        | Just afterAlgo <- T.stripPrefix ":" rest -> Right (method, algo, afterAlgo)+      _ -> Left ("content address hash must be in form '<algo>:<hash>', but found: " <> spelled)++-- | A content address as upstream renders it: the method, the algorithm+-- and the digest in nix-base32.+renderContentAddress :: ContentAddress -> Text+renderContentAddress (ContentAddress method algo digest) = prefix <> algo <> ":" <> Nix32.encode digest+  where+    prefix = case method of+      TextMethod -> "text:"+      FixedMethod FlatIngestion -> "fixed:"+      FixedMethod NarIngestion -> "fixed:r:"++-- | Upstream's refusal for an experimental feature it has not been given,+-- with the reason it needed it, if it gives one.+missingExperimentalFeature :: Text -> Maybe Text -> Text+missingExperimentalFeature feature reason =+  "experimental Nix feature '"+    <> feature+    <> "' is disabled"+    <> maybe "" (\why -> " (" <> why <> ")") reason+    <> "; add '--extra-experimental-features "+    <> feature+    <> "' to enable it"++-- | A content address.+getContentAddress :: Decoder ContentAddress+getContentAddress = getBytes >>= either malformed pure . parseContentAddress . grammarText++-- | Write a content address.+putContentAddress :: ContentAddress -> Builder+putContentAddress = putBytes . TE.encodeUtf8 . renderContentAddress++-- | A content address, or 'Nothing' for the empty string.+getOptionalContentAddress :: Decoder (Maybe ContentAddress)+getOptionalContentAddress = getBytes >>= parsed+  where+    parsed bytes+      | BS.null bytes = pure Nothing+      | otherwise = either malformed (pure . Just) (parseContentAddress (grammarText bytes))++-- | Write a content address, or the empty string for none.+putOptionalContentAddress :: Maybe ContentAddress -> Builder+putOptionalContentAddress = maybe (putBytes BS.empty) putContentAddress++-- | What the store records of a valid path, but the path.+data UnkeyedValidPathInfo = UnkeyedValidPathInfo+  { -- | The derivation that built the path, if it is known.+    upiDeriver :: !(Maybe StorePath),+    -- | The hash of the path's NAR serialisation.+    upiNarHash :: !NarHash,+    -- | The store paths the path refers to.+    upiReferences :: !(Set StorePath),+    -- | When the path was registered, in seconds since the epoch.+    upiRegistrationTime :: !Int64,+    -- | The size of the path's NAR serialisation.+    upiNarSize :: !Word64,+    -- | Whether the path was built here rather than copied in, from 1.16.+    upiUltimate :: !Bool,+    -- | The path's signatures, from 1.16.+    upiSignatures :: !(Set Signature),+    -- | The path's content address, if it has one, from 1.16.+    upiContentAddress :: !(Maybe ContentAddress)+  }+  deriving (Eq, Show)++-- | Read a path's info.+getUnkeyedValidPathInfo :: StoreDir -> Version -> Decoder UnkeyedValidPathInfo+getUnkeyedValidPathInfo storeDir version = do+  deriver <- getOptionalStorePath storeDir+  narHash <- getNarHash+  references <- getStorePathSet storeDir+  registrationTime <- getInt64+  narSize <- getWord64+  (ultimate, sigs, ca) <-+    since version pathInfoTrustSince (False, Set.empty, Nothing) $+      (,,) <$> getBool <*> getSignatureSet <*> getOptionalContentAddress+  pure (UnkeyedValidPathInfo deriver narHash references registrationTime narSize ultimate sigs ca)++-- | Write a path's info, as far as the version carries it.+putUnkeyedValidPathInfo :: StoreDir -> Version -> UnkeyedValidPathInfo -> Builder+putUnkeyedValidPathInfo storeDir version info =+  putOptionalStorePath storeDir (upiDeriver info)+    <> putNarHash (upiNarHash info)+    <> putStorePathSet storeDir (upiReferences info)+    <> putNum (upiRegistrationTime info)+    <> putNum (upiNarSize info)+    <> whenAtLeast+      version+      pathInfoTrustSince+      ( putBool (upiUltimate info)+          <> putSignatureSet (upiSignatures info)+          <> putOptionalContentAddress (upiContentAddress info)+      )++-- | A valid path and what the store records of it.+data ValidPathInfo = ValidPathInfo+  { -- | The path.+    vpiPath :: !StorePath,+    -- | What the store records of it.+    vpiInfo :: !UnkeyedValidPathInfo+  }+  deriving (Eq, Show)++-- | Read a path and its info.+getValidPathInfo :: StoreDir -> Version -> Decoder ValidPathInfo+getValidPathInfo storeDir version =+  ValidPathInfo <$> getStorePath storeDir <*> getUnkeyedValidPathInfo storeDir version++-- | Write a path and its info.+putValidPathInfo :: StoreDir -> Version -> ValidPathInfo -> Builder+putValidPathInfo storeDir version (ValidPathInfo path info) =+  putStorePath storeDir path <> putUnkeyedValidPathInfo storeDir version info++-- ---------------------------------------------------------------------------+-- Derived paths+-- ---------------------------------------------------------------------------++-- | The name of a derivation's output.  Upstream checks an output name+-- only where it reads a derived path from 1.30 and takes any bytes+-- elsewhere; a name here is text, so one that is not UTF-8 is refused+-- wherever it is read.+newtype OutputName = OutputName Text+  deriving (Eq, Ord, Show)++-- | An output name, unchecked.+getOutputName :: Decoder OutputName+getOutputName = getBytes >>= outputNameFromBytes++-- | Write an output name.+putOutputName :: OutputName -> Builder+putOutputName (OutputName name) = putBytes (TE.encodeUtf8 name)++-- | An output name from wire bytes, which must be UTF-8.+outputNameText :: ByteString -> Either Text OutputName+outputNameText bytes =+  either (const (Left ("output name '" <> grammarText bytes <> "' is not valid UTF-8"))) (Right . OutputName) (TE.decodeUtf8' bytes)++-- | 'outputNameText' in a t'Decoder'.+outputNameFromBytes :: ByteString -> Decoder OutputName+outputNameFromBytes = either malformed pure . outputNameText++-- | The byte that separates a derived path from its outputs.+bang :: Word8+bang = 0x21++-- | The byte that separates output names.+comma :: Word8+comma = 0x2c++-- | Which outputs of a derivation are asked for: all of them, or some,+-- by name.+data OutputsSpec+  = -- | Every output.+    AllOutputs+  | -- | The outputs named, which are never none.+    SomeOutputs !(Set OutputName)+  deriving (Eq, Show)++-- | Some outputs by name, or 'Nothing' for no names.+namedOutputs :: Set OutputName -> Maybe OutputsSpec+namedOutputs names+  | Set.null names = Nothing+  | otherwise = Just (SomeOutputs names)++-- | The outputs named, or 'Nothing' for every output.+outputsSpecNames :: OutputsSpec -> Maybe (Set OutputName)+outputsSpecNames spec = case spec of+  AllOutputs -> Nothing+  SomeOutputs names -> Just names++-- | A path a client asks the daemon to make valid.+data DerivedPath+  = -- | A store path as it is.+    DerivedOpaque !StorePath+  | -- | Outputs of the derivation at a store path.+    DerivedBuilt !StorePath !OutputsSpec+  deriving (Eq, Show)++-- | Whether a store path names a derivation, as upstream's+-- @isDerivation@ asks: its name ends in @.drv@.+isDerivationPath :: StorePath -> Bool+isDerivationPath path = ".drv" `T.isSuffixOf` spName path++-- | Read a derived path.  From 1.30 it is upstream's @parseLegacy@+-- (derived-path.cc at 2.35.4): the path, then after the last @!@ either+-- @*@ or names checked as store path names, and a path built from another+-- built output needs upstream's @dynamic-derivations@ experimental feature,+-- which nova-nix does not have.  Before 1.30 it is @parsePathWithOutputs@+-- (path-with-outputs.cc): names after the first @!@, unchecked, and a bare+-- derivation path asks for all of its outputs.+getDerivedPath :: StoreDir -> Version -> Decoder DerivedPath+getDerivedPath storeDir version = getBytes >>= either malformed pure . parse+  where+    parse spelled+      | atLeast version derivedPathOutputsSince = parseLegacy storeDir spelled+      | otherwise = parseWithOutputs storeDir spelled++-- | A derived path as upstream reads one from 1.30.  A second @!@ makes+-- the path before the last one a built output itself, which upstream+-- refuses once it has read the store path before the first, naming the+-- output between the first and the second.+parseLegacy :: StoreDir -> ByteString -> Either Text DerivedPath+parseLegacy storeDir spelled = case BS.break (== bang) spelled of+  (path, rest)+    | BS.null rest -> DerivedOpaque <$> parseWireStorePath storeDir (grammarText path)+    | otherwise -> do+        drv <- parseWireStorePath storeDir (grammarText path)+        case BS.break (== bang) (BS.drop 1 rest) of+          (outputs, more)+            | BS.null more -> DerivedBuilt drv <$> parseOutputsSpec outputs+            | otherwise ->+                Left (missingExperimentalFeature "dynamic-derivations" (Just ("building output '" <> grammarText outputs <> "' of '" <> storePathBasename drv <> "'")))++-- | Which outputs a derived path asks for from 1.30, as upstream's+-- @OutputsSpec::parse@ reads them: @*@, or names separated by commas,+-- each checked as a store path name.  Upstream checks the names in order+-- once they are a set, so the first refused is the least.+parseOutputsSpec :: ByteString -> Either Text OutputsSpec+parseOutputsSpec spelled+  | spelled == "*" = Right AllOutputs+  | otherwise = do+      names <- traverse checkedName (Set.toAscList (Set.fromList (BS.split comma spelled)))+      maybe (Left "name must not be empty") Right (namedOutputs (Set.fromList names))+  where+    checkedName bytes =+      let name = grammarText bytes+       in either (Left . storePathNameUpstreamText) (const (Right (OutputName name))) (checkStorePathName name)++-- | A derived path as upstream reads one before 1.30.+parseWithOutputs :: StoreDir -> ByteString -> Either Text DerivedPath+parseWithOutputs storeDir spelled = do+  let (pathPart, rest) = BS.break (== bang) spelled+      names = filter (not . BS.null) (BS.split comma (BS.drop 1 rest))+  path <- parseWireStorePath storeDir (grammarText pathPart)+  outputs <- traverse outputNameText names+  pure $ case namedOutputs (Set.fromList outputs) of+    Just spec -> DerivedBuilt path spec+    Nothing+      | isDerivationPath path -> DerivedBuilt path AllOutputs+      | otherwise -> DerivedOpaque path++-- | Write a derived path, or upstream's refusal of one the version cannot+-- spell: before 1.30 a derivation file itself, which reads back as asking+-- for its outputs.+putDerivedPath :: StoreDir -> Version -> DerivedPath -> Either Text Builder+putDerivedPath storeDir version derived = putBytes . TE.encodeUtf8 <$> spelling+  where+    pathText = storePathToText storeDir+    joinNames names = T.intercalate "," [name | OutputName name <- Set.toAscList names]+    spelling+      | atLeast version derivedPathOutputsSince = Right $ case derived of+          DerivedOpaque path -> pathText path+          DerivedBuilt drv AllOutputs -> pathText drv <> "!*"+          DerivedBuilt drv (SomeOutputs names) -> pathText drv <> "!" <> joinNames names+      | otherwise = case derived of+          DerivedOpaque path+            | isDerivationPath path ->+                Left+                  ( "trying to request '"+                      <> pathText path+                      <> "', but daemon protocol "+                      <> T.pack (show (vnMajor (versionNumber version)))+                      <> "."+                      <> T.pack (show (vnMinor (versionNumber version)))+                      <> " is too old (< 1.29) to request a derivation file"+                  )+            | otherwise -> Right (pathText path)+          DerivedBuilt drv AllOutputs -> Right (pathText drv)+          DerivedBuilt drv (SomeOutputs names) -> Right (pathText drv <> "!" <> joinNames names)++-- ---------------------------------------------------------------------------+-- Realisations+-- ---------------------------------------------------------------------------++-- | The path a derivation's output was realised at, and its signatures.+data UnkeyedRealisation = UnkeyedRealisation+  { -- | The output's path.+    urOutPath :: !StorePath,+    -- | Signatures over the realisation.+    urSignatures :: !(Set Signature)+  }+  deriving (Eq, Show)++-- | Upstream's refusal of a realisation where the version lacks the+-- feature that lets one cross the wire, saying what it was needed for.+missingRealisationFeature :: Text -> Text+missingRealisationFeature neededFor =+  "the daemon is missing the '" <> featureName <> "' protocol feature, needed to " <> neededFor+  where+    Feature nameBytes = featureRealisationWithPath+    featureName = grammarText nameBytes++-- | What upstream says a realisation without its path was needed for.+buildTracePurpose :: Text+buildTracePurpose = "understand build trace"++-- | What upstream says a derivation's output was needed for.+contentAddressingPurpose :: Text+contentAddressingPurpose = "support content-addressing derivations"++-- | Refuse to read a realisation where the version lacks the feature.+requireRealisationFeature :: Version -> Text -> Decoder ()+requireRealisationFeature version neededFor =+  unless (hasFeature featureRealisationWithPath version) (malformed (missingRealisationFeature neededFor))++-- | Bytes a version with the feature reads, or upstream's refusal to write+-- them for one without it.+withRealisationFeature :: Version -> Text -> Builder -> Either Text Builder+withRealisationFeature version neededFor bytes+  | hasFeature featureRealisationWithPath version = Right bytes+  | otherwise = Left (missingRealisationFeature neededFor)++-- | Read where an output was realised.+getUnkeyedRealisation :: StoreDir -> Version -> Decoder UnkeyedRealisation+getUnkeyedRealisation storeDir version = do+  requireRealisationFeature version buildTracePurpose+  UnkeyedRealisation <$> getStorePath storeDir <*> getSignatureSet++-- | Write where an output was realised, or upstream's refusal where the+-- version lacks 'featureRealisationWithPath'.+putUnkeyedRealisation :: StoreDir -> Version -> UnkeyedRealisation -> Either Text Builder+putUnkeyedRealisation storeDir version realisation =+  withRealisationFeature version buildTracePurpose (unkeyedRealisationBytes storeDir realisation)++-- | Where an output was realised, as a version with the feature reads it.+unkeyedRealisationBytes :: StoreDir -> UnkeyedRealisation -> Builder+unkeyedRealisationBytes storeDir (UnkeyedRealisation path sigs) =+  putStorePath storeDir path <> putSignatureSet sigs++-- | Where an output was realised, if it was.  Without the feature,+-- upstream reads a string in its place and takes it as none.+getOptionalUnkeyedRealisation :: StoreDir -> Version -> Decoder (Maybe UnkeyedRealisation)+getOptionalUnkeyedRealisation storeDir version+  | hasFeature featureRealisationWithPath version =+      getWord8 >>= \case+        0 -> pure Nothing+        1 -> Just <$> getUnkeyedRealisation storeDir version+        _ -> malformed "Invalid optional build trace from remote"+  | otherwise = Nothing <$ getBytes++-- | Write where an output was realised, if it was: none at any version,+-- which a version without the feature reads as an empty string, and a+-- realisation as 'putUnkeyedRealisation' writes it.+putOptionalUnkeyedRealisation :: StoreDir -> Version -> Maybe UnkeyedRealisation -> Either Text Builder+putOptionalUnkeyedRealisation storeDir version realisation = case realisation of+  Nothing -> Right (putNum (0 :: Word8))+  Just unkeyed -> (putNum (1 :: Word8) <>) <$> putUnkeyedRealisation storeDir version unkeyed++-- | An output of a derivation, named by the derivation's path.+data DrvOutput = DrvOutput+  { -- | The derivation's path.+    doDrvPath :: !StorePath,+    -- | The output's name.+    doOutputName :: !OutputName+  }+  deriving (Eq, Show)++-- | Read an output of a derivation.+getDrvOutput :: StoreDir -> Version -> Decoder DrvOutput+getDrvOutput storeDir version = do+  requireRealisationFeature version contentAddressingPurpose+  DrvOutput <$> getStorePath storeDir <*> getOutputName++-- | Write an output of a derivation, or upstream's refusal where the+-- version lacks 'featureRealisationWithPath'.+putDrvOutput :: StoreDir -> Version -> DrvOutput -> Either Text Builder+putDrvOutput storeDir version (DrvOutput drv name) =+  withRealisationFeature version contentAddressingPurpose (putStorePath storeDir drv <> putOutputName name)++-- | An output of a derivation and where it was realised.+data Realisation = Realisation+  { -- | The output.+    rId :: !DrvOutput,+    -- | Where it was realised.+    rRealisation :: !UnkeyedRealisation+  }+  deriving (Eq, Show)++-- | Read a realisation.+getRealisation :: StoreDir -> Version -> Decoder Realisation+getRealisation storeDir version =+  Realisation <$> getDrvOutput storeDir version <*> getUnkeyedRealisation storeDir version++-- | Write a realisation, or upstream's refusal where the version lacks+-- 'featureRealisationWithPath', which names the output it writes first.+putRealisation :: StoreDir -> Version -> Realisation -> Either Text Builder+putRealisation storeDir version (Realisation output realisation) =+  (<>) <$> putDrvOutput storeDir version output <*> putUnkeyedRealisation storeDir version realisation++-- ---------------------------------------------------------------------------+-- Builds+-- ---------------------------------------------------------------------------++-- | How a build treats outputs that are already valid.+data BuildMode+  = -- | Keep them.+    BuildNormal+  | -- | Build them again and replace them.+    BuildRepair+  | -- | Build them again and compare.+    BuildCheck+  deriving (Eq, Show)++-- | Read a build mode.+getBuildMode :: Decoder BuildMode+getBuildMode =+  getWord8 >>= \case+    0 -> pure BuildNormal+    1 -> pure BuildRepair+    2 -> pure BuildCheck+    _ -> malformed "Invalid build mode"++-- | Write a build mode.+putBuildMode :: BuildMode -> Builder+putBuildMode mode = putNum $ case mode of+  BuildNormal -> 0 :: Word8+  BuildRepair -> 1+  BuildCheck -> 2++-- | How a build that succeeded did.+data SuccessStatus+  = -- | The outputs were built.+    Built+  | -- | The outputs were substituted.+    Substituted+  | -- | The outputs were valid already.+    AlreadyValid+  | -- | The derivation resolved to one whose outputs were valid already.+    ResolvesToAlreadyValid+  deriving (Eq, Show, Enum, Bounded)++-- | Why a build failed.  Upstream's @HashMismatch@ goes to the client as+-- 'OutputRejected', since the protocol has no word for it, so it has no+-- constructor here.+data FailureStatus+  = -- | The builder failed.+    PermanentFailure+  | -- | An input was refused.+    InputRejected+  | -- | An output was refused, or its hash was not the one fixed.+    OutputRejected+  | -- | The build failed in a way that may not recur.+    TransientFailure+  | -- | The build failed before and the failure was cached.+    CachedFailure+  | -- | The build ran past its time limit or its silence limit.+    TimedOut+  | -- | Any other failure.+    MiscFailure+  | -- | A dependency failed to build.+    DependencyFailed+  | -- | The build logged more than its limit.+    LogLimitExceeded+  | -- | A repeated build gave different outputs.+    NotDeterministic+  | -- | The outputs could not be substituted, and building was not+    -- allowed.+    NoSubstituters+  deriving (Eq, Show, Enum, Bounded)++-- | A status's byte on the wire (@buildResultStatusTable@,+-- common-protocol.cc at 2.35.4).+statusByte :: Either SuccessStatus FailureStatus -> Word8+statusByte status = case status of+  Left Built -> 0+  Left Substituted -> 1+  Left AlreadyValid -> 2+  Right PermanentFailure -> 3+  Right InputRejected -> 4+  Right OutputRejected -> 5+  Right TransientFailure -> 6+  Right CachedFailure -> 7+  Right TimedOut -> 8+  Right MiscFailure -> 9+  Right DependencyFailed -> 10+  Right LogLimitExceeded -> 11+  Right NotDeterministic -> 12+  Left ResolvesToAlreadyValid -> 13+  Right NoSubstituters -> 14++-- | Every status, keyed by its byte.+statusesByByte :: Map Word8 (Either SuccessStatus FailureStatus)+statusesByByte =+  Map.fromList [(statusByte status, status) | status <- map Left [minBound .. maxBound] ++ map Right [minBound .. maxBound]]++-- | Read a build's status.+getBuildStatus :: Decoder (Either SuccessStatus FailureStatus)+getBuildStatus = getWord8 >>= \byte -> maybe (malformed ("Invalid BuildResult status " <> T.pack (show byte) <> " from remote")) pure (Map.lookup byte statusesByByte)++-- | A build that succeeded.+data Success = Success+  { -- | How.+    successStatus :: !SuccessStatus,+    -- | Where each output was realised.+    successOutputs :: !(Map OutputName UnkeyedRealisation)+  }+  deriving (Eq, Show)++-- | A build that failed.+data Failure = Failure+  { -- | Why.+    failureStatus :: !FailureStatus,+    -- | What the build said.+    failureMessage :: !ByteString,+    -- | Whether builds of it that were repeated gave different outputs.+    failureNonDeterministic :: !Bool+  }+  deriving (Eq, Show)++-- | How a build ended.+data BuildOutcome+  = -- | It succeeded.+    Succeeded !Success+  | -- | It failed.+    Failed !Failure+  deriving (Eq, Show)++-- | A build's result, as far as the version carries it.+data BuildResult = BuildResult+  { -- | How it ended.+    brOutcome :: !BuildOutcome,+    -- | How many times it was built, from 1.29.+    brTimesBuilt :: !Word32,+    -- | When it started, in seconds since the epoch, from 1.29.+    brStartTime :: !Int64,+    -- | When it stopped, from 1.29.+    brStopTime :: !Int64,+    -- | The user CPU time it took, in microseconds, from 1.37.+    brCpuUser :: !(Maybe Int64),+    -- | The system CPU time it took, in microseconds, from 1.37.+    brCpuSystem :: !(Maybe Int64)+  }+  deriving (Eq, Show)++-- | A duration that may be absent: a tag, then the microseconds.+getOptionalMicroseconds :: Decoder (Maybe Int64)+getOptionalMicroseconds =+  getWord8 >>= \case+    0 -> pure Nothing+    1 -> Just <$> getInt64+    _ -> malformed "Invalid optional tag from remote"++-- | Write a duration that may be absent.+putOptionalMicroseconds :: Maybe Int64 -> Builder+putOptionalMicroseconds = maybe (putNum (0 :: Word8)) (\micros -> putNum (1 :: Word8) <> putNum micros)++-- | The hash upstream puts in the identifiers of a build's outputs where it+-- sends them in JSON: @Hash::dummy@, a SHA-256 digest of zeros, which an+-- older client splits off unread.+dummyOutputHash :: Text+dummyOutputHash = "sha256:" <> T.replicate 64 "0"++-- | Read a build result.+getBuildResult :: StoreDir -> Version -> Decoder BuildResult+getBuildResult storeDir version = do+  status <- getBuildStatus+  message <- getBytes+  (timesBuilt, nonDeterministic, startTime, stopTime) <-+    since version buildTimesSince (0, False, 0, 0) $+      (,,,) <$> getWord32 <*> getBool <*> getInt64 <*> getInt64+  (cpuUser, cpuSystem) <-+    since version cpuTimesSince (Nothing, Nothing) $+      (,) <$> getOptionalMicroseconds <*> getOptionalMicroseconds+  outputs <- getBuiltOutputs storeDir version+  let outcome = case status of+        Left success -> Succeeded (Success success outputs)+        Right failure -> Failed (Failure failure message nonDeterministic)+  pure (BuildResult outcome timesBuilt startTime stopTime cpuUser cpuSystem)++-- | A build's outputs: with the feature, each name and its realisation;+-- from 1.28 without it, upstream's older JSON form, of which only each+-- output's name and path are read; before 1.28, none.+getBuiltOutputs :: StoreDir -> Version -> Decoder (Map OutputName UnkeyedRealisation)+getBuiltOutputs storeDir version+  | hasFeature featureRealisationWithPath version =+      Map.fromList <$> getList ((,) <$> getOutputName <*> getUnkeyedRealisation storeDir version)+  | atLeast version builtOutputsSince = do+      -- Upstream reads the pairs into a map, the last of a repeated key+      -- winning, and then walks it in key order.+      pairs <- Map.fromList <$> getList ((,) <$> getBytes <*> getBytes)+      foldM addOutput Map.empty (Map.toAscList pairs)+  | otherwise = pure Map.empty+  where+    addOutput outputs (outputId, json) = case BS.breakSubstring "!" outputId of+      (_, rest)+        | BS.null rest -> malformed ("Invalid derivation output id " <> grammarText outputId)+        | otherwise -> do+            name <- outputNameFromBytes (BS.drop 1 rest)+            path <- either malformed pure (outPathOf json)+            pure (Map.insert name (UnkeyedRealisation path Set.empty) outputs)+    outPathOf json = do+      document <- either (const (Left ("output realisation is not valid JSON: " <> grammarText json))) Right (TE.decodeUtf8' json) >>= parseJson+      members <- expectJson "object" (\case JsonObject members -> Just members; _ -> Nothing) document+      value <- maybe (Left ("Expected JSON object to contain key 'outPath' but it doesn't: " <> jsonText document)) Right (Map.lookup "outPath" members)+      base <- expectJson "string" (\case JsonString text -> Just text; _ -> Nothing) value+      storePathFromBaseName base++-- | Write a build result, as far as the version carries it.+putBuildResult :: StoreDir -> Version -> BuildResult -> Builder+putBuildResult storeDir version result =+  putNum (statusByte status)+    <> putBytes message+    <> whenAtLeast+      version+      buildTimesSince+      (putNum (brTimesBuilt result) <> putBool nonDeterministic <> putNum (brStartTime result) <> putNum (brStopTime result))+    <> whenAtLeast version cpuTimesSince (putOptionalMicroseconds (brCpuUser result) <> putOptionalMicroseconds (brCpuSystem result))+    <> putBuiltOutputs storeDir version outputs+  where+    -- The protocol carries a failure's message and determinism with a+    -- success too, and a success's outputs with a failure, each empty+    -- where its case has none.+    (status, message, nonDeterministic, outputs) = case brOutcome result of+      Succeeded (Success how built) -> (Left how, BS.empty, False, built)+      Failed (Failure why said differed) -> (Right why, said, differed, Map.empty)++-- | Write a build's outputs, as far as the version carries them.  Without+-- the feature, each goes as upstream's older JSON form, under an+-- identifier made with 'dummyOutputHash', and its signatures are not+-- sent.+putBuiltOutputs :: StoreDir -> Version -> Map OutputName UnkeyedRealisation -> Builder+putBuiltOutputs storeDir version outputs+  | hasFeature featureRealisationWithPath version =+      putList (\(name, realisation) -> putOutputName name <> unkeyedRealisationBytes storeDir realisation) (Map.toAscList outputs)+  | atLeast version builtOutputsSince = putList jsonEntry (Map.toAscList outputs)+  | otherwise = mempty+  where+    jsonEntry (OutputName name, UnkeyedRealisation path _) =+      let outputId = dummyOutputHash <> "!" <> name+       in putBytes (TE.encodeUtf8 outputId)+            <> putBytes (renderJson (JsonObject (Map.fromList [("id", JsonString outputId), ("outPath", JsonString (storePathBasename path))])))++-- | A build result and the derived path it answers.+data KeyedBuildResult = KeyedBuildResult+  { -- | The path that was asked for.+    kbrPath :: !DerivedPath,+    -- | Its result.+    kbrResult :: !BuildResult+  }+  deriving (Eq, Show)++-- | Read a keyed build result.+getKeyedBuildResult :: StoreDir -> Version -> Decoder KeyedBuildResult+getKeyedBuildResult storeDir version =+  KeyedBuildResult <$> getDerivedPath storeDir version <*> getBuildResult storeDir version++-- | Write a keyed build result, or the refusal 'putDerivedPath' gives its+-- path.+putKeyedBuildResult :: StoreDir -> Version -> KeyedBuildResult -> Either Text Builder+putKeyedBuildResult storeDir version (KeyedBuildResult path result) =+  (<> putBuildResult storeDir version result) <$> putDerivedPath storeDir version path++-- ---------------------------------------------------------------------------+-- Garbage collection+-- ---------------------------------------------------------------------------++-- | What a collection does.+data GCAction+  = -- | Report the paths that are live.+    ReturnLive+  | -- | Report the paths that are dead.+    ReturnDead+  | -- | Delete the paths that are dead.+    DeleteDead+  | -- | Delete the paths given, which must be dead.+    DeleteSpecific+  deriving (Eq, Show)++-- | Read a collection's action.+getGCAction :: Decoder GCAction+getGCAction =+  getWord32 >>= \case+    0 -> pure ReturnLive+    1 -> pure ReturnDead+    2 -> pure DeleteDead+    3 -> pure DeleteSpecific+    _ -> malformed "Invalid GC action"++-- | Write a collection's action.+putGCAction :: GCAction -> Builder+putGCAction action = putNum $ case action of+  ReturnLive -> 0 :: Word32+  ReturnDead -> 1+  DeleteDead -> 2+  DeleteSpecific -> 3++-- | Which paths a collection considers.+data GCPaths+  = -- | Every path in the store.+    WholeStore+  | -- | The paths given, and whether their referrers go with them.+    SpecificPaths !(Set StorePath) !Bool+  deriving (Eq, Show)++-- | Read which paths a collection considers.+getGCPaths :: StoreDir -> Decoder GCPaths+getGCPaths storeDir =+  getWord8 >>= \case+    0 -> SpecificPaths <$> getStorePathSet storeDir <*> getBool+    1 -> pure WholeStore+    _ -> malformed "Invalid whole store indicator from remote"++-- | Write which paths a collection considers.+putGCPaths :: StoreDir -> GCPaths -> Builder+putGCPaths storeDir paths = case paths of+  SpecificPaths specific deleteReferrers ->+    putNum (0 :: Word8) <> putStorePathSet storeDir specific <> putBool deleteReferrers+  WholeStore -> putNum (1 :: Word8)++-- ---------------------------------------------------------------------------+-- Replies+-- ---------------------------------------------------------------------------++-- | What realising some paths would take, as a daemon answers a client+-- that asks.+data Missing = Missing+  { missingWillBuild :: !(Set StorePath),+    missingWillSubstitute :: !(Set StorePath),+    missingUnknown :: !(Set StorePath),+    -- | The bytes substituting would download.+    missingDownloadSize :: !Word64,+    -- | The NAR bytes substituting would unpack.+    missingNarSize :: !Word64+  }+  deriving (Eq, Show)++-- | Read what realising some paths would take: the paths to build, to+-- substitute and that are unknown, then the two sizes.+getMissing :: StoreDir -> Decoder Missing+getMissing storeDir =+  Missing <$> getStorePathSet storeDir <*> getStorePathSet storeDir <*> getStorePathSet storeDir <*> getWord64 <*> getWord64++-- | Write what realising some paths would take.+putMissing :: StoreDir -> Missing -> Builder+putMissing storeDir missing =+  putStorePathSet storeDir (missingWillBuild missing)+    <> putStorePathSet storeDir (missingWillSubstitute missing)+    <> putStorePathSet storeDir (missingUnknown missing)+    <> putNum (missingDownloadSize missing)+    <> putNum (missingNarSize missing)++-- | What a collection did.+data GCResult = GCResult+  { -- | The paths it found or deleted, as upstream names them.+    gcResultPaths :: !(Set ByteString),+    -- | The bytes it freed.+    gcResultBytesFreed :: !Word64+  }+  deriving (Eq, Show)++-- | The word that follows a collection's result, which no client reads.+obsoleteCollectionWord :: Word64+obsoleteCollectionWord = 0++-- | Read what a collection did, and pass over the obsolete word after+-- it.+getGCResult :: Decoder GCResult+getGCResult = GCResult . Set.fromList <$> getList getBytes <*> getWord64 <* getWord64++-- | Write what a collection did.+putGCResult :: GCResult -> Builder+putGCResult result =+  putList putBytes (Set.toAscList (gcResultPaths result))+    <> putNum (gcResultBytesFreed result)+    <> putNum obsoleteCollectionWord++-- | Read a derivation's outputs and their paths, where known.+getOutputMap :: StoreDir -> Decoder (Map OutputName (Maybe StorePath))+getOutputMap storeDir = Map.fromList <$> getList ((,) <$> getOutputName <*> getOptionalStorePath storeDir)++-- | Write a derivation's outputs and their paths.+putOutputMap :: StoreDir -> Map OutputName (Maybe StorePath) -> Builder+putOutputMap storeDir outputs = putList (\(name, path) -> putOutputName name <> putOptionalStorePath storeDir path) (Map.toAscList outputs)++-- | Read the roots: how many there are, then each one's link and the+-- path it keeps.+getRoots :: StoreDir -> Decoder (Map StorePath (Set ByteString))+getRoots storeDir =+  Map.fromListWith Set.union <$> getList ((\link path -> (path, Set.singleton link)) <$> getBytes <*> getStorePath storeDir)++-- | Write the roots, in the order of the paths and then of the links.+putRoots :: StoreDir -> Map StorePath (Set ByteString) -> Builder+putRoots storeDir roots =+  putNum (sum (map Set.size (Map.elems roots)))+    <> foldMap (\(target, links) -> foldMap (\link -> putBytes link <> putStorePath storeDir target) (Set.toAscList links)) (Map.toAscList roots)++-- | Read build results with the paths they answer.+getKeyedBuildResults :: StoreDir -> Version -> Decoder [KeyedBuildResult]+getKeyedBuildResults storeDir version = getList (getKeyedBuildResult storeDir version)++-- | Write build results with the paths they answer, as far as they can+-- be written, and the refusal of the first that cannot: upstream writes+-- each as it goes, so what comes before that one is written.+putKeyedBuildResults :: StoreDir -> Version -> [KeyedBuildResult] -> (Builder, Maybe Text)+putKeyedBuildResults storeDir version results = go (putNum (length results)) results+  where+    go written = \case+      [] -> (written, Nothing)+      result : rest -> either (\refusal -> (written, Just refusal)) (\bytes -> go (written <> bytes) rest) (putKeyedBuildResult storeDir version result)++-- ---------------------------------------------------------------------------+-- Messages to the client+-- ---------------------------------------------------------------------------++-- | How loud a message is: upstream's @Verbosity@, 0 for an error.+newtype Verbosity = Verbosity Word32+  deriving (Eq, Show)++-- | The verbosity of an error (@lvlError@).+errorVerbosity :: Verbosity+errorVerbosity = Verbosity 0++-- | An activity's number, unique within the daemon.+newtype ActivityId = ActivityId Word64+  deriving (Eq, Show)++-- | What kind of activity one is: upstream's @ActivityType@.+newtype ActivityType = ActivityType Word32+  deriving (Eq, Show)++-- | A derivation's build, and a path's substitution.+actBuild, actSubstitute :: ActivityType+actBuild = ActivityType 105+actSubstitute = ActivityType 108++-- | What kind of result an activity reports: upstream's @ResultType@.+newtype ResultType = ResultType Word32+  deriving (Eq, Show)++-- | A line a build's builder wrote, and one its post-build hook wrote.+resBuildLogLine, resPostBuildLogLine :: ResultType+resBuildLogLine = ResultType 101+resPostBuildLogLine = ResultType 107++-- | A field of an activity or a result.+data Field+  = -- | A number.+    FieldInt !Word64+  | -- | A string.+    FieldString !ByteString+  deriving (Eq, Show)++-- | An activity's start.+data Activity = Activity+  { -- | The activity's number.+    actId :: !ActivityId,+    -- | How loud it is.+    actLevel :: !Verbosity,+    -- | What kind it is.+    actType :: !ActivityType,+    -- | What it says it is doing.+    actText :: !ByteString,+    -- | Its fields, as its type defines them.+    actFields :: ![Field],+    -- | The activity it is part of, 0 for none.+    actParent :: !ActivityId+  }+  deriving (Eq, Show)++-- | An error a daemon sends its client.  From 1.26 it goes as a record and+-- its exit status stays behind, reading back as upstream's default of 1;+-- before 1.26 only its message and exit status go, and it reads back at+-- the error level with no traces.+data DaemonError = DaemonError+  { -- | How loud it is.+    errLevel :: !Verbosity,+    -- | What went wrong.+    errMessage :: !ByteString,+    -- | What was being done when it happened, as upstream lists it: each+    -- added in front, so the outermost first.+    errTraces :: ![ByteString],+    -- | The status a command that fails with it exits with.+    errExitStatus :: !Word32+  }+  deriving (Eq, Show)++-- | What a daemon tells its client while it works on an operation.+data StderrMessage+  = -- | A line to log.+    StderrNext !ByteString+  | -- | A request for up to this many bytes of the client's upload.+    StderrRead !Word64+  | -- | Bytes for the client's sink.+    StderrWrite !ByteString+  | -- | The operation's work is done, and its reply follows.+    StderrLast+  | -- | The operation failed.+    StderrError !DaemonError+  | -- | An activity started.+    StderrStartActivity !Activity+  | -- | An activity stopped.+    StderrStopActivity !ActivityId+  | -- | An activity reported a result, of a type and with fields.+    StderrResult !ActivityId !ResultType ![Field]+  deriving (Eq, Show)++-- The words that open each message (worker-protocol.hh at 2.35.4).++stderrNext, stderrRead, stderrWrite, stderrLast, stderrError, stderrStartActivity, stderrStopActivity, stderrResult :: Word64+stderrNext = 0x6f6c6d67+stderrRead = 0x64617461+stderrWrite = 0x64617416+stderrLast = 0x616c7473+stderrError = 0x63787470+stderrStartActivity = 0x53545254+stderrStopActivity = 0x53544f50+stderrResult = 0x52534c54++-- | The type an error record names, the only one upstream writes or reads.+errorRecordType :: ByteString+errorRecordType = "Error"++-- | The exit status of an error that does not carry one (@ErrorInfo@'s+-- default).+defaultExitStatus :: Word32+defaultExitStatus = 1++-- | Read a message from a daemon, as upstream's client reads it+-- (@processStderrReturn@, worker-protocol-connection.cc at 2.35.4).+getStderrMessage :: Version -> Decoder StderrMessage+getStderrMessage version = getWord64 >>= message+  where+    message code+      | code == stderrNext = StderrNext <$> getBytes+      | code == stderrRead = StderrRead <$> getWord64+      | code == stderrWrite = StderrWrite <$> getBytes+      | code == stderrLast = pure StderrLast+      | code == stderrError = StderrError <$> getDaemonError version+      | code == stderrStartActivity =+          fmap StderrStartActivity $+            (Activity . ActivityId <$> getWord64)+              <*> (Verbosity <$> getWord32)+              <*> (ActivityType <$> getWord32)+              <*> getBytes+              <*> getFields+              <*> (ActivityId <$> getWord64)+      | code == stderrStopActivity = StderrStopActivity . ActivityId <$> getWord64+      | code == stderrResult = (StderrResult . ActivityId <$> getWord64) <*> (ResultType <$> getWord32) <*> getFields+      | otherwise = malformed ("got unknown message type " <> T.pack (showHex code "") <> " from Nix daemon")++-- | Write a message to a client.+putStderrMessage :: Version -> StderrMessage -> Builder+putStderrMessage version message = case message of+  StderrNext line -> putNum stderrNext <> putBytes line+  StderrRead size -> putNum stderrRead <> putNum size+  StderrWrite bytes -> putNum stderrWrite <> putBytes bytes+  StderrLast -> putNum stderrLast+  StderrError err -> putNum stderrError <> putDaemonError version err+  StderrStartActivity (Activity (ActivityId act) (Verbosity level) (ActivityType kind) text fields (ActivityId parent)) ->+    putNum stderrStartActivity <> putNum act <> putNum level <> putNum kind <> putBytes text <> putFields fields <> putNum parent+  StderrStopActivity (ActivityId act) -> putNum stderrStopActivity <> putNum act+  StderrResult (ActivityId act) (ResultType kind) fields -> putNum stderrResult <> putNum act <> putNum kind <> putFields fields++-- | An activity's fields: a count, then each field's type and value.+getFields :: Decoder [Field]+getFields = getWord32 >>= \count -> replicateM (fromIntegral count) field+  where+    field =+      getWord32 >>= \case+        0 -> FieldInt <$> getWord64+        1 -> FieldString <$> getBytes+        kind -> malformed ("got unsupported field type " <> T.pack (showHex kind "") <> " from Nix daemon")++-- | Write an activity's fields.+putFields :: [Field] -> Builder+putFields = putList field+  where+    field (FieldInt n) = putNum (0 :: Word32) <> putNum n+    field (FieldString s) = putNum (1 :: Word32) <> putBytes s++-- | Read an error, as upstream's @readError@ reads its record from 1.26+-- (serialise.cc at 2.35.4).+getDaemonError :: Version -> Decoder DaemonError+getDaemonError version+  | atLeast version errorRecordSince = do+      kind <- getBytes+      unless (kind == errorRecordType) (malformed ("unexpected error type '" <> grammarText kind <> "'"))+      level <- getWord32+      _name <- getBytes+      msg <- getBytes+      noPosition+      traceCount <- getCount+      traces <- replicateM traceCount (noPosition *> getBytes)+      pure (DaemonError (Verbosity level) msg traces defaultExitStatus)+  | otherwise = do+      msg <- getBytes+      DaemonError errorVerbosity msg [] <$> getWord32+  where+    noPosition = getWord64 >>= \havePos -> unless (havePos == 0) (malformed "deserializing error positions is not supported")++-- | Write an error, as far as the version carries it.+putDaemonError :: Version -> DaemonError -> Builder+putDaemonError version (DaemonError (Verbosity level) msg traces status)+  | atLeast version errorRecordSince =+      putBytes errorRecordType+        <> putNum level+        <> putBytes errorRecordType+        <> putBytes msg+        <> noPosition+        <> putList (\hint -> noPosition <> putBytes hint) traces+  | otherwise = putBytes msg <> putNum status+  where+    noPosition = putNum (0 :: Word64)
+ src/Nix/Daemon/StoreChoice.hs view
@@ -0,0 +1,367 @@+{-# LANGUAGE LambdaCase #-}++-- | Which store a command uses, and whether it reaches the store itself+-- or through a daemon ("Nix.Daemon.ClientStore").+--+-- == What names a store+--+-- The value comes from @--store@, else nix.conf's @store@ setting, else+-- @NIX_REMOTE@, else @auto@ ('storeReference'), and 'parseStoreTarget'+-- reads it as upstream reads a store reference: the empty string and+-- @auto@ choose by what the machine allows, @daemon@ is the daemon at its+-- default address, @unix:\/\/PATH@ the daemon at another, @local@ the+-- platform store, opened directly, and a path a store directory.  A+-- @unix:\/\/@ path is percent-decoded, split at @\/@ and folded lexically,+-- as upstream folds it, and must be absolute.  On Windows it is the named+-- pipe's path, as written.  A word with no path separator that is none of+-- the above, such as a misspelt @daemon@, is refused as a store that+-- cannot be parsed, as upstream refuses it, and is never a directory.+--+-- nova-nix reads three things differently.  It refuses a value with a query+-- (@?@) or with a scheme it does not open, where upstream opens many more+-- kinds of store; it reads a path as the store itself, as it has always+-- read @--store@, where upstream reads it as the root of a store beneath+-- it, and on Windows a drive path too, which upstream reads as a URL+-- whose scheme is the drive's letter when it has a @\/@; and it makes no+-- store of its own under the user's data directory+-- where a Linux system has no @\/nix@ and no daemon, which upstream does+-- for a user who is not root, but opens the platform store directly, where+-- the opening fails as it would have.+--+-- == What a daemon is sent+--+-- A daemon is told the @store@ setting when the setting was set, as+-- upstream's client tells it, and is told the reference as the setting+-- renders it ('storeOverride').+--+-- == Choosing+--+-- @auto@ opens the store directly when this process can keep its state+-- directory ('Nix.Store.Access.probeStoreWriting'), goes through the+-- daemon when it cannot and something is at the daemon's address+-- ('Nix.Daemon.Dial.addressPresence'), and otherwise opens the store+-- directly, where the opening fails as it would have.  It never connects:+-- a daemon that is not answering is a failure of the first operation+-- that needs it, as upstream's connection is made when its store is first+-- used.  A store that is named asks nothing of the machine.+module Nix.Daemon.StoreChoice+  ( -- * What names a store+    StoreTarget (..),+    parseStoreTarget,+    parseStoreTargetOn,+    storeReference,++    -- * What a daemon is sent+    StoreFlag (..),+    storeOverride,++    -- * Choosing+    StoreProbe (..),+    StoreChoice (..),+    chooseStore,+  )+where++import Control.Applicative ((<|>))+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BC+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe, isJust)+import Data.Text (Text)+import qualified Data.Text.Encoding as TE+import Data.Word (Word8)+import Nix.Daemon.ClientStore (DaemonAddress (..))+import Nix.Daemon.Dial (AddressPresence (..))+import Nix.Eval.Policy (PathRules (..), hostPathRules)+import Nix.Fetch.Url (Leniency (..), ParsedUrl (..), encodeUrlPath, isAbsoluteHostPath, parseUrl, percentDecode, renderAuthority, runChecked, urlPathToPath)+import Nix.Store.Access (StoreWriting (..))++-- ---------------------------------------------------------------------------+-- What names a store+-- ---------------------------------------------------------------------------++-- | What a store reference names.+data StoreTarget+  = -- | @auto@, or nothing: the store directly when this process can keep+    -- it, the daemon when it cannot and one is there, the store directly+    -- otherwise.+    AutoStore+  | -- | @daemon@, the daemon at its default address, or @unix:\/\/PATH@,+    -- the daemon at that address, as the bytes of a socket's path or on+    -- Windows a named pipe's.+    DaemonSocket !(Maybe ByteString)+  | -- | @local@, the platform store, or a directory, the store there,+    -- each opened directly.  The directory is as the reference spells it.+    LocalStore !(Maybe ByteString)+  deriving (Eq, Show)++-- | A store reference as the host reads it ('parseStoreTargetOn').+parseStoreTarget :: ByteString -> Either Text StoreTarget+parseStoreTarget = parseStoreTargetOn hostPathRules++-- | What a store reference names, or why nova-nix does not take it, under+-- the path rules given, which a path separator and a @unix:\/\/@ address+-- depend on.+--+-- The reference is read in the order upstream reads one: a value that is a+-- URL, one with a scheme, is the daemon at its address when the scheme is+-- @unix@ and is refused with any other, since nova-nix opens no other kind+-- of store; a value that is not a URL is @auto@ or nothing, @daemon@ or+-- @local@, or, when it has a path separator and no @:\/\/@, a store+-- directory, which nova-nix has always read @--store@ as and which+-- upstream reads as the root of a store beneath it; any other value, a+-- single word that is none of the first three included, is refused as a+-- store that cannot be parsed.  A value with a query (@?@) is refused+-- before any of this, as nova-nix opens no store that takes settings.+--+-- Windows adds three readings, each made before the URL is read, since the+-- URL grammar takes the value another way or not at all.  A value that+-- starts with the extended-length prefix (@\\\\?\\@) is a store directory,+-- and is read before the query refusal, since the prefix holds the @?@+-- that starts a query.  A drive path is a store directory, where a drive+-- path with a @\/@ is a URL whose scheme is the drive's letter.  A+-- @unix:\/\/@ address is a named pipe's path as written, which holds the+-- backslashes no URL holds.+parseStoreTargetOn :: PathRules -> ByteString -> Either Text StoreTarget+parseStoreTargetOn rules value =+  readReference rules value >>= \case+    ReferenceAuto -> Right AutoStore+    ReferenceDaemon -> Right (DaemonSocket Nothing)+    ReferenceLocal -> Right (LocalStore Nothing)+    ReferenceSocket _ address -> Right (DaemonSocket address)+    ReferenceDirectory directory -> Right (LocalStore (Just directory))++-- | A store reference read, before it is taken as a target: each kind of+-- reference nova-nix opens, with what rendering it needs.+data Reference+  = ReferenceAuto+  | ReferenceDaemon+  | ReferenceLocal+  | -- | A @unix:\/\/@ reference: what follows the scheme when upstream+    -- renders it, which is the authority and the path with its segments+    -- percent-encoded and none folded, and the address it names+    -- ('socketAddress').+    ReferenceSocket !ByteString !(Maybe ByteString)+  | -- | A directory, as the reference spells it.+    ReferenceDirectory !ByteString++-- | Read a reference in the order 'parseStoreTargetOn' describes.+readReference :: PathRules -> ByteString -> Either Text Reference+readReference rules value+  | WindowsPaths <- rules, extendedLengthPrefix `BS.isPrefixOf` value = Right (ReferenceDirectory value)+  | BC.elem queryMark value = Left ("store settings in a store's URL are not supported by nova-nix: '" <> shown value <> "'")+  | WindowsPaths <- rules, isAbsoluteHostPath rules value = Right (ReferenceDirectory value)+  | WindowsPaths <- rules, Just pipe <- BS.stripPrefix unixScheme value = socketReference rules pipe+  | (Right url, _) <- runChecked (parseUrl Lenient value) = urlReference rules value url+  | otherwise = spelledReference rules value++-- | The reference a URL is: the daemon at the address it renders as when+-- its scheme is @unix@, and otherwise one nova-nix does not open.+urlReference :: PathRules -> ByteString -> ParsedUrl -> Either Text Reference+urlReference rules value url+  | urlScheme url == unixSchemeName = socketReference rules (maybe BS.empty renderAuthority (urlAuthority url) <> encodeUrlPath (urlPath url))+  | otherwise = Left ("store '" <> shown value <> "' is not one nova-nix opens: it takes auto, daemon, local, unix://PATH or a store directory")++-- | The reference a value is that no URL grammar takes: @auto@ or+-- nothing, @daemon@, @local@, a path, or a value that cannot be parsed.+spelledReference :: PathRules -> ByteString -> Either Text Reference+spelledReference rules value+  | value `elem` [BS.empty, autoSpelling] = Right ReferenceAuto+  | value == daemonSpelling = Right ReferenceDaemon+  | value == localSpelling = Right ReferenceLocal+  | isNonUriPath rules value = Right (ReferenceDirectory value)+  | otherwise = Left ("Cannot parse Nix store '" <> shown value <> "'")++-- | Whether a value is a path and not a URL: it has no scheme separator,+-- and a path separator, so that a single word that might be special, as+-- @auto@ is, is not one.+isNonUriPath :: PathRules -> ByteString -> Bool+isNonUriPath rules value = not (schemeSeparator `BS.isInfixOf` value) && hasPathSeparator rules value++-- | Whether a value holds a path separator under the rules: @\/@, and on+-- Windows @\\@ too.+hasPathSeparator :: PathRules -> ByteString -> Bool+hasPathSeparator rules value = BS.elem slash value || (rules == WindowsPaths && BC.elem '\\' value)++-- | The spellings of the references that name no path.+autoSpelling, daemonSpelling, localSpelling :: ByteString+autoSpelling = "auto"+daemonSpelling = "daemon"+localSpelling = "local"++-- | The scheme of a daemon's address, what ends any scheme, and the two+-- together.+unixSchemeName, schemeSeparator, unixScheme :: ByteString+unixSchemeName = "unix"+schemeSeparator = "://"+unixScheme = unixSchemeName <> schemeSeparator++-- | What starts the settings of a store's URL.+queryMark :: Char+queryMark = '?'++-- | What starts a Windows path in the extended-length form.+extendedLengthPrefix :: ByteString+extendedLengthPrefix = "\\\\?\\"++-- | The byte that separates the components of a POSIX path.+slash :: Word8+slash = 0x2f++-- | The @unix:\/\/@ reference an address is, given the address as the+-- reference renders it.+socketReference :: PathRules -> ByteString -> Either Text Reference+socketReference rules rendered = ReferenceSocket rendered <$> socketAddress rules rendered++-- | The address a @unix:\/\/@ reference names: none for the daemon's+-- default, a named pipe's path as written on Windows, and on a POSIX+-- system a socket's path, absolute, percent-decoded and folded.+socketAddress :: PathRules -> ByteString -> Either Text (Maybe ByteString)+socketAddress rules address+  | BS.null address = Right Nothing+  | otherwise = case rules of+      WindowsPaths -> Right (Just address)+      PosixPaths -> Just <$> posixSocketPath address++-- | A socket's path from the address of a @unix:\/\/@ reference: the+-- address percent-decoded, split at @\/@ and put back together as a+-- path, which must be absolute, then folded.+posixSocketPath :: ByteString -> Either Text ByteString+posixSocketPath address = do+  decoded <- checked (percentDecode address)+  path <- checked (urlPathToPath PosixPaths (BS.split slash decoded))+  if BS.isPrefixOf rootPath path+    then Right (foldPath path)+    else Left ("not an absolute path: \"" <> shown path <> "\"")+  where+    checked = fst . runChecked+    rootPath = "/"++-- | An absolute path with its repeated separators, @.@ components and+-- @..@ components folded, as upstream folds a path it is given: lexically,+-- no link followed, a @..@ at the root dropped.+foldPath :: ByteString -> ByteString+foldPath path = BS.cons slash (BS.intercalate (BS.singleton slash) (reverse (foldl' step [] (BS.split slash path))))+  where+    step kept component+      | BS.null component || component == currentDirectory = kept+      | component == parentDirectory = drop 1 kept+      | otherwise = component : kept+    currentDirectory = "."+    parentDirectory = ".."++-- | Bytes shown in a message, any that are not UTF-8 replaced.+shown :: ByteString -> Text+shown = TE.decodeUtf8Lenient++-- | The reference a command uses, given what @--store@ says, what the+-- @store@ setting says where a source set it and what @NIX_REMOTE@ says,+-- the first of them that says anything and @auto@ when none does.  The+-- setting's default is @NIX_REMOTE@, so a setting a source set overrides+-- it, and the flag overrides both.  A setting or variable that is set to+-- nothing says the empty reference, which is @auto@, and so overrides+-- what is weaker than it.+storeReference :: Maybe ByteString -> Maybe ByteString -> Maybe ByteString -> ByteString+storeReference flag setting environment = fromMaybe autoSpelling (flag <|> setting <|> environment)++-- ---------------------------------------------------------------------------+-- What a daemon is sent+-- ---------------------------------------------------------------------------++-- | How a command's @--store@ flag sets the @store@ setting.+data StoreFlag+  = -- | The flag gives the setting a value and leaves the record of whether+    -- a source set it as it was, as the flag of upstream's @nix-build@ and+    -- its other legacy commands does: it changes what a setting that is+    -- already set holds, and a setting nothing set is not made one.+    ValueFlag+  | -- | The flag also marks the setting as set, as the flag every setting+    -- has in upstream's @nix@ command does.+    SettingFlag+  deriving (Eq, Show)++-- | The override a command tells its daemon for the @store@ setting, as+-- the map of the one setting it sends or no setting at all, given the+-- rules, how the command's flag sets the setting, and what @--store@, the+-- setting and @NIX_REMOTE@ say ('storeReference'); or why the reference+-- they name is not one nova-nix opens, as 'parseStoreTargetOn' says.+--+-- Upstream's client sends the settings that were set, each as the setting+-- renders its value.  The setting is set when a source set it, or when+-- the flag marks it ('SettingFlag'); @NIX_REMOTE@ only gives its default.+-- What is sent is the value the setting holds, which the flag has+-- replaced, rendered as upstream's setting renders it: @auto@ for the+-- empty reference and for @auto@, @daemon@, @local@, and @unix:\/\/@ and+-- the address as the reference spells it, a @unix:\/\/PATH@ with its+-- authority and path as they render and no path folded, and with a path+-- of one slash, such as @unix:\/PATH@, in the form of three.+--+-- A directory is not sent: its rendering names it by its absolute path,+-- which only IO can tell, and a command whose reference is a directory+-- opens the store directly and sends no daemon anything.+storeOverride :: PathRules -> StoreFlag -> Maybe ByteString -> Maybe ByteString -> Maybe ByteString -> Either Text (Map ByteString ByteString)+storeOverride rules how flag setting environment+  | not marked = Right Map.empty+  | otherwise = maybe Map.empty (Map.singleton storeSettingName) . renderReference <$> readReference rules (storeReference flag setting environment)+  where+    marked = isJust setting || (how == SettingFlag && isJust flag)++-- | A reference as upstream's @store@ setting renders it, or 'Nothing'+-- for a directory.+renderReference :: Reference -> Maybe ByteString+renderReference = \case+  ReferenceAuto -> Just autoSpelling+  ReferenceDaemon -> Just daemonSpelling+  ReferenceLocal -> Just localSpelling+  ReferenceSocket rendered _ -> Just (unixScheme <> rendered)+  ReferenceDirectory _ -> Nothing++-- | The name of the setting that says which store commands use.+storeSettingName :: ByteString+storeSettingName = "store"++-- ---------------------------------------------------------------------------+-- Choosing+-- ---------------------------------------------------------------------------++-- | What the machine is asked to choose by under @auto@, over the monad+-- the questions are asked in.+data StoreProbe m = StoreProbe+  { -- | Whether this process can keep the store directly+    -- ('Nix.Store.Access.probeStoreWriting').+    probeWriting :: !(m StoreWriting),+    -- | Whether anything is at the address given, the daemon's default+    -- ('Nix.Daemon.Dial.addressPresence').+    probePresence :: !(ByteString -> m AddressPresence)+  }++-- | Where a command's store is.+data StoreChoice+  = -- | Opened directly: the platform store for none, otherwise the+    -- directory the reference spelled.+    DirectStore !(Maybe ByteString)+  | -- | Through the daemon at an address.+    ThroughDaemon !DaemonAddress+  deriving (Eq, Show)++-- | Where the store a reference names is, given how to look at the machine+-- and the daemon's default address.  Only @auto@ looks: it asks whether+-- the store can be kept and, when it cannot, whether anything is at the+-- default address, and asks nothing further.  A daemon at the default+-- address, named or not, is a 'DefaultSocket'.+chooseStore :: (Monad m) => StoreProbe m -> ByteString -> StoreTarget -> m StoreChoice+chooseStore probe defaultAddress = \case+  AutoStore ->+    probeWriting probe >>= \case+      StoreWritable -> pure (DirectStore Nothing)+      StoreNotWritable ->+        probePresence probe defaultAddress >>= \case+          AddressPresent -> pure (ThroughDaemon (DefaultSocket defaultAddress))+          AddressAbsent -> pure (DirectStore Nothing)+  DaemonSocket Nothing -> pure (ThroughDaemon (DefaultSocket defaultAddress))+  DaemonSocket (Just address)+    | address == defaultAddress -> pure (ThroughDaemon (DefaultSocket address))+    | otherwise -> pure (ThroughDaemon (NamedSocket address))+  LocalStore directory -> pure (DirectStore directory)
+ src/Nix/Daemon/Wire.hs view
@@ -0,0 +1,261 @@+{-# LANGUAGE GeneralizedNewtypeDeriving #-}++-- | The framing upstream's worker protocol puts on bytes, as upstream's+-- @serialise.hh@ and @serialise.cc@ define it (at 2.35.4): every number is+-- a 64-bit little-endian word, a string is its length, its bytes and zero+-- padding to a multiple of eight, a list is its count and then its items,+-- and a framed stream is a run of chunks, each its length and its bytes,+-- ended by an empty one.+--+-- A t'Decoder' reads incrementally: 'startDecoding' gives a t'Decoding'+-- that asks for input until it has a value, so a connection hands it each+-- read as it arrives, and a framed stream is read a chunk at a time with+-- 'getFrame'.  Encoders are @bytestring@ 'Builder's.  Nothing here knows+-- what the values mean; "Nix.Daemon.Protocol" reads and writes those.+module Nix.Daemon.Wire+  ( -- * Decoding+    Decoder,+    DecodeError (..),+    malformed,+    Decoding (..),+    startDecoding,+    feedInput,+    runDecoder,++    -- ** Numbers+    getWord64,+    getWord32,+    getWord8,+    getInt64,+    getBool,+    getCount,++    -- ** Strings and lists+    getBytes,+    getList,++    -- ** Framed streams+    getFrame,++    -- * Encoding+    putNum,+    putBool,+    putBytes,+    putList,+    putFrame,+    putFrameEnd,+  )+where++import Control.Monad (replicateM, unless)+import Control.Monad.Except (ExceptT (..), runExceptT)+import qualified Data.Binary.Get as Get+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import Data.ByteString.Builder (Builder)+import qualified Data.ByteString.Builder as BB+import Data.Int (Int64)+import Data.Text (Text)+import qualified Data.Text as T+import Data.Word (Word32, Word64, Word8)++-- ---------------------------------------------------------------------------+-- Decoding+-- ---------------------------------------------------------------------------++-- | A reader of wire bytes.  It fails with upstream's message where+-- upstream's reader throws, and asks for more input where upstream's would+-- block on its source.+newtype Decoder a = Decoder (ExceptT Text Get.Get a)+  deriving (Functor, Applicative, Monad)++-- | Why a t'Decoder' gave no value.+data DecodeError+  = -- | The input ended inside a value, where upstream's read throws+    -- @EndOfFile@.+    InputEnded+  | -- | Bytes upstream refuses, with the message it refuses them with.+    Malformed !Text+  deriving (Eq, Show)++-- | Refuse what has been read, with upstream's message for it.+malformed :: Text -> Decoder a+malformed = Decoder . ExceptT . pure . Left++-- | A decode in progress.+data Decoding a+  = -- | The value, and the input that followed it.+    Decoded !a !ByteString+  | -- | More input is needed: the next chunk, or 'Nothing' at the end of+    -- the input.+    NeedInput (Maybe ByteString -> Decoding a)+  | -- | The input holds no value: why, and the input after the bytes the+    -- refused read took, where upstream's source is left when its read+    -- throws.+    DecodeFailed !DecodeError !ByteString++-- | Begin decoding, before any input has arrived.+startDecoding :: Decoder a -> Decoding a+startDecoding (Decoder reader) = fromBinary (Get.runGetIncremental (runExceptT reader))+  where+    -- A binary failure is always the end of the input: no reader here+    -- calls 'fail', and every refusal is the 'Left' of 'Malformed'.+    fromBinary step = case step of+      Get.Done rest _ (Right value) -> Decoded value rest+      Get.Done rest _ (Left message) -> DecodeFailed (Malformed message) rest+      Get.Fail rest _ _ -> DecodeFailed InputEnded rest+      Get.Partial more -> NeedInput (fromBinary . more)++-- | Hand a decode the next chunk of input, or 'Nothing' at its end.  A+-- decode that is over keeps a chunk as input that followed it.+feedInput :: Maybe ByteString -> Decoding a -> Decoding a+feedInput chunk decoding = case decoding of+  NeedInput more -> more chunk+  Decoded value rest -> Decoded value (maybe rest (rest <>) chunk)+  DecodeFailed err rest -> DecodeFailed err (maybe rest (rest <>) chunk)++-- | Decode a value from input that is all there is, giving the value and+-- the bytes after it.+runDecoder :: Decoder a -> ByteString -> Either DecodeError (a, ByteString)+runDecoder reader input = case feedInput Nothing (feedInput (Just input) (startDecoding reader)) of+  Decoded value rest -> Right (value, rest)+  DecodeFailed err _ -> Left err+  -- A decode told that its input ended never asks for more.+  NeedInput _ -> Left InputEnded++-- | Lift a reader of @binary@'s into a t'Decoder'.+fromGet :: Get.Get a -> Decoder a+fromGet = Decoder . ExceptT . fmap Right++-- ---------------------------------------------------------------------------+-- Numbers+-- ---------------------------------------------------------------------------++-- | A 64-bit word, as upstream's @readNum<uint64_t>@ reads it.+getWord64 :: Decoder Word64+getWord64 = fromGet Get.getWord64le++-- | A word read as upstream's @readNum<T>@ reads it for a type whose+-- largest value is @bound@: a larger one is refused, and the message names+-- the type as @typeid(T).name()@ does under the Itanium ABI on 64-bit+-- Linux, which is what upstream prints there.+getBounded :: Text -> Word64 -> Decoder Word64+getBounded typeName bound = getWord64 >>= checked+  where+    checked n+      | n > bound = malformed ("serialised integer " <> T.pack (show n) <> " is too large for type '" <> typeName <> "'")+      | otherwise = pure n++-- | A number upstream reads as an @unsigned int@ (its @readInt@).+getWord32 :: Decoder Word32+getWord32 = fromIntegral <$> getBounded "j" (fromIntegral (maxBound :: Word32))++-- | A number upstream reads as a @uint8_t@.+getWord8 :: Decoder Word8+getWord8 = fromIntegral <$> getBounded "h" (fromIntegral (maxBound :: Word8))++-- | A number upstream reads as an @int64_t@ or a @time_t@: a word above+-- the largest of those is refused, so a negative one, which upstream+-- writes as its two's complement, does not read back.+getInt64 :: Decoder Int64+getInt64 = fromIntegral <$> getBounded "l" (fromIntegral (maxBound :: Int64))++-- | A flag, which upstream reads as a @bool@ through @readNum@, so a word+-- other than 0 or 1 is refused.+getBool :: Decoder Bool+getBool = (/= 0) <$> getBounded "b" 1++-- | A length or a count, which upstream reads as a @size_t@.  One larger+-- than this process can hold is refused; upstream's @size_t@ holds every+-- word, and it goes on to allocate a string that long or to read a list's+-- items until its input ends.+getCount :: Decoder Int+getCount = fromIntegral <$> getBounded "m" (fromIntegral (maxBound :: Int))++-- ---------------------------------------------------------------------------+-- Strings and lists+-- ---------------------------------------------------------------------------++-- | Bytes are padded with zeros to a multiple of this many.+wordBytes :: Int+wordBytes = 8++-- | How many zero bytes follow a string of the given length.+paddingLength :: Int -> Int+paddingLength len = negate len `mod` wordBytes++-- | A string, as upstream's @readString@ reads it: its length, its bytes,+-- and padding, which must be zeros.  The bytes are copied out of the+-- input, so a string kept does not keep the chunk it arrived in.+getBytes :: Decoder ByteString+getBytes = do+  len <- getCount+  bytes <- fromGet (Get.getByteString len)+  padding <- fromGet (Get.getByteString (paddingLength len))+  unless (BS.all (== 0) padding) (malformed "non-zero padding")+  pure $! BS.copy bytes++-- | A list: its count, then each item.+getList :: Decoder a -> Decoder [a]+getList item = getCount >>= (`replicateM` item)++-- ---------------------------------------------------------------------------+-- Framed streams+-- ---------------------------------------------------------------------------++-- | The next chunk of a framed stream, or 'Nothing' at the empty chunk+-- that ends it, as upstream's @FramedSource@ reads them: a length read as+-- an @unsigned int@, then that many bytes with no padding.  The chunk is+-- a slice of the input, for a caller that passes it on rather than keeping+-- it.+getFrame :: Decoder (Maybe ByteString)+getFrame = getWord32 >>= chunkOf+  where+    chunkOf len+      | len == 0 = pure Nothing+      | otherwise = Just <$> fromGet (Get.getByteString (fromIntegral len))++-- ---------------------------------------------------------------------------+-- Encoding+-- ---------------------------------------------------------------------------++-- | A number as the 64-bit little-endian word upstream writes for every+-- integer type; a negative one is its two's complement, as upstream's+-- conversion to @uint64_t@ makes it.+putNum :: (Integral a) => a -> Builder+putNum n = BB.word64LE (fromIntegral n)++-- | A flag, as 0 or 1.+putBool :: Bool -> Builder+putBool = putNum . fromEnum++-- | A string: its length, its bytes and zero padding.+putBytes :: ByteString -> Builder+putBytes bytes =+  putNum len <> BB.byteString bytes <> BB.byteString (BS.replicate (paddingLength len) 0)+  where+    len = BS.length bytes++-- | A list: its count, then each item.+putList :: (a -> Builder) -> [a] -> Builder+putList item items = putNum (length items) <> foldMap item items++-- | The longest chunk upstream's @FramedSource@ reads, whose length is an+-- @unsigned int@.+maxFrameLength :: Int+maxFrameLength = fromIntegral (maxBound :: Word32)++-- | Bytes as chunks of a framed stream, as upstream's @FramedSink@ writes+-- them: each chunk its length and its bytes.  Nothing is written for no+-- bytes, since an empty chunk ends the stream, and bytes longer than a+-- chunk can hold go as several.+putFrame :: ByteString -> Builder+putFrame bytes+  | BS.null bytes = mempty+  | otherwise =+      let (chunk, rest) = BS.splitAt maxFrameLength bytes+       in putNum (BS.length chunk) <> BB.byteString chunk <> putFrame rest++-- | The empty chunk that ends a framed stream.+putFrameEnd :: Builder+putFrameEnd = putNum (0 :: Word64)
src/Nix/DependencyGraph.hs view
@@ -11,6 +11,7 @@      -- * Graph construction     buildDepGraph,+    buildDepGraphFrom,      -- * Topological sort     topoSort,@@ -39,8 +40,11 @@     dnDrvPath :: !StorePath,     -- | The parsed derivation.     dnDerivation :: !Derivation,-    -- | Direct dependency .drv paths (from drvInputDrvs keys).-    dnDeps :: ![StorePath]+    -- | Each direct dependency's .drv path, with the outputs of it this+    -- derivation names in 'drvInputDrvs': the outputs upstream's goal for+    -- the dependency wants (@DerivationGoal::gaveUpOnSubstitution@ at+    -- 2.24.9).+    dnDeps :: !(Map StorePath (Set Text))   }   deriving (Eq, Show) @@ -52,7 +56,9 @@ data TopoResult   = -- | Successfully sorted: build order with leaves (no deps) first.     TopoSorted ![StorePath]-  | -- | Cycle detected: the paths involved in the cycle.+  | -- | Cycle detected: the paths the sort placed before it stalled,+    -- leaves first, none of them on a cycle.  The paths on a cycle, and+    -- those depending on one, are the rest of the graph.     TopoCycle ![StorePath]   deriving (Eq, Show) @@ -74,15 +80,38 @@   Derivation ->   StorePath ->   m (Either Text DepGraph)-buildDepGraph readDrv rootDrv rootPath =-  runExceptT (go Map.empty (Seq.singleton (rootPath, rootDrv)))+buildDepGraph readDrv rootDrv rootPath = runExceptT (graphFrom readDrv [(rootPath, rootDrv)])++-- | Build the dependency graph of several root derivations, each read+-- with @readDrv@ as an input is, so the graph holds every root and every+-- derivation one of them depends on.  The roots are read in the order of+-- their paths, and @Left@ answers for the first .drv file that cannot be+-- read, a root's included.+buildDepGraphFrom ::+  (Monad m) =>+  (StorePath -> m (Either Text Derivation)) ->+  [StorePath] ->+  m (Either Text DepGraph)+buildDepGraphFrom readDrv roots =+  runExceptT (traverse readRoot (Set.toAscList (Set.fromList roots)) >>= graphFrom readDrv)   where+    readRoot root = (,) root <$> ExceptT (readDrv root)++-- | The graph reached from derivations already read, reading each input+-- the first time it is reached.+graphFrom ::+  (Monad m) =>+  (StorePath -> m (Either Text Derivation)) ->+  [(StorePath, Derivation)] ->+  ExceptT Text m DepGraph+graphFrom readDrv roots = go Map.empty (Seq.fromList roots)+  where     go visited queue = case Seq.viewl queue of       Seq.EmptyL -> pure (DepGraph visited)       (sp, drv) Seq.:< rest         | Map.member sp visited -> go visited rest         | otherwise -> do-            let deps = Map.keys (drvInputDrvs drv)+            let deps = Map.map Set.fromList (drvInputDrvs drv)                 node =                   DepNode                     { dnDrvPath = sp,@@ -90,7 +119,7 @@                       dnDeps = deps                     }                 visitedWithNode = Map.insert sp node visited-            newItems <- resolveNewDeps readDrv visitedWithNode deps+            newItems <- resolveNewDeps readDrv visitedWithNode (Map.keys deps)             go visitedWithNode (foldl' (|>) rest newItems)  -- | Resolve unvisited dependencies by reading their .drv files.@@ -126,7 +155,7 @@ -- | Count how many of a node's dependencies exist in the graph. countGraphDeps :: Set StorePath -> DepNode -> Int countGraphDeps allNodes node =-  length (filter (`Set.member` allNodes) (dnDeps node))+  Set.size (Set.intersection allNodes (Map.keysSet (dnDeps node)))  -- | Build reverse adjacency: maps each dep to the list of nodes that depend on it. buildReverseAdj :: Map StorePath DepNode -> Set StorePath -> Map StorePath [StorePath]@@ -134,7 +163,7 @@   Map.foldlWithKey' addReverse (Map.fromSet (const []) allNodes) graph   where     addReverse acc sp node =-      let depsInGraph = filter (`Set.member` allNodes) (dnDeps node)+      let depsInGraph = filter (`Set.member` allNodes) (Map.keys (dnDeps node))        in foldl' (flip (Map.adjust (sp :))) acc depsInGraph  -- | Kahn's algorithm main loop.@@ -188,7 +217,7 @@     go !visited queue = case Seq.viewl queue of       Seq.EmptyL -> visited       sp Seq.:< rest ->-        enqueueFresh visited rest (maybe [] dnDeps (Map.lookup sp graph))+        enqueueFresh visited rest (maybe [] (Map.keys . dnDeps) (Map.lookup sp graph))     -- Mark and enqueue each dep not yet seen, then continue the walk.     enqueueFresh !visited !queue deps = case deps of       [] -> go visited queue@@ -199,4 +228,4 @@ -- | Direct dependencies of a store path. directDeps :: DepGraph -> StorePath -> [StorePath] directDeps (DepGraph graph) sp =-  maybe [] dnDeps (Map.lookup sp graph)+  maybe [] (Map.keys . dnDeps) (Map.lookup sp graph)
src/Nix/Derivation.hs view
@@ -18,7 +18,7 @@ -- -- @ -- Derive(---   [("out", "\/nix\/store\/abc...-hello-2.12.1", "", "sha256")],+--   [("out", "\/nix\/store\/abc...-hello-2.12.1", "", "")], --   [("\/nix\/store\/def...-zlib-1.3.1.drv", ["out"]), --    ("\/nix\/store\/ghi...-bash-5.2.drv", ["out"])], --   ["\/nix\/store\/jkl...-hello-2.12.1.tar.gz"],@@ -45,19 +45,35 @@ -- 6. __Args__: command-line arguments to the builder -- 7. __Environment__: environment variables for the build ----- The HASH of this .drv file (after ATerm serialization) determines the--- output store path.  Change any input yields a different hash and a different output--- path.  This is how Nix achieves reproducibility.+-- An input-addressed output's store path comes from a hash of this+-- derivation's ATerm with every output's path, hash fields and variable+-- empty and each input derivation replaced by that same hash of its own+-- ('inputAddressed'); the hash of the .drv file itself names the .drv+-- ('drvFile').  Change any input and you get a different hash and a+-- different output path.  This is how Nix achieves reproducibility. module Nix.Derivation   ( -- * Derivation type     Derivation (..),     DerivationOutput (..),+    fixedOutput,+    impureOutputHash,      -- * ATerm serialization     toATerm,     toATermForHash,     fromATerm, +    -- * The .drv file+    drvExtension,+    fixedOutputModulo,+    inputAddressedModulo,+    DrvFile,+    drvFileDerivation,+    drvFileATerm,+    drvFilePath,+    drvFile,+    inputAddressed,+     -- * Platform     Platform (..),     currentPlatform,@@ -73,7 +89,7 @@ import qualified Data.ByteString.Char8 as BC import qualified Data.ByteString.Lazy as LBS import Data.Function (on)-import Data.List (sortBy)+import Data.List (sort, sortBy) import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import qualified Data.Set as Set@@ -81,6 +97,7 @@ import qualified Data.Text as T import qualified Data.Text.Encoding as TE import Data.Text.Encoding.Error (lenientDecode)+import Nix.Hash (makeOutputPath, makeTextPath, sha256Digest) import Nix.Store.Path (StorePath) import qualified Nix.Store.Path as SP import qualified System.Info as SI@@ -115,10 +132,12 @@ -- @extra-platforms@ lists them: an x86_64 Linux kernel runs i686 binaries, -- so upstream adds @i686-linux@ on @x86_64-linux@ (outside WSL1, which -- cannot), and 64-bit Windows runs i686 binaries through WoW64, the same--- rule for the platform upstream has no entry for yet.  Upstream also adds--- @x86_64-darwin@ on @aarch64-darwin@ when Rosetta is installed; that is a--- filesystem probe, not a property of the platform, and is not modelled--- here, so such a build needs a launcher named on the command line.+-- rule for the platform upstream has no entry for.  Upstream also adds+-- @x86_64-darwin@ on @aarch64-darwin@ when Rosetta is installed.  The WSL1+-- exception and the Rosetta check probe the running machine, not the+-- platform, and neither is modelled here: @x86_64-linux@ under WSL1 still+-- lists @i686-linux@, and a Rosetta build needs a launcher named on the+-- command line. extraPlatforms :: Platform -> [Platform] extraPlatforms X86_64_Linux = [I686_Linux] extraPlatforms X86_64_Windows = [I686_Windows]@@ -167,9 +186,12 @@     doName :: !Text,     -- | The store path this output will be placed at.     doPath :: !StorePath,-    -- | Hash algorithm (empty for input-addressed, "sha256" for fixed).+    -- | The content-addressing method and hash algorithm, such as+    -- @sha256@ or @r:sha256@: empty for an input-addressed output.     doHashAlgo :: !Text,-    -- | Expected hash (empty for input-addressed, actual hash for fixed).+    -- | The hash that fixes the output: empty for an input-addressed or+    -- a floating content-addressed output, and upstream's @impure@+    -- marker for an impure one.     doHash :: !Text   }   deriving (Eq, Show)@@ -200,6 +222,34 @@   }   deriving (Eq, Show) +-- | The output of a fixed-output derivation: its one output, @out@, with+-- the hash that fixes it, as upstream's derivation type has it+-- (@BasicDerivation::type@ in derivations.cc at 2.24.9, @derivation::type@+-- there at 2.36.0).  A floating content-addressed output names an algorithm+-- and no hash, and an impure one upstream's @impure@ marker; neither is+-- fixed.  Nor is a fixed output beside others or named otherwise, whose+-- derivation upstream refuses (the same function).+fixedOutput :: Derivation -> Maybe DerivationOutput+fixedOutput drv = case drvOutputs drv of+  [out]+    | doName out == fixedOutputName,+      not (T.null (doHashAlgo out)),+      not (T.null (doHash out)),+      doHash out /= impureOutputHash ->+        Just out+  _ -> Nothing++-- | The name of the one output a fixed-output derivation has.+fixedOutputName :: Text+fixedOutputName = "out"++-- | What an impure derivation's output records as its hash, upstream's+-- @DerivationOutput::Impure@ in a @.drv@ (@parseDerivationOutput@ in+-- derivations.cc at 2.24.9, @parseOutput@ in derivation\/aterm.cc at+-- 2.36.0).+impureOutputHash :: Text+impureOutputHash = "impure"+ -- | Serialize a derivation to ATerm format (the .drv file format). -- This serialization is what gets hashed to compute the store path, -- so the result is BYTES: env values, args, and the builder land in it@@ -356,6 +406,103 @@     escapeOne '\t' = "\\t"     -- Unreachable: 'BC.break atermSpecial' only stops at the five specials.     escapeOne c = B.charUtf8 c++-- ---------------------------------------------------------------------------+-- The .drv file+-- ---------------------------------------------------------------------------++-- | A derivation and the @.drv@ file it is written as: its ATerm, and the+-- text path that ATerm, its inputs and its name give it, as upstream's+-- @infoForDerivation@ makes them (derivations.cc).  The constructor is not+-- exported, so the bytes are always the derivation's rendering and the path+-- always theirs.+data DrvFile = DrvFile !Derivation !ByteString !StorePath+  deriving (Eq, Show)++-- | The derivation the file holds.+drvFileDerivation :: DrvFile -> Derivation+drvFileDerivation (DrvFile drv _ _) = drv++-- | The file's contents: the derivation's 'toATerm'.+drvFileATerm :: DrvFile -> ByteString+drvFileATerm (DrvFile _ aterm _) = aterm++-- | The file's store path, the derivation's @drvPath@.+drvFilePath :: DrvFile -> StorePath+drvFilePath (DrvFile _ _ path) = path++-- | The @.drv@ file of a derivation named @name@: the text path named+-- @name.drv@ for its ATerm, referring to its input sources and input+-- derivations and not to its outputs.  'Left' when @name.drv@ breaks the+-- store-path name rules, as 'makeTextPath' refuses it.+drvFile :: Text -> Derivation -> Either SP.BadStorePath DrvFile+drvFile name drv =+  DrvFile drv aterm <$> makeTextPath (name <> drvExtension) (sha256Digest aterm) references+  where+    aterm = toATerm drv+    references = drvInputSrcs drv <> Map.keys (drvInputDrvs drv)++-- | What a derivation's file name ends in, after the derivation's name.+drvExtension :: Text+drvExtension = ".drv"++-- | The modulo hash of a fixed-output derivation, as upstream hashes one+-- for what depends on it: the SHA-256 of+-- @fixed:out:\<algo\>:\<hash\>:\<path\>@, which leaves the rest of the+-- derivation out, so what depends on a fixed output does not change when+-- the way it is fetched does.  'Nothing' for a derivation that is not one+-- output named @out@ with a hash.+fixedOutputModulo :: Derivation -> Maybe ByteString+fixedOutputModulo drv = case drvOutputs drv of+  [DerivationOutput name outPath algoField hashHex]+    | name == fixedOutputName,+      not (T.null algoField),+      not (T.null hashHex) ->+        Just (sha256Digest (TE.encodeUtf8 ("fixed:out:" <> algoField <> ":" <> hashHex <> ":" <> SP.storePathToText SP.defaultStoreDir outPath)))+  _ -> Nothing++-- | The modulo hash of any other derivation, as upstream hashes it, given+-- the modulo hash (hex) of each input+-- derivation with the outputs taken from it: the SHA-256 of its rendering+-- with those hashes in place of the input derivations ('toATermForHash').+inputAddressedModulo :: [(Text, [Text])] -> Derivation -> ByteString+inputAddressedModulo inputHashes drv = sha256Digest (toATermForHash False (Just inputHashes) drv)++-- | The @.drv@ file of a derivation named @name@ with every output+-- input-addressed.  Upstream makes one by deferring its outputs with their+-- variables empty, as @derivationStrict@ does (@derivationStrictInternal@+-- in primops.cc) and @nix develop@ does to a fixed or input-addressed+-- target (@getDerivationEnvironment@ in develop.cc), then filling the+-- outputs in (@fillInOutputPaths@ in derivations.cc) and writing the result+-- (@writeDerivation@, from @derivationStrictInternal@).+--+-- @inputHashes@ pairs the modulo hash (hex) of each input derivation with+-- the outputs taken from it, as 'toATermForHash' substitutes them.  Each+-- output keeps its name and gets the path @makeOutputPath@ gives for+-- upstream's masked @hashDerivationModulo@ in derivations.cc: the+-- hash of the rendering with every output's path, hash fields and variable+-- empty and the input hashes in place of the input derivations.  The+-- variable of each output's name then holds its path.  Whatever the+-- outputs and their variables held before counts for nothing, and the rest+-- of the derivation is kept.+--+-- 'Left' on a name the store-path rules refuse: an output's composed name+-- first, in name order, then @name.drv@, as upstream refuses them.+inputAddressed :: Text -> [(Text, [Text])] -> Derivation -> Either SP.BadStorePath DrvFile+inputAddressed name inputHashes drv = do+  outputs <- traverse filledIn (sort (map doName (drvOutputs drv)))+  drvFile name drv {drvOutputs = outputs, drvEnv = foldr withPath (drvEnv drv) outputs}+  where+    masked =+      drv+        { drvOutputs = [output {doHashAlgo = "", doHash = ""} | output <- drvOutputs drv],+          drvEnv = foldr (\output -> Map.insert (doName output) "") (drvEnv drv) (drvOutputs drv)+        }+    moduloHash = sha256Digest (toATermForHash True (Just inputHashes) masked)+    filledIn outputName = do+      path <- makeOutputPath outputName moduloHash name+      pure (DerivationOutput outputName path "" "")+    withPath output = Map.insert (doName output) (TE.encodeUtf8 (SP.storePathToText SP.defaultStoreDir (doPath output)))  -- --------------------------------------------------------------------------- -- ATerm parser (hand-rolled recursive descent)
+ src/Nix/Develop/Capture.hs view
@@ -0,0 +1,208 @@+-- | The derivation @nix develop@ builds to capture a target's build+-- environment, as upstream Nix 2.35.4 makes it+-- (@getDerivationEnvironment@ in @src\/nix\/develop.cc@).+--+-- The capture is the target's derivation with upstream's @get-env.sh@ as+-- its builder's one argument.  Its builder sources the stdenv's setup as+-- the target's build would, then writes what bash holds as JSON to the+-- first output, which "Nix.Develop.Environment" reads.  The checks on+-- what the outputs refer to are dropped, the derivation is renamed+-- @NAME-env@, and its outputs are input-addressed again, so a fixed-output+-- target's capture is input-addressed too.+--+-- Everything here is pure: the caller adds the script to the store,+-- writes and builds the capture, and reads which of its outputs holds+-- the environment.+module Nix.Develop.Capture+  ( -- * The script+    getEnvScriptName,+    getEnvScriptContents,+    getEnvScriptPath,++    -- * The capture+    CaptureFailure (..),+    captureFailureMessage,+    captureDerivation,++    -- * The environment's output+    OutputObject (..),+    environmentOutput,+    noEnvironmentMessage,+  )+where++import Data.Bifunctor (first)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BC+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (listToMaybe)+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Word (Word64)+import Nix.Derivation (Derivation (..), DerivationOutput (..), DrvFile, impureOutputHash, inputAddressed)+import Nix.Derivation.StructuredAttrs (StructuredAttrs (..), encodeStructuredAttrs, structuredAttrsKey)+import Nix.Hash (makeTextPath, sha256Digest)+import Nix.Json (Json (..), parseJson)+import Nix.Store.Path (BadStorePath, StorePath)+import qualified Nix.Store.Path as SP++-- ---------------------------------------------------------------------------+-- The script+-- ---------------------------------------------------------------------------++-- | The name upstream adds @get-env.sh@ to the store under.+getEnvScriptName :: Text+getEnvScriptName = "get-env.sh"++-- | What upstream stores for @get-env.sh@, given the file's bytes: a+-- newline, then the file.  Upstream's build embeds the file in a raw+-- string literal its generator opens with @R"__NIX_STR(@ and a newline (the+-- @gen_header@ generator in+-- @nix-meson-build-support\/generate-header\/meson.build@, from 2.34.9), so+-- the string, and the store object made from it, starts with that newline.+getEnvScriptContents :: ByteString -> ByteString+getEnvScriptContents = BC.cons '\n'++-- | The store path of @get-env.sh@, given the file's bytes: a text object+-- with no references, as upstream adds it (@getDerivationEnvironment@ in+-- develop.cc).+getEnvScriptPath :: ByteString -> Either BadStorePath StorePath+getEnvScriptPath file = makeTextPath getEnvScriptName (sha256Digest (getEnvScriptContents file)) []++-- ---------------------------------------------------------------------------+-- The capture+-- ---------------------------------------------------------------------------++-- | Why a derivation has no capture.+data CaptureFailure+  = -- | Its builder's base name is not @bash@.+    NotBashBuilder+  | -- | An output is floating content-addressed or impure, which upstream+    -- keeps in the capture and nova-nix builds for no derivation.+    UncapturableOutputs+  | -- | Its structured attributes are not a JSON object, with why.+    UnreadableStructuredAttrs !Text+  | -- | The capture's name breaks the store-path name rules.+    BadCaptureName !BadStorePath+  deriving (Eq, Show)++-- | A capture failure in upstream's words where upstream has them.+captureFailureMessage :: CaptureFailure -> Text+captureFailureMessage failure = case failure of+  NotBashBuilder -> "'nix develop' only works on derivations that use 'bash' as their builder"+  UncapturableOutputs -> "the derivation has a floating content-addressed or impure output, which nova-nix does not build"+  UnreadableStructuredAttrs reason -> "cannot process " <> structuredAttrsKey <> " attribute: " <> reason+  BadCaptureName bad -> SP.badStorePathText bad++-- | The capture of the derivation whose @.drv@ is named @NAME.drv@, given+-- @get-env.sh@'s store path and the modulo hashes of its input+-- derivations as 'inputAddressed' takes them.  Upstream's steps+-- (@getDerivationEnvironment@ in develop.cc):+--+-- * a builder whose base name is not @bash@ is refused;+-- * the script is the one argument, and an input source;+-- * the checks on what the outputs refer to are removed: the four+--   variables, or under structured attributes their @outputChecks@, with+--   @__json@ written again as nlohmann's @dump()@ writes it+--   (@StructuredAttrs::unparse@ in parsed-derivations.cc);+-- * @name@ is @NAME-env@, the capture's name, and a variable even under+--   structured attributes;+-- * each input-addressed or fixed output is deferred and then filled in+--   input-addressed (@fillInOutputPaths@).+--+-- Everything else is kept.  An output that is neither, which upstream+-- would keep as it is, is refused.+captureDerivation :: StorePath -> Text -> [(Text, [Text])] -> Derivation -> Either CaptureFailure DrvFile+captureDerivation script name inputHashes drv+  | builderBaseName (drvBuilder drv) /= bashBuilder = Left NotBashBuilder+  | not (capturable drv) = Left UncapturableOutputs+  | otherwise = do+      env <- withoutChecks (drvEnv drv)+      first BadCaptureName $+        inputAddressed+          captureName+          inputHashes+          drv+            { drvArgs = [TE.encodeUtf8 (SP.storePathToText SP.defaultStoreDir script)],+              drvInputSrcs = if script `elem` drvInputSrcs drv then drvInputSrcs drv else drvInputSrcs drv <> [script],+              drvEnv = Map.insert "name" (TE.encodeUtf8 captureName) env+            }+  where+    captureName = name <> captureSuffix++-- | What upstream appends to the target's name.+captureSuffix :: Text+captureSuffix = "-env"++-- | The base name a builder must have.+bashBuilder :: ByteString+bashBuilder = "bash"++-- | Upstream's @baseNameOf@ (file-system.cc): what follows the last @/@, once+-- trailing ones but the first byte are dropped.+builderBaseName :: ByteString -> ByteString+builderBaseName path = case BS.uncons path of+  Nothing -> BS.empty+  Just (start, rest) -> BC.takeWhileEnd (/= '/') (BS.cons start (BC.dropWhileEnd (== '/') rest))++-- | Whether every output is one upstream defers in the capture: an+-- input-addressed output, or a fixed one, beside others or under another+-- name than @out@ too, since upstream defers each before anything reads+-- the derivation's outputs together.+capturable :: Derivation -> Bool+capturable = all deferred . drvOutputs+  where+    deferred output = T.null (doHashAlgo output) || not (T.null (doHash output) || doHash output == impureOutputHash)++-- | The environment less the checks on what the outputs refer to+-- (@getDerivationEnvironment@ in develop.cc).  A derivation is structured+-- when it has @__json@, as upstream's @StructuredAttrs::tryExtract@ in+-- parsed-derivations.cc decides, and its @__json@ is read as+-- @StructuredAttrs::parse@ there reads it, into an object (the+-- @structuredAttrs@ field in parsed-derivations.hh): @null@ is refused there,+-- where 'Nix.Derivation.StructuredAttrs.decodeStructuredAttrs', which reads+-- the entry for a build as 2.24.9 does, takes it as an empty object.+withoutChecks :: Map Text ByteString -> Either CaptureFailure (Map Text ByteString)+withoutChecks env = case Map.lookup structuredAttrsKey env of+  Nothing -> Right (foldr Map.delete env referenceChecks)+  Just encoded -> do+    text <- first (UnreadableStructuredAttrs . T.pack . show) (TE.decodeUtf8' encoded)+    parsed <- first UnreadableStructuredAttrs (parseJson text)+    case parsed of+      JsonObject attrs -> Right (Map.insert structuredAttrsKey (encodeStructuredAttrs (StructuredAttrs (Map.delete outputChecks attrs))) env)+      _ -> Left (UnreadableStructuredAttrs "type must be object")++-- | The structured attribute that holds the checks.+outputChecks :: Text+outputChecks = "outputChecks"++-- | The variables that hold the checks without structured attributes.+referenceChecks :: [Text]+referenceChecks = ["allowedReferences", "allowedRequisites", "disallowedReferences", "disallowedRequisites"]++-- ---------------------------------------------------------------------------+-- The environment's output+-- ---------------------------------------------------------------------------++-- | What one of a capture's built outputs is, as upstream's @maybeLstat@+-- of its root answers.+data OutputObject+  = -- | A regular file of this many bytes.+    RegularFile !Word64+  | -- | A directory or a symlink.+    NotRegularFile+  deriving (Eq, Show)++-- | The output the environment is read from: the first, in name order,+-- that is a regular file of at least one byte, as upstream reads the+-- outputs (@getDerivationEnvironment@ in develop.cc).  'Nothing' when none+-- is, where upstream fails with 'noEnvironmentMessage'.+environmentOutput :: Map Text OutputObject -> Maybe Text+environmentOutput outputs = listToMaybe [name | (name, RegularFile size) <- Map.toAscList outputs, size > 0]++-- | Upstream's failure when no output holds an environment.+noEnvironmentMessage :: Text+noEnvironmentMessage = "get-env.sh failed to produce an environment"
+ src/Nix/Develop/Environment.hs view
@@ -0,0 +1,546 @@+-- | The build environment @nix develop@ replays, and the bash script that+-- replays it, as upstream Nix 2.35.4 makes them (@src\/nix\/develop.cc@).+--+-- A capture builds a copy of the target's derivation whose builder runs+-- upstream's @get-env.sh@: it sources the stdenv's setup, then writes+-- the variables and functions bash holds, less bash's own, as JSON.  That+-- document is a t'BuildEnvironment', read by 'parseBuildEnvironment' and written by+-- 'buildEnvironmentJson'.  'environmentScript' turns one into the script+-- @print-dev-env@ prints, which sets each variable and function again+-- with each output's path moved under the working directory, and+-- 'renderRcfile' wraps that script for the shell @develop@ starts.+--+-- Everything here is pure: the caller reads the capture, writes the+-- files, and starts the shell.  A path is the bytes nova-nix holds for it+-- ("Nix.HostPath"), and the scripts are bytes, since a path need not be+-- UTF-8.+module Nix.Develop.Environment+  ( -- * The captured environment+    BuildEnvironment (..),+    Variable (..),+    AttrsFiles (..),+    parseBuildEnvironment,+    buildEnvironmentJson,++    -- * The environment script+    ignoreVars,+    escapeShellArgAlways,+    ScriptDirectories (..),+    EnvironmentScript (..),+    ScriptFile (..),+    environmentScript,+    appendPath,++    -- * The rcfile+    Shell (..),+    ShellMode (..),+    Prompt (..),+    renderRcfile,+  )+where++import Control.Monad (foldM)+import Data.Bifunctor (first)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Builder as BB+import qualified Data.ByteString.Lazy as BL+import Data.Foldable (toList)+import Data.List (intersperse)+import Data.List.NonEmpty (NonEmpty)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Nix.Json (Json (..), parseJson)++-- ---------------------------------------------------------------------------+-- The captured environment+-- ---------------------------------------------------------------------------++-- | What @get-env.sh@ captured from a builder's bash: upstream's+-- @BuildEnvironment@ in develop.cc.+data BuildEnvironment = BuildEnvironment+  { -- | Each variable, by name.+    beVariables :: !(Map Text Variable),+    -- | Each function's body, by name: what bash's @type@ prints between+    -- the function's outer braces.+    beFunctions :: !(Map Text Text),+    -- | The structured attributes' files the builder read, when the+    -- derivation has structured attributes.+    beAttrsFiles :: !(Maybe AttrsFiles)+  }+  deriving (Eq, Show)++-- | A variable's value, of one of the four kinds @get-env.sh@ writes.+data Variable+  = -- | A string bash does not export.+    ShellString !Text+  | -- | A string bash exports.+    ExportedString !Text+  | -- | An indexed array.+    IndexedArray ![Text]+  | -- | An associative array, by key.+    AssociativeArray !(Map Text Text)+  deriving (Eq, Show)++-- | The contents of the two files a structured-attributes builder reads,+-- as @get-env.sh@ read them, which drops their trailing newlines.+data AttrsFiles = AttrsFiles+  { -- | @.attrs.sh@.+    attrsSh :: !Text,+    -- | @.attrs.json@.+    attrsJson :: !Text+  }+  deriving (Eq, Show)++-- | The document's members, as @get-env.sh@ and upstream's @toJSON@ name+-- them.+variablesMember, functionsMember, attrsFilesMember, attrsShMember, attrsJsonMember, typeMember, valueMember :: Text+variablesMember = "variables"+functionsMember = "bashFunctions"+attrsFilesMember = "structuredAttrs"+attrsShMember = ".attrs.sh"+attrsJsonMember = ".attrs.json"+typeMember = "type"+valueMember = "value"++-- | The name each 'Variable' kind has in the document.+shellStringType, exportedStringType, indexedArrayType, associativeArrayType :: Text+shellStringType = "var"+exportedStringType = "exported"+indexedArrayType = "array"+associativeArrayType = "associative"++-- | Read a captured environment as upstream's @BuildEnvironment::parseJSON@+-- does (with @BuildEnvironment::fromJSON@, in develop.cc): the document as+-- nlohmann parses it, which refuses one that is not UTF-8, then each+-- variable, each function and the structured attributes' files.  A variable+-- of a kind other than the four is dropped, as upstream drops it:+-- @get-env.sh@ writes @\"unknown\"@ and no value for a readonly, integer or+-- reference variable.+--+-- Upstream takes the document's shape on trust: a member it reads that is+-- missing is undefined behaviour in nlohmann's lookup, and one of the+-- wrong JSON type an exception.  Each is a 'Left' here, naming the member.+parseBuildEnvironment :: ByteString -> Either Text BuildEnvironment+parseBuildEnvironment bytes = do+  text <- first (const "the build environment is not UTF-8") (TE.decodeUtf8' bytes)+  top <- parseJson text >>= jsonObject document+  variables <- member document variablesMember top >>= jsonObject (quote variablesMember) >>= Map.traverseMaybeWithKey readVariable+  functions <- member document functionsMember top >>= jsonObject (quote functionsMember) >>= Map.traverseWithKey (jsonString . ("function " <>) . quote)+  attrsFiles <- traverse readAttrsFiles (Map.lookup attrsFilesMember top)+  pure (BuildEnvironment variables functions attrsFiles)+  where+    document = "the build environment"+    readAttrsFiles json = do+      files <- jsonObject (quote attrsFilesMember) json+      AttrsFiles <$> attrsFile attrsShMember files <*> attrsFile attrsJsonMember files+    attrsFile name files = member (quote attrsFilesMember) name files >>= jsonString (quote name)++-- | One variable of the document, or 'Nothing' for a kind it drops.+readVariable :: Text -> Json -> Either Text (Maybe Variable)+readVariable name json = do+  info <- jsonObject what json+  kind <- member what typeMember info >>= jsonString ("the type of " <> what)+  readKind kind info+  where+    what = "variable " <> quote name+    value = member what valueMember+    valueWhat = "the value of " <> what+    readKind kind info+      | kind == shellStringType = Just . ShellString <$> (value info >>= jsonString valueWhat)+      | kind == exportedStringType = Just . ExportedString <$> (value info >>= jsonString valueWhat)+      | kind == indexedArrayType = Just . IndexedArray <$> (value info >>= jsonArray valueWhat >>= traverse (jsonString valueWhat))+      | kind == associativeArrayType = Just . AssociativeArray <$> (value info >>= jsonObject valueWhat >>= traverse (jsonString valueWhat))+      | otherwise = Right Nothing++-- | A name in single quotes, for an error message.+quote :: Text -> Text+quote name = "'" <> name <> "'"++-- | A member of an object, which @what@ names in the error.+member :: Text -> Text -> Map Text Json -> Either Text Json+member what name members = maybe (Left (what <> " has no " <> quote name)) Right (Map.lookup name members)++jsonObject :: Text -> Json -> Either Text (Map Text Json)+jsonObject _ (JsonObject members) = Right members+jsonObject what _ = Left (what <> " is not a JSON object")++jsonArray :: Text -> Json -> Either Text [Json]+jsonArray _ (JsonArray items) = Right items+jsonArray what _ = Left (what <> " is not a JSON array")++jsonString :: Text -> Json -> Either Text Text+jsonString _ (JsonString s) = Right s+jsonString what _ = Left (what <> " is not a JSON string")++-- | A captured environment as upstream's @BuildEnvironment::toJSON@ writes+-- it (develop.cc), which 'parseBuildEnvironment' reads back as the+-- same environment.+buildEnvironmentJson :: BuildEnvironment -> Json+buildEnvironmentJson env =+  JsonObject . Map.fromList $+    [ (variablesMember, JsonObject (Map.map variableJson (beVariables env))),+      (functionsMember, JsonObject (Map.map JsonString (beFunctions env)))+    ]+      <> [(attrsFilesMember, attrsFilesJson files) | Just files <- [beAttrsFiles env]]+  where+    variableJson variable = case variable of+      ShellString s -> typed shellStringType (JsonString s)+      ExportedString s -> typed exportedStringType (JsonString s)+      IndexedArray items -> typed indexedArrayType (JsonArray (map JsonString items))+      AssociativeArray entries -> typed associativeArrayType (JsonObject (Map.map JsonString entries))+    typed kind value = JsonObject (Map.fromList [(typeMember, JsonString kind), (valueMember, value)])+    attrsFilesJson files =+      JsonObject (Map.fromList [(attrsShMember, JsonString (attrsSh files)), (attrsJsonMember, JsonString (attrsJson files))])++-- ---------------------------------------------------------------------------+-- The environment script+-- ---------------------------------------------------------------------------++-- | The variables the script leaves as the shell has them: upstream's+-- @ignoreVars@ (a member of @Common@ in develop.cc), the build's home,+-- terminal, log descriptor and temporary directories among them.+ignoreVars :: Set Text+ignoreVars =+  Set.fromList+    [ "BASHOPTS",+      "HOME",+      "NIX_BUILD_TOP",+      "NIX_ENFORCE_PURITY",+      "NIX_LOG_FD",+      "NIX_REMOTE",+      "PPID",+      "SHELLOPTS",+      "SSL_CERT_FILE",+      "TEMP",+      "TEMPDIR",+      "TERM",+      "TMP",+      "TMPDIR",+      "TZ",+      "UID"+    ]++-- | Upstream's @escapeShellArgAlways@ (@src\/libutil\/util.cc@):+-- the bytes in single quotes, each single quote among them closed, escaped+-- and reopened.  A POSIX shell reads the word back as the same bytes when+-- they hold no NUL.+escapeShellArgAlways :: ByteString -> ByteString+escapeShellArgAlways s = BL.toStrict (BB.toLazyByteString (quotedWord s))++-- | 'escapeShellArgAlways' as a builder.+quotedWord :: ByteString -> BB.Builder+quotedWord s = "'" <> mconcat (intersperse "'\\''" (map BB.byteString (BS.split singleQuote s))) <> "'"+  where+    singleQuote = 0x27++-- | Where the script puts what it moves out of the build, each the bytes+-- of an absolute path.+data ScriptDirectories = ScriptDirectories+  { -- | The directory the shell runs in.  Each output's path becomes+    -- @outputs\/NAME@ under it, upstream's default @outputsDir@+    -- (@Common::makeRcScript@ in develop.cc).+    workingDirectory :: !ByteString,+    -- | A directory the caller made for the structured attributes' files.+    temporaryDirectory :: !ByteString+  }+  deriving (Eq, Show)++-- | The script @print-dev-env@ prints, and the files it names.+data EnvironmentScript = EnvironmentScript+  { -- | The script.+    scriptText :: !ByteString,+    -- | The structured attributes' files, @.attrs.sh@ then @.attrs.json@,+    -- in the temporary directory, which the caller writes before a shell+    -- reads the script; none without structured attributes.+    scriptFiles :: ![ScriptFile]+  }+  deriving (Eq, Show)++-- | A file a script names, with what the caller writes to it.+data ScriptFile = ScriptFile+  { -- | The bytes of the file's path.+    scriptFilePath :: !ByteString,+    -- | What the file holds.+    scriptFileContents :: !ByteString+  }+  deriving (Eq, Show)++-- | The variables a script saves before setting the environment's and+-- appends again after (@savedVars@ in @Common::makeRcScript@, develop.cc):+-- enough of the user's own for the shell to stay usable.+savedVariables :: [BB.Builder]+savedVariables = ["PATH", "XDG_DATA_DIRS"]++-- | The variables a script points at the fresh directory it makes in+-- place of the build's (@Common::makeRcScript@ in develop.cc),+-- @NIX_BUILD_TOP@ first.+temporaryDirectoryVariables :: [BB.Builder]+temporaryDirectoryVariables = ["TMP", "TMPDIR", "TEMP", "TEMPDIR"]++-- | Upstream's @makeRcScript@ (develop.cc), as @develop@ and+-- @print-dev-env@ both run it, with the outputs moved under the working+-- directory:+--+-- * @shellHook@ unset, and @PATH@ and @XDG_DATA_DIRS@ saved;+-- * each variable not in 'ignoreVars', in name order: a string quoted by+--   'escapeShellArgAlways' and exported when it was, an array declared+--   with each element, or each key and value, quoted and followed by a+--   space;+-- * each function, in name order;+-- * the saved values appended to the environment's;+-- * @NIX_BUILD_TOP@ and the temporary-directory variables set to a fresh+--   @mktemp -d -t nix-shell.XXXXXX@ directory;+-- * @shellHook@ evaluated.+--+-- Then each output's captured path is replaced by its directory under the+-- working directory, and under structured attributes each file+-- variable's value by its file in the temporary directory.  Without+-- structured attributes the outputs are the words of an @outputs@ string+-- (or an array's elements, or an associative array's keys), each with a+-- string variable holding its path; with them, @outputs@ maps each name+-- to its path.  A path two outputs share goes to the first's directory.+-- Each replacement runs over the whole script, in the byte order of the+-- paths, and after replacing an occurrence the search resumes where the+-- replacement starts, as upstream's @rewriteStrings@ does+-- (@src\/libutil\/util.cc@), so a match the replacement completes with the+-- text after it is replaced too.+--+-- 'Left' in upstream's words for an environment with no @outputs@, an+-- output variable that is not a string, and structured attributes whose+-- @outputs@ is not an associative array.  Upstream asserts that each+-- output and file variable is set, and its replacement never ends when the+-- text replacing a path holds it; each is a 'Left' here too.+environmentScript :: ScriptDirectories -> BuildEnvironment -> Either Text EnvironmentScript+environmentScript directories env = do+  outputs <- maybe (Left "derivation does not have an 'outputs' attribute") Right (Map.lookup outputsVariable variables)+  outputRewrites <- case beAttrsFiles env of+    Just _ -> do+      paths <- associativeValue outputs+      pure [(TE.encodeUtf8 path, outputDirectory name) | (name, path) <- Map.toAscList paths]+    Nothing -> traverse outputRewrite (outputNames outputs)+  files <- maybe (Right []) attrsFileRewrites (beAttrsFiles env)+  -- Upstream inserts each rewrite into a map, which keeps the first for a+  -- path given twice.+  let rewrites = Map.fromListWith (\_ earlier -> earlier) (outputRewrites <> map snd files)+  text <- rewriteStrings rewrites (BL.toStrict (BB.toLazyByteString (scriptBody env)))+  pure (EnvironmentScript text (map fst files))+  where+    variables = beVariables env+    outputDirectory name = appendPath (appendPath (workingDirectory directories) outputsDirectoryName) (TE.encodeUtf8 name)+    outputRewrite name = do+      path <- setVariable name >>= stringValue+      pure (TE.encodeUtf8 path, outputDirectory name)+    attrsFileRewrites files =+      sequence+        [ attrsFile attrsShFileVariable attrsShMember (attrsSh files),+          attrsFile attrsJsonFileVariable attrsJsonMember (attrsJson files)+        ]+    attrsFile variable fileName contents = do+      path <- setVariable variable >>= stringValue+      let file = appendPath (temporaryDirectory directories) (TE.encodeUtf8 fileName)+      pure (ScriptFile file (TE.encodeUtf8 contents), (TE.encodeUtf8 path, file))+    setVariable name = maybe (Left ("the build environment has no variable " <> quote name)) Right (Map.lookup name variables)++-- | The variable naming a derivation's outputs.+outputsVariable :: Text+outputsVariable = "outputs"++-- | The directory under the working directory that holds the outputs.+outputsDirectoryName :: ByteString+outputsDirectoryName = "outputs"++-- | The variables naming the structured attributes' files in the build.+attrsShFileVariable, attrsJsonFileVariable :: Text+attrsShFileVariable = "NIX_ATTRS_SH_FILE"+attrsJsonFileVariable = "NIX_ATTRS_JSON_FILE"++-- | Upstream's @getString@: the value of a string variable, exported or+-- not.+stringValue :: Variable -> Either Text Text+stringValue variable = case variable of+  ShellString s -> Right s+  ExportedString s -> Right s+  _ -> Left "bash variable is not a string"++-- | Upstream's @getAssociative@.+associativeValue :: Variable -> Either Text (Map Text Text)+associativeValue variable = case variable of+  AssociativeArray entries -> Right entries+  _ -> Left "bash variable is not an associative array"++-- | Upstream's @getStrings@: a string's words, split on space, tab,+-- newline and carriage return, an array's elements, or an associative+-- array's keys.+outputNames :: Variable -> [Text]+outputNames variable = case variable of+  ShellString s -> wordsOf s+  ExportedString s -> wordsOf s+  IndexedArray items -> items+  AssociativeArray entries -> Map.keys entries+  where+    wordsOf = filter (not . T.null) . T.split (`elem` [' ', '\t', '\n', '\r'])++-- | @std::filesystem::path@'s @/@ on POSIX: a name with a root replaces the+-- directory, and otherwise follows it after a separator unless the+-- directory is empty or ends in one.+appendPath :: ByteString -> ByteString -> ByteString+appendPath directory name+  | separator `BS.isPrefixOf` name = name+  | BS.null directory || separator `BS.isSuffixOf` directory = directory <> name+  | otherwise = directory <> separator <> name+  where+    separator = "/"++-- | The script before its paths are replaced.+scriptBody :: BuildEnvironment -> BB.Builder+scriptBody env =+  "unset shellHook\n"+    <> foldMap saveVariable savedVariables+    <> Map.foldMapWithKey variableLines (Map.withoutKeys (beVariables env) ignoreVars)+    <> Map.foldMapWithKey functionLines (beFunctions env)+    <> foldMap restoreVariable savedVariables+    <> "export NIX_BUILD_TOP=\"$(mktemp -d -t nix-shell.XXXXXX)\"\n"+    <> foldMap (\name -> "export " <> name <> "=\"$NIX_BUILD_TOP\"\n") temporaryDirectoryVariables+    <> "eval \"${shellHook:-}\"\n"+  where+    saveVariable name = name <> "=${" <> name <> ":-}\n" <> "nix_saved_" <> name <> "=\"$" <> name <> "\"\n"+    restoreVariable name = name <> "=\"$" <> name <> "${nix_saved_" <> name <> ":+:$nix_saved_" <> name <> "}\"\n"++-- | Upstream's @toBash@ for one variable (@BuildEnvironment::toBash@ in+-- develop.cc).+variableLines :: Text -> Variable -> BB.Builder+variableLines name variable = case variable of+  ShellString s -> assignment s+  ExportedString s -> assignment s <> "export " <> nameBytes <> "\n"+  IndexedArray items -> "declare -a " <> nameBytes <> "=(" <> foldMap (\item -> quoted item <> " ") items <> ")\n"+  AssociativeArray entries ->+    "declare -A " <> nameBytes <> "=(" <> Map.foldMapWithKey (\key value -> "[" <> quoted key <> "]=" <> quoted value <> " ") entries <> ")\n"+  where+    nameBytes = TE.encodeUtf8Builder name+    assignment s = nameBytes <> "=" <> quoted s <> "\n"+    quoted = quotedWord . TE.encodeUtf8++-- | Upstream's @toBash@ for one function (@BuildEnvironment::toBash@ in+-- develop.cc).+functionLines :: Text -> Text -> BB.Builder+functionLines name body = TE.encodeUtf8Builder name <> " ()\n{\n" <> TE.encodeUtf8Builder body <> "}\n"++-- | Upstream's @rewriteStrings@ (util.cc): each rewrite in the byte+-- order of the text it replaces, replacing every occurrence, the search+-- resuming where each replacement starts.  When a replacement holds the+-- text it replaces, and the script holds that text, upstream's loop never+-- ends; that is a 'Left' here.+rewriteStrings :: Map ByteString ByteString -> ByteString -> Either Text ByteString+rewriteStrings rewrites script = foldM rewrite script (Map.toAscList rewrites)+  where+    rewrite text (from, to)+      | from == to = Right text+      | from `BS.isInfixOf` to && from `BS.isInfixOf` text =+          Left ("replacing '" <> shown from <> "' with '" <> shown to <> "', which holds it, would not end")+      | otherwise = Right (replaceAll from to text)+    -- For an error message only.+    shown = TE.decodeUtf8Lenient++-- | Every occurrence of @from@ replaced by @to@, the search resuming at the+-- start of each replacement.  @to@ does not hold @from@, so the loop ends:+-- a match starting in a replacement runs past it into text not yet+-- searched, or, when @to@ is the shorter, the text left shrinks.+replaceAll :: ByteString -> ByteString -> ByteString -> ByteString+replaceAll from to = go []+  where+    go done rest = case BS.breakSubstring from rest of+      (before, after)+        | BS.null after -> BS.concat (reverse (before : done))+        | otherwise -> go (before : done) (to <> BS.drop (BS.length from) after)++-- ---------------------------------------------------------------------------+-- The rcfile+-- ---------------------------------------------------------------------------++-- | The shell an rcfile is written for.+data Shell = Shell+  { -- | Where the rcfile is: it removes itself once it has set the+    -- environment.+    shellRcfile :: !ByteString,+    -- | What the shell does once the environment is set.+    shellMode :: !ShellMode,+    -- | What @SHELL@ is set to: the shell the caller starts.+    shellProgram :: !ByteString+  }+  deriving (Eq, Show)++-- | What the shell does once the environment is set.+data ShellMode+  = -- | Reads commands, with this prompt.+    Interactive !Prompt+  | -- | Replaces itself with this command and its arguments: @--command@.+    RunCommand !(NonEmpty ByteString)+  | -- | Runs the phase of this name, such as @build@: @--phase@.+    RunPhase !ByteString+  deriving (Eq, Show)++-- | The @bash-prompt@ settings (@DevelopSettings@ in develop.cc), each empty+-- when unset, as upstream defaults them.  An empty one writes nothing.+data Prompt = Prompt+  { -- | @bash-prompt@: the prompt in place of the user's.+    bashPrompt :: !ByteString,+    -- | @bash-prompt-prefix@: text before the prompt.+    bashPromptPrefix :: !ByteString,+    -- | @bash-prompt-suffix@: text after it.+    bashPromptSuffix :: !ByteString+  }+  deriving (Eq, Show)++-- | The rcfile @develop@ starts bash with, as upstream's @CmdDevelop::run@+-- writes it (develop.cc): the environment script, then a line+-- removing the rcfile, then by mode+--+-- * 'RunPhase': @foundMakefile=1@ and the phase run through @runPhase@+--   when the environment defines it, otherwise through @runHook@;+-- * 'RunCommand': @exec@ and each word quoted by 'escapeShellArgAlways';+-- * 'Interactive': before the script, a line sourcing @~\/.bashrc@ when+--   @PS1@ is set and one turning aliases off; after the removal, an empty+--   line, one turning aliases back on, and a line for each prompt setting+--   that is not empty;+--+-- and last @SHELL@ set to the shell.  The rcfile path, phase and shell go+-- in as they are, unescaped (the path between single quotes, the shell+-- between double quotes, the phase bare), as upstream writes them.+--+-- Upstream also writes @set -x@ at debug verbosity, and after @SHELL@ a+-- @PATH@ line naming @nixpkgs#bashInteractive@'s directory when it finds+-- that package.  nova-nix has neither the verbosity nor the lookup, so+-- neither line is written.+renderRcfile :: Shell -> EnvironmentScript -> ByteString+renderRcfile shell script = BL.toStrict . BB.toLazyByteString $ case shellMode shell of+  RunPhase phase ->+    body+      <> "foundMakefile=1\n"+      <> "if declare -f runPhase >/dev/null; then\n"+      <> ("  runPhase " <> BB.byteString phase <> "Phase\n")+      <> "else\n"+      <> ("  runHook " <> BB.byteString phase <> "Phase\n")+      <> "fi\n"+      <> shellLine+  RunCommand command ->+    body <> "exec " <> mconcat (intersperse " " (map quotedWord (toList command))) <> "\n" <> shellLine+  Interactive prompt ->+    "[ -n \"$PS1\" ] && [ -e ~/.bashrc ] && source ~/.bashrc;\nshopt -u expand_aliases\n"+      <> body+      <> "\nshopt -s expand_aliases\n"+      <> promptLine (bashPrompt prompt) (\p -> "PS1=" <> p <> ";\n")+      <> promptLine (bashPromptPrefix prompt) (\p -> "PS1=" <> p <> "\"$PS1\";\n")+      <> promptLine (bashPromptSuffix prompt) (\p -> "PS1+=" <> p <> ";\n")+      <> shellLine+  where+    body = BB.byteString (scriptText script) <> "command rm -f '" <> BB.byteString (shellRcfile shell) <> "'\n"+    shellLine = "SHELL=\"" <> BB.byteString (shellProgram shell) <> "\"\n"+    promptLine setting assignment+      | BS.null setting = mempty+      | otherwise = "[ -n \"$PS1\" ] && " <> assignment (quotedWord setting)
+ src/Nix/Develop/Shell.hs view
@@ -0,0 +1,337 @@+{-# LANGUAGE CPP #-}++-- | The shell @nova-nix develop@ starts, as upstream Nix 2.35.4's+-- @CmdDevelop::run@ starts it (@src\/nix\/develop.cc@) through+-- @execProgramInStore@ (@src\/nix\/run.cc@).+--+-- What the shell runs, its arguments and the environment it starts with+-- are pure: 'shellModeFor', 'shellArguments' and 'shellEnvironment', each+-- refusing what upstream refuses in upstream's words.  The rest belongs+-- to the host, a t'DevelopHost': the temporary files upstream names, the+-- process's environment, and the shell itself, which replaces nova-nix+-- as upstream's replaces @nix@, so that the shell has the terminal, its+-- signals and its exit status to itself.  Only a POSIX host has one.  No+-- Windows stdenv's builder is bash yet, so on Windows neither @develop@+-- nor @print-dev-env@ has a capture to read or a shell to start.+module Nix.Develop.Shell+  ( -- * What the shell runs+    shellModeFor,+    bashProgram,+    shellArguments,++    -- * The shell's environment+    EnvironmentBase (..),+    EnvironmentChanges (..),+    shellEnvironment,++    -- * The host+    DevelopHost (..),+    developHost,+  )+where++import Data.ByteString (ByteString)+import qualified Data.ByteString.Char8 as BC+import Data.List.NonEmpty (NonEmpty)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import Data.Void (Void)+#if defined(mingw32_HOST_OS)+import Nix.Develop.Environment (Prompt, ShellMode (..))+#else+import Control.Exception (bracket, catchJust, try, tryJust)+import Control.Monad (guard)+import qualified Data.ByteString as BS+import Data.Maybe (fromMaybe, mapMaybe)+import Data.Word (Word32)+import Foreign.C.Error (Errno (..), eBADF, eINVAL)+import Foreign.C.Types (CInt)+import GHC.IO.Exception (IOException (..))+import Nix.Develop.Environment (Prompt, ShellMode (..), appendPath)+import qualified System.Directory.OsPath as OsDir+import System.IO (hClose, hFlush, stderr, stdout)+import System.IO.Error (isAlreadyExistsError)+import qualified System.OsPath as OP+import System.Posix.Directory.ByteString (closeDirStream, createDirectory, openDirStream, readDirStream)+import qualified System.Posix.Env.ByteString as PosixEnv+import System.Posix.IO (FdOption (CloseOnExec), setFdOption)+import System.Posix.Process.ByteString (executeFile, getProcessID)+import System.Posix.Resource (Resource (ResourceOpenFiles), ResourceLimit (..), getResourceLimit, softLimit)+import System.Posix.Temp.ByteString (mkstemp)+import System.Posix.Types (Fd (..), FileMode)+import System.Posix.Unistd (SysVar (OpenFileLimit), getSysVar)+import System.Random (randomIO)+import Text.Read (readMaybe)+#endif++-- ---------------------------------------------------------------------------+-- What the shell runs+-- ---------------------------------------------------------------------------++-- | What the shell does once the environment is set, from the words+-- @--command@ took and the phase the phase flags named last, as+-- upstream's @CmdDevelop::run@ decides it (develop.cc): the phase, the+-- command, or else an interactive shell with the prompt settings.  Upstream+-- refuses the two together once the environment is built, in these words.+shellModeFor :: Maybe (NonEmpty ByteString) -> Maybe ByteString -> Prompt -> Either Text ShellMode+shellModeFor command phase prompt = case (command, phase) of+  (Just _, Just _) -> Left "you cannot use both '--command' and '--phase'"+  (Nothing, Just name) -> Right (RunPhase name)+  (Just commandWords, Nothing) -> Right (RunCommand commandWords)+  (Nothing, Nothing) -> Right (Interactive prompt)++-- | The shell upstream starts when @nixpkgs#bashInteractive@ does not+-- resolve, as it cannot without flakes (@CmdDevelop::run@ in develop.cc):+-- @bash@, found on the @PATH@ of the environment the shell starts with.  It+-- is also what @SHELL@ holds.+bashProgram :: ByteString+bashProgram = "bash"++-- | The shell's arguments after its name (@CmdDevelop::run@ in develop.cc):+-- the rcfile alone for a command or a phase, which bash then runs as a+-- script, so that an interrupt ends it rather than leaving an interactive+-- shell behind; @--rcfile@ and the rcfile for an interactive shell.+shellArguments :: ShellMode -> ByteString -> [ByteString]+shellArguments mode rcfile = case mode of+  Interactive _ -> ["--rcfile", rcfile]+  RunCommand _ -> [rcfile]+  RunPhase _ -> [rcfile]++-- ---------------------------------------------------------------------------+-- The shell's environment+-- ---------------------------------------------------------------------------++-- | What the shell's environment starts from.+data EnvironmentBase+  = -- | The caller's: the environment nova-nix was started with.+    CallerEnvironment+  | -- | Only the variables @--keep-env-var@ names: @--ignore-env@.+    EmptyEnvironment+  deriving (Eq, Show)++-- | How the command line changes the shell's environment, upstream's+-- @MixEnvironment@ (its constructor in @src\/libcmd\/command.cc@, from+-- 2.34.9).  A variable is named by its bytes.+data EnvironmentChanges = EnvironmentChanges+  { -- | Where it starts: @--ignore-env@.+    ecBase :: !EnvironmentBase,+    -- | @--keep-env-var@: the caller's variables kept under+    -- @--ignore-env@.+    ecKeep :: !(Set ByteString),+    -- | @--unset-env-var@: the variables removed.+    ecUnset :: !(Set ByteString),+    -- | @--set-env-var@: each variable set, with its value.+    ecSet :: !(Map ByteString ByteString)+  }+  deriving (Eq, Show)++-- | The environment the shell starts with, given the store path of the+-- environment the capture built and the caller's environment: upstream's+-- @setEnviron@ (command.cc), the variables @--set-env-var@ sets replacing the+-- caller's and those @--unset-env-var@ names removed after, then @NIX_GCROOT@+-- naming the store path and @SHELL@ the shell, whatever the flags said of+-- either (@CmdDevelop::run@ in develop.cc).  Upstream replaces the process's+-- environment through @setenv@, which refuses a name that is empty or holds+-- @=@, and goes on without it; such a name is left out here.+--+-- 'Left' in upstream's words for @--unset-env-var@ under+-- @--ignore-env@, and for @--keep-env-var@ without it.+shellEnvironment :: EnvironmentChanges -> ByteString -> Map ByteString ByteString -> Either Text (Map ByteString ByteString)+shellEnvironment changes gcroot caller = case ecBase changes of+  EmptyEnvironment+    | not (Set.null (ecUnset changes)) -> Left "--unset-env-var does not make sense with --ignore-env"+    | otherwise -> Right (finish (Map.restrictKeys caller (ecKeep changes)))+  CallerEnvironment+    | not (Set.null (ecKeep changes)) -> Left "--keep-env-var does not make sense without --ignore-env"+    | otherwise -> Right (finish caller)+  where+    finish base =+      Map.filterWithKey (const . settable)+        $ Map.insert shellVariable bashProgram . Map.insert gcrootVariable gcroot+        $ Map.withoutKeys (Map.union (ecSet changes) base) (ecUnset changes)+    settable name = not (BC.null name) && BC.notElem '=' name++-- | The variable naming the environment's store path, which upstream's+-- collector on Linux keeps while a process's environment holds it+-- (@findRuntimeRootsUnchecked@ in @src\/libstore\/local-gc.cc@ from 2.34.9,+-- @LocalStore::findRuntimeRoots@ in gc.cc at 2.24.9).+gcrootVariable :: ByteString+gcrootVariable = "NIX_GCROOT"++-- | The variable naming the shell.+shellVariable :: ByteString+shellVariable = "SHELL"++-- ---------------------------------------------------------------------------+-- The host+-- ---------------------------------------------------------------------------++-- | What @develop@ and @print-dev-env@ ask of the host beyond its store:+-- the temporary files upstream makes, the process's environment, and a+-- shell that replaces the process.  'developHost' gives this host's,+-- where it has one.+data DevelopHost = DevelopHost+  { -- | Make a fresh directory @PREFIX-PID-N@, mode 0755 less the umask,+    -- in the temporary root with its links resolved, as upstream's+    -- @createTempDir@ makes one (with @makeTempPath@, in+    -- @src\/libutil\/file-system.cc@ from 2.34.9), @N@ counting up from a+    -- random number past each name that exists, and give its path's bytes.+    makeTemporaryDirectory :: !(ByteString -> IO ByteString),+    -- | Make a fresh file @nix-shell.XXXXXX@ in the temporary root, mode+    -- 0600, as upstream's @createTempFile@ makes the rcfile+    -- (file-system.cc), write to it what the function makes of its path,+    -- close it and give the path's bytes.+    createRcfile :: !((ByteString -> ByteString) -> IO ByteString),+    -- | The process's environment, as upstream's @getEnv@ reads it: an+    -- entry without @=@ is passed over, and of two entries with one name+    -- the first is kept.+    processEnvironment :: !(IO (Map ByteString ByteString)),+    -- | Replace the process with 'bashProgram' and these arguments, in+    -- this environment.  It returns only by throwing the failure to start+    -- the shell.+    replaceProcess :: !([ByteString] -> Map ByteString ByteString -> IO Void)+  }++-- | A t'DevelopHost' for this host, or why it has none.+developHost :: Either Text DevelopHost+#if defined(mingw32_HOST_OS)+developHost = Left "develop and print-dev-env do not run on Windows yet"+#else+developHost = Right (DevelopHost posixTemporaryDirectory posixRcfile posixEnvironment posixReplace)++-- | Upstream's @defaultTempDir@ (@src\/libutil\/unix\/file-system.cc@ from+-- 2.34.9, file-system.cc at 2.24.9): @TMPDIR@ when it is set and not empty,+-- else @\/tmp@.+temporaryRoot :: IO ByteString+temporaryRoot = fromMaybe "/tmp" . (>>= nonEmpty) <$> PosixEnv.getEnv "TMPDIR"+  where+    nonEmpty value+      | BS.null value = Nothing+      | otherwise = Just value++-- | The mode upstream's @createTempDir@ gives a directory.+temporaryDirectoryMode :: FileMode+temporaryDirectoryMode = 0o755++-- | 'makeTemporaryDirectory'.  The root's links are resolved as upstream's+-- @canonPath@ resolves them, through the directory package's @realpath@+-- on the root's own bytes.+posixTemporaryDirectory :: ByteString -> IO ByteString+posixTemporaryDirectory prefix = do+  root <- temporaryRoot >>= fmap osPathBytes . OsDir.canonicalizePath . bytesOsPath+  pid <- getProcessID+  start <- randomIO+  let attempt :: Word32 -> IO ByteString+      attempt counter = do+        let path = appendPath root (prefix <> "-" <> BC.pack (show pid) <> "-" <> BC.pack (show counter))+        made <- tryJust (guard . isAlreadyExistsError) (createDirectory path temporaryDirectoryMode)+        either (const (attempt (counter + 1))) (const (pure path)) made+  attempt start++-- | 'createRcfile'.  The root is upstream's, its links left as they are.+posixRcfile :: (ByteString -> ByteString) -> IO ByteString+posixRcfile render = do+  root <- temporaryRoot+  bracket (mkstemp (appendPath root rcfilePrefix)) (hClose . snd) $ \(path, handle) ->+    path <$ BS.hPut handle (render path)++-- | What the rcfile's name starts with, before the six characters+-- @mkstemp@ adds.+rcfilePrefix :: ByteString+rcfilePrefix = "nix-shell."++-- | 'processEnvironment'.+posixEnvironment :: IO (Map ByteString ByteString)+posixEnvironment = Map.fromListWith (\_ earlier -> earlier) . concatMap entry <$> PosixEnv.getEnvironmentPrim+  where+    entry raw = case BC.break (== '=') raw of+      (name, rest) | Just ('=', value) <- BC.uncons rest -> [(name, value)]+      _ -> []++-- | 'replaceProcess': the standard handles flushed, every variable unset+-- and the new ones set, as upstream's @replaceEnv@ does+-- (with @clearEnv@, in @src\/libutil\/environment-variables.cc@), every other+-- descriptor marked close-on-exec ('closeOnExec'), then @execvp@, which finds+-- the shell on the new environment's @PATH@, as upstream's does+-- (@execProgramInStore@ in run.cc).  unix's @executeFile@ with no environment+-- is that call; given one it is @execvpe@, which searches the old @PATH@.  An+-- entry @unsetenv@ refuses, one with an empty name, stays, as upstream goes+-- on past the refusal.+--+-- GHC's runtime installs its own handlers for SIGINT, SIGPIPE, SIGQUIT+-- and SIGTSTP at start, whatever the process inherited, an ignored+-- signal included (@initDefaultHandlers@ and @set_sigtstp_action@ in+-- rts\/posix\/Signals.c at 9.14.1), and the exec resets a handled+-- signal to its default.  So the shell starts with those four at their+-- defaults even where nova-nix was started with one ignored.  Upstream+-- leaves them as it found them on Linux, so an ignored one stays ignored+-- in its shell, and sets SIGINT, SIGPIPE and SIGQUIT to their defaults on+-- macOS (@initNix@ in @src\/libmain\/shared.cc@ at 2.35.4).+posixReplace :: [ByteString] -> Map ByteString ByteString -> IO Void+posixReplace arguments variables = do+  hFlush stdout+  hFlush stderr+  posixEnvironment >>= mapM_ (passingOver eINVAL . PosixEnv.unsetEnv) . Map.keys+  mapM_ (\(name, value) -> PosixEnv.setEnv name value True) (Map.toList variables)+  closeOnExec+  executeFile bashProgram True arguments Nothing++-- | Mark every descriptor from 3 up close-on-exec, so that none the+-- process holds reaches the shell: the HTTP client's pool keeps a+-- connection a substitution used open, without the flag.  The descriptors+-- are those the process's descriptor directory lists, @\/proc\/self\/fd@+-- on Linux and @\/dev\/fd@ on macOS, or where neither can be read, every+-- number below the soft limit on open files, or below @OPEN_MAX@ when+-- that limit is infinite, and never past the largest a descriptor can+-- be.  One closed since it was listed, as the listing's own is, is passed+-- over.+closeOnExec :: IO ()+closeOnExec = do+  listed <- firstListing descriptorDirectories+  descriptors <- maybe everyDescriptor pure listed+  mapM_ (\descriptor -> passingOver eBADF (setFdOption (Fd descriptor) CloseOnExec True)) (filter (>= firstOtherDescriptor) descriptors)+  where+    firstListing [] = pure Nothing+    firstListing (directory : rest) = descriptorListing directory >>= maybe (firstListing rest) (pure . Just)+    everyDescriptor = do+      limits <- getResourceLimit ResourceOpenFiles+      bound <- case softLimit limits of+        ResourceLimit limit -> pure limit+        _ -> getSysVar OpenFileLimit+      pure [firstOtherDescriptor .. fromInteger (min bound (toInteger (maxBound :: CInt))) - 1]++-- | The first descriptor past standard input, output and error.+firstOtherDescriptor :: CInt+firstOtherDescriptor = 3++-- | The directories that list a process's own descriptors, by name.+descriptorDirectories :: [ByteString]+descriptorDirectories = ["/proc/self/fd", "/dev/fd"]++-- | The descriptors a directory lists, or 'Nothing' when it cannot be+-- read.+descriptorListing :: ByteString -> IO (Maybe [CInt])+descriptorListing directory = do+  listed <- try (bracket (openDirStream directory) closeDirStream readAll) :: IO (Either IOException [ByteString])+  pure (either (const Nothing) (Just . mapMaybe (readMaybe . BC.unpack)) listed)+  where+    readAll stream = do+      entry <- readDirStream stream+      if BS.null entry then pure [] else (entry :) <$> readAll stream++-- | Run an action, passing over its failure with this errno and no+-- other.+passingOver :: Errno -> IO () -> IO ()+passingOver expected action = catchJust (\failure -> guard (fmap Errno (ioe_errno failure) == Just expected)) action pure++-- | The host path a POSIX path's bytes name: each byte one unit.+bytesOsPath :: ByteString -> OP.OsPath+bytesOsPath = OP.pack . map OP.unsafeFromChar . BC.unpack++-- | A POSIX host path's bytes, the inverse of 'bytesOsPath'.+osPathBytes :: OP.OsPath -> ByteString+osPathBytes = BC.pack . map OP.toChar . OP.unpack+#endif
+ src/Nix/DrvName.hs view
@@ -0,0 +1,34 @@+-- | Where a derivation name splits into its name and its version, as+-- upstream splits one: at the first dash that something other than a+-- letter follows, so @apache-httpd-2.0.48@ is @apache-httpd@ and+-- @2.0.48@, and @foo-.1@ is @foo@ and @.1@.  A letter is an ASCII+-- letter: upstream asks the C library with no locale set, where no+-- other byte is one.  A dash that ends the name is followed by nothing+-- and does not split it.+--+-- @builtins.parseDrvName@ splits a Nix string, which is bytes, and a+-- profile names an element by the name part of a store path's name,+-- which is text, so the split runs over whichever units the caller+-- takes off its string.+module Nix.DrvName+  ( drvNameDash,+  )+where++import Data.Char (isAsciiLower, isAsciiUpper)++-- | The position of the dash a derivation name splits at, counted in+-- the units @uncons@ takes off: the name is everything before it and+-- the version everything after it.  'Nothing' when no dash splits the+-- string, which is then all name.+drvNameDash :: (s -> Maybe (Char, s)) -> s -> Maybe Int+drvNameDash uncons = go 0+  where+    go !at s = case uncons s of+      Nothing -> Nothing+      Just ('-', rest)+        | Just (next, _) <- uncons rest,+          not (isAsciiLetter next) ->+            Just at+      Just (_, rest) -> go (at + 1) rest+    isAsciiLetter c = isAsciiLower c || isAsciiUpper c
src/Nix/Environment.hs view
@@ -16,10 +16,18 @@ -- Nix string carries, and a name is read as UTF-8.  An unpaired -- surrogate has no UTF-8 form, so a value holding one is refused rather -- than approximated, the rule the NAR serialiser applies to such a file--- name.+-- name.  A variable set to nothing is set, as upstream reads it on every+-- platform: @GetEnvironmentVariableW@ is asked first for the space the+-- value needs, which is none only when the variable is not set, where+-- 'System.Environment.lookupEnv' reads a value of no characters as unset.+--+-- A command-line argument is read the same way: its bytes as the file+-- system takes them when it names a file, which on POSIX are the bytes+-- the program was given, and on Windows the UTF-8 form of its UTF-16. module Nix.Environment   ( EnvLookup (..),     lookupEnvBytes,+    argumentBytes,   ) where @@ -28,8 +36,13 @@ import Data.Char (GeneralCategory (Surrogate), generalCategory) import qualified Data.Text as T import qualified Data.Text.Encoding as TE-import System.Environment (lookupEnv)+import Data.Word (Word32)+import Foreign.C.String (CWString, peekCWStringLen, withCWString)+import Foreign.Marshal.Array (allocaArray)+import Foreign.Ptr (nullPtr) #else+import qualified Data.ByteString.Char8 as BS8+import qualified System.OsPath as OP import qualified System.Posix.Env.ByteString as PosixEnv #endif @@ -46,22 +59,61 @@  -- | Look up a variable by the bytes of its name.  Nothing is caught: the -- read cannot fail other than by finding nothing, since @getenv@ answers--- NULL for a missing name and base's 'System.Environment.lookupEnv'--- answers 'Nothing' whenever @GetEnvironmentVariableW@ finds no value.+-- NULL for a missing name and @GetEnvironmentVariableW@ needs no space+-- for one. lookupEnvBytes :: ByteString -> IO EnvLookup #if defined(mingw32_HOST_OS) lookupEnvBytes name = case TE.decodeUtf8' name of   -- A Windows name is UTF-16, so bytes with no UTF-8 reading name no   -- variable.   Left _ -> pure EnvUnset-  Right decoded -> maybe EnvUnset utf8Value <$> lookupEnv (T.unpack decoded)+  Right decoded -> maybe EnvUnset utf8Value <$> windowsVariable (T.unpack decoded)   where     -- base decodes a surrogate pair into one character and keeps an-    -- unpaired surrogate as its own code point, which 'T.pack' would-    -- replace with U+FFFD.+    -- unpaired surrogate as its own code point ('hasNoUtf8Form').     utf8Value value-      | any ((== Surrogate) . generalCategory) value = EnvUnpairedSurrogate+      | any hasNoUtf8Form value = EnvUnpairedSurrogate       | otherwise = EnvValue (TE.encodeUtf8 (T.pack value)) #else lookupEnvBytes name = maybe EnvUnset EnvValue <$> PosixEnv.getEnv name+#endif++-- | The bytes of a command-line argument as 'System.Environment.getArgs'+-- gave it, or 'Nothing' for a Windows argument holding an unpaired+-- surrogate.  On POSIX they are the argument encoded back with the file+-- system encoding it was decoded with, which keeps a byte with no UTF-8+-- reading as it was.+argumentBytes :: String -> IO (Maybe ByteString)+#if defined(mingw32_HOST_OS)+argumentBytes arg+  | any hasNoUtf8Form arg = pure Nothing+  | otherwise = pure (Just (TE.encodeUtf8 (T.pack arg)))+#else+argumentBytes arg = Just . BS8.pack . map OP.toChar . OP.unpack <$> OP.encodeFS arg+#endif++#if defined(mingw32_HOST_OS)+-- | Whether a character is an unpaired surrogate's own code point, which+-- has no UTF-8 form and which 'T.pack' would replace with U+FFFD.+hasNoUtf8Form :: Char -> Bool+hasNoUtf8Form = (== Surrogate) . generalCategory++-- | A variable's value, as upstream reads one: @GetEnvironmentVariableW@+-- asked for the space the value needs with its terminating NUL, none for+-- a variable that is not set, then for the value, which on success is+-- shorter than the space given and otherwise is the space it now needs,+-- had it grown between the calls.+windowsVariable :: String -> IO (Maybe String)+windowsVariable name = withCWString name $ \key -> do+  needed <- c_GetEnvironmentVariable key nullPtr 0+  if needed == 0 then pure Nothing else Just <$> readValue key needed+  where+    readValue key space = allocaArray (fromIntegral space) $ \buffer -> do+      written <- c_GetEnvironmentVariable key buffer space+      if written >= space+        then readValue key written+        else peekCWStringLen (buffer, fromIntegral written)++foreign import ccall unsafe "windows.h GetEnvironmentVariableW"+  c_GetEnvironmentVariable :: CWString -> CWString -> Word32 -> IO Word32 #endif
src/Nix/Eval.hs view

12113 lines of diff, too many to show among the others: show this file

+ src/Nix/Eval/AllocSite.hs view
@@ -0,0 +1,154 @@+-- | The construct or builtin behind each environment and each attribute+-- set the C data layer allocates.+--+-- The evaluator passes a site with every such allocation, and while the+-- census counts sites ("Nix.Eval.CStats") the allocators count each+-- allocation under it (@cbits\/nn_stats.h@).  With counting off a site+-- costs the argument that carries it.+module Nix.Eval.AllocSite+  ( -- * Environments+    EnvSite (..),+    envSiteIndex,+    envSiteName,++    -- * Attribute sets+    SetSite (..),+    setSiteIndex,+    setSiteName,+  )+where++import qualified Data.ByteString as BS+import Data.Word (Word32)++-- | What makes an environment.+data EnvSite+  = -- | The root environment: an evaluation session's, which every+    -- imported file is evaluated in, a @scopedImport@'s and the+    -- @derivation@ wrapper's.+    EnvRoot+  | -- | A call of a lambda with an argument name: the argument.+    EnvCall+  | -- | A call of a lambda with formals: the formals, and the name an @\@@+    -- binds.+    EnvCallFormals+  | -- | A lambda value closed over the variables it uses, which it+    -- copies out of its scope.+    EnvClosure+  | -- | A @let@'s bindings.+    EnvLet+  | -- | The variables a @let@ uses from outside it, copied out of its+    -- scope as a closure's are.+    EnvLetCapture+  | -- | A @rec@ set's bindings.+    EnvRec+  | -- | The variables a @rec@ set uses from outside it.+    EnvRecCapture+  | -- | An @inherit (from)@ clause: the from-expression, which each name+    -- the clause inherits selects from.+    EnvInheritFrom+  | -- | A @with@.+    EnvWith+  deriving (Eq, Ord, Show, Enum, Bounded)++-- | The site's number in the C counts, below @NN_STATS_ENV_SITES@.+envSiteIndex :: EnvSite -> Word32+envSiteIndex = fromIntegral . fromEnum++-- | The site's name in the census report.+envSiteName :: EnvSite -> BS.ByteString+envSiteName site = case site of+  EnvRoot -> "root"+  EnvCall -> "call"+  EnvCallFormals -> "call-formals"+  EnvClosure -> "closure"+  EnvLet -> "let"+  EnvLetCapture -> "let-capture"+  EnvRec -> "rec"+  EnvRecCapture -> "rec-capture"+  EnvInheritFrom -> "inherit-from"+  EnvWith -> "with"++-- | What makes an attribute set.+data SetSite+  = -- | The root environment's sets: @builtins@, the names around every+    -- expression, the @derivation@ wrapper's scope, the search path's+    -- entries, and the argument a command line's target is called with+    -- ("Nix.Eval.AutoCall").+    SetRoot+  | -- | A non-recursive attribute set literal.+    SetLiteral+  | -- | A @rec@ set.+    SetRec+  | -- | The name table of a @let@ or @rec@ set with a dynamic name.+    SetScope+  | -- | The @//@ operator.+    SetUpdate+  | -- | @listToAttrs@.+    SetListToAttrs+  | -- | @removeAttrs@.+    SetRemoveAttrs+  | -- | @intersectAttrs@.+    SetIntersectAttrs+  | -- | @mapAttrs@.+    SetMapAttrs+  | -- | @zipAttrsWith@.+    SetZipAttrsWith+  | -- | @functionArgs@.+    SetFunctionArgs+  | -- | @groupBy@.+    SetGroupBy+  | -- | @partition@.+    SetPartition+  | -- | @parseDrvName@.+    SetParseDrvName+  | -- | @tryEval@.+    SetTryEval+  | -- | @getContext@: the result and each path's entry in it.+    SetGetContext+  | -- | @fromJSON@: each object.+    SetFromJSON+  | -- | @fromTOML@: each table.+    SetFromTOML+  | -- | @readDir@.+    SetReadDir+  | -- | @fetchGit@.+    SetFetchGit+  | -- | @parseFlakeRef@.+    SetParseFlakeRef+  | -- | @derivationStrict@.+    SetDerivationStrict+  | -- | A position's value, as @unsafeGetAttrPos@ and @__curPos@ make it.+    SetPosition+  deriving (Eq, Ord, Show, Enum, Bounded)++-- | The site's number in the C counts, below @NN_STATS_SET_SITES@.+setSiteIndex :: SetSite -> Word32+setSiteIndex = fromIntegral . fromEnum++-- | The site's name in the census report.+setSiteName :: SetSite -> BS.ByteString+setSiteName site = case site of+  SetRoot -> "root"+  SetLiteral -> "literal"+  SetRec -> "rec"+  SetScope -> "scope"+  SetUpdate -> "update"+  SetListToAttrs -> "listToAttrs"+  SetRemoveAttrs -> "removeAttrs"+  SetIntersectAttrs -> "intersectAttrs"+  SetMapAttrs -> "mapAttrs"+  SetZipAttrsWith -> "zipAttrsWith"+  SetFunctionArgs -> "functionArgs"+  SetGroupBy -> "groupBy"+  SetPartition -> "partition"+  SetParseDrvName -> "parseDrvName"+  SetTryEval -> "tryEval"+  SetGetContext -> "getContext"+  SetFromJSON -> "fromJSON"+  SetFromTOML -> "fromTOML"+  SetReadDir -> "readDir"+  SetFetchGit -> "fetchGit"+  SetParseFlakeRef -> "parseFlakeRef"+  SetDerivationStrict -> "derivationStrict"+  SetPosition -> "position"
src/Nix/Eval/Arena.hs view
@@ -1,129 +1,111 @@--- | Unified arena lifecycle for the C data layer.------ Initializes and destroys all C sub-arenas (symbol table, thunk arena,--- env slot allocator, bytecode store) with a single pair of calls.--- Handles StablePtr cleanup on destruction: iterates all thunks,--- identifies payloads that are Haskell StablePtrs (PENDING +--- COMPUTED\/PTR), and frees them before tearing down the C memory.------ Everything that evaluates runs between the two calls:------ @--- bracket_ arenaInit arenaDestroy $ do---   ... evaluation ...--- @------ Outside that window the C layer has no memory to hand out, and every--- path into it ('Nix.Builtins.builtinEnv', 'Nix.Eval.eval',--- 'Nix.Eval.force', the value constructors) raises--- 'ArenaNotInitialized' naming the C entry point that refused, rather--- than dereferencing state that does not exist.  Parsing ("Nix.Parser")--- is pure and needs no arena.+-- | The C data layer's arena lifecycle, which an evaluation session owns+-- ('Nix.Eval.IO.withEvalSession'): 'arenaInit' sets up every C sub-arena+-- (symbol table, string arena, thunk arena, env pages, bytecode store) as+-- the outermost session starts, and 'arenaDestroy' tears them down as it+-- ends.  Every value lives in C, so the teardown frees a session's values+-- whole, with nothing in GHC's heap to release.  The module is internal to+-- the library: no caller sets the arena up or tears it down. ----- 'ArenaNotInitialized' is a setup diagnosis: add the bracket and start--- the process again.  It is not an error to catch and retry in the same--- process, because GHC updates a thunk whose evaluation raised with that--- exception: any shared value whose evaluation reached C before the--- window re-raises it inside a later, live arena.  The @null@, @true@--- and @false@ thunks are C statics outside every arena, so forcing one--- needs no window and survives every cycle.+-- Outside a session the sub-arenas have no memory to hand out, and every+-- path that allocates from one ('Nix.Builtins.builtinEnv', 'Nix.Eval.eval',+-- 'Nix.Eval.force', the value constructors that make a cell or intern a+-- name) raises 'Nix.Eval.CStatus.ArenaNotInitialized' naming the C entry+-- point that refused, rather than dereferencing state that does not+-- exist.  The tracked objects (sets, list headers, lambdas, strings with+-- context, partial applications) are malloc'd, but their trackers take+-- one only while a session holds the arena (@cbits\/nn_tracker.h@), so+-- the binding modules' own constructors for them raise it too.  Outside+-- a session the one list there is to make is the empty one, which is a+-- null pointer and allocates nothing.  Parsing ("Nix.Parser") is+-- pure and needs no arena.  The @null@, @true@, @false@ and empty list+-- cells and each builtin's own cell are C statics outside every arena, so+-- forcing one needs no session and survives every one. module Nix.Eval.Arena-  ( -- * Lifecycle-    arenaInit,+  ( arenaInit,     arenaDestroy,-    arenaLive,--    -- * Errors-    CStatusError (..),   ) where -import Data.Word (Word32)-import Foreign.Marshal.Array (allocaArray, peekArray)-import Foreign.Ptr (Ptr)-import Foreign.StablePtr (castPtrToStablePtr, freeStablePtr)-import Nix.Eval.CBytecode (cbcDestroy, cbcInit)-import Nix.Eval.CCtxStr (cctxstrFreeAll)-import Nix.Eval.CEnv (cenvDestroy, cenvInit)-import Nix.Eval.CLambda (clambdaFreeAll)-import Nix.Eval.CList (clistFreeAll)-import Nix.Eval.CStatus (CStatusError (..), arenaLive)-import Nix.Eval.CThunk (cthunkDestroy, cthunkInit)-import Nix.Eval.Symbol (symbolDestroy, symbolInit)+import Nix.Eval.StartupSymbols (startupSymbols)+import Nix.Eval.Symbol (symbolIntern)  -- ------------------------------------------------------------------------------ FFI imports for batch StablePtr collection+-- The C lifecycle, which only this module calls -- --------------------------------------------------------------------------- -foreign import ccall unsafe "nn_arena_stableptr_count"-  c_nn_arena_stableptr_count :: IO Word32+foreign import ccall unsafe "nn_symbol_init" c_nn_symbol_init :: IO () -foreign import ccall unsafe "nn_arena_collect_stableptrs"-  c_nn_arena_collect_stableptrs :: Ptr (Ptr ()) -> Word32 -> IO Word32+foreign import ccall unsafe "nn_symbol_destroy" c_nn_symbol_destroy :: IO () --- ------------------------------------------------------------------------------ FFI import for bulk CAttrSet cleanup--- ---------------------------------------------------------------------------+foreign import ccall unsafe "nn_str_init" c_nn_str_init :: IO () -foreign import ccall unsafe "nn_attrset_free_all"-  cattrsetFreeAll :: IO ()+foreign import ccall unsafe "nn_str_destroy" c_nn_str_destroy :: IO () +foreign import ccall unsafe "nn_thunk_init" c_nn_thunk_init :: IO ()++foreign import ccall unsafe "nn_thunk_destroy" c_nn_thunk_destroy :: IO ()++foreign import ccall unsafe "nn_env_init" c_nn_env_init :: IO ()++foreign import ccall unsafe "nn_env_destroy" c_nn_env_destroy :: IO ()++foreign import ccall unsafe "nn_bytecode_init" c_nn_bytecode_init :: IO ()++foreign import ccall unsafe "nn_bytecode_destroy" c_nn_bytecode_destroy :: IO ()++foreign import ccall unsafe "nn_roots_clear" c_nn_roots_clear :: IO ()++foreign import ccall unsafe "nn_ctxstr_free_all" c_nn_ctxstr_free_all :: IO ()++foreign import ccall unsafe "nn_lambda_free_all" c_nn_lambda_free_all :: IO ()++foreign import ccall unsafe "nn_primop_app_free_all" c_nn_primop_app_free_all :: IO ()++foreign import ccall unsafe "nn_list_free_all" c_nn_list_free_all :: IO ()++foreign import ccall unsafe "nn_attrset_free_all" c_nn_attrset_free_all :: IO ()+ -- --------------------------------------------------------------------------- -- Lifecycle -- --------------------------------------------------------------------------- --- | Initialize all C data layer arenas.  Call once before evaluation.--- Initializes: symbol table, thunk arena, env slot allocator, bytecode store.+-- | Initialize all C data layer arenas, as the outermost evaluation+-- session starts: symbol table, string arena, thunk arena, env pages,+-- bytecode store.  The new symbol table interns upstream's startup names+-- ('startupSymbols') before anything else can, so that a name gets the+-- symbol upstream's would. arenaInit :: IO () arenaInit = do-  symbolInit 0-  cthunkInit 0-  cenvInit-  cbcInit 0 0+  c_nn_symbol_init+  mapM_ symbolIntern startupSymbols+  c_nn_str_init+  c_nn_thunk_init+  c_nn_env_init+  c_nn_bytecode_init --- | Destroy all C arenas, properly freeing StablePtrs first.------ This ends the process's use of the evaluator; a second 'arenaInit' does--- not restore one.  Thunks the library allocates once for the process,--- explicitly (@derivationWrapper@ in "Nix.Builtins") or as a--- parameter-free entry of 'Nix.Builtins.builtinEnv' that GHC shares--- across its calls (@storeDir@, @map@), keep pointing into the memory--- freed here, and only an entry built per call (@currentTime@) or one of--- the static @null@, @true@ and @false@ thunks survives a second cycle.+-- | Destroy all C arenas: the registered roots, the tracked objects+-- (strings with context, lambdas, partial applications, lists, sets),+-- then the bytecode store+-- with the code's strings, the env pages, the thunk blocks, the string+-- arena and the symbol table. ----- 1. Collects all StablePtr payloads from thunks (batch C call)--- 2. Frees each StablePtr from Haskell--- 3. Frees all tracked CLists (bulk cleanup)--- 4. Frees all tracked CAttrSets (bulk cleanup)--- 5. Destroys bytecode store--- 6. Destroys env slot pages--- 7. Destroys thunk arena blocks--- 8. Destroys symbol table + string arena+-- A second 'arenaInit' starts the evaluator afresh: no constant of the+-- program points into the memory freed here, since an evaluation+-- session builds its base environment and @derivation@ wrapper as it+-- starts ('Nix.Eval.IO.withEvalSession'), and the @null@, @true@, @false@+-- and empty list cells and the builtins' own cells are C statics that+-- survive every cycle.  A session's own values do not: one started+-- before the teardown is not used after it. arenaDestroy :: IO () arenaDestroy = do-  cleanupStablePtrs-  cctxstrFreeAll-  clambdaFreeAll-  clistFreeAll-  cattrsetFreeAll-  cbcDestroy-  cenvDestroy-  cthunkDestroy-  symbolDestroy---- | Free all StablePtrs held by thunk payloads.--- Uses batch C-side collection to avoid per-thunk FFI crossing.--- Frees payloads from three thunk states:---   PENDING:              StablePtr (Expr, Env)---   BLACKHOLE:            original PENDING StablePtr (eval failed/in-progress)---   COMPUTED/NN_VALUE_PTR: StablePtr NixValue--- Inline scalar/C-pointer payloads (INT..CTXSTR) are skipped.-cleanupStablePtrs :: IO ()-cleanupStablePtrs = do-  count <- c_nn_arena_stableptr_count-  if count == 0-    then pure ()-    else allocaArray (fromIntegral count) $ \buf -> do-      written <- c_nn_arena_collect_stableptrs buf count-      ptrs <- peekArray (fromIntegral written) buf-      mapM_ (freeStablePtr . castPtrToStablePtr) ptrs+  c_nn_roots_clear+  c_nn_ctxstr_free_all+  c_nn_lambda_free_all+  c_nn_primop_app_free_all+  c_nn_list_free_all+  c_nn_attrset_free_all+  c_nn_bytecode_destroy+  c_nn_env_destroy+  c_nn_thunk_destroy+  c_nn_str_destroy+  c_nn_symbol_destroy
src/Nix/Eval/AttrPath.hs view
@@ -1,3 +1,5 @@+{-# LANGUAGE LambdaCase #-}+ -- | Attribute-path selection, the machinery behind @build -A@. -- -- An attribute path is a dotted sequence of names selected left to right@@ -82,20 +84,26 @@ -- ---------------------------------------------------------------------------  -- | Follow an attribute path into an evaluated value, forcing each step.+-- Before each component, the value it indexes is passed through @call@,+-- as upstream's @findAlongAttrPath@ calls it with the command line's+-- arguments (attr-path.cc, "Nix.Eval.AutoCall"); a caller with nothing to+-- call passes 'pure'. -- -- Only the components named are forced: selecting one attribute leaves its -- siblings as thunks, so naming one package does not evaluate the rest of -- a package set.-selectAttrPath :: (MonadEval m) => Text -> NixValue -> m (Either Text NixValue)-selectAttrPath path root = case parseAttrPath path of+selectAttrPath :: (MonadEval m) => (NixValue -> m NixValue) -> Text -> NixValue -> m (Either Text NixValue)+selectAttrPath call path root = case parseAttrPath path of   Left err -> pure (Left err)   Right names -> walk names root   where     walk [] val = pure (Right val)-    walk (name : rest) val = case val of+    walk (name : rest) val = call val >>= select name rest+    select name rest val = case val of       VAttrs attrs         | T.null name -> pure (Left (emptyNameMessage path))-        | otherwise -> case attrSetLookup name attrs of+        | otherwise ->+            attrSetLookup name attrs >>= \case               Nothing -> pure (Left (notFoundMessage name path))               Just thunk -> force thunk >>= walk rest       -- Ordered as upstream orders it: the type of what is being indexed
+ src/Nix/Eval/AutoCall.hs view
@@ -0,0 +1,78 @@+{-# LANGUAGE LambdaCase #-}++-- | Calling the function a command line's target evaluates to, with the+-- values @--arg@ and @--argstr@ give: upstream's @autoCallFunction@+-- (eval.cc).+--+-- Only a function with a set pattern is called.  One with an ellipsis is+-- passed every argument; any other is passed the arguments its formals+-- name, and a formal with neither an argument nor a default fails before+-- the call, with upstream's message.  A set with @__functor@ is the+-- function its functor gives, called the same way, and anything else is+-- left as it is.+--+-- Upstream points that failure at the formal; a formal here carries no+-- position, so the message stands alone.+module Nix.Eval.AutoCall+  ( AutoArgs,+    autoCallFunction,+  )+where++import Data.List.NonEmpty (NonEmpty (..))+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import Nix.Eval (MonadEval (..), NixValue (..), Thunk, attrSetFromMap, attrSetLookup, deferApply, evaluated, force)+import Nix.Eval.AllocSite (SetSite (SetRoot))+import Nix.Eval.EvalFormals (EvalFormal (..), EvalFormals (..), hasDefault)+import Nix.Eval.Symbol (symbolText)++-- | The arguments by name.  A call shares each cell, so an argument the+-- function never uses is never evaluated.+type AutoArgs = Map Text Thunk++-- | The attribute that makes a set callable.+functorName :: Text+functorName = "__functor"++-- | The value the function a target evaluates to gives when called with+-- the arguments, or the value itself when it is no function with a set+-- pattern.+autoCallFunction :: (MonadEval m) => AutoArgs -> NixValue -> m NixValue+autoCallFunction args fun = case fun of+  VAttrs attrs ->+    attrSetLookup functorName attrs >>= \case+      Just functorThunk -> do+        functor <- force functorThunk+        self <- evaluated fun+        deferApply functor self >>= force >>= autoCallFunction args+      Nothing -> pure fun+  VLambda _ (EFSet _ formals ellipsis) _ -> callWith formals ellipsis+  VLambda _ (EFNamedSet _ _ formals ellipsis) _ -> callWith formals ellipsis+  _ -> pure fun+  where+    callWith formals ellipsis = do+      passed <- if ellipsis then pure args else taken formals+      argSet <- attrSetFromMap SetRoot passed+      evaluated (VAttrs argSet) >>= deferApply fun >>= force+    -- Upstream walks the formals in symbol order and fails at the first+    -- it cannot fill (autoCallFunction in eval.cc).+    taken formals = case [efName formal | formal <- formals, not (Map.member (symbolText (efName formal)) args), not (hasDefault (efDefault formal))] of+      [] -> pure (Map.restrictKeys args (Set.fromList (map (symbolText . efName) formals)))+      missing : more -> throwEvalError (missingArgumentMessage (symbolText (minimum (missing :| more))))++-- | Upstream's @MissingArgumentError@ for a formal no argument or default+-- fills (@autoCallFunction@ in eval.cc at 2.24.9).+missingArgumentMessage :: Text -> Text+missingArgumentMessage name =+  T.intercalate+    "\n"+    [ "cannot evaluate a function that has an argument without a value ('" <> name <> "')",+      "Nix attempted to evaluate a function as a top level expression; in",+      "this case it must have its arguments supplied either by default",+      "values, or passed explicitly with '--arg' or '--argstr'. See",+      "https://nixos.org/manual/nix/stable/language/constructs.html#functions."+    ]
+ src/Nix/Eval/Builtin.hs view
@@ -0,0 +1,262 @@+-- | The builtins the evaluator knows: one constructor for each primop of+-- upstream's base environment that nova-nix binds.  A builtin value names+-- one ('Nix.Eval.Types.VBuiltin'), and "Nix.Eval" gives each its+-- arguments and implementation in one total definition, so a builtin+-- with no definition does not compile.  The C data layer holds a builtin+-- as its index ('builtinIndex'), its constructor's position.+--+-- Meant to be imported qualified, its constructors named as+-- @Builtin.Map@, beside the type imported unqualified.+module Nix.Eval.Builtin+  ( Builtin (..),+    builtinName,+    builtinNamed,+    builtinIndex,+    builtinAtIndex,+  )+where++import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Text (Text)+import Data.Word (Word32)++-- | A builtin, by its name less upstream's @__@ prefix.+data Builtin+  = Abort+  | Add+  | AddDrvOutputDependencies+  | AddErrorContext+  | All+  | Any+  | AppendContext+  | AttrNames+  | AttrValues+  | BaseNameOf+  | BitAnd+  | BitOr+  | BitXor+  | Break+  | CatAttrs+  | Ceil+  | CompareVersions+  | ConcatLists+  | ConcatMap+  | ConcatStringsSep+  | ConvertHash+  | DeepSeq+  | DerivationStrict+  | DirOf+  | Div+  | Elem+  | ElemAt+  | FetchGit+  | FetchMercurial+  | FetchTarball+  | Fetchurl+  | Filter+  | FilterSource+  | FindFile+  | FlakeRefToString+  | Floor+  | FoldlStrict+  | FromJSON+  | FromTOML+  | FunctionArgs+  | GenList+  | GenericClosure+  | GetAttr+  | GetContext+  | GetEnv+  | GetFlake+  | GroupBy+  | HasAttr+  | HasContext+  | HashFile+  | HashString+  | Head+  | Import+  | IntersectAttrs+  | IsAttrs+  | IsBool+  | IsFloat+  | IsFunction+  | IsInt+  | IsList+  | IsNull+  | IsPath+  | IsString+  | Length+  | LessThan+  | ListToAttrs+  | Map+  | MapAttrs+  | Match+  | Mul+  | ParseDrvName+  | ParseFlakeRef+  | Partition+  | Path+  | PathExists+  | Placeholder+  | ReadDir+  | ReadFile+  | ReadFileType+  | RemoveAttrs+  | ReplaceStrings+  | ScopedImport+  | Seq+  | Sort+  | Split+  | SplitVersion+  | StorePath+  | StringLength+  | Sub+  | Substring+  | Tail+  | Throw+  | ToFile+  | ToJSON+  | ToPath+  | ToString+  | ToXML+  | Trace+  | TraceVerbose+  | TryEval+  | TypeOf+  | UnsafeDiscardOutputDependency+  | UnsafeDiscardStringContext+  | UnsafeGetAttrPos+  | Warn+  | ZipAttrsWith+  deriving (Eq, Ord, Show, Enum, Bounded)++-- | The name a builtin is bound under in @builtins@.+builtinName :: Builtin -> Text+builtinName builtin = case builtin of+  Abort -> "abort"+  Add -> "add"+  AddDrvOutputDependencies -> "addDrvOutputDependencies"+  AddErrorContext -> "addErrorContext"+  All -> "all"+  Any -> "any"+  AppendContext -> "appendContext"+  AttrNames -> "attrNames"+  AttrValues -> "attrValues"+  BaseNameOf -> "baseNameOf"+  BitAnd -> "bitAnd"+  BitOr -> "bitOr"+  BitXor -> "bitXor"+  Break -> "break"+  CatAttrs -> "catAttrs"+  Ceil -> "ceil"+  CompareVersions -> "compareVersions"+  ConcatLists -> "concatLists"+  ConcatMap -> "concatMap"+  ConcatStringsSep -> "concatStringsSep"+  ConvertHash -> "convertHash"+  DeepSeq -> "deepSeq"+  DerivationStrict -> "derivationStrict"+  DirOf -> "dirOf"+  Div -> "div"+  Elem -> "elem"+  ElemAt -> "elemAt"+  FetchGit -> "fetchGit"+  FetchMercurial -> "fetchMercurial"+  FetchTarball -> "fetchTarball"+  Fetchurl -> "fetchurl"+  Filter -> "filter"+  FilterSource -> "filterSource"+  FindFile -> "findFile"+  FlakeRefToString -> "flakeRefToString"+  Floor -> "floor"+  FoldlStrict -> "foldl'"+  FromJSON -> "fromJSON"+  FromTOML -> "fromTOML"+  FunctionArgs -> "functionArgs"+  GenList -> "genList"+  GenericClosure -> "genericClosure"+  GetAttr -> "getAttr"+  GetContext -> "getContext"+  GetEnv -> "getEnv"+  GetFlake -> "getFlake"+  GroupBy -> "groupBy"+  HasAttr -> "hasAttr"+  HasContext -> "hasContext"+  HashFile -> "hashFile"+  HashString -> "hashString"+  Head -> "head"+  Import -> "import"+  IntersectAttrs -> "intersectAttrs"+  IsAttrs -> "isAttrs"+  IsBool -> "isBool"+  IsFloat -> "isFloat"+  IsFunction -> "isFunction"+  IsInt -> "isInt"+  IsList -> "isList"+  IsNull -> "isNull"+  IsPath -> "isPath"+  IsString -> "isString"+  Length -> "length"+  LessThan -> "lessThan"+  ListToAttrs -> "listToAttrs"+  Map -> "map"+  MapAttrs -> "mapAttrs"+  Match -> "match"+  Mul -> "mul"+  ParseDrvName -> "parseDrvName"+  ParseFlakeRef -> "parseFlakeRef"+  Partition -> "partition"+  Path -> "path"+  PathExists -> "pathExists"+  Placeholder -> "placeholder"+  ReadDir -> "readDir"+  ReadFile -> "readFile"+  ReadFileType -> "readFileType"+  RemoveAttrs -> "removeAttrs"+  ReplaceStrings -> "replaceStrings"+  ScopedImport -> "scopedImport"+  Seq -> "seq"+  Sort -> "sort"+  Split -> "split"+  SplitVersion -> "splitVersion"+  StorePath -> "storePath"+  StringLength -> "stringLength"+  Sub -> "sub"+  Substring -> "substring"+  Tail -> "tail"+  Throw -> "throw"+  ToFile -> "toFile"+  ToJSON -> "toJSON"+  ToPath -> "toPath"+  ToString -> "toString"+  ToXML -> "toXML"+  Trace -> "trace"+  TraceVerbose -> "traceVerbose"+  TryEval -> "tryEval"+  TypeOf -> "typeOf"+  UnsafeDiscardOutputDependency -> "unsafeDiscardOutputDependency"+  UnsafeDiscardStringContext -> "unsafeDiscardStringContext"+  UnsafeGetAttrPos -> "unsafeGetAttrPos"+  Warn -> "warn"+  ZipAttrsWith -> "zipAttrsWith"++-- | The builtin bound under a name, if any.+builtinNamed :: Text -> Maybe Builtin+builtinNamed name = Map.lookup name byName++-- | Every builtin by its name.+byName :: Map Text Builtin+byName = Map.fromList [(builtinName builtin, builtin) | builtin <- [minBound .. maxBound]]++-- | A builtin's index in the C data layer: its constructor's position.+builtinIndex :: Builtin -> Word32+builtinIndex = fromIntegral . fromEnum++-- | The builtin at an index, if any.+builtinAtIndex :: Word32 -> Maybe Builtin+builtinAtIndex index = Map.lookup index byIndex++-- | Every builtin by its index.+byIndex :: Map Word32 Builtin+byIndex = Map.fromList [(builtinIndex builtin, builtin) | builtin <- [minBound .. maxBound]]
src/Nix/Eval/CAttrSet.hs view
@@ -1,29 +1,46 @@ -- | C-backed sorted attribute set via FFI. ----- Wraps @cbits/nn_attrset.c@ - a contiguous sorted array of--- @(nn_symbol_t, position, void*)@ entries.  Replaces Haskell's--- @Data.Map.Strict@ for attribute sets, cutting per-entry overhead from--- ~48 bytes (Map.Bin node) to ~16 bytes (4-byte symbol + 4-byte position--- + 8-byte pointer).+-- Wraps @cbits/nn_attrset.c@: parallel arrays of symbols, positions and+-- values, sorted by symbol, at about 16 bytes an entry (a 4-byte symbol,+-- a 4-byte position and an 8-byte pointer) against the 48 of a+-- @Data.Map.Strict@ node. -- -- Construction is two-phase: insert entries, then freeze (sort + dedup).--- After freeze, lookup is O(log n) binary search over contiguous memory.+-- After freeze, a lookup is a binary search of each layer's contiguous+-- arrays, top first, at most @NN_ATTRSET_MAX_LAYERS@ (8) of them. ----- Values are opaque @CThunkPtr@ handles stored as @void*@ on the C side.--- The C side never dereferences them.  Thunk lifetimes are managed by--- the thunk arena; attribute set cleanup only frees the key\/value arrays.+-- A set 'cattrsetUpdate' makes can be a layer on its left operand,+-- holding the right operand's entries alone, as upstream 2.34's+-- @Bindings@ layer on one another (attr-set.hh).  A set is read by name+-- ('cattrsetLookup', 'cattrsetFind', 'cattrsetMember'), which searches its+-- layers top first, or walked in symbol order ('cattrsetWalk').  Only a name+-- table ('cattrsetFromNames'), a t'FlatCAttrSet', is read and written by+-- index into its arrays. --+-- Values are 'CThunkPtr' cells stored as @void*@ on the C side.  The set+-- never dereferences them, and the census ("Nix.Eval.CStats") follows+-- them.  The thunk arena owns the cells, so freeing a set frees its own+-- arrays alone.+--+-- Every constructor names its 'SetSite', under which the census counts+-- the set.  'cattrsetEmpty' is the one set no constructor makes: the+-- shared set with no entries.+-- -- A set holds at most 'maxBound' :: 'Word32' entries, upstream's own -- ceiling (its @Bindings@ counts in @uint32_t@).  Every constructor and -- insert checks its C result, so a set the C side cannot build raises -- 'Nix.Eval.CStatus.CStatusError' instead of leaving a NULL or a short -- set behind. module Nix.Eval.CAttrSet-  ( -- * Opaque handle+  ( -- * Opaque handles     CAttrSet,+    FlatCAttrSet,+    flatCAttrSet,      -- * Lifecycle     cattrsetNew,+    cattrsetEmpty,+    cattrsetFromNames,      -- * Construction     cattrsetInsert,@@ -31,30 +48,41 @@      -- * Query     cattrsetLookup,+    cattrsetFind,+    cattrsetMember,++    -- * Walks+    CAttrSetWalk,+    CAttrSetStep (..),+    cattrsetWalk,+    cattrsetWalkNext,++    -- * Name tables by index     cattrsetIndex,-    cattrsetGetValue,     cattrsetSetValue,-    cattrsetGetKey,-    cattrsetGetPos,      -- * Bulk access     cattrsetSize,-    cattrsetKeys,      -- * Set operations     cattrsetUnion,+    cattrsetUpdate,     cattrsetRemoveKeys,   ) where -import Control.Monad (unless)+import Control.Monad (forM, forM_, unless) import Data.Word (Word32) import Foreign.C.Types (CInt (..))-import Foreign.Marshal.Array (peekArray, withArray)-import Foreign.Ptr (Ptr, castPtr, nullPtr)+import Foreign.Marshal.Alloc (allocaBytesAligned)+import Foreign.Marshal.Array (allocaArray, withArray)+import Foreign.Ptr (Ptr, castPtr, nullPtr, plusPtr)+import Foreign.Storable (alignment, peek, peekElemOff, sizeOf)+import Nix.Eval.AllocSite (SetSite, setSiteIndex)+import Nix.Eval.CData (MonadCData, cdataIO) import Nix.Eval.CStatus (cStatusFailure, checkedCPtr) import Nix.Eval.CThunk (CThunkPtr)-import Nix.Eval.SourcePos (PosIdx (..))+import Nix.Eval.SourcePos (PosIdx (..), noPos) import Nix.Eval.Symbol (Symbol (..))  -- | Opaque handle to a C-allocated attribute set.@@ -64,13 +92,32 @@ -- | Convenience alias. type CAttrSet = Ptr NnAttrSet +-- | A frozen set whose own arrays hold every entry it binds, sorted by+-- symbol, so that an index into them names one of its entries: the set+-- 'cattrsetIndex' and 'cattrsetSetValue' take.  The constructor is not+-- exported, so every one is a name table 'cattrsetFromNames' made.+newtype FlatCAttrSet = FlatCAttrSet CAttrSet++-- | The set a t'FlatCAttrSet' is.+flatCAttrSet :: FlatCAttrSet -> CAttrSet+flatCAttrSet (FlatCAttrSet set) = set+ -- --------------------------------------------------------------------------- -- FFI imports (all unsafe - no callbacks, fast data access) -- ---------------------------------------------------------------------------  foreign import ccall unsafe "nn_attrset_new"-  c_nn_attrset_new :: Word32 -> IO CAttrSet+  c_nn_attrset_new :: Word32 -> Word32 -> IO CAttrSet +-- The empty set is a C static, one address for the life of the process,+-- so this import is pure, as the empty env of "Nix.Eval.CEnv" is: no+-- arena window, nor its absence, changes what it returns.++-- | The shared set with no entries (@nn_attrset_empty@): frozen, and+-- refused by every write.+foreign import ccall unsafe "nn_attrset_empty"+  cattrsetEmpty :: CAttrSet+ foreign import ccall unsafe "nn_attrset_insert"   c_nn_attrset_insert :: CAttrSet -> Word32 -> Ptr () -> Word32 -> IO CInt @@ -80,6 +127,9 @@ foreign import ccall unsafe "nn_attrset_lookup"   c_nn_attrset_lookup :: CAttrSet -> Word32 -> IO (Ptr ()) +foreign import ccall unsafe "nn_attrset_find"+  c_nn_attrset_find :: CAttrSet -> Word32 -> Ptr Word32 -> Ptr (Ptr ()) -> IO CInt+ foreign import ccall unsafe "nn_attrset_index"   c_nn_attrset_index :: CAttrSet -> Word32 -> IO Word32 @@ -98,14 +148,23 @@ foreign import ccall unsafe "nn_attrset_size"   c_nn_attrset_size :: CAttrSet -> IO Word32 -foreign import ccall unsafe "nn_attrset_keys_ptr"-  c_nn_attrset_keys_ptr :: CAttrSet -> IO (Ptr Word32)+foreign import ccall unsafe "nn_attrset_layer_count"+  c_nn_attrset_layer_count :: CAttrSet -> IO Word32 +foreign import ccall unsafe "nn_attrset_base"+  c_nn_attrset_base :: CAttrSet -> IO CAttrSet++foreign import ccall unsafe "nn_attrset_entries"+  c_nn_attrset_entries :: CAttrSet -> Ptr Word32 -> Ptr Word32 -> Ptr (Ptr ()) -> IO ()+ foreign import ccall unsafe "nn_attrset_union"-  c_nn_attrset_union :: CAttrSet -> CAttrSet -> IO CAttrSet+  c_nn_attrset_union :: CAttrSet -> CAttrSet -> Word32 -> IO CAttrSet +foreign import ccall unsafe "nn_attrset_update"+  c_nn_attrset_update :: CAttrSet -> CAttrSet -> Word32 -> IO CAttrSet+ foreign import ccall unsafe "nn_attrset_remove_keys"-  c_nn_attrset_remove_keys :: CAttrSet -> Ptr Word32 -> Word32 -> IO CAttrSet+  c_nn_attrset_remove_keys :: CAttrSet -> Ptr Word32 -> Word32 -> Word32 -> IO CAttrSet  -- | @NN_ATTRSET_NOT_FOUND@, the index answer for an absent key.  Must -- stay in lockstep with @cbits\/nn_attrset.h@.@@ -116,30 +175,46 @@ -- Lifecycle -- --------------------------------------------------------------------------- --- | Allocate a new empty attribute set sized for the expected number of--- entries.  The count only sizes the first allocation, so one past the--- ceiling is clamped to it: the inserts are what enforce the ceiling.-cattrsetNew :: Int -> IO CAttrSet-cattrsetNew expected = checkedCPtr "nn_attrset_new" =<< c_nn_attrset_new capacity+-- | Allocate a new empty attribute set at a site, sized for the expected+-- number of entries.  The count only sizes the first allocation, so one+-- past the ceiling is clamped to it: the inserts are what enforce the+-- ceiling.+cattrsetNew :: (MonadCData m) => SetSite -> Int -> m CAttrSet+cattrsetNew site expected = cdataIO (checkedCPtr "nn_attrset_new" =<< c_nn_attrset_new capacity (setSiteIndex site))   where     capacity = fromIntegral (max 0 (min expected entryCeiling))     entryCeiling = fromIntegral (maxBound :: Word32) +-- | A frozen set at a site binding each name to no value, a null+-- pointer, at no position: a table whose values are written afterwards,+-- by index ('cattrsetSetValue').  No names give the shared empty set,+-- which holds no index to write at.+cattrsetFromNames :: (MonadCData m) => SetSite -> [Symbol] -> m FlatCAttrSet+cattrsetFromNames _ [] = pure (FlatCAttrSet cattrsetEmpty)+cattrsetFromNames site names = do+  set <- cattrsetNew site (length names)+  forM_ names $ \name -> cattrsetInsert set name noPos nullPtr+  cattrsetFreeze set+  pure (FlatCAttrSet set)+ -- --------------------------------------------------------------------------- -- Construction -- --------------------------------------------------------------------------- --- | Insert a key-value pair defined at a position.  Call before freeze.--- The value is a CThunkPtr cast to Ptr () - C never dereferences it.-cattrsetInsert :: CAttrSet -> Symbol -> PosIdx -> CThunkPtr -> IO ()-cattrsetInsert set (Symbol sym) (PosIdx pos) ptr = do+-- | Insert a key-value pair defined at a position, into a set not yet+-- frozen: a frozen one aborts in C.+-- The value is a 'CThunkPtr' cast to @Ptr ()@: the set never dereferences+-- it, and the census follows it.+cattrsetInsert :: (MonadCData m) => CAttrSet -> Symbol -> PosIdx -> CThunkPtr -> m ()+cattrsetInsert set (Symbol sym) (PosIdx pos) ptr = cdataIO $ do   status <- c_nn_attrset_insert set sym (castPtr ptr) pos   unless (status == 0) $     cStatusFailure "nn_attrset_insert" "the attribute set cannot grow (allocation failure or its 4294967295-entry ceiling)" --- | Sort and deduplicate.  Must be called once before any queries.-cattrsetFreeze :: CAttrSet -> IO ()-cattrsetFreeze = c_nn_attrset_freeze+-- | Sort the entries and keep the last insert of a repeated key, which a+-- lookup needs.  Freezing a frozen set does nothing.+cattrsetFreeze :: (MonadCData m) => CAttrSet -> m ()+cattrsetFreeze = cdataIO . c_nn_attrset_freeze  -- --------------------------------------------------------------------------- -- Query@@ -147,61 +222,150 @@  -- | Look up a key.  Returns 'Nothing' if not found. -- The returned 'CThunkPtr' is borrowed - the thunk arena owns it.-cattrsetLookup :: CAttrSet -> Symbol -> IO (Maybe CThunkPtr)-cattrsetLookup set (Symbol sym) = do+cattrsetLookup :: (MonadCData m) => CAttrSet -> Symbol -> m (Maybe CThunkPtr)+cattrsetLookup set (Symbol sym) = cdataIO $ do   ptr <- c_nn_attrset_lookup set sym   pure (if ptr == nullPtr then Nothing else Just (castPtr ptr)) +-- | The position a set binds a name at and the value it binds it to, or+-- 'Nothing' if it binds no such name.  A value not filled yet, the null+-- pointer a name table holds until its frame fills it, is found as such,+-- where 'cattrsetLookup' answers 'Nothing'.+cattrsetFind :: (MonadCData m) => CAttrSet -> Symbol -> m (Maybe (PosIdx, CThunkPtr))+cattrsetFind set (Symbol sym) = cdataIO $+  allocaBytesAligned findOutputBytes findOutputAlignment $ \outputs -> do+    let valuePtr = castPtr outputs+        posPtr = outputs `plusPtr` findPositionOffset+    found <- c_nn_attrset_find set sym posPtr valuePtr+    if found == 0+      then pure Nothing+      else (\pos value -> Just (PosIdx pos, castPtr value)) <$> peek posPtr <*> peek valuePtr++-- | One buffer holds both of @nn_attrset_find@'s outputs, so a find+-- allocates once: the value's pointer at its start, aligned for a+-- pointer, and the position right after it, at an offset of a pointer's+-- size, which its own alignment divides.+findPositionOffset, findOutputBytes, findOutputAlignment :: Int+findPositionOffset = sizeOf (nullPtr :: Ptr ())+findOutputBytes = findPositionOffset + sizeOf (0 :: Word32)+findOutputAlignment = alignment (nullPtr :: Ptr ())++-- | Whether a set binds a name, one whose value is not filled yet among+-- them, as 'cattrsetFind' finds it, with nothing read back.+cattrsetMember :: (MonadCData m) => CAttrSet -> Symbol -> m Bool+cattrsetMember set (Symbol sym) = cdataIO ((/= 0) <$> c_nn_attrset_find set sym nullPtr nullPtr)++-- ---------------------------------------------------------------------------+-- Walks+-- ---------------------------------------------------------------------------++-- | A walk over a set's entries in symbol order, at the entry it reads+-- next.+data CAttrSetWalk+  = -- | A flat set read in place: the set, that entry's index into its+    -- arrays, and how many entries they hold.+    CAttrSetInPlace !CAttrSet !Word32 !Word32+  | -- | A layered set's entries still to read, copied out of its layers+    -- when the walk began.+    CAttrSetCopied ![CAttrSetCopy]++-- | An entry copied out of a layered set: its name, position and value.+data CAttrSetCopy = CAttrSetCopy !Symbol !PosIdx !CThunkPtr++-- | What a walk reads next.+data CAttrSetStep+  = -- | The end of the set.+    CAttrSetDone+  | -- | An entry, its name, the position it was defined at and its value,+    -- with the walk past it.+    CAttrSetEntry !Symbol !PosIdx !CThunkPtr !CAttrSetWalk++-- | A walk from a set's first entry.  A flat set's arrays are read in+-- place, one entry at a time: a frozen set's entries never move, so+-- whatever runs between two steps, the walk reads each entry once.  A+-- layered set's entries are copied out of its layers in symbol order+-- first (@nn_attrset_entries@), each name from its topmost layer.+{-# INLINE cattrsetWalk #-}+cattrsetWalk :: (MonadCData m) => CAttrSet -> m CAttrSetWalk+cattrsetWalk set = cdataIO $ do+  base <- c_nn_attrset_base set+  if base == nullPtr+    then CAttrSetInPlace set 0 <$> c_nn_attrset_layer_count set+    else CAttrSetCopied <$> copiedEntries set++-- | The entries a layered set binds, copied out of its layers in symbol+-- order into arrays sized for them.+copiedEntries :: CAttrSet -> IO [CAttrSetCopy]+copiedEntries set = do+  size <- fromIntegral <$> c_nn_attrset_size set+  allocaArray size $ \names -> allocaArray size $ \positions -> allocaArray size $ \values -> do+    c_nn_attrset_entries set names positions values+    forM [0 .. size - 1] $ \i -> do+      name <- peekElemOff names i+      pos <- peekElemOff positions i+      value <- peekElemOff values i+      pure $! CAttrSetCopy (Symbol name) (PosIdx pos) (castPtr value)++-- | The entry a walk reads next, or 'CAttrSetDone' past the last.+{-# INLINE cattrsetWalkNext #-}+cattrsetWalkNext :: (MonadCData m) => CAttrSetWalk -> m CAttrSetStep+cattrsetWalkNext (CAttrSetInPlace set idx count)+  | idx >= count = pure CAttrSetDone+  | otherwise = cdataIO $ do+      name <- c_nn_attrset_get_key set idx+      pos <- c_nn_attrset_get_pos set idx+      value <- c_nn_attrset_get_value set idx+      pure (CAttrSetEntry (Symbol name) (PosIdx pos) (castPtr value) (CAttrSetInPlace set (idx + 1) count))+cattrsetWalkNext (CAttrSetCopied []) = pure CAttrSetDone+cattrsetWalkNext (CAttrSetCopied (CAttrSetCopy name pos value : rest)) = pure (CAttrSetEntry name pos value (CAttrSetCopied rest))++-- ---------------------------------------------------------------------------+-- Name tables by index+-- ---------------------------------------------------------------------------+ -- | Find the index of a key, or 'Nothing' if not found.-cattrsetIndex :: CAttrSet -> Symbol -> IO (Maybe Word32)-cattrsetIndex set (Symbol sym) = do+cattrsetIndex :: (MonadCData m) => FlatCAttrSet -> Symbol -> m (Maybe Word32)+cattrsetIndex (FlatCAttrSet set) (Symbol sym) = cdataIO $ do   idx <- c_nn_attrset_index set sym   pure (if idx == indexNotFound then Nothing else Just idx) --- | Get the value at a known index.-cattrsetGetValue :: CAttrSet -> Word32 -> IO CThunkPtr-cattrsetGetValue set idx = castPtr <$> c_nn_attrset_get_value set idx- -- | Update the value at a known index (for two-phase construction).-cattrsetSetValue :: CAttrSet -> Word32 -> CThunkPtr -> IO ()-cattrsetSetValue set idx ptr = c_nn_attrset_set_value set idx (castPtr ptr)---- | Get the key symbol at a known index.-cattrsetGetKey :: CAttrSet -> Word32 -> IO Symbol-cattrsetGetKey set idx = Symbol <$> c_nn_attrset_get_key set idx---- | Get the position of the entry at a known index.-cattrsetGetPos :: CAttrSet -> Word32 -> IO PosIdx-cattrsetGetPos set idx = PosIdx <$> c_nn_attrset_get_pos set idx+cattrsetSetValue :: (MonadCData m) => FlatCAttrSet -> Word32 -> CThunkPtr -> m ()+cattrsetSetValue (FlatCAttrSet set) idx ptr = cdataIO (c_nn_attrset_set_value set idx (castPtr ptr))  -- --------------------------------------------------------------------------- -- Bulk access -- --------------------------------------------------------------------------- --- | Number of entries (unique keys after freeze).-cattrsetSize :: CAttrSet -> IO Word32-cattrsetSize = c_nn_attrset_size---- | Read all keys as a list of symbols (sorted).-cattrsetKeys :: CAttrSet -> IO [Symbol]-cattrsetKeys set = do-  n <- cattrsetSize set-  ptr <- c_nn_attrset_keys_ptr set-  raw <- peekArray (fromIntegral n) ptr-  pure (map Symbol raw)+-- | Number of entries (after freeze: the names the set binds, in every+-- layer, each once).+cattrsetSize :: (MonadCData m) => CAttrSet -> m Word32+cattrsetSize = cdataIO . c_nn_attrset_size  -- --------------------------------------------------------------------------- -- Set operations -- --------------------------------------------------------------------------- --- | Right-biased union (// semantics).  Result is frozen.-cattrsetUnion :: CAttrSet -> CAttrSet -> IO CAttrSet-cattrsetUnion a b = checkedCPtr "nn_attrset_union" =<< c_nn_attrset_union a b+-- | Right-biased union (// semantics) at a site: a new flat set holding+-- the entries of both.  Result is frozen.+cattrsetUnion :: (MonadCData m) => SetSite -> CAttrSet -> CAttrSet -> m CAttrSet+cattrsetUnion site a b = cdataIO (checkedCPtr "nn_attrset_union" =<< c_nn_attrset_union a b (setSiteIndex site)) --- | Remove a list of keys.  Result is frozen.-cattrsetRemoveKeys :: CAttrSet -> [Symbol] -> IO CAttrSet-cattrsetRemoveKeys set syms = do+-- | @a // b@ at a site, as upstream 2.34 makes it (@ExprOpUpdate::eval@ in+-- eval.cc): a layer on @a@ holding @b@'s entries while @a@'s chain holds+-- fewer than @NN_ATTRSET_MAX_LAYERS@ (8) sets and @b@ at most+-- @NN_ATTRSET_LAYER_RHS_MAX@ entries (16 where a pointer takes 8 bytes),+-- else the set 'cattrsetUnion' makes.  While+-- the census counts sites ("Nix.Eval.CStats") it counts the entries+-- copied, @b@'s for a layer and the result's for a union, as upstream+-- counts them in @nrOpUpdateValuesCopied@.  Result is frozen.+cattrsetUpdate :: (MonadCData m) => SetSite -> CAttrSet -> CAttrSet -> m CAttrSet+cattrsetUpdate site a b = cdataIO (checkedCPtr "nn_attrset_update" =<< c_nn_attrset_update a b (setSiteIndex site))++-- | Remove a list of keys, making the result at a site.  Result is frozen.+cattrsetRemoveKeys :: (MonadCData m) => SetSite -> CAttrSet -> [Symbol] -> m CAttrSet+cattrsetRemoveKeys site set syms = cdataIO $ do   let raw = map unSymbol syms       n = fromIntegral (length raw)   withArray raw $ \ptr ->-    checkedCPtr "nn_attrset_remove_keys" =<< c_nn_attrset_remove_keys set ptr n+    checkedCPtr "nn_attrset_remove_keys" =<< c_nn_attrset_remove_keys set ptr n (setSiteIndex site)
src/Nix/Eval/CBytecode.hs view
@@ -2,25 +2,27 @@  -- | C-backed bytecode storage via FFI. ----- Wraps @cbits/nn_bytecode.c@ - two growable arrays storing flat Nix--- expression bytecode: an @nn_op_t[]@ instruction array (16 bytes each)--- and a @uint32_t[]@ data buffer for variable-length operands.+-- Wraps @cbits/nn_bytecode.c@ - growable arrays storing flat Nix+-- expression bytecode: an @nn_op_t[]@ instruction array (16 bytes each),+-- a @uint32_t[]@ data buffer for variable-length operands, and a table of+-- the code's strings, the bytes of its literals, which an instruction or+-- a data word names by index.  The code's strings live as long as the+-- code, so a value a literal evaluates to can point at one rather than+-- copy it. --+-- In an evaluation session ('Nix.Eval.IO.withEvalSession'):+-- -- @--- cbcInit 0 0 -- idx <- cbcEmit OpLitInt 0 0 42 0 0--- cbcOpcode idx   -- NN_OP_LIT_INT (0)+-- cbcOpcode idx   -- OpLitInt (0) -- cbcArg1 idx     -- 42--- cbcDestroy -- @ module Nix.Eval.CBytecode-  ( -- * Lifecycle-    cbcInit,-    cbcDestroy,--    -- * Emit+  ( -- * Emit     cbcEmit,     cbcEmitData,+    cbcEmitString,+    cbcEmitText,      -- * Read instructions     cbcOpcode,@@ -33,14 +35,15 @@     -- * Read data     cbcData, +    -- * Read strings+    cbcString,+    cbcStringBytes,+    cbcStringText,+     -- * Counted payloads (short_arg spill)     spilledCountSentinel,     cbcCountedPayload, -    -- * Reserved instructions-    reservedApply1,-    reservedApply2,-     -- * Diagnostics     cbcOpCount,     cbcDataCount,@@ -69,12 +72,13 @@     pattern OpAssert,     pattern OpUnary,     pattern OpBinary,-    pattern OpSearchPath,     pattern OpPathStr,+    pattern OpPos, -    -- * App flags-    appDirect,-    appDeferred,+    -- * Attribute set flags+    attrsPlain,+    attrsRec,+    attrsRecOverrides,      -- * UnaryOp flags     unaryNot,@@ -102,6 +106,11 @@     formalSet,     formalNamedSet, +    -- * Formal default kinds+    formalNoDefault,+    formalDefault,+    formalSharedDefault,+     -- * String part tags     strpartLit,     strpartInterp,@@ -123,25 +132,33 @@   ) where +import Data.ByteString (ByteString)+import qualified Data.ByteString.Unsafe as BSU+import Data.Text (Text)+import qualified Data.Text.Foreign as TF import Data.Word (Word16, Word32, Word8)-import Nix.Eval.CStatus (cStatusFailure)+import Foreign.C.Types (CChar, CSize (..))+import Foreign.Ptr (Ptr, nullPtr)+import Nix.Eval.CData (MonadCData, cdataIO)+import Nix.Eval.CStatus (cInvariantViolated, cStatusFailure)+import Nix.Eval.CStr (CStrPtr, cstrBytes, cstrText)  -- --------------------------------------------------------------------------- -- FFI imports (all unsafe - no callbacks, fast data access) -- --------------------------------------------------------------------------- -foreign import ccall unsafe "nn_bytecode_init"-  c_nn_bytecode_init :: Word32 -> Word32 -> IO ()--foreign import ccall unsafe "nn_bytecode_destroy"-  c_nn_bytecode_destroy :: IO ()- foreign import ccall unsafe "nn_bc_emit"   c_nn_bc_emit :: Word8 -> Word8 -> Word16 -> Word32 -> Word32 -> Word32 -> IO Word32  foreign import ccall unsafe "nn_bc_emit_data"   c_nn_bc_emit_data :: Word32 -> IO Word32 +foreign import ccall unsafe "nn_bc_emit_string"+  c_nn_bc_emit_string :: Ptr CChar -> CSize -> IO Word32++foreign import ccall unsafe "nn_bc_string"+  c_nn_bc_string :: Word32 -> IO CStrPtr+ foreign import ccall unsafe "nn_bc_opcode"   c_nn_bc_opcode :: Word32 -> IO Word8 @@ -170,33 +187,34 @@   c_nn_bc_data_count :: IO Word32  -- ------------------------------------------------------------------------------ Lifecycle--- ------------------------------------------------------------------------------- | Initialize the global bytecode store.  Call once before evaluation.--- Arguments are capacity hints (0 = defaults: 65536 ops, 131072 data).--- The store starts with the reserved instructions ('reservedApply1',--- 'reservedApply2') already in place.-cbcInit :: Word32 -> Word32 -> IO ()-cbcInit = c_nn_bytecode_init---- | Destroy the global bytecode store, freeing all memory.-cbcDestroy :: IO ()-cbcDestroy = c_nn_bytecode_destroy---- --------------------------------------------------------------------------- -- Emit -- ---------------------------------------------------------------------------  -- | Append one instruction.  Returns the instruction index.-cbcEmit :: Word8 -> Word8 -> Word16 -> Word32 -> Word32 -> Word32 -> IO Word32+cbcEmit :: (MonadCData m) => Word8 -> Word8 -> Word16 -> Word32 -> Word32 -> Word32 -> m Word32 cbcEmit opcode flags shortArg arg1 arg2 arg3 =-  checkedEmit "nn_bc_emit" =<< c_nn_bc_emit opcode flags shortArg arg1 arg2 arg3+  cdataIO $ checkedEmit "nn_bc_emit" =<< c_nn_bc_emit opcode flags shortArg arg1 arg2 arg3  -- | Append one uint32 to the data buffer.  Returns the data offset.-cbcEmitData :: Word32 -> IO Word32-cbcEmitData value = checkedEmit "nn_bc_emit_data" =<< c_nn_bc_emit_data value+cbcEmitData :: (MonadCData m) => Word32 -> m Word32+cbcEmitData value = cdataIO (checkedEmit "nn_bc_emit_data" =<< c_nn_bc_emit_data value) +-- | Copy bytes into a new string of the code's and answer its index,+-- which 'cbcString' reads back.  'BSU.unsafeUseAsCStringLen' is safe+-- here: @nn_bc_emit_string@ copies the bytes and keeps no pointer to+-- them.+cbcEmitString :: (MonadCData m) => ByteString -> m Word32+cbcEmitString bytes =+  cdataIO . BSU.unsafeUseAsCStringLen bytes $ \(ptr, len) ->+    checkedEmit "nn_bc_emit_string" =<< c_nn_bc_emit_string ptr (fromIntegral len)++-- | 'cbcEmitString' for text's UTF-8 bytes: a path, a URI or a source+-- file's path, which the evaluator reads back as text ('cbcStringText').+cbcEmitText :: (MonadCData m) => Text -> m Word32+cbcEmitText text =+  cdataIO . TF.withCStringLen text $ \(ptr, len) ->+    checkedEmit "nn_bc_emit_string" =<< c_nn_bc_emit_string ptr (fromIntegral len)+ -- | @UINT32_MAX@ from a C emit function signals a failed append (realloc -- exhaustion or the uint32 index ceiling), not a valid index.  Must stay -- in lockstep with the emit docs in @cbits\/nn_bytecode.h@.@@ -205,8 +223,8 @@  -- | Reject the failure sentinel before it can flow onward as an index: -- the bytecode arrays are global C state, so a failed append leaves--- nothing to recover, and the read-side bounds on a sentinel index do--- not survive a release build.+-- nothing to recover, and the sentinel read back as an index would abort+-- at the first read's bound (@NN_ASSERT@) instead of raising here. checkedEmit :: String -> Word32 -> IO Word32 checkedEmit site idx   | idx == emitFailedSentinel = cStatusFailure site "bytecode append failed (allocation failure or index ceiling)"@@ -217,39 +235,67 @@ -- ---------------------------------------------------------------------------  -- | The opcode byte of instruction @i@ (one of the @Op*@ constants).-cbcOpcode :: Word32 -> IO Word8-cbcOpcode = c_nn_bc_opcode+cbcOpcode :: (MonadCData m) => Word32 -> m Word8+cbcOpcode = cdataIO . c_nn_bc_opcode  -- | The flags byte of instruction @i@ - the sub-type selector (e.g. which -- unary/binary operator), interpreted via the sub-type-flag constants below.-cbcFlags :: Word32 -> IO Word8-cbcFlags = c_nn_bc_flags+cbcFlags :: (MonadCData m) => Word32 -> m Word8+cbcFlags = cdataIO . c_nn_bc_flags --- | The inline 16-bit argument of instruction @i@ (e.g. a de Bruijn slot).-cbcShortArg :: Word32 -> IO Word16-cbcShortArg = c_nn_bc_short_arg+-- | The inline 16-bit argument of instruction @i@: a Boolean literal's+-- value, the count of a counted payload (string parts, bindings, list+-- elements, an attribute path's names) or 'spilledCountSentinel' for one+-- too long to hold ('cbcCountedPayload' reads either), and 0 for every+-- other instruction.+cbcShortArg :: (MonadCData m) => Word32 -> m Word16+cbcShortArg = cdataIO . c_nn_bc_short_arg  -- | The first 32-bit argument of instruction @i@.-cbcArg1 :: Word32 -> IO Word32-cbcArg1 = c_nn_bc_arg1+cbcArg1 :: (MonadCData m) => Word32 -> m Word32+cbcArg1 = cdataIO . c_nn_bc_arg1  -- | The second 32-bit argument of instruction @i@.-cbcArg2 :: Word32 -> IO Word32-cbcArg2 = c_nn_bc_arg2+cbcArg2 :: (MonadCData m) => Word32 -> m Word32+cbcArg2 = cdataIO . c_nn_bc_arg2  -- | The third 32-bit argument of instruction @i@.-cbcArg3 :: Word32 -> IO Word32-cbcArg3 = c_nn_bc_arg3+cbcArg3 :: (MonadCData m) => Word32 -> m Word32+cbcArg3 = cdataIO . c_nn_bc_arg3  -- --------------------------------------------------------------------------- -- Read data -- --------------------------------------------------------------------------- --- | Read entry @i@ of the bytecode data pool (interned literals, symbols).-cbcData :: Word32 -> IO Word32-cbcData = c_nn_bc_data+-- | Read entry @i@ of the bytecode data pool (symbols, string indices,+-- child indices and the rest).+cbcData :: (MonadCData m) => Word32 -> m Word32+cbcData = cdataIO . c_nn_bc_data  -- ---------------------------------------------------------------------------+-- Read strings+-- ---------------------------------------------------------------------------++-- | The code's string at an index 'cbcEmitString' answered.  It lives as+-- long as the code, so a cell may point at it.  The compiler writes every+-- index the evaluator reads, so an index with no string is a corrupt+-- store.+cbcString :: (MonadCData m) => Word32 -> m CStrPtr+cbcString index = cdataIO $ do+  str <- c_nn_bc_string index+  if str == nullPtr+    then cInvariantViolated "nn_bc_string" ("no string at index " ++ show index)+    else pure str++-- | A copy of the bytes of the code's string at an index.+cbcStringBytes :: (MonadCData m) => Word32 -> m ByteString+cbcStringBytes index = cbcString index >>= cstrBytes++-- | The text of the code's string at an index 'cbcEmitText' answered.+cbcStringText :: (MonadCData m) => Word32 -> m Text+cbcStringText index = cbcString index >>= cstrText++-- --------------------------------------------------------------------------- -- Counted payloads (short_arg spill) -- --------------------------------------------------------------------------- @@ -266,8 +312,8 @@ -- spill convention.  @dataOff@ is the raw offset stored in the op's arg -- word (arg1 for most counted ops, arg2 for select\/hasAttr paths). -- The inline case costs one compare.-cbcCountedPayload :: Word32 -> Word32 -> IO (Int, Word32)-cbcCountedPayload bcIdx dataOff = do+cbcCountedPayload :: (MonadCData m) => Word32 -> Word32 -> m (Int, Word32)+cbcCountedPayload bcIdx dataOff = cdataIO $ do   inline <- cbcShortArg bcIdx   if inline == spilledCountSentinel     then do@@ -276,27 +322,6 @@     else pure (fromIntegral inline, dataOff)  -- ------------------------------------------------------------------------------ Reserved instructions--- ------------------------------------------------------------------------------- | Code that applies slot 0 of its env to slot 1, a deferred call--- (upstream's @mkApp@).  'cbcInit' lays it down at this index in every--- store, so a builtin that makes such a thunk per element (@map@,--- @genList@) points each one here instead of compiling its own copy.--- Must stay in lockstep with @NN_BC_RESERVED_APPLY1@ in--- @cbits\/nn_bytecode.h@.-reservedApply1 :: Word32-reservedApply1 = 2---- | Code that applies slot 0 to slot 1 and the result to slot 2, both--- deferred: @f name value@ as upstream's @mapAttrs@ builds it from two--- nested @mkApp@s, so the name application runs a frame below the value--- application's.  Its function is 'reservedApply1'.  Must stay in--- lockstep with @NN_BC_RESERVED_APPLY2@ in @cbits\/nn_bytecode.h@.-reservedApply2 :: Word32-reservedApply2 = 4---- --------------------------------------------------------------------------- -- Diagnostics -- --------------------------------------------------------------------------- @@ -365,27 +390,28 @@ pattern OpUnary = 21 pattern OpBinary = 22 --- | Search-path opcode: an angle-bracket path lookup like @\<nixpkgs\>@.-pattern OpSearchPath :: Word8-pattern OpSearchPath = 23- -- | Interpolated-path opcode: a path holding an antiquotation, such as -- @.\/a\/${x}@, whose string parts begin with the path's literal head. pattern OpPathStr :: Word8 pattern OpPathStr = 24 +-- | Position opcode: @__curPos@, whose first argument is the index+-- "Nix.Eval.SourcePos" recorded its position at.+pattern OpPos :: Word8+pattern OpPos = 25+ -- --------------------------------------------------------------------------- -- Sub-type flags -- --------------------------------------------------------------------------- --- | @OpApp@ flag values: a source application ('Nix.Expr.Types.EApp')--- evaluates its function before the call frame opens; a deferred one--- forces it inside the frame.  Must stay in lockstep with @NN_APP_*@ in--- @cbits\/nn_bytecode.h@, whose reserved instructions are the deferred--- applications.-appDirect, appDeferred :: Word8-appDirect = 0-appDeferred = 1+-- | @OpAttrs@ flag values: a set, a recursive set, or a recursive set+-- that binds @__overrides@ statically, in which upstream makes every+-- static value but an inherited name's a thunk of its own+-- (@ExprAttrs::eval@ in eval.cc).+attrsPlain, attrsRec, attrsRecOverrides :: Word8+attrsPlain = 0+attrsRec = 1+attrsRecOverrides = 2  -- | @OpUnary@ flag values: which unary operator to apply. unaryNot, unaryNegate :: Word8@@ -429,6 +455,17 @@ formalSet = 1 formalNamedSet = 2 +-- | Kinds of a set pattern formal's default, the second of the three+-- words of its entry, the formal's name before it and its code after it:+-- none, code made in the call's frame, or a variable naming a slot of the+-- call's frame whose cell the formal's slot shares+-- ('Nix.Eval.EvalFormals.SharedDefault').  A C lambda's formal entries+-- hold the same words (@nn_formal_entry_t@, cbits/nn_lambda.h).+formalNoDefault, formalDefault, formalSharedDefault :: Word32+formalNoDefault = 0+formalDefault = 1+formalSharedDefault = 2+ -- | String-part kinds: a literal chunk, an interpolated @${...}@ -- expression, or an indented-string escape (literal text the indentation -- scan must not measure).@@ -439,6 +476,15 @@  -- | Attribute-binding kinds: a @name = value@ binding, one name of an -- @inherit@, or an @inherit (from) ...@.+--+-- A binding list's words are the count of the names it binds statically,+-- the count of its bindings with a dynamic name, the count of its shares+-- and the shares, two words each, then the bindings, each led by its+-- kind.  A share is a binding whose whole value is a variable naming+-- another of the frame's names, which takes that name's cell+-- ('Nix.Eval.Compile.siblingShares'): its slot and the slot whose cell it+-- takes in a frame that holds its names in slots, and their symbols in+-- one that holds them in a name table. bindNamed, bindInherit, bindInheritFrom :: Word32 bindNamed = 0 bindInherit = 1
src/Nix/Eval/CCtxStr.hs view
@@ -1,9 +1,12 @@+{-# LANGUAGE PatternSynonyms #-}+ -- | C-backed context-bearing strings via FFI. -- -- Wraps @cbits/nn_ctxstr.c@ - a string with its StringContext stored--- as a contiguous C struct.  Context-free strings continue to use--- thunk tag 4 (bare nn_symbol_t); this module handles tag 8 for--- strings with non-empty context.+-- as a contiguous C struct, its text and each store path's hash and name+-- and output name a string's bytes ("Nix.Eval.CStr").  Context-free+-- strings use thunk tag 4 (a string's bytes alone); this module handles+-- tag 8 for strings with non-empty context. -- -- This module provides raw FFI bindings only.  The higher-level -- marshalling between t'Nix.Eval.Types.StringContext' and C is in "Nix.Eval.Types"@@ -15,7 +18,6 @@      -- * Lifecycle     cctxstrNew,-    cctxstrFreeAll,      -- * Element setters     cctxstrSetPlain,@@ -29,11 +31,19 @@     cctxstrElemHash,     cctxstrElemName,     cctxstrElemOutput,++    -- * Element tags+    pattern ScePlain,+    pattern SceDrvOutput,+    pattern SceAllOutputs,   ) where  import Data.Word (Word32, Word8) import Foreign.Ptr (Ptr)+import Nix.Eval.CData (MonadCData, cdataIO)+import Nix.Eval.CStatus (checkedCPtr)+import Nix.Eval.CStr (CStrPtr)  -- | Phantom type for C-side @nn_ctxstr_t@. data NnCtxStr@@ -46,22 +56,19 @@ -- ---------------------------------------------------------------------------  foreign import ccall unsafe "nn_ctxstr_new"-  c_nn_ctxstr_new :: Word32 -> Word32 -> IO CCtxStrPtr--foreign import ccall unsafe "nn_ctxstr_free_all"-  c_nn_ctxstr_free_all :: IO ()+  c_nn_ctxstr_new :: CStrPtr -> Word32 -> IO CCtxStrPtr  foreign import ccall unsafe "nn_ctxstr_set_plain"-  c_nn_ctxstr_set_plain :: CCtxStrPtr -> Word32 -> Word32 -> Word32 -> IO ()+  c_nn_ctxstr_set_plain :: CCtxStrPtr -> Word32 -> CStrPtr -> CStrPtr -> IO ()  foreign import ccall unsafe "nn_ctxstr_set_drv_output"-  c_nn_ctxstr_set_drv_output :: CCtxStrPtr -> Word32 -> Word32 -> Word32 -> Word32 -> IO ()+  c_nn_ctxstr_set_drv_output :: CCtxStrPtr -> Word32 -> CStrPtr -> CStrPtr -> CStrPtr -> IO ()  foreign import ccall unsafe "nn_ctxstr_set_all_outputs"-  c_nn_ctxstr_set_all_outputs :: CCtxStrPtr -> Word32 -> Word32 -> Word32 -> IO ()+  c_nn_ctxstr_set_all_outputs :: CCtxStrPtr -> Word32 -> CStrPtr -> CStrPtr -> IO ()  foreign import ccall unsafe "nn_ctxstr_text"-  c_nn_ctxstr_text :: CCtxStrPtr -> IO Word32+  c_nn_ctxstr_text :: CCtxStrPtr -> IO CStrPtr  foreign import ccall unsafe "nn_ctxstr_ctx_count"   c_nn_ctxstr_ctx_count :: CCtxStrPtr -> IO Word32@@ -70,72 +77,83 @@   c_nn_ctxstr_elem_tag :: CCtxStrPtr -> Word32 -> IO Word8  foreign import ccall unsafe "nn_ctxstr_elem_hash"-  c_nn_ctxstr_elem_hash :: CCtxStrPtr -> Word32 -> IO Word32+  c_nn_ctxstr_elem_hash :: CCtxStrPtr -> Word32 -> IO CStrPtr  foreign import ccall unsafe "nn_ctxstr_elem_name"-  c_nn_ctxstr_elem_name :: CCtxStrPtr -> Word32 -> IO Word32+  c_nn_ctxstr_elem_name :: CCtxStrPtr -> Word32 -> IO CStrPtr  foreign import ccall unsafe "nn_ctxstr_elem_output"-  c_nn_ctxstr_elem_output :: CCtxStrPtr -> Word32 -> IO Word32+  c_nn_ctxstr_elem_output :: CCtxStrPtr -> Word32 -> IO CStrPtr  -- --------------------------------------------------------------------------- -- Lifecycle -- --------------------------------------------------------------------------- --- | Allocate a new context string with space for @ctxCount@ elements.--- Elements are uninitialized - caller must fill via set functions.--- Returns 'Foreign.Ptr.nullPtr' on allocation failure or if the--- element array size would overflow - the caller must check.-cctxstrNew :: Word32 -> Word32 -> IO CCtxStrPtr-cctxstrNew = c_nn_ctxstr_new---- | Free all tracked nn_ctxstr_t allocations (arena-style cleanup).-cctxstrFreeAll :: IO ()-cctxstrFreeAll = c_nn_ctxstr_free_all+-- | Allocate a new context string over its text's bytes with space for+-- @ctxCount@ elements, which the caller fills via the set functions.+-- The NULL @nn_ctxstr_new@ answers when it refuses+-- (@cbits/nn_ctxstr.h@ says when) is raised as+-- 'Nix.Eval.CStatus.CStatusError'.+cctxstrNew :: (MonadCData m) => CStrPtr -> Word32 -> m CCtxStrPtr+cctxstrNew text ctxCount = cdataIO (checkedCPtr "nn_ctxstr_new" =<< c_nn_ctxstr_new text ctxCount)  -- --------------------------------------------------------------------------- -- Element setters -- ---------------------------------------------------------------------------  -- | Set context element @i@ to a plain store-path reference (@SCPlain@),--- identified by its name and hash symbols.-cctxstrSetPlain :: CCtxStrPtr -> Word32 -> Word32 -> Word32 -> IO ()-cctxstrSetPlain = c_nn_ctxstr_set_plain+-- identified by its hash and name.+cctxstrSetPlain :: (MonadCData m) => CCtxStrPtr -> Word32 -> CStrPtr -> CStrPtr -> m ()+cctxstrSetPlain ptr idx hash name = cdataIO (c_nn_ctxstr_set_plain ptr idx hash name)  -- | Set context element @i@ to a derivation-output reference (@SCDrvOutput@):--- name and hash symbols plus the output-name symbol.-cctxstrSetDrvOutput :: CCtxStrPtr -> Word32 -> Word32 -> Word32 -> Word32 -> IO ()-cctxstrSetDrvOutput = c_nn_ctxstr_set_drv_output+-- hash and name plus the output name.+cctxstrSetDrvOutput :: (MonadCData m) => CCtxStrPtr -> Word32 -> CStrPtr -> CStrPtr -> CStrPtr -> m ()+cctxstrSetDrvOutput ptr idx hash name output = cdataIO (c_nn_ctxstr_set_drv_output ptr idx hash name output)  -- | Set context element @i@ to an all-outputs reference (@SCAllOutputs@),--- identified by its name and hash symbols.-cctxstrSetAllOutputs :: CCtxStrPtr -> Word32 -> Word32 -> Word32 -> IO ()-cctxstrSetAllOutputs = c_nn_ctxstr_set_all_outputs+-- identified by its hash and name.+cctxstrSetAllOutputs :: (MonadCData m) => CCtxStrPtr -> Word32 -> CStrPtr -> CStrPtr -> m ()+cctxstrSetAllOutputs ptr idx hash name = cdataIO (c_nn_ctxstr_set_all_outputs ptr idx hash name)  -- --------------------------------------------------------------------------- -- Accessors -- --------------------------------------------------------------------------- --- | The interned-symbol id of the context string's text.-cctxstrText :: CCtxStrPtr -> IO Word32-cctxstrText = c_nn_ctxstr_text+-- | The context string's text.+cctxstrText :: (MonadCData m) => CCtxStrPtr -> m CStrPtr+cctxstrText = cdataIO . c_nn_ctxstr_text  -- | The number of context elements attached to the string.-cctxstrCtxCount :: CCtxStrPtr -> IO Word32-cctxstrCtxCount = c_nn_ctxstr_ctx_count+cctxstrCtxCount :: (MonadCData m) => CCtxStrPtr -> m Word32+cctxstrCtxCount = cdataIO . c_nn_ctxstr_ctx_count --- | The tag of context element @i@ (plain / drv-output / all-outputs).-cctxstrElemTag :: CCtxStrPtr -> Word32 -> IO Word8-cctxstrElemTag = c_nn_ctxstr_elem_tag+-- | The tag of context element @i@: 'ScePlain', 'SceDrvOutput' or+-- 'SceAllOutputs'.+cctxstrElemTag :: (MonadCData m) => CCtxStrPtr -> Word32 -> m Word8+cctxstrElemTag ptr idx = cdataIO (c_nn_ctxstr_elem_tag ptr idx) --- | The store-path-hash symbol of context element @i@.-cctxstrElemHash :: CCtxStrPtr -> Word32 -> IO Word32-cctxstrElemHash = c_nn_ctxstr_elem_hash+-- | The store path's hash of context element @i@.+cctxstrElemHash :: (MonadCData m) => CCtxStrPtr -> Word32 -> m CStrPtr+cctxstrElemHash ptr idx = cdataIO (c_nn_ctxstr_elem_hash ptr idx) --- | The store-path-name symbol of context element @i@.-cctxstrElemName :: CCtxStrPtr -> Word32 -> IO Word32-cctxstrElemName = c_nn_ctxstr_elem_name+-- | The store path's name of context element @i@.+cctxstrElemName :: (MonadCData m) => CCtxStrPtr -> Word32 -> m CStrPtr+cctxstrElemName ptr idx = cdataIO (c_nn_ctxstr_elem_name ptr idx) --- | The output-name symbol of context element @i@ (drv-output elements only).-cctxstrElemOutput :: CCtxStrPtr -> Word32 -> IO Word32-cctxstrElemOutput = c_nn_ctxstr_elem_output+-- | The output name of context element @i@ (drv-output elements only).+cctxstrElemOutput :: (MonadCData m) => CCtxStrPtr -> Word32 -> m CStrPtr+cctxstrElemOutput ptr idx = cdataIO (c_nn_ctxstr_elem_output ptr idx)++-- ---------------------------------------------------------------------------+-- Element tags+-- ---------------------------------------------------------------------------++-- | The tags of a string context element, mirroring the @NN_SCE_*@ macros+-- in @cbits\/nn_ctxstr.h@, with which they stay in lockstep: a plain+-- store path (@SCPlain@), a derivation's output (@SCDrvOutput@) and all+-- of a derivation's outputs (@SCAllOutputs@).+pattern ScePlain, SceDrvOutput, SceAllOutputs :: Word8+pattern ScePlain = 0+pattern SceDrvOutput = 1+pattern SceAllOutputs = 2
+ src/Nix/Eval/CData.hs view
@@ -0,0 +1,115 @@+{-# LANGUAGE GeneralizedNewtypeDeriving #-}++-- | The evaluator's boundary with the C data layer.+--+-- Thunks, environments, attribute sets, lists, lambdas, the bytes of+-- strings and paths, strings with context, interned names and the+-- bytecode the evaluator runs all live in C (@cbits/@), reached through+-- the bindings in the @Nix.Eval.C*@ modules, "Nix.Eval.Symbol" and+-- "Nix.Eval.SourcePos".  Every read of,+-- write to and allocation in that memory the evaluator makes is a+-- t'CData' action, and the evaluator runs one in its own monad through+-- 'MonadCData'; the arena's lifecycle, the regions, the census and the+-- counters ('Nix.Eval.Symbol.symbolCount') call the layer in 'IO'.  An action+-- runs where the evaluation reaches it, in order with the actions around+-- it: a read sees memory as it is at that point and not whenever a lazy+-- value happens to be demanded, and an allocation happens once each time+-- the evaluation passes it, never shared by GHC between two passes.+-- A collector of the layer's memory needs that order: nothing still+-- unevaluated can read a cell at a point the evaluation cannot see.+--+-- Two functions read the layer outside a monad, each for one kind of+-- use, with the invariant that makes it sound:+--+-- * 'readImmutable' reads an interned symbol's bytes ("Nix.Eval.Symbol"),+--   which do not change once interned, until the arena is destroyed.+--   They can move: the table grows its byte storage with @realloc@ as+--   later strings are interned, and a read takes the bytes' address+--   before it copies them.  So no intern may run between the two, which+--   holds while one thread at a time uses the layer.+-- * 'runCDataPure' runs a whole computation as a value: a pure+--   evaluation ('Nix.Eval.Types.runPureEval').  Such a computation+--   writes only memory it allocated, the with-scope array entries it+--   resolves ('Nix.Eval.Types.resolveWithScopeAt'), each from a set's+--   thunk to the set the thunk evaluates to, and the static cell+--   of a builtin it binds ('Nix.Eval.CThunk.cthunkPrimop'), which it+--   fills with the one value that cell ever holds.  Two runs that resolve+--   one entry make two sets with the same contents in different cells, so+--   a value carried from one run into another can meet the other run's+--   set where it would have met its own, which the repeated marker and+--   @==@'s shortcut for one cell tell apart.  Only an environment whose+--   with-scope is still unresolved when it passes between runs can show+--   this, and only tests pass one.+--+-- Whatever runs, reads or allocates through these outside an evaluation+-- session ('Nix.Eval.IO.withEvalSession') raises+-- 'Nix.Eval.CStatus.ArenaNotInitialized' or reads freed memory, as any+-- other action does.+module Nix.Eval.CData+  ( -- * Actions+    CData,+    runCData,+    MonadCData (..),+    cdataIO,++    -- * Outside a monad+    readImmutable,+    runCDataPure,+  )+where++import System.IO.Unsafe (unsafeDupablePerformIO, unsafePerformIO)++-- | An action on the C data layer: an FFI call into @cbits/@, or a peek+-- or poke of memory the layer handed out.  Nothing else is wrapped, so a+-- function whose result is a t'CData' touches nothing but that memory.+-- The constructor is not exported: the modules that bind the layer make+-- an action with 'cdataIO', and 'runCData', 'readImmutable' and+-- 'runCDataPure' run one.+newtype CData a = CData (IO a)+  deriving (Functor, Applicative, Monad)++-- | Run an action in 'IO', for the 'MonadCData' instance of a monad over+-- 'IO'.+runCData :: CData a -> IO a+runCData (CData io) = io+{-# INLINE runCData #-}++-- | A monad that runs C data-layer actions in sequence with its own.+-- The evaluator's monads ('Nix.Eval.Types.MonadEval') are instances, and+-- so is 'IO', for the executable and the tests.+class (Monad m) => MonadCData m where+  -- | Run the action at this point of the computation.+  liftCData :: CData a -> m a++instance MonadCData IO where+  liftCData = runCData+  {-# INLINE liftCData #-}++instance MonadCData CData where+  liftCData = id+  {-# INLINE liftCData #-}++-- | Run a binding's IO action as a t'CData' action in any 'MonadCData'.+-- For the modules that bind the layer, whose IO actions are FFI calls and+-- peeks and pokes of its memory.+cdataIO :: (MonadCData m) => IO a -> m a+cdataIO = liftCData . CData+{-# INLINE cdataIO #-}++-- | Read memory whose contents do not change while the value naming it+-- exists, until the arena is destroyed, and which nothing moves while the+-- read runs (see the module header).  The read may run any number of+-- times, or never: every run answers the same.+readImmutable :: CData a -> a+readImmutable (CData io) = unsafeDupablePerformIO io+{-# INLINE readImmutable #-}++-- | Run a computation that allocates as a value.  Sound for a computation+-- that writes only memory it allocated, with-scope entries it resolves,+-- with what two runs resolving one entry can show, and builtins' static+-- cells, which every run fills alike (see the module header): each run+-- allocates memory of its own, and a run GHC shares or never makes is not+-- observable except through the addresses of the values it returns.+runCDataPure :: CData a -> a+runCDataPure (CData io) = unsafePerformIO io
src/Nix/Eval/CEnv.hs view
@@ -1,51 +1,49 @@ -- | C-backed evaluation environments. ----- Wraps @cbits/nn_env.c@ - arena-allocated @nn_env_t@ structs that--- hold slot arrays, lazy scopes, parent pointers, and with-scopes.--- All memory is freed in bulk via 'cenvDestroy' at evaluation end.+-- Wraps @cbits/nn_env.c@ - arena-allocated @nn_env_t@ envs that hold+-- their slots inline, and a parent, a name table and with-scopes when+-- they have them.  All memory is freed in bulk at arena teardown, and the+-- region collector ("Nix.Eval.CRegion") hands out again the lines of a+-- page that hold nothing it reached. ----- This moves Env records off the GHC heap.  Each @nn_env_t@ is 48--- bytes (arena-allocated, zero GC overhead), replacing the former--- Haskell record (~80-100 bytes with GHC info pointers, Maybe--- constructors, and list cons cells per env).+-- An env is a word and its slots (@cbits/nn_env.h@).  One of one to+-- seven slots and no scopes keeps its parent in that word, as upstream's+-- @Env@ is a parent and its values: a call's env of one slot takes 16+-- bytes, none of them on GHC's heap.  Any other env's word is a header,+-- followed after the slots by its parent when it has one and by its+-- scopes when it has them.+-- Every allocation names its 'EnvSite', under which the census counts+-- it. module Nix.Eval.CEnv   ( -- * Opaque C type     NnEnv, -    -- * Lifecycle-    cenvInit,-    cenvDestroy,--    -- * Slot allocation-    cenvAllocSlots,-     -- * Env constructors     cenvEmpty,     cenvNew,-    cenvFromSlots,+    cenvNewScoped,     cenvPushWith,-    cenvNewMinimal,+    cenvResolveWith,      -- * Accessors     cenvSlots,     cenvSlotCount,-    cenvLazyScope,+    cenvNameTable,     cenvParent,     cenvWithScopes,     cenvWithCount,      -- * Lookup     cenvLookupResolved,-    cenvRootScope,--    -- * With-scopes array-    cenvAllocWithScopes,+    cenvWithOwner,   ) where  import Data.Word (Word32)-import Foreign.C.Types (CInt (..))-import Foreign.Ptr (Ptr)+import Foreign.Ptr (Ptr, nullPtr)+import Nix.Eval.AllocSite (EnvSite, envSiteIndex)+import Nix.Eval.CData (MonadCData, cdataIO)+import Nix.Eval.CStatus (cInvariantViolated, checkedCPtr) import Nix.Eval.CThunk (CThunkPtr)  -- ---------------------------------------------------------------------------@@ -59,37 +57,34 @@ -- FFI imports (all unsafe - no callbacks, fast operations) -- --------------------------------------------------------------------------- -foreign import ccall unsafe "nn_env_init"-  c_nn_env_init :: IO ()--foreign import ccall unsafe "nn_env_destroy"-  c_nn_env_destroy :: IO ()--foreign import ccall unsafe "nn_env_alloc_slots"-  c_nn_env_alloc_slots :: Word32 -> IO (Ptr CThunkPtr)+-- The empty env is a C static, one address for the life of the process,+-- so this import is pure, as the null and Boolean cells of+-- "Nix.Eval.CThunk" are: no arena window, nor its absence, changes what+-- it returns. +-- | The global empty env: no slots, no parent, no scopes.  Not to be+-- modified. foreign import ccall unsafe "nn_env_empty"-  c_nn_env_empty :: IO (Ptr NnEnv)+  cenvEmpty :: Ptr NnEnv  foreign import ccall unsafe "nn_env_new"-  c_nn_env_new ::-    Ptr CThunkPtr ->+  c_nn_env_new :: Word32 -> Ptr NnEnv -> Word32 -> IO (Ptr NnEnv)++foreign import ccall unsafe "nn_env_new_scoped"+  c_nn_env_new_scoped ::     Word32 ->-    Ptr () ->     Ptr NnEnv ->+    Ptr () ->     Ptr (Ptr ()) ->     Word32 ->+    Word32 ->     IO (Ptr NnEnv) -foreign import ccall unsafe "nn_env_from_slots"-  c_nn_env_from_slots ::-    Ptr CThunkPtr -> Word32 -> Ptr NnEnv -> IO (Ptr NnEnv)- foreign import ccall unsafe "nn_env_push_with"-  c_nn_env_push_with :: Ptr NnEnv -> Ptr () -> IO (Ptr NnEnv)+  c_nn_env_push_with :: Ptr NnEnv -> Ptr () -> Word32 -> IO (Ptr NnEnv) -foreign import ccall unsafe "nn_env_new_minimal"-  c_nn_env_new_minimal :: Ptr CThunkPtr -> Word32 -> IO (Ptr NnEnv)+foreign import ccall unsafe "nn_env_resolve_with"+  c_nn_env_resolve_with :: Ptr (Ptr ()) -> Word32 -> Ptr () -> IO ()  foreign import ccall unsafe "nn_env_slots"   c_nn_env_slots :: Ptr NnEnv -> IO (Ptr CThunkPtr)@@ -97,8 +92,8 @@ foreign import ccall unsafe "nn_env_slot_count"   c_nn_env_slot_count :: Ptr NnEnv -> IO Word32 -foreign import ccall unsafe "nn_env_lazy_scope"-  c_nn_env_lazy_scope :: Ptr NnEnv -> IO (Ptr ())+foreign import ccall unsafe "nn_env_name_table"+  c_nn_env_name_table :: Ptr NnEnv -> IO (Ptr ())  foreign import ccall unsafe "nn_env_parent"   c_nn_env_parent :: Ptr NnEnv -> IO (Ptr NnEnv)@@ -110,116 +105,99 @@   c_nn_env_with_count :: Ptr NnEnv -> IO Word32  foreign import ccall unsafe "nn_env_lookup_resolved"-  c_nn_env_lookup_resolved :: Ptr NnEnv -> CInt -> CInt -> IO CThunkPtr--foreign import ccall unsafe "nn_env_root_scope"-  c_nn_env_root_scope :: Ptr NnEnv -> IO (Ptr ())--foreign import ccall unsafe "nn_env_alloc_with_scopes"-  c_nn_env_alloc_with_scopes :: Word32 -> IO (Ptr (Ptr ()))---- ------------------------------------------------------------------------------ Lifecycle--- ------------------------------------------------------------------------------- | Initialize the global env allocator.  Call once before evaluation.-cenvInit :: IO ()-cenvInit = c_nn_env_init---- | Destroy the global env allocator, freeing all page memory.--- All env and slot array pointers become invalid after this call.-cenvDestroy :: IO ()-cenvDestroy = c_nn_env_destroy---- ------------------------------------------------------------------------------ Slot allocation--- ---------------------------------------------------------------------------+  c_nn_env_lookup_resolved :: Ptr NnEnv -> Word32 -> Word32 -> IO CThunkPtr --- | Allocate a C array of @count@ 'CThunkPtr' slots.  O(1) amortized.--- Returns 'Foreign.Ptr.nullPtr' if count is 0.  All slots are zero-initialized.-cenvAllocSlots :: Word32 -> IO (Ptr CThunkPtr)-cenvAllocSlots = c_nn_env_alloc_slots+foreign import ccall unsafe "nn_env_with_owner"+  c_nn_env_with_owner :: Ptr NnEnv -> IO (Ptr NnEnv)  -- --------------------------------------------------------------------------- -- Env constructors -- --------------------------------------------------------------------------- --- | Return a pointer to the global empty env (all fields zero/NULL).-cenvEmpty :: IO (Ptr NnEnv)-cenvEmpty = c_nn_env_empty+-- | An env of @count@ empty slots under a parent, or under none for+-- 'Foreign.Ptr.nullPtr', made at a site.  Arena-allocated; the C side's+-- NULL, when it cannot allocate the env, is raised as+-- 'Nix.Eval.CStatus.CStatusError'.  A parent no env could be (an address+-- with any bit of @NN_ENV_SHORT_MASK@ set) aborts in C.+cenvNew :: (MonadCData m) => EnvSite -> Word32 -> Ptr NnEnv -> m (Ptr NnEnv)+cenvNew site slotCount parent = cdataIO (checkedCPtr "nn_env_new" =<< c_nn_env_new slotCount parent (envSiteIndex site)) --- | Full constructor: set all fields explicitly.  Arena-allocated.-cenvNew ::-  Ptr CThunkPtr ->+-- | 'cenvNew' for an env with scopes: a name table (or+-- 'Foreign.Ptr.nullPtr') and with-scopes of its own (or+-- 'Foreign.Ptr.nullPtr' and 0, to see its parent's).  The env holds the+-- with-scopes array itself, so envs may share one.  A with-scope count+-- above 0 without an array aborts in C.+cenvNewScoped ::+  (MonadCData m) =>+  EnvSite ->   Word32 ->-  Ptr () ->   Ptr NnEnv ->+  Ptr () ->   Ptr (Ptr ()) ->   Word32 ->-  IO (Ptr NnEnv)-cenvNew = c_nn_env_new---- | Child env with positional slots, inheriting parent's with-scopes.-cenvFromSlots :: Ptr CThunkPtr -> Word32 -> Ptr NnEnv -> IO (Ptr NnEnv)-cenvFromSlots = c_nn_env_from_slots+  m (Ptr NnEnv)+cenvNewScoped site slotCount parent nameTable withs withCount =+  cdataIO (checkedCPtr "nn_env_new_scoped" =<< c_nn_env_new_scoped slotCount parent nameTable withs withCount (envSiteIndex site)) --- | Copy base env with a new with-scope prepended.-cenvPushWith :: Ptr NnEnv -> Ptr () -> IO (Ptr NnEnv)-cenvPushWith = c_nn_env_push_with+-- | The env a with's body runs in, made at a site: a copy of the base+-- with a new with-scope prepended to those it sees.+cenvPushWith :: (MonadCData m) => EnvSite -> Ptr NnEnv -> Ptr () -> m (Ptr NnEnv)+cenvPushWith site base scope = cdataIO (checkedCPtr "nn_env_push_with" =<< c_nn_env_push_with base scope (envSiteIndex site)) --- | Minimal env: slots only, no parent, no with-scopes.-cenvNewMinimal :: Ptr CThunkPtr -> Word32 -> IO (Ptr NnEnv)-cenvNewMinimal = c_nn_env_new_minimal+-- | Resolve the entry at an index of a with-scopes array to the set its+-- thunk evaluated to: the one write into the array after its creation,+-- which a census of regions records ("Nix.Eval.CRegion").+cenvResolveWith :: (MonadCData m) => Ptr (Ptr ()) -> Word32 -> Ptr () -> m ()+cenvResolveWith withScopes idx set = cdataIO (c_nn_env_resolve_with withScopes idx set)  -- --------------------------------------------------------------------------- -- Accessors -- --------------------------------------------------------------------------- --- | Read the slot array pointer from a C env.-cenvSlots :: Ptr NnEnv -> IO (Ptr CThunkPtr)-cenvSlots = c_nn_env_slots+-- | The slots of a C env, inline in it.+cenvSlots :: (MonadCData m) => Ptr NnEnv -> m (Ptr CThunkPtr)+cenvSlots = cdataIO . c_nn_env_slots --- | Read the slot count from a C env.-cenvSlotCount :: Ptr NnEnv -> IO Word32-cenvSlotCount = c_nn_env_slot_count+-- | How many slots a C env has.+cenvSlotCount :: (MonadCData m) => Ptr NnEnv -> m Word32+cenvSlotCount = cdataIO . c_nn_env_slot_count --- | Read the lazy scope pointer from a C env (NULL if none).-cenvLazyScope :: Ptr NnEnv -> IO (Ptr ())-cenvLazyScope = c_nn_env_lazy_scope+-- | Read the name table pointer from a C env (NULL if none).+cenvNameTable :: (MonadCData m) => Ptr NnEnv -> m (Ptr ())+cenvNameTable = cdataIO . c_nn_env_name_table --- | Read the parent pointer from a C env (NULL if root).-cenvParent :: Ptr NnEnv -> IO (Ptr NnEnv)-cenvParent = c_nn_env_parent+-- | Read the parent pointer from a C env (NULL if none).+cenvParent :: (MonadCData m) => Ptr NnEnv -> m (Ptr NnEnv)+cenvParent = cdataIO . c_nn_env_parent --- | Read the with-scopes array pointer from a C env.-cenvWithScopes :: Ptr NnEnv -> IO (Ptr (Ptr ()))-cenvWithScopes = c_nn_env_with_scopes+-- | A C env's own with-scopes array (NULL if it has none of its own;+-- 'cenvWithOwner' finds the env whose with-scopes it sees).+cenvWithScopes :: (MonadCData m) => Ptr NnEnv -> m (Ptr (Ptr ()))+cenvWithScopes = cdataIO . c_nn_env_with_scopes --- | Read the with-scope count from a C env.-cenvWithCount :: Ptr NnEnv -> IO Word32-cenvWithCount = c_nn_env_with_count+-- | The count of a C env's own with-scopes (0 if it has none of its own).+cenvWithCount :: (MonadCData m) => Ptr NnEnv -> m Word32+cenvWithCount = cdataIO . c_nn_env_with_count  -- --------------------------------------------------------------------------- -- Lookup -- ---------------------------------------------------------------------------  -- | Resolved variable lookup: walk @level@ parent hops, then read--- @slots[idx]@.  Single FFI call - O(level) in C.-cenvLookupResolved :: Ptr NnEnv -> Int -> Int -> IO CThunkPtr-cenvLookupResolved env level idx =-  -- C @int@ params: convert at the boundary (CInt), not HsInt (64-bit).-  c_nn_env_lookup_resolved env (fromIntegral level) (fromIntegral idx)---- | Walk parent chain to root, return root's lazy scope (NULL if none).-cenvRootScope :: Ptr NnEnv -> IO (Ptr ())-cenvRootScope = c_nn_env_root_scope---- ------------------------------------------------------------------------------ With-scopes array allocation--- ---------------------------------------------------------------------------+-- @slots[idx]@.  Single FFI call - O(level) in C.  The resolver chose the+-- level and index for this env's shape, so the NULL the C side answers+-- for one outside the env, or for a slot a frame has not filled yet, is a+-- defect in this library, raised as+-- 'Nix.Eval.CStatus.CInvariantViolated' rather than handed on as a cell+-- the next force would dereference.+cenvLookupResolved :: (MonadCData m) => Ptr NnEnv -> Word32 -> Word32 -> m CThunkPtr+cenvLookupResolved env level idx = cdataIO $ do+  cell <- c_nn_env_lookup_resolved env level idx+  if cell == nullPtr+    then cInvariantViolated "nn_env_lookup_resolved" ("no thunk at level " ++ show level ++ ", index " ++ show idx)+    else pure cell --- | Allocate an arena array for with-scopes.  Zero-initialized.--- Returns 'Foreign.Ptr.nullPtr' if the count is 0 or the allocation--- fails - the caller must check.-cenvAllocWithScopes :: Word32 -> IO (Ptr (Ptr ()))-cenvAllocWithScopes = c_nn_env_alloc_with_scopes+-- | The env whose with-scopes a C env sees: the first on its parent+-- chain, itself included, with with-scopes of its own (NULL if none).+cenvWithOwner :: (MonadCData m) => Ptr NnEnv -> m (Ptr NnEnv)+cenvWithOwner = cdataIO . c_nn_env_with_owner
src/Nix/Eval/CLambda.hs view
@@ -1,12 +1,15 @@+{-# LANGUAGE PatternSynonyms #-}+ -- | C-backed lambda closure structs via FFI. -- -- Wraps @cbits/nn_lambda.c@ - a malloc'd struct holding the closure -- environment (nn_env_t*), body bytecode index, and formal parameter--- specification.  Replaces StablePtr NixValue for VLambda (~25% of--- remaining GHC heap after M6) with C-native tag 9 in the thunk system.+-- specification.  A thunk holds one under tag 9, so a closure takes+-- nothing on GHC's heap. ----- Lambda structs are tracked for bulk cleanup via 'clambdaFreeAll'--- at evaluation end.+-- Lambda structs are tracked and freed in bulk at arena teardown, or one+-- by one by the region collector ("Nix.Eval.CRegion") once nothing+-- reaches them. module Nix.Eval.CLambda   ( -- * Opaque handle     NnLambda,@@ -15,24 +18,37 @@     -- * Lifecycle     clambdaNew,     clambdaSetEntry,-    clambdaFreeAll,      -- * Accessors     clambdaEnv,     clambdaBody,     clambdaFormalsType,     clambdaNameSym,+    clambdaLambdaNameSym,     clambdaAllowExtra,     clambdaFormalCount,     clambdaEntryName,     clambdaEntryHasDefault,     clambdaEntryDefault,++    -- * Shape+    clambdaShape,+    clambdaShapeFormalsType,+    clambdaShapeAllowExtra,+    clambdaShapeFormalCount,++    -- * Formals types+    pattern FormalsName,+    pattern FormalsSet,+    pattern FormalsNamedSet,   ) where  import Data.Word (Word32, Word8) import Foreign.Ptr (Ptr)+import Nix.Eval.CData (MonadCData, cdataIO) import Nix.Eval.CEnv (NnEnv)+import Nix.Eval.CStatus (checkedCPtr)  -- | Phantom type for C-side @nn_lambda_t@. data NnLambda@@ -45,14 +61,11 @@ -- ---------------------------------------------------------------------------  foreign import ccall unsafe "nn_lambda_new"-  c_nn_lambda_new :: Ptr NnEnv -> Word32 -> Word8 -> Word32 -> Word8 -> Word32 -> IO CLambdaPtr+  c_nn_lambda_new :: Ptr NnEnv -> Word32 -> Word8 -> Word32 -> Word32 -> Word8 -> Word32 -> IO CLambdaPtr  foreign import ccall unsafe "nn_lambda_set_entry"   c_nn_lambda_set_entry :: CLambdaPtr -> Word32 -> Word32 -> Word32 -> Word32 -> IO () -foreign import ccall unsafe "nn_lambda_free_all"-  c_nn_lambda_free_all :: IO ()- foreign import ccall unsafe "nn_lambda_env"   c_nn_lambda_env :: CLambdaPtr -> IO (Ptr NnEnv) @@ -65,6 +78,9 @@ foreign import ccall unsafe "nn_lambda_name_sym"   c_nn_lambda_name_sym :: CLambdaPtr -> IO Word32 +foreign import ccall unsafe "nn_lambda_lambda_name_sym"+  c_nn_lambda_lambda_name_sym :: CLambdaPtr -> IO Word32+ foreign import ccall unsafe "nn_lambda_allow_extra"   c_nn_lambda_allow_extra :: CLambdaPtr -> IO Word8 @@ -80,61 +96,119 @@ foreign import ccall unsafe "nn_lambda_entry_default"   c_nn_lambda_entry_default :: CLambdaPtr -> Word32 -> IO Word32 +-- The shape functions read and write no memory, so they are pure.+foreign import ccall unsafe "nn_lambda_shape"+  c_nn_lambda_shape :: Word8 -> Word8 -> Word32 -> Word32++foreign import ccall unsafe "nn_lambda_shape_formals_type"+  c_nn_lambda_shape_formals_type :: Word32 -> Word8++foreign import ccall unsafe "nn_lambda_shape_allow_extra"+  c_nn_lambda_shape_allow_extra :: Word32 -> Word8++foreign import ccall unsafe "nn_lambda_shape_formal_count"+  c_nn_lambda_shape_formal_count :: Word32 -> Word32+ -- --------------------------------------------------------------------------- -- Lifecycle -- --------------------------------------------------------------------------- --- | Allocate a new lambda closure with space for @formalCount@ entries.--- Fill entries via 'clambdaSetEntry' after construction.--- Returns 'Foreign.Ptr.nullPtr' on allocation failure or if the--- entries array size would overflow - the caller must check.-clambdaNew :: Ptr NnEnv -> Word32 -> Word8 -> Word32 -> Word8 -> Word32 -> IO CLambdaPtr-clambdaNew = c_nn_lambda_new---- | Set a formal entry at the given index.-clambdaSetEntry :: CLambdaPtr -> Word32 -> Word32 -> Word32 -> Word32 -> IO ()-clambdaSetEntry = c_nn_lambda_set_entry+-- | Allocate a new lambda closure with space for @formalCount@ entries:+-- its env, body, formals type, binding name symbol, the function's own+-- name symbol ('Nix.Eval.EvalFormals.lambdaNameSymbol'), ellipsis flag+-- and formal count.  Fill entries via 'clambdaSetEntry' after+-- construction.  The NULL @nn_lambda_new@ answers when it refuses+-- (@cbits/nn_lambda.h@ says when) is raised as+-- 'Nix.Eval.CStatus.CStatusError'.+clambdaNew :: (MonadCData m) => Ptr NnEnv -> Word32 -> Word8 -> Word32 -> Word32 -> Word8 -> Word32 -> m CLambdaPtr+clambdaNew env body formalsType nameSym lambdaNameSym allowExtra formalCount =+  cdataIO (checkedCPtr "nn_lambda_new" =<< c_nn_lambda_new env body formalsType nameSym lambdaNameSym allowExtra formalCount) --- | Free all tracked lambda structs (arena-style cleanup).-clambdaFreeAll :: IO ()-clambdaFreeAll = c_nn_lambda_free_all+-- | Set a formal entry at the given index: its name's symbol, then its+-- default's kind ('Nix.Eval.CBytecode.formalNoDefault' and its siblings)+-- and bytecode index.+clambdaSetEntry :: (MonadCData m) => CLambdaPtr -> Word32 -> Word32 -> Word32 -> Word32 -> m ()+clambdaSetEntry lam idx nameSym defaultKind defaultIdx = cdataIO (c_nn_lambda_set_entry lam idx nameSym defaultKind defaultIdx)  -- --------------------------------------------------------------------------- -- Accessors -- ---------------------------------------------------------------------------  -- | Read the closure environment pointer.-clambdaEnv :: CLambdaPtr -> IO (Ptr NnEnv)-clambdaEnv = c_nn_lambda_env+clambdaEnv :: (MonadCData m) => CLambdaPtr -> m (Ptr NnEnv)+clambdaEnv = cdataIO . c_nn_lambda_env  -- | Read the body bytecode index.-clambdaBody :: CLambdaPtr -> IO Word32-clambdaBody = c_nn_lambda_body+clambdaBody :: (MonadCData m) => CLambdaPtr -> m Word32+clambdaBody = cdataIO . c_nn_lambda_body --- | Read the formals type (0=Name, 1=Set, 2=NamedSet).-clambdaFormalsType :: CLambdaPtr -> IO Word8-clambdaFormalsType = c_nn_lambda_formals_type+-- | Read the formals type: 'FormalsName', 'FormalsSet' or+-- 'FormalsNamedSet'.+clambdaFormalsType :: (MonadCData m) => CLambdaPtr -> m Word8+clambdaFormalsType = cdataIO . c_nn_lambda_formals_type  -- | Read the binding name symbol (for Name/NamedSet).-clambdaNameSym :: CLambdaPtr -> IO Word32-clambdaNameSym = c_nn_lambda_name_sym+clambdaNameSym :: (MonadCData m) => CLambdaPtr -> m Word32+clambdaNameSym = cdataIO . c_nn_lambda_name_sym +-- | Read the function's own name symbol (for Set/NamedSet), the one+-- 'clambdaNew' was given.+clambdaLambdaNameSym :: (MonadCData m) => CLambdaPtr -> m Word32+clambdaLambdaNameSym = cdataIO . c_nn_lambda_lambda_name_sym+ -- | Read the ellipsis flag (1 if ... present).-clambdaAllowExtra :: CLambdaPtr -> IO Word8-clambdaAllowExtra = c_nn_lambda_allow_extra+clambdaAllowExtra :: (MonadCData m) => CLambdaPtr -> m Word8+clambdaAllowExtra = cdataIO . c_nn_lambda_allow_extra  -- | Read the number of formal entries.-clambdaFormalCount :: CLambdaPtr -> IO Word32-clambdaFormalCount = c_nn_lambda_formal_count+clambdaFormalCount :: (MonadCData m) => CLambdaPtr -> m Word32+clambdaFormalCount = cdataIO . c_nn_lambda_formal_count  -- | Read a formal entry's name symbol.-clambdaEntryName :: CLambdaPtr -> Word32 -> IO Word32-clambdaEntryName = c_nn_lambda_entry_name+clambdaEntryName :: (MonadCData m) => CLambdaPtr -> Word32 -> m Word32+clambdaEntryName lam idx = cdataIO (c_nn_lambda_entry_name lam idx) --- | Read whether a formal entry has a default.-clambdaEntryHasDefault :: CLambdaPtr -> Word32 -> IO Word32-clambdaEntryHasDefault = c_nn_lambda_entry_has_default+-- | Read the kind of a formal entry's default+-- ('Nix.Eval.CBytecode.formalNoDefault' and its siblings).+clambdaEntryHasDefault :: (MonadCData m) => CLambdaPtr -> Word32 -> m Word32+clambdaEntryHasDefault lam idx = cdataIO (c_nn_lambda_entry_has_default lam idx)  -- | Read a formal entry's default bytecode index.-clambdaEntryDefault :: CLambdaPtr -> Word32 -> IO Word32-clambdaEntryDefault = c_nn_lambda_entry_default+clambdaEntryDefault :: (MonadCData m) => CLambdaPtr -> Word32 -> m Word32+clambdaEntryDefault lam idx = cdataIO (c_nn_lambda_entry_default lam idx)++-- ---------------------------------------------------------------------------+-- Shape+-- ---------------------------------------------------------------------------++-- | The word a closure keeps its formals type, ellipsis flag and formal+-- count in (@nn_lambda_shape@): the type taken mod 4, any nonzero flag as+-- 1 and the count mod 2^29, the widths @cbits\/nn_lambda.h@ gives them.+-- 'clambdaNew' takes only a type and a count that fit.+clambdaShape :: Word8 -> Word8 -> Word32 -> Word32+clambdaShape = c_nn_lambda_shape++-- | The formals type a shape holds.+clambdaShapeFormalsType :: Word32 -> Word8+clambdaShapeFormalsType = c_nn_lambda_shape_formals_type++-- | The ellipsis flag a shape holds, 0 or 1.+clambdaShapeAllowExtra :: Word32 -> Word8+clambdaShapeAllowExtra = c_nn_lambda_shape_allow_extra++-- | The formal count a shape holds.+clambdaShapeFormalCount :: Word32 -> Word32+clambdaShapeFormalCount = c_nn_lambda_shape_formal_count++-- ---------------------------------------------------------------------------+-- Formals types+-- ---------------------------------------------------------------------------++-- | The formals types of a closure, mirroring the @NN_FORMALS_*@ macros+-- in @cbits\/nn_lambda.h@, with which they stay in lockstep: a plain+-- name (@x: body@), a set pattern (@{ a, b }: body@) and a named set+-- pattern (@x\@{ a, b }: body@).+pattern FormalsName, FormalsSet, FormalsNamedSet :: Word8+pattern FormalsName = 0+pattern FormalsSet = 1+pattern FormalsNamedSet = 2
src/Nix/Eval/CList.hs view
@@ -1,12 +1,13 @@ -- | C-backed contiguous list of thunk pointers via FFI. ----- Wraps @cbits/nn_list.c@ - a flat array of @nn_thunk_t*@ pointers.--- Replaces Haskell's @[Thunk]@ (linked-list cons cells, ~48 bytes per--- element) with a contiguous C array (8 bytes per element).+-- Wraps @cbits/nn_list.c@: a flat array of @nn_thunk_t*@ pointers, 8+-- bytes an element against the ~48 of the cons cells of a @[Thunk]@. ----- Lists are immutable after construction: allocate with 'clistNew',--- fill with 'clistSet', then read with 'clistGet'/'clistCount'.--- All memory is freed in bulk via 'clistFreeAll' at evaluation end.+-- Lists are immutable after construction: 'clistFromThunks' builds one+-- and 'clistThunks' reads its items.  The headers are freed in bulk at+-- arena teardown, and the items arrays with the env pages that hold them;+-- the region collector ("Nix.Eval.CRegion") frees a header, and the lines+-- of an items array, once nothing reaches them. -- -- 'nullPtr' is the empty list, so the C constructors report failure -- through a status of their own rather than a NULL, and every one is@@ -26,18 +27,8 @@     clistIndex,     clistDrop, -    -- * Lifecycle-    clistNew,-    clistFreeAll,--    -- * Access-    clistCount,-    clistGet,-    clistSet,-     -- * Conversion     thunkListToCList,-    clistToThunkList,   ) where @@ -47,9 +38,9 @@ import Foreign.Marshal.Alloc (alloca) import Foreign.Ptr (Ptr, nullPtr) import Foreign.Storable (peek)+import Nix.Eval.CData (MonadCData, cdataIO) import Nix.Eval.CStatus (cStatusFailure) import Nix.Eval.CThunk (CThunkPtr)-import System.IO.Unsafe (unsafePerformIO)  -- | Phantom type for C-side @nn_list_t@. data NnList@@ -64,9 +55,6 @@ foreign import ccall unsafe "nn_list_new"   c_nn_list_new :: Ptr CListPtr -> Word32 -> IO CInt -foreign import ccall unsafe "nn_list_free_all"-  c_nn_list_free_all :: IO ()- foreign import ccall unsafe "nn_list_count"   c_nn_list_count :: CListPtr -> IO Word32 @@ -86,8 +74,8 @@ -- | Allocate a new list with space for @count@ thunk pointers, or -- 'nullPtr' (the empty list) when count is 0.  Raises -- 'Nix.Eval.CStatus.CStatusError' when the C side cannot allocate it.-clistNew :: Word32 -> IO CListPtr-clistNew count = alloca $ \out -> do+clistNew :: (MonadCData m) => Word32 -> m CListPtr+clistNew count = cdataIO $ alloca $ \out -> do   checkedListStatus "nn_list_new" =<< c_nn_list_new out count   peek out @@ -97,26 +85,21 @@ checkedListStatus site status =   unless (status == 0) (cStatusFailure site "list allocation failed") --- | Free all tracked list headers (arena-style cleanup).--- Items arrays are freed by the env page allocator.-clistFreeAll :: IO ()-clistFreeAll = c_nn_list_free_all- -- --------------------------------------------------------------------------- -- Access -- ---------------------------------------------------------------------------  -- | Number of elements in the list.-clistCount :: CListPtr -> IO Word32-clistCount = c_nn_list_count+clistCount :: (MonadCData m) => CListPtr -> m Word32+clistCount = cdataIO . c_nn_list_count  -- | Get the thunk pointer at the given index.-clistGet :: CListPtr -> Word32 -> IO CThunkPtr-clistGet = c_nn_list_get+clistGet :: (MonadCData m) => CListPtr -> Word32 -> m CThunkPtr+clistGet list idx = cdataIO (c_nn_list_get list idx)  -- | Set the thunk pointer at the given index (for construction).-clistSet :: CListPtr -> Word32 -> CThunkPtr -> IO ()-clistSet = c_nn_list_set+clistSet :: (MonadCData m) => CListPtr -> Word32 -> CThunkPtr -> m ()+clistSet list idx ptr = cdataIO (c_nn_list_set list idx ptr)  -- --------------------------------------------------------------------------- -- Conversion helpers@@ -127,11 +110,11 @@ -- Returns 'nullPtr' for empty lists.  A list longer than the C count -- can hold is refused rather than wrapped to a shorter allocation that -- the fill would then run past.-thunkListToCList :: [CThunkPtr] -> IO CListPtr+thunkListToCList :: (MonadCData m) => [CThunkPtr] -> m CListPtr thunkListToCList [] = pure nullPtr thunkListToCList ptrs   | len > fromIntegral (maxBound :: Word32) =-      cStatusFailure "nn_list_new" ("a list of " ++ show len ++ " elements is past the uint32_t count a C list holds")+      cdataIO (cStatusFailure "nn_list_new" ("a list of " ++ show len ++ " elements is past the uint32_t count a C list holds"))   | otherwise = do       clist <- clistNew (fromIntegral len)       fillList clist 0 ptrs@@ -145,7 +128,7 @@  -- | Convert a C list back to a Haskell list of 'CThunkPtr'. -- Returns @[]@ for 'nullPtr'.-clistToThunkList :: CListPtr -> IO [CThunkPtr]+clistToThunkList :: (MonadCData m) => CListPtr -> m [CThunkPtr] clistToThunkList cl   | cl == nullPtr = pure []   | otherwise = do@@ -156,63 +139,57 @@ -- CList newtype (wraps CListPtr for use in NixValue ADT) -- --------------------------------------------------------------------------- --- | Opaque wrapper around a C-backed list.  Used as the payload of--- @VList@ in the t'Nix.Eval.Types.NixValue' ADT.  The underlying @nn_list_t*@ is--- arena-allocated and valid until evaluation end.+-- | A C list, the payload of @VList@ in t'Nix.Eval.Types.NixValue': an+-- @nn_list_t@ that lives until the outermost evaluation session ends, or+-- until the region collector frees it once nothing reaches it+-- ("Nix.Eval.CRegion"), or null for the empty list.+--+-- Two lists are equal when they are one C list, and 'show' gives its+-- address.  Neither reads the list; 'clistThunks' reads its items. newtype CList = CList {unCList :: CListPtr}---- | Pointer equality - two CLists are the same if they point to the--- same C struct.  Deep equality is handled by the evaluator.-instance Eq CList where-  CList a == CList b = a == b--instance Show CList where-  show (CList p)-    | p == nullPtr = "<list 0>"-    | otherwise =-        let n = unsafePerformIO (clistCount p)-         in "<list " ++ show n ++ ">"+  deriving (Eq, Show)  -- | The empty CList (null pointer, zero elements). emptyCList :: CList emptyCList = CList nullPtr  -- | Convert a Haskell list of 'CThunkPtr' to a t'CList'.--- Uses 'unsafePerformIO' - safe because allocation is idempotent--- per call (no shared mutable state beyond the tracking array).-{-# NOINLINE clistFromThunks #-}-clistFromThunks :: [CThunkPtr] -> CList-clistFromThunks ptrs = CList (unsafePerformIO (thunkListToCList ptrs))+clistFromThunks :: (MonadCData m) => [CThunkPtr] -> m CList+clistFromThunks ptrs = CList <$> thunkListToCList ptrs  -- | Convert a t'CList' back to a Haskell list of 'CThunkPtr'.-clistThunks :: CList -> [CThunkPtr]-clistThunks (CList p) = unsafePerformIO (clistToThunkList p)+clistThunks :: (MonadCData m) => CList -> m [CThunkPtr]+clistThunks (CList p) = clistToThunkList p  -- | Number of elements in the list.-clistLen :: CList -> Int+clistLen :: (MonadCData m) => CList -> m Int clistLen (CList p)-  | p == nullPtr = 0-  | otherwise = fromIntegral (unsafePerformIO (clistCount p))+  | p == nullPtr = pure 0+  | otherwise = fromIntegral <$> clistCount p  -- | The element at an index, or 'Nothing' outside the list, read from the--- C array without materializing the list.  Pure because a list is never--- written after construction.-clistIndex :: CList -> Int -> Maybe CThunkPtr-clistIndex cl@(CList p) i-  | i < 0 || i >= clistLen cl = Nothing-  | otherwise = Just $! unsafePerformIO (clistGet p (fromIntegral i))+-- C array without materializing the list.+clistIndex :: (MonadCData m) => CList -> Int -> m (Maybe CThunkPtr)+clistIndex cl@(CList p) i = do+  len <- clistLen cl+  if i < 0 || i >= len+    then pure Nothing+    else Just <$> clistGet p (fromIntegral i)  -- | The list without its first @n@ elements, as 'drop' is on lists.  The -- result is a new header over this list's C array (@nn_list_drop@), so it--- costs the same whatever the length.  Allocating it under--- 'unsafePerformIO' is safe because the array is immutable: a header--- built twice or shared between calls describes the same elements.-clistDrop :: Int -> CList -> CList+-- costs the same whatever the length; sharing the array cannot be+-- observed, because a list is never written after construction.+-- @nn_list_drop@ answers the empty list for a count at or past the+-- length, so a count past its @uint32_t@ is clamped to the largest one,+-- at or past every length.+clistDrop :: (MonadCData m) => Int -> CList -> m CList clistDrop n cl@(CList p)-  | n <= 0 = cl-  | n >= clistLen cl = emptyCList-  | otherwise = CList (unsafePerformIO (alloca dropInto))+  | n <= 0 = pure cl+  | otherwise = CList <$> cdataIO (alloca dropInto)   where+    count = fromIntegral (min n countCeiling)+    countCeiling = fromIntegral (maxBound :: Word32)     dropInto out = do-      checkedListStatus "nn_list_drop" =<< c_nn_list_drop out p (fromIntegral n)+      checkedListStatus "nn_list_drop" =<< c_nn_list_drop out p count       peek out
+ src/Nix/Eval/CPrimop.hs view
@@ -0,0 +1,90 @@+-- | A builtin's partial application in the C data layer+-- (@cbits\/nn_primop.h@): the builtin's index, the cells of the arguments+-- it has taken, and which of them were taken forced.  A thunk holds one+-- under @NN_VALUE_PRIMOP_APP@, so a partial application, like every+-- other value, lives in C and holds nothing in GHC's heap.+--+-- Applications are tracked and freed in bulk at arena teardown, or one by+-- one by the region collector ("Nix.Eval.CRegion") once nothing reaches+-- them.+module Nix.Eval.CPrimop+  ( -- * Opaque handle+    NnPrimopApp,+    CPrimopAppPtr,++    -- * Lifecycle+    cprimopAppNew,++    -- * Accessors+    cprimopAppPrimop,+    cprimopAppTaken,+    cprimopAppForced,+    cprimopAppArg,+  )+where++import Data.Word (Word16, Word32)+import Foreign.Marshal.Array (withArrayLen)+import Foreign.Ptr (Ptr)+import Nix.Eval.CData (MonadCData, cdataIO)+import Nix.Eval.CStatus (checkedCPtr)+import Nix.Eval.CThunk (CThunkPtr)++-- | Phantom type for C-side @nn_primop_app_t@.+data NnPrimopApp++-- | Pointer to a C-allocated partial application.+type CPrimopAppPtr = Ptr NnPrimopApp++-- ---------------------------------------------------------------------------+-- FFI imports (all unsafe - no callbacks, fast data access)+-- ---------------------------------------------------------------------------++foreign import ccall unsafe "nn_primop_app_new"+  c_nn_primop_app_new :: Word32 -> Word16 -> Ptr CThunkPtr -> Word16 -> IO CPrimopAppPtr++foreign import ccall unsafe "nn_primop_app_primop"+  c_nn_primop_app_primop :: CPrimopAppPtr -> IO Word32++foreign import ccall unsafe "nn_primop_app_taken"+  c_nn_primop_app_taken :: CPrimopAppPtr -> IO Word16++foreign import ccall unsafe "nn_primop_app_forced"+  c_nn_primop_app_forced :: CPrimopAppPtr -> IO Word16++foreign import ccall unsafe "nn_primop_app_arg"+  c_nn_primop_app_arg :: CPrimopAppPtr -> Word16 -> IO CThunkPtr++-- ---------------------------------------------------------------------------+-- Lifecycle+-- ---------------------------------------------------------------------------++-- | A partial application of the builtin at an index to the cells of the+-- arguments it has taken, first to last, with bit @i@ of the mask set+-- when argument @i@ was taken forced.  No argument, or more than the+-- mask has bits, aborts in C; a partial application never has either.+cprimopAppNew :: (MonadCData m) => Word32 -> Word16 -> [CThunkPtr] -> m CPrimopAppPtr+cprimopAppNew primop forced args =+  cdataIO $ withArrayLen args $ \taken argsPtr ->+    checkedCPtr "nn_primop_app_new" =<< c_nn_primop_app_new primop forced argsPtr (fromIntegral taken)++-- ---------------------------------------------------------------------------+-- Accessors+-- ---------------------------------------------------------------------------++-- | The builtin's index.+cprimopAppPrimop :: (MonadCData m) => CPrimopAppPtr -> m Word32+cprimopAppPrimop = cdataIO . c_nn_primop_app_primop++-- | How many arguments it has taken.+cprimopAppTaken :: (MonadCData m) => CPrimopAppPtr -> m Word16+cprimopAppTaken = cdataIO . c_nn_primop_app_taken++-- | Which arguments were taken forced, bit @i@ for argument @i@.+cprimopAppForced :: (MonadCData m) => CPrimopAppPtr -> m Word16+cprimopAppForced = cdataIO . c_nn_primop_app_forced++-- | Argument @i@'s cell.  @i@ is below 'cprimopAppTaken': an index past+-- it aborts (@NN_ASSERT@ in @nn_primop_app_arg@).+cprimopAppArg :: (MonadCData m) => CPrimopAppPtr -> Word16 -> m CThunkPtr+cprimopAppArg app i = cdataIO (c_nn_primop_app_arg app i)
+ src/Nix/Eval/CRegion.hs view
@@ -0,0 +1,418 @@+-- | Regions (@cbits\/nn_region.h@): the C data layer's collector, which+-- frees, at the end of the forces of thunks it marks at, what they+-- allocated that nothing reaches, and a census of what collectors would+-- free there, which frees nothing.+--+-- A session runs its regions for its arena's whole life ('withRegions'),+-- and each force in it opens a region as it starts and closes it once its+-- value is stored or it throws ('inRegion').  Under 'RegionsCollect' the+-- collector marks at the close of a force that allocated at least the+-- tenure threshold (@NN_REGION_TENURE_THRESHOLD@), and frees the attribute+-- sets, list headers, lambdas, builtins' partial applications and strings+-- with context that the force allocated, that no close inside it tenured,+-- and that nothing reaches, and the lines of thunk blocks, env pages and+-- string blocks that hold nothing it reached, which the allocators then+-- bump from again.  What closes inside it tenured is marked too where a+-- close marks its region whole: at an outermost close, and where the+-- region holds 1 MiB tenured since its last whole mark.  Under 'RegionsCensus'+-- each close marks, among what the force allocated, what its writes into+-- older cells and with-scopes and the roots it registered still reach, and+-- frees nothing.  'regionFigures' reads the census's counts by size of region,+-- and a simulation of collectors that mark only at the closes of regions past+-- a threshold of bytes, freeing single objects, whole blocks of each of+-- several sizes, or whole lines of a block of each of two lengths.  It also+-- counts what a close reached after an earlier close found it unreached,+-- which a collector would have freed under a live pointer.  And it simulates,+-- each as a t'Tenure', collectors that tenure what their closes marked and+-- mark it again only where a close marks its region whole.+--+-- Under 'RegionsOff' a force pays for regions one match on its session's+-- setting, and the allocators one flag test per block, tracked object+-- and stored object.+module Nix.Eval.CRegion+  ( -- * Running regions+    Regions (..),+    withRegions,+    regionsRunning,+    inRegion,++    -- * Figures+    SizeClass (..),+    Threshold (..),+    Tenure (..),+    RegionFigures (..),+    regionFigures,+    renderRegionFigures,+  )+where++import Control.Exception (bracket_, throwIO)+import Control.Monad (unless)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Builder as BB+import qualified Data.ByteString.Lazy as BL+import Data.Word (Word32, Word64)+import Foreign.C.Types (CInt (..))+import Foreign.Marshal.Array (allocaArray)+import Foreign.Ptr (Ptr)+import Foreign.Storable (peek, peekElemOff)+import Nix.Eval.CStatus (CStatusError (..))++-- ---------------------------------------------------------------------------+-- FFI imports+-- ---------------------------------------------------------------------------++foreign import ccall unsafe "nn_region_begin"+  c_nn_region_begin :: CInt -> IO CInt++foreign import ccall unsafe "nn_region_end"+  c_nn_region_end :: IO ()++foreign import ccall unsafe "&nn_region_mode"+  c_nn_region_mode :: Ptr CInt++-- A close marks and retires one region, work bounded by what the force+-- allocated, between two steps of the single-threaded evaluator: an+-- unsafe call, as every allocation is.++foreign import ccall unsafe "nn_region_open"+  c_nn_region_open :: IO ()++foreign import ccall unsafe "nn_region_close"+  c_nn_region_close :: IO ()++foreign import ccall unsafe "nn_region_totals"+  c_nn_region_totals :: Ptr Word64 -> IO ()++foreign import ccall unsafe "nn_region_classes"+  c_nn_region_classes :: Ptr Word64 -> IO ()++foreign import ccall unsafe "nn_region_thresholds"+  c_nn_region_thresholds :: Ptr Word64 -> IO ()++foreign import ccall unsafe "nn_region_tenure"+  c_nn_region_tenure :: Word32 -> Ptr Word64 -> IO ()++foreign import ccall unsafe "nn_region_tenure_budget"+  c_nn_region_tenure_budget :: Word32 -> Word64++foreign import ccall unsafe "nn_region_threshold_bytes"+  c_nn_region_threshold_bytes :: Word32 -> Word64++foreign import ccall unsafe "nn_region_grain_bytes"+  c_nn_region_grain_bytes :: CInt -> Word32 -> Word64++-- ---------------------------------------------------------------------------+-- The layout of the figures, in lockstep with cbits/nn_region.h+-- ---------------------------------------------------------------------------++-- | @NN_REGION_TOTALS@ and the totals' places.+totalCount, totalCloses, totalAllocated, totalOutside, totalDepth, totalRecords, totalUnplaced, totalResurrected, totalResurrectedBytes, totalFailed :: Int+totalCount = 9+totalCloses = 0+totalAllocated = 1+totalOutside = 2+totalDepth = 3+totalRecords = 4+totalUnplaced = 5+totalResurrected = 6+totalResurrectedBytes = 7+totalFailed = 8++-- | @NN_REGION_SIZE_CLASSES@ and @NN_REGION_CLASS_FIGURES@.+classCount, classFigures :: Int+classCount = 48+classFigures = 6++-- | @NN_REGION_THRESHOLDS@, @NN_REGION_GRAINS@, @NN_REGION_BLOCK_GRAINS@+-- and @NN_REGION_THRESHOLD_FIGURES@: three counts, then a peak per grain.+thresholdCount, grainCount, blockGrainCount, thresholdFigures :: Int+thresholdCount = 9+grainCount = 8+blockGrainCount = 5+thresholdFigures = 3 + grainCount++-- | @NN_REGION_TENURE_VARIANTS@, @NN_REGION_TENURE_THRESHOLD@, and+-- @NN_REGION_TENURE_FIGURES@: eleven counts, then a peak per grain.+tenureVariants :: Word32+tenureVariants = 4++tenureThreshold :: Word32+tenureThreshold = 2++tenureFigures :: Int+tenureFigures = 11 + grainCount++-- | The bump kinds in order: @NN_REGION_THUNK_BLOCK@,+-- @NN_REGION_ENV_PAGE@ and @NN_REGION_STR_BLOCK@.+bumpKinds :: [CInt]+bumpKinds = [0, 1, 2]++-- | The bump kind a line grain's bytes are asked for, @NN_REGION_THUNK_BLOCK@:+-- a line is one size in every kind.+lineKind :: CInt+lineKind = 0++-- ---------------------------------------------------------------------------+-- Running regions+-- ---------------------------------------------------------------------------++-- | What a session's regions run for.+data Regions+  = -- | Nothing: no force opens a region, and the arena frees everything+    -- at its teardown.+    RegionsOff+  | -- | A census, which measures what collectors would free and frees+    -- nothing.+    RegionsCensus+  | -- | The collector.+    RegionsCollect+  deriving (Eq, Show)++-- | @NN_REGION_CENSUS@ and @NN_REGION_COLLECT@.+regionCensusMode, regionCollectMode :: CInt+regionCensusMode = 1+regionCollectMode = 2++-- | Run an action that sets up and tears down an arena with its regions+-- running, from before the arena's first block to after its teardown.+-- Raises 'CAllocationFailed' when the regions' tables cannot be+-- allocated.+withRegions :: Regions -> IO a -> IO a+withRegions regions action = case regions of+  RegionsOff -> action+  RegionsCensus -> running regionCensusMode+  RegionsCollect -> running regionCollectMode+  where+    running mode = bracket_ (begin mode) c_nn_region_end action+    begin mode = do+      status <- c_nn_region_begin mode+      unless (status == 0) (throwIO (CAllocationFailed "nn_region_begin" "the regions' tables could not be allocated"))++-- | What the regions running now run for, which a session sharing a+-- running arena takes on.+regionsRunning :: IO Regions+regionsRunning = running <$> peek c_nn_region_mode+  where+    running mode+      | mode == regionCensusMode = RegionsCensus+      | mode == regionCollectMode = RegionsCollect+      | otherwise = RegionsOff++-- | Run a force's work in a region of its own, while regions run.+inRegion :: Regions -> IO a -> IO a+inRegion RegionsOff action = action+inRegion _ action = bracket_ c_nn_region_open c_nn_region_close action++-- ---------------------------------------------------------------------------+-- Figures+-- ---------------------------------------------------------------------------++-- | The closes of regions that allocated from 'classFloor' bytes to+-- under twice that, or nothing for a floor of 0.+data SizeClass = SizeClass+  { classFloor :: !Word64,+    classCloses :: !Word64,+    -- | Bytes the regions allocated.+    classAllocated :: !Word64,+    -- | Bytes of theirs the closes reached.+    classSurviving :: !Word64,+    -- | Objects the marks entered.+    classEntered :: !Word64,+    -- | Pointers the marks examined.+    classExamined :: !Word64,+    -- | Records the closes read.+    classRecords :: !Word64+  }+  deriving (Eq, Show)++-- | A simulated collector that marks at a close only when its region+-- allocated at least 'thresholdBytes'.+data Threshold = Threshold+  { thresholdBytes :: !Word64,+    -- | The closes that mark, and their marks' objects and pointers.+    thresholdCloses :: !Word64,+    thresholdEntered :: !Word64,+    thresholdExamined :: !Word64,+    -- | The most bytes held at once, freeing single objects first, then+    -- freeing whole blocks of each block grain's size, largest first,+    -- then whole lines of each line grain's size, longest first.+    thresholdPeaks :: ![Word64]+  }+  deriving (Eq, Show)++-- | A simulated collector that marks at the closes of regions that+-- allocated at least 'tenureBytes' and then tenures the whole region:+-- each such close marks only what no such close of its inside tenured,+-- but one that marks its region whole, an outermost one or one whose+-- region holds at least 'tenureBudget' tenured bytes no mark of the+-- whole has reached since.+data Tenure = Tenure+  { -- | 0 for no budget, so that only outermost closes mark the whole.+    tenureBudget :: !Word64,+    tenureBytes :: !Word64,+    -- | The closes that mark, and of them those that mark the whole.+    tenureCloses :: !Word64,+    tenureFull :: !Word64,+    -- | Objects the marks entered, and pointers they examined.+    tenureEntered :: !Word64,+    tenureExamined :: !Word64,+    -- | The most records held at once.+    tenureRecords :: !Word64,+    -- | Pointers closes remembered for regions around them, and the most+    -- held at once.+    tenureRemembered :: !Word64,+    tenureHeld :: !Word64,+    -- | Units and places it freed that the census's own mark at the same+    -- close reached.+    tenureReached :: !Word64,+    -- | Objects and array entries a later close reached once it freed+    -- them, and their bytes.+    tenureResurrected :: !Word64,+    tenureResurrectedBytes :: !Word64,+    -- | Bytes of single objects the marks of the whole freed.+    tenureFullFreed :: !Word64,+    -- | The most bytes held at once, at each grain as 'thresholdPeaks'.+    tenurePeaks :: ![Word64]+  }+  deriving (Eq, Show)++-- | What a census of regions found.+data RegionFigures = RegionFigures+  { regionCloses :: !Word64,+    -- | Bytes the data layer allocated while the census ran.+    regionAllocated :: !Word64,+    -- | Of those, bytes allocated outside every region: between forces,+    -- which no close can free.+    regionOutside :: !Word64,+    -- | The most regions open at once.+    regionDepth :: !Word64,+    -- | The most records held at once.+    regionRecords :: !Word64,+    -- | Pointers the census could not place, which a graph it models in+    -- full never holds.+    regionUnplaced :: !Word64,+    -- | Objects and array entries a close reached after an earlier one+    -- found them unreached, and their bytes.+    regionResurrected :: !Word64,+    regionResurrectedBytes :: !Word64,+    -- | Every size class with a close in it, smallest first.+    regionClasses :: ![SizeClass],+    -- | Each threshold, smallest first.+    regionThresholds :: ![Threshold],+    -- | Each tenure collector, by its budget, smallest first and no+    -- budget first of all.+    regionTenures :: ![Tenure]+  }+  deriving (Eq, Show)++-- | The census's figures, read in the session it runs in.  'Left' when+-- one of its tables could not grow and it stopped counting.+regionFigures :: IO (Either CStatusError RegionFigures)+regionFigures =+  allocaArray totalCount $ \totals ->+    allocaArray (classCount * classFigures) $ \classes ->+      allocaArray (thresholdCount * thresholdFigures) $ \thresholds -> do+        c_nn_region_totals totals+        c_nn_region_classes classes+        c_nn_region_thresholds thresholds+        let total = peekElemOff totals+        failed <- total totalFailed+        if failed /= 0+          then pure (Left (CAllocationFailed "nn_region_close" "the census's tables could not grow"))+          else do+            sizeClasses <- traverse (sizeClass classes) [0 .. classCount - 1]+            simulated <- traverse (threshold thresholds) [0 .. thresholdCount - 1]+            tenured <- traverse tenure [0 .. tenureVariants - 1]+            figures <-+              RegionFigures+                <$> total totalCloses+                <*> total totalAllocated+                <*> total totalOutside+                <*> total totalDepth+                <*> total totalRecords+                <*> total totalUnplaced+                <*> total totalResurrected+                <*> total totalResurrectedBytes+                <*> pure (filter ((> 0) . classCloses) sizeClasses)+                <*> pure simulated+                <*> pure tenured+            pure (Right figures)+  where+    sizeClass classes n = do+      let figure i = peekElemOff classes (n * classFigures + i)+      SizeClass (classFloorOf n)+        <$> figure 0+        <*> figure 1+        <*> figure 2+        <*> figure 3+        <*> figure 4+        <*> figure 5+    classFloorOf n+      | n == 0 = 0+      | otherwise = 2 ^ (n - 1)+    threshold thresholds k = do+      let figure i = peekElemOff thresholds (k * thresholdFigures + i)+      Threshold (c_nn_region_threshold_bytes (fromIntegral k))+        <$> figure 0+        <*> figure 1+        <*> figure 2+        <*> traverse (figure . (3 +)) [0 .. grainCount - 1]+    tenure variant = allocaArray tenureFigures $ \tenures -> do+      c_nn_region_tenure variant tenures+      let figure = peekElemOff tenures+      Tenure (c_nn_region_tenure_budget variant) (c_nn_region_threshold_bytes tenureThreshold)+        <$> figure 0+        <*> figure 1+        <*> figure 2+        <*> figure 3+        <*> figure 4+        <*> figure 5+        <*> figure 6+        <*> figure 7+        <*> figure 8+        <*> figure 9+        <*> figure 10+        <*> traverse (figure . (11 +)) [0 .. grainCount - 1]++-- | The figures as lines of a name and its values: totals as+-- @regions.NAME VALUE@, a size class as @regions.class FLOOR CLOSES+-- ALLOCATED SURVIVING ENTERED EXAMINED RECORDS@, a threshold as+-- @regions.threshold BYTES CLOSES ENTERED EXAMINED@ and its peaks by+-- grain, each tenure collector as @regions.tenure BUDGET BYTES CLOSES FULL+-- ENTERED EXAMINED FULLFREED@ and its peaks, with its records, what it+-- remembered and held, what it freed that was reached and what was+-- reached once freed on lines of their own after its budget, each block+-- grain as @regions.grain GRAIN@ and its block bytes for thunk cells, env+-- pages and strings, and each line grain as @regions.line GRAIN BYTES@.+renderRegionFigures :: RegionFigures -> BS.ByteString+renderRegionFigures figures =+  BL.toStrict . BB.toLazyByteString $+    field "regions.closes" [regionCloses figures]+      <> field "regions.allocated.bytes" [regionAllocated figures]+      <> field "regions.outside.bytes" [regionOutside figures]+      <> field "regions.depth" [regionDepth figures]+      <> field "regions.records" [regionRecords figures]+      <> field "regions.unplaced" [regionUnplaced figures]+      <> field "regions.resurrected.count" [regionResurrected figures]+      <> field "regions.resurrected.bytes" [regionResurrectedBytes figures]+      <> foldMap sizeClass (regionClasses figures)+      <> foldMap threshold (regionThresholds figures)+      <> foldMap tenure (regionTenures figures)+      <> foldMap grain [1 .. fromIntegral blockGrainCount]+      <> foldMap line [fromIntegral blockGrainCount + 1 .. fromIntegral grainCount - 1]+  where+    field name values =+      BB.byteString name <> foldMap ((BB.char7 ' ' <>) . BB.word64Dec) values <> BB.char7 '\n'+    sizeClass (SizeClass lowest closes allocated surviving entered examined records) =+      field "regions.class" [lowest, closes, allocated, surviving, entered, examined, records]+    threshold (Threshold bytes closes entered examined peaks) =+      field "regions.threshold" ([bytes, closes, entered, examined] <> peaks)+    tenure t =+      field "regions.tenure" ([tenureBudget t, tenureBytes t, tenureCloses t, tenureFull t, tenureEntered t, tenureExamined t, tenureFullFreed t] <> tenurePeaks t)+        <> field "regions.tenure.records" [tenureBudget t, tenureRecords t]+        <> field "regions.tenure.remembered" [tenureBudget t, tenureRemembered t, tenureHeld t]+        <> field "regions.tenure.reached" [tenureBudget t, tenureReached t]+        <> field "regions.tenure.resurrected" [tenureBudget t, tenureResurrected t, tenureResurrectedBytes t]+    grain g = field "regions.grain" (fromIntegral g : [c_nn_region_grain_bytes kind g | kind <- bumpKinds])+    line g = field "regions.line" [fromIntegral g, c_nn_region_grain_bytes lineKind g]
+ src/Nix/Eval/CRoots.hs view
@@ -0,0 +1,67 @@+-- | The roots of an evaluation session in the C data layer+-- (@cbits\/nn_roots.h@): each C object Haskell keeps beyond one+-- evaluation step, registered as it is made, so a census given+-- 'Nix.Eval.CStats.RootRegistered' marks from it without the caller+-- naming it.  A session registers its base environment as it starts+-- (its search path is reached through @builtins.nixPath@ in it), and+-- each imported file's value as the import cache takes it+-- ("Nix.Eval.IO").  A session forgets the roots registered within it as+-- it ends ('crootsMark', 'crootsRelease'), and the arena's teardown+-- forgets them all.+module Nix.Eval.CRoots+  ( crootsAddThunk,+    crootsAddEnv,+    RootsMark,+    crootsMark,+    crootsRelease,+  )+where++import Control.Monad (unless)+import Data.Word (Word32)+import Foreign.C.Types (CInt (..))+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (Ptr)+import Foreign.Storable (peek)+import Nix.Eval.CData (MonadCData, cdataIO)+import Nix.Eval.CEnv (NnEnv)+import Nix.Eval.CStatus (cStatusFailure)+import Nix.Eval.CThunk (CThunkPtr)++foreign import ccall unsafe "nn_roots_add_thunk"+  c_nn_roots_add_thunk :: CThunkPtr -> IO CInt++foreign import ccall unsafe "nn_roots_add_env"+  c_nn_roots_add_env :: Ptr NnEnv -> IO CInt++foreign import ccall unsafe "nn_roots_mark"+  c_nn_roots_mark :: Ptr Word32 -> Ptr Word32 -> IO ()++foreign import ccall unsafe "nn_roots_release"+  c_nn_roots_release :: Word32 -> Word32 -> IO ()++-- | The registry's size at a point, to release back to.+data RootsMark = RootsMark !Word32 !Word32++-- | The registry's size now.+crootsMark :: IO RootsMark+crootsMark =+  alloca $ \thunks -> alloca $ \envs -> do+    c_nn_roots_mark thunks envs+    RootsMark <$> peek thunks <*> peek envs++-- | Forget every root registered since the mark.+crootsRelease :: RootsMark -> IO ()+crootsRelease (RootsMark thunks envs) = c_nn_roots_release thunks envs++-- | Register a thunk cell as a root.+crootsAddThunk :: (MonadCData m) => CThunkPtr -> m ()+crootsAddThunk cell = cdataIO (c_nn_roots_add_thunk cell >>= registered "nn_roots_add_thunk")++-- | Register an environment as a root.+crootsAddEnv :: (MonadCData m) => Ptr NnEnv -> m ()+crootsAddEnv env = cdataIO (c_nn_roots_add_env env >>= registered "nn_roots_add_env")++-- | Raise the failure of a registration the registry could not hold.+registered :: String -> CInt -> IO ()+registered site status = unless (status == 0) (cStatusFailure site "the root registry could not grow")
+ src/Nix/Eval/CStats.hs view
@@ -0,0 +1,585 @@+{-# LANGUAGE DeriveTraversable #-}++-- | A census of the C data layer (@cbits\/nn_stats.h@): what it holds by+-- kind of object, and what a set of roots reaches.+--+-- 'takeCensus' counts every object the allocators hold and then marks+-- from the roots it is given, the session's registered roots+-- ("Nix.Eval.CRoots") among them when it is given 'RootRegistered',+-- following every C pointer: every value lives in C, so the mark runs in+-- C alone.  It frees and writes nothing in the data layer.  A process+-- that never takes a census pays for it the env allocator's count and+-- bytes of deferred applications' cells, the string arena's count of+-- strings, and the flag test below.+--+-- Once 'countSites' turns counting on, the allocators also count each+-- environment and attribute set under its site ("Nix.Eval.AllocSite"),+-- and @//@ the entries it copies, which 'siteCounts' and every census+-- after it read.  With counting off, an allocation tests one C flag and+-- counts nothing.+--+-- What it reaches is exact for the roots it is given, and how close that+-- is to what the process still uses depends on the roots.  Haskell holds+-- C pointers in values the C side cannot enumerate, so an object only+-- such a value holds goes unmarked unless a root reaches it: the reached+-- figures are a lower bound on what is live, and the rest an upper bound+-- on what no root reaches.  Two parts of the layer are not marked at all.+-- Symbols are reached through the values that hold them, not through the+-- compiled code that names them, so the symbols reached are a lower bound+-- on the symbols in use.  The bytecode store is counted and never marked,+-- since nothing frees code, and a value pointing at one of the code's+-- strings (a literal's bytes) reaches nothing the census counts.+module Nix.Eval.CStats+  ( -- * Kinds of object+    PerKind (..),++    -- * Figures+    Figures (..),+    Census (..),++    -- * Counting by site+    EnvSize (..),+    EnvSiteFigures (..),+    SetSiteFigures (..),+    SiteCounts (..),+    countSites,+    siteCounts,+    envSitesCounted,+    setSitesCounted,++    -- * Roots+    CRoot (..),+    valueRoots,++    -- * Taking a census+    takeCensus,++    -- * Report+    renderCensus,+  )+where++import Control.Exception (finally)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Builder as BB+import qualified Data.ByteString.Lazy as BL+import Data.Foldable (toList)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Word (Word32, Word64)+import Foreign.C.Types (CInt (..))+import Foreign.Marshal.Alloc (alloca)+import Foreign.Marshal.Array (allocaArray, peekArray)+import Foreign.Ptr (Ptr, castPtr, nullPtr)+import Foreign.Storable (peek, peekElemOff)+import GHC.Clock (getMonotonicTime)+import Nix.Eval.AllocSite (EnvSite, SetSite, envSiteIndex, envSiteName, setSiteIndex, setSiteName)+import Nix.Eval.CCtxStr (CCtxStrPtr)+import Nix.Eval.CList (CList (..))+import Nix.Eval.CStatus (CStatusError (..))+import Nix.Eval.CStr (CStrPtr)+import Nix.Eval.Types (AttrSet (..), BuiltinArg (..), Env (..), HeldBytes (..), NixValue (..), Thunk (..))+import Numeric (showFFloat)++-- ---------------------------------------------------------------------------+-- FFI imports+-- ---------------------------------------------------------------------------++-- The index build and the mark run for as long as the data layer is big,+-- so they are safe calls, which let the RTS go on without them.++foreign import ccall safe "nn_stats_begin"+  c_nn_stats_begin :: IO CInt++foreign import ccall unsafe "nn_stats_end"+  c_nn_stats_end :: IO ()++foreign import ccall unsafe "nn_stats_allocated"+  c_nn_stats_allocated :: Ptr Word64 -> Ptr Word64 -> IO ()++foreign import ccall unsafe "nn_stats_overhead_bytes"+  c_nn_stats_overhead_bytes :: IO Word64++foreign import ccall unsafe "nn_stats_code_bytes"+  c_nn_stats_code_bytes :: IO Word64++foreign import ccall unsafe "nn_stats_root_thunk"+  c_nn_stats_root_thunk :: Ptr () -> IO ()++foreign import ccall unsafe "nn_stats_root_env"+  c_nn_stats_root_env :: Ptr () -> IO ()++foreign import ccall unsafe "nn_stats_root_attrset"+  c_nn_stats_root_attrset :: Ptr () -> IO ()++foreign import ccall unsafe "nn_stats_root_list"+  c_nn_stats_root_list :: Ptr () -> IO ()++foreign import ccall unsafe "nn_stats_root_string"+  c_nn_stats_root_string :: Ptr () -> IO ()++foreign import ccall unsafe "nn_stats_root_ctxstr"+  c_nn_stats_root_ctxstr :: Ptr () -> IO ()++foreign import ccall unsafe "nn_stats_root_registered"+  c_nn_stats_root_registered :: IO ()++foreign import ccall safe "nn_stats_mark"+  c_nn_stats_mark :: IO CInt++foreign import ccall unsafe "nn_stats_reached"+  c_nn_stats_reached :: Ptr Word64 -> Ptr Word64 -> IO ()++foreign import ccall unsafe "nn_stats_visited"+  c_nn_stats_visited :: Ptr Word64 -> Ptr Word64 -> Ptr Word64 -> IO ()++foreign import ccall safe "nn_stats_reached_set_sizes"+  c_nn_stats_reached_set_sizes :: Ptr Word32 -> Ptr Word64 -> Word32 -> Ptr Word32 -> IO CInt++foreign import ccall unsafe "nn_stats_count_sites"+  c_nn_stats_count_sites :: IO ()++foreign import ccall unsafe "&nn_stats_counting"+  c_nn_stats_counting :: Ptr CInt++foreign import ccall unsafe "nn_stats_env_sites"+  c_nn_stats_env_sites :: Ptr Word64 -> Ptr Word64 -> Ptr Word64 -> Word32 -> IO Word32++foreign import ccall unsafe "nn_stats_env_sizes"+  c_nn_stats_env_sizes :: Ptr Word64 -> Word32 -> IO Word32++foreign import ccall unsafe "nn_stats_set_sites"+  c_nn_stats_set_sites :: Ptr Word64 -> Ptr Word64 -> Ptr Word64 -> Word32 -> IO Word32++foreign import ccall unsafe "nn_stats_update_copied"+  c_nn_stats_update_copied :: IO Word64++-- ---------------------------------------------------------------------------+-- Kinds of object+-- ---------------------------------------------------------------------------++-- | One of something for each kind of object the data layer holds.+data PerKind a = PerKind+  { -- | Thunk cells in the arena's blocks.+    kindThunks :: !a,+    -- | Envs, with their slots, and their with-scope arrays.+    kindEnvs :: !a,+    -- | Attribute sets: each header with its keys, positions and values.+    kindAttrSets :: !a,+    -- | List headers, with the items arrays they span.+    kindLists :: !a,+    -- | Lambda closures and their formal entries.+    kindLambdas :: !a,+    -- | Builtins' partial applications, with their argument cells.+    kindPrimopApps :: !a,+    -- | Deferred applications' cells, a function's and its arguments',+    -- which a builtin makes per element as upstream makes an app value.+    kindApps :: !a,+    -- | Strings with context.+    kindCtxStrs :: !a,+    -- | The bytes of strings and paths, a string with context's text and+    -- its context's store paths and output names among them.+    kindStrings :: !a,+    -- | Interned names: attribute names, formals and variables.+    kindSymbols :: !a+  }+  deriving (Eq, Show, Functor, Foldable, Traversable)++-- | Kind by kind: 'pure' is the same value for every kind, and '<*>'+-- applies each kind's function to that kind's value.+instance Applicative PerKind where+  pure a = PerKind a a a a a a a a a a+  PerKind f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 <*> PerKind a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 =+    PerKind (f1 a1) (f2 a2) (f3 a3) (f4 a4) (f5 a5) (f6 a6) (f7 a7) (f8 a8) (f9 a9) (f10 a10)++-- | Each kind's index in the arrays @nn_stats_allocated@ and+-- @nn_stats_reached@ fill: the @NN_STATS_*@ constants of+-- @cbits\/nn_stats.h@, which this must match.+kindIndices :: PerKind Int+kindIndices = PerKind 0 1 2 3 4 5 6 7 8 9++-- | @NN_STATS_KIND_COUNT@: the length of those arrays.+kindCount :: Int+kindCount = 10++-- | @NN_STATS_UNCOUNTED@: a count no allocator keeps.+uncounted :: Word64+uncounted = maxBound++-- | Each kind's name in 'renderCensus'.+kindNames :: PerKind BS.ByteString+kindNames = PerKind "thunks" "envs" "attrsets" "lists" "lambdas" "primopapps" "apps" "ctxstrs" "strings" "symbols"++-- ---------------------------------------------------------------------------+-- Figures+-- ---------------------------------------------------------------------------++-- | Objects of one kind and the bytes they hold from the allocator.+data Figures = Figures+  { -- | How many, or 'Nothing' where no allocator keeps a count: the env+    -- pages hold envs and with-scope arrays side by side, so unless+    -- counting by site ('countSites') has covered every env, the envs+    -- allocated are known in bytes and not in number.+    figuresCount :: !(Maybe Word64),+    figuresBytes :: !Word64+  }+  deriving (Eq, Show)++-- | A census: what the data layer holds, what the roots reach, and what+-- reaching it cost.+data Census = Census+  { -- | Everything allocated, by kind.+    censusAllocated :: !(PerKind Figures),+    -- | What the roots reach, by kind.  An env's with-scope array counts+    -- in the bytes of the first env over it reached and not in its count;+    -- a list's items array counts once whichever header over it is+    -- reached.+    censusReached :: !(PerKind Figures),+    -- | Bytes the allocators hold that no object does: block and page+    -- headers and unused tails, the tracking arrays, and the symbol+    -- table beyond its text.+    censusOverheadBytes :: !Word64,+    -- | Bytes the bytecode store holds.+    censusCodeBytes :: !Word64,+    -- | Objects the mark entered: thunks, envs, with-scope arrays, sets,+    -- list headers, items arrays, lambdas, partial applications,+    -- deferred applications' cells and strings with context.+    -- Strings and symbols hold no pointer, and are marked and not entered.+    censusVisitedObjects :: !Word64,+    -- | The bytes those objects hold.+    censusVisitedBytes :: !Word64,+    -- | Pointers the mark met that it could not place in its index, and so+    -- did not follow: none while the mark models+    -- every pointer the data layer stores.+    censusUnplaced :: !Word64,+    -- | Wall-clock seconds the count and the index took.+    censusIndexSeconds :: !Double,+    -- | Wall-clock seconds the mark took.+    censusMarkSeconds :: !Double,+    -- | The reached attribute sets by the number of entries each holds in+    -- its own arrays, a layer's without the set under it.+    censusSetSizes :: !(Map Word32 Word64),+    -- | What counting by site has found, when it is on.+    censusSites :: !(Maybe SiteCounts)+  }+  deriving (Eq, Show)++-- ---------------------------------------------------------------------------+-- Counting by site+-- ---------------------------------------------------------------------------++-- | The size of an environment: the slots it holds.+data EnvSize+  = -- | Exactly this many.+    EnvSlots !Word32+  | -- | This many or more: the sizes from @NN_STATS_ENV_SIZES@ - 1 on+    -- share one count.+    EnvSlotsAtLeast !Word32+  deriving (Eq, Ord, Show)++-- | The environments one site allocated.+data EnvSiteFigures = EnvSiteFigures+  { -- | How many.+    envSiteEnvs :: !Word64,+    -- | The slots they hold.+    envSiteSlots :: !Word64,+    -- | Every byte of the env pages they took: the envs with their slots,+    -- and their with-scope arrays.+    envSiteBytes :: !Word64+  }+  deriving (Eq, Show)++-- | The attribute sets one site allocated.+data SetSiteFigures = SetSiteFigures+  { -- | How many.+    setSiteSets :: !Word64,+    -- | Those made equal to a set that already existed, which upstream+    -- would not make: one made with room for no entries or by removal+    -- from a set with none, or a union one of whose operands had none.+    -- The evaluator makes none, so a count above 0 is a regression.+    setSiteShareable :: !Word64,+    -- | Their bytes once built: headers, keys, positions and values.+    setSiteBytes :: !Word64+  }+  deriving (Eq, Show)++-- | What counting by site has found since 'countSites'.+data SiteCounts = SiteCounts+  { -- | Every env site, with what it allocated.+    sitesEnvs :: !(Map EnvSite EnvSiteFigures),+    -- | The environments allocated, by size; sizes none had are absent.+    sitesEnvSizes :: !(Map EnvSize Word64),+    -- | Every set site, with what it allocated.+    sitesSets :: !(Map SetSite SetSiteFigures),+    -- | The entries @//@ copied into the sets it made, which upstream+    -- counts in @nrOpUpdateValuesCopied@.+    sitesUpdateCopied :: !Word64+  }+  deriving (Eq, Show)++-- | @NN_STATS_ENV_SIZES@: the buckets of environments by size, the last+-- for every size from its index on.+envSizeBuckets :: Word32+envSizeBuckets = 33++-- | The size from which environments share one bucket.+envSizeOpen :: Word32+envSizeOpen = envSizeBuckets - 1++-- | Turn counting by site on, every count from zero.  Turned on before the+-- first environment is allocated, it covers every one, and a census then+-- reports their number.+countSites :: IO ()+countSites = c_nn_stats_count_sites++-- | What counting by site has found, or 'Nothing' while it is off.+siteCounts :: IO (Maybe SiteCounts)+siteCounts = do+  counting <- peek c_nn_stats_counting+  if counting == 0+    then pure Nothing+    else do+      envs <- readSites envSiteCount c_nn_stats_env_sites+      sizes <- allocaArray (fromIntegral envSizeBuckets) $ \buf -> do+        buckets <- c_nn_stats_env_sizes buf envSizeBuckets+        counts <- peekArray (fromIntegral (min buckets envSizeBuckets)) buf+        pure (Map.fromList [(bucket i, n) | (i, n) <- zip [0 ..] counts, n /= 0])+      sets <- readSites setSiteCount c_nn_stats_set_sites+      Just . SiteCounts (siteMap envSiteIndex envFigures envs) sizes (siteMap setSiteIndex setFigures sets)+        <$> c_nn_stats_update_copied+  where+    bucket i+      | i < envSizeOpen = EnvSlots i+      | otherwise = EnvSlotsAtLeast envSizeOpen+    envFigures (envs, slots, bytes) = EnvSiteFigures envs slots bytes+    setFigures (sets, shareable, bytes) = SetSiteFigures sets shareable bytes+    siteMap index figures counted =+      Map.fromList [(site, figures (Map.findWithDefault (0, 0, 0) (index site) counted)) | site <- [minBound .. maxBound]]++-- | How many env sites the C side counts, which must be every 'EnvSite'.+envSitesCounted :: IO Word32+envSitesCounted = c_nn_stats_env_sites nullPtr nullPtr nullPtr 0++-- | How many set sites the C side counts, which must be every 'SetSite'.+setSitesCounted :: IO Word32+setSitesCounted = c_nn_stats_set_sites nullPtr nullPtr nullPtr 0++-- | The number of sites the evaluator names.+envSiteCount, setSiteCount :: Word32+envSiteCount = fromIntegral (length [minBound .. maxBound :: EnvSite])+setSiteCount = fromIntegral (length [minBound .. maxBound :: SetSite])++-- | Three figures per site, keyed by site number, from a C function that+-- fills three arrays for the first @count@ sites and answers how many it+-- counts.+readSites ::+  Word32 ->+  (Ptr Word64 -> Ptr Word64 -> Ptr Word64 -> Word32 -> IO Word32) ->+  IO (Map Word32 (Word64, Word64, Word64))+readSites count fill =+  allocaArray n $ \first -> allocaArray n $ \second -> allocaArray n $ \third -> do+    counted <- fill first second third count+    let k = fromIntegral (min counted count)+    rows <- zip3 <$> peekArray k first <*> peekArray k second <*> peekArray k third+    pure (Map.fromList (zip [0 ..] rows))+  where+    n = fromIntegral count++-- ---------------------------------------------------------------------------+-- Roots+-- ---------------------------------------------------------------------------++-- | A C object a census marks from.+data CRoot+  = RootThunk !Thunk+  | RootEnv !Env+  | RootAttrSet !AttrSet+  | RootList !CList+  | -- | A string's or a path's bytes.+    RootString !CStrPtr+  | -- | A string with context.+    RootCtxStr !CCtxStrPtr+  | -- | Every root the session registered ("Nix.Eval.CRoots").+    RootRegistered++-- | The C objects a value holds.  A value read from a cell is a view of+-- the cell's C objects; a partial application built in Haskell and not+-- yet stored holds them through its arguments.+valueRoots :: NixValue -> [CRoot]+valueRoots value = case value of+  VInt _ -> []+  VFloat _ -> []+  VBool _ -> []+  VNull -> []+  VStrHeld _ _ held -> heldRoots held+  VPathHeld _ held -> heldRoots held+  VList list -> [RootList list]+  VAttrs set -> [RootAttrSet set]+  VLambda env _ _ -> [RootEnv env]+  VBuiltin _ args -> concatMap argumentRoots args+  where+    argumentRoots (ArgForced forced) = valueRoots forced+    argumentRoots (ArgDeferred thunk) = [RootThunk thunk]+    heldRoots NotHeld = []+    heldRoots (HeldStr str) = [RootString str]+    heldRoots (HeldCtxStr csptr) = [RootCtxStr csptr]++-- | Name a root to the open session.+nameRoot :: CRoot -> IO ()+nameRoot root = case root of+  RootThunk (Thunk ptr) -> c_nn_stats_root_thunk (castPtr ptr)+  RootEnv (Env ptr) -> c_nn_stats_root_env (castPtr ptr)+  RootAttrSet (AttrSet ptr) -> c_nn_stats_root_attrset (castPtr ptr)+  RootList (CList ptr) -> c_nn_stats_root_list (castPtr ptr)+  RootString str -> c_nn_stats_root_string (castPtr str)+  RootCtxStr csptr -> c_nn_stats_root_ctxstr (castPtr csptr)+  RootRegistered -> c_nn_stats_root_registered++-- ---------------------------------------------------------------------------+-- Taking a census+-- ---------------------------------------------------------------------------++-- | Count what the data layer holds and mark what the roots reach.  Runs+-- inside the arena's window, with nothing else using the data layer.+-- Every root's object exists when the count runs: the C objects a caller+-- can name are made by actions ("Nix.Eval.CData"), so forcing a root makes+-- none.+-- 'Left' when the C side cannot allocate the index, the mark's work+-- stack, or the array it sorts the reached sets' sizes in.+takeCensus :: [CRoot] -> IO (Either CStatusError Census)+takeCensus roots = do+  started <- getMonotonicTime+  begun <- c_nn_stats_begin+  if begun /= 0+    then pure (Left (CAllocationFailed "nn_stats_begin" "the census index could not be allocated"))+    else measure started `finally` c_nn_stats_end+  where+    measure started = do+      allocated <- readFigures c_nn_stats_allocated+      overhead <- c_nn_stats_overhead_bytes+      code <- c_nn_stats_code_bytes+      indexed <- getMonotonicTime+      marked <- markFrom roots+      finished <- getMonotonicTime+      reached <- readFigures c_nn_stats_reached+      (objects, bytes, unplaced) <- readVisited+      sizes <- readSetSizes+      sites <- siteCounts+      pure $ case (marked, sizes) of+        (False, _) -> Left (CAllocationFailed "nn_stats_mark" "the mark's work stack could not grow")+        (_, Nothing) -> Left (CAllocationFailed "nn_stats_reached_set_sizes" "the set sizes could not be sorted")+        (True, Just setSizes) ->+          Right+            Census+              { censusAllocated = allocated,+                censusReached = reached,+                censusOverheadBytes = overhead,+                censusCodeBytes = code,+                censusVisitedObjects = objects,+                censusVisitedBytes = bytes,+                censusUnplaced = unplaced,+                censusIndexSeconds = indexed - started,+                censusMarkSeconds = finished - indexed,+                censusSetSizes = setSizes,+                censusSites = sites+              }++-- | Mark from the roots.  'False' when the C side ran out of memory.+markFrom :: [CRoot] -> IO Bool+markFrom roots = do+  mapM_ nameRoot roots+  (== 0) <$> c_nn_stats_mark++-- | Figures by kind from a C function that fills a count and a byte+-- array.+readFigures :: (Ptr Word64 -> Ptr Word64 -> IO ()) -> IO (PerKind Figures)+readFigures fill =+  allocaArray kindCount $ \counts -> allocaArray kindCount $ \bytes -> do+    fill counts bytes+    traverse (\i -> Figures . countOf <$> peekElemOff counts i <*> peekElemOff bytes i) kindIndices+  where+    countOf n+      | n == uncounted = Nothing+      | otherwise = Just n++-- | The mark's objects, bytes and unplaced pointers.+readVisited :: IO (Word64, Word64, Word64)+readVisited =+  alloca $ \objects -> alloca $ \bytes -> alloca $ \unplaced -> do+    c_nn_stats_visited objects bytes unplaced+    (,,) <$> peek objects <*> peek bytes <*> peek unplaced++-- | The reached sets by size, or 'Nothing' when C cannot sort them.  The+-- first call asks how many sizes there are, the second fetches them.+readSetSizes :: IO (Maybe (Map Word32 Word64))+readSetSizes = alloca $ \distinctPtr -> do+  first <- c_nn_stats_reached_set_sizes nullPtr nullPtr 0 distinctPtr+  distinct <- peek distinctPtr+  if first /= 0+    then pure Nothing+    else allocaArray (fromIntegral distinct) $ \sizes -> allocaArray (fromIntegral distinct) $ \counts -> do+      status <- c_nn_stats_reached_set_sizes sizes counts distinct distinctPtr+      if status /= 0+        then pure Nothing+        else do+          sizeList <- peekArray (fromIntegral distinct) sizes+          countList <- peekArray (fromIntegral distinct) counts+          pure (Just (Map.fromDistinctAscList (zip sizeList countList)))++-- ---------------------------------------------------------------------------+-- Report+-- ---------------------------------------------------------------------------++-- | A census as lines of a name and a value, each set size a line of its+-- own with the size and the number of reached sets that have it.  A+-- count no allocator keeps has no line.  With counting by site on, the+-- environments' slots and sizes follow, the open size written @N+@, then+-- each site's figures, environments first, and last the entries @//@+-- copied.+renderCensus :: Census -> BS.ByteString+renderCensus census =+  BL.toStrict . BB.toLazyByteString $+    mconcat (toList (kindLines <$> kindNames <*> censusAllocated census <*> censusReached census))+      <> field "overhead.bytes" (BB.word64Dec (censusOverheadBytes census))+      <> field "code.bytes" (BB.word64Dec (censusCodeBytes census))+      <> field "mark.objects" (BB.word64Dec (censusVisitedObjects census))+      <> field "mark.bytes" (BB.word64Dec (censusVisitedBytes census))+      <> field "mark.unplaced" (BB.word64Dec (censusUnplaced census))+      <> field "mark.index-seconds" (seconds (censusIndexSeconds census))+      <> field "mark.seconds" (seconds (censusMarkSeconds census))+      <> foldMap setSize (Map.toAscList (censusSetSizes census))+      <> foldMap siteLines (censusSites census)+  where+    kindLines name allocated reached =+      figureLines (name <> ".allocated") allocated <> figureLines (name <> ".reached") reached+    figureLines prefix (Figures count bytes) =+      foldMap (field (prefix <> ".count") . BB.word64Dec) count+        <> field (prefix <> ".bytes") (BB.word64Dec bytes)+    field name value = BB.byteString name <> BB.char7 ' ' <> value <> BB.char7 '\n'+    seconds s = BB.string7 (showFFloat (Just secondsDigits) s "")+    setSize (size, count) =+      field "attrsets.reached.size" (BB.word32Dec size <> BB.char7 ' ' <> BB.word64Dec count)+    siteLines (SiteCounts envs sizes sets copied) =+      field "envs.allocated.slots" (BB.word64Dec (sum (fmap envSiteSlots envs)))+        <> foldMap envSize (Map.toAscList sizes)+        <> foldMap envSite (Map.toAscList envs)+        <> foldMap setSite (Map.toAscList sets)+        <> field "attrsets.update.copied" (BB.word64Dec copied)+    envSize (size, count) =+      field "envs.allocated.size" (sizeName size <> BB.char7 ' ' <> BB.word64Dec count)+    sizeName (EnvSlots n) = BB.word32Dec n+    sizeName (EnvSlotsAtLeast n) = BB.word32Dec n <> BB.char7 '+'+    envSite (site, EnvSiteFigures envs slots bytes) =+      let prefix = "envs.site." <> envSiteName site+       in field (prefix <> ".count") (BB.word64Dec envs)+            <> field (prefix <> ".slots") (BB.word64Dec slots)+            <> field (prefix <> ".bytes") (BB.word64Dec bytes)+    setSite (site, SetSiteFigures sets shareable bytes) =+      let prefix = "attrsets.site." <> setSiteName site+       in field (prefix <> ".count") (BB.word64Dec sets)+            <> field (prefix <> ".shareable") (BB.word64Dec shareable)+            <> field (prefix <> ".bytes") (BB.word64Dec bytes)++-- | Decimal places of a time in 'renderCensus': microseconds.+secondsDigits :: Int+secondsDigits = 6
src/Nix/Eval/CStatus.hs view
@@ -4,18 +4,23 @@ -- instead of aborting: a NULL pointer, @UINT32_MAX@ from the bytecode -- emitters, @NN_SYMBOL_INVALID@ from the symbol table, @-1@ from the -- list constructors and the attribute set insert.  Each covers two--- causes a caller needs to tell apart: the sub-arena is outside its--- init .. destroy window (nothing ran 'Nix.Eval.Arena.arenaInit', or--- 'Nix.Eval.Arena.arenaDestroy' already ran), or it is live and could--- not grow.  Only the C side knows which, so the failure path asks it--- once, through @nn_arena_live@, and raises a 'CStatusError' that names--- the C entry point.  The question is asked only after a failure, so--- the hot path pays the sentinel comparison and nothing more.+-- causes a caller needs to tell apart: the call ran outside an+-- evaluation session ('Nix.Eval.IO.withEvalSession'), so the sub-arena+-- has no memory, or the arena is live and could not grow.  Only the C+-- side knows which, so the failure path asks it once, through+-- @nn_arena_live@, and raises a 'CStatusError' that names the C entry+-- point.  The boundary asks only after a failure, so on the Haskell side+-- the hot path pays the sentinel comparison and nothing more; the C side+-- asks as well, as each tracked object joins its tracker+-- (@cbits\/nn_tracker.h@). ----- The thunk state transitions report a third kind of refusal: a thunk--- not in the state the transition needs.  The boundary only asks for a--- transition it has just made valid, so that refusal is a defect in this--- library, raised as 'CInvariantViolated' rather than carried on.+-- A third kind of failure is a defect in this library: an answer from+-- the C side that its own invariants rule out.  A thunk refuses a state+-- transition the boundary had just made valid, a cell holds a state,+-- tag, form or builtin index nothing produces, an index the compiler or+-- resolver chose holds nothing, or a string stored from text holds bytes+-- that are not UTF-8.  Each is raised as 'CInvariantViolated' rather+-- than carried on. module Nix.Eval.CStatus   ( -- * Errors     CStatusError (..),@@ -48,30 +53,27 @@ -- | Why a C data-layer call reported failure.  Each constructor carries -- the C entry point that refused. data CStatusError-  = -- | The call ran outside the 'Nix.Eval.Arena.arenaInit' ..-    -- 'Nix.Eval.Arena.arenaDestroy' window.  A setup diagnosis to act-    -- on by adding the bracket and starting the process again, not an-    -- error to catch and retry in place: GHC updates a thunk whose-    -- evaluation raised with that exception, so any shared value whose-    -- evaluation reached C before the window re-raises this inside a-    -- later, live arena.  The @null@, @true@ and @false@ thunks are C-    -- statics rather than arena cells, so they are not among them.+  = -- | The call ran outside an evaluation session+    -- ('Nix.Eval.IO.withEvalSession').  A setup diagnosis to act on by+    -- running the evaluation in a session, not an error to catch and+    -- retry in place: GHC updates a thunk whose evaluation raised with+    -- that exception, so a shared value whose evaluation reached C+    -- outside a session re-raises it inside a later one.     ArenaNotInitialized !String   | -- | The arena is live and the allocation itself failed: exhaustion,     -- or a size the C side rejects.  The second field is the detail.     CAllocationFailed !String !String-  | -- | The C side refused a state transition the boundary had just made-    -- valid, or reported a state no transition produces.  A defect in-    -- this library, never a resource failure; the second field says-    -- which state was wrong.+  | -- | The C side gave an answer this library's invariants rule out+    -- (see the module header).  A defect in this library, never a+    -- resource failure; the second field says what was wrong.     CInvariantViolated !String !String   deriving (Eq, Show)  instance Exception CStatusError where   displayException (ArenaNotInitialized site) =     site-      ++ ": the C data layer is not initialized; evaluation must run between "-      ++ "Nix.Eval.Arena.arenaInit and Nix.Eval.Arena.arenaDestroy"+      ++ ": the C data layer is not initialized; evaluation must run in an "+      ++ "evaluation session (Nix.Eval.IO.withEvalSession)"   displayException (CAllocationFailed site detail) = site ++ ": " ++ detail   displayException (CInvariantViolated site detail) =     site ++ ": internal invariant violated: " ++ detail@@ -82,7 +84,7 @@  -- | Reject a NULL from a C allocator before it can flow onward as a -- pointer: the C side signals failure deliberately, and the next--- dereference would be undefined behaviour in a release build.+-- dereference would be undefined behaviour. checkedCPtr :: String -> Ptr a -> IO (Ptr a) checkedCPtr site ptr   | ptr == nullPtr = cStatusFailure site "C allocation failed"@@ -96,9 +98,10 @@   live <- arenaLive   throwIO (if live then CAllocationFailed site detail else ArenaNotInitialized site) --- | Raise 'CInvariantViolated' for a transition @site@ refused.  Unlike--- 'cStatusFailure' it does not ask whether the arena is live: the caller--- holds a cell the arena handed out, so liveness is not the question.+-- | Raise 'CInvariantViolated' for an answer from @site@ that this+-- library's invariants rule out.  Unlike+-- 'cStatusFailure' it does not ask whether the arena is live: the answer+-- is a defect whatever the arena's state, so liveness is not the question. cInvariantViolated :: String -> String -> IO a cInvariantViolated site detail = throwIO (CInvariantViolated site detail) 
+ src/Nix/Eval/CStr.hs view
@@ -0,0 +1,118 @@+-- | The bytes of string and path values in the C data layer+-- (@cbits\/nn_str.c@).+--+-- A cell holding a string or a path, and a string with context, points at+-- an @nn_str_t@: a length and the bytes after it, made once and never+-- moved or written again while anything reaches it.  The region+-- collector hands its line out again once nothing does+-- ("Nix.Eval.CRegion"), and the arena's teardown frees the rest.  A cell+-- takes a copy of a new value's bytes ('cstrNew'), and shares the object+-- of a value read from another cell or of a literal in the compiled code+-- ("Nix.Eval.CBytecode"), which the value carries+-- ('Nix.Eval.Types.HeldBytes').  A read gives back a copy ('cstrBytes'),+-- so a t'ByteString' in a 'Nix.Eval.Types.NixValue' never points into C+-- memory.  Nothing is interned: the symbol table+-- ("Nix.Eval.Symbol") holds names alone, so a string value never takes a+-- symbol, and never moves the place of a name interned after it.+module Nix.Eval.CStr+  ( -- * Opaque handle+    NnStr,+    CStrPtr,++    -- * Making+    cstrNew,+    cstrFromText,++    -- * Reading+    cstrBytes,+    cstrText,+  )+where++import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Unsafe as BSU+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import qualified Data.Text.Foreign as TF+import Data.Word (Word32)+import Foreign.C.Types (CChar, CSize (..))+import Foreign.Ptr (Ptr, nullPtr)+import Nix.Eval.CData (MonadCData, cdataIO)+import Nix.Eval.CStatus (cInvariantViolated, cStatusFailure)++-- | Phantom type for C-side @nn_str_t@.+data NnStr++-- | Pointer to a string's bytes in C.+type CStrPtr = Ptr NnStr++-- ---------------------------------------------------------------------------+-- FFI imports (all unsafe - no callbacks)+-- ---------------------------------------------------------------------------++foreign import ccall unsafe "nn_str_new"+  c_nn_str_new :: Ptr CChar -> CSize -> IO CStrPtr++foreign import ccall unsafe "nn_str_len"+  c_nn_str_len :: CStrPtr -> IO Word32++foreign import ccall unsafe "nn_str_bytes"+  c_nn_str_bytes :: CStrPtr -> IO (Ptr CChar)++-- ---------------------------------------------------------------------------+-- Making+-- ---------------------------------------------------------------------------++-- | Copy bytes into a new string.  'BSU.unsafeUseAsCStringLen' is safe+-- here: @nn_str_new@ copies the bytes and keeps no pointer to them.+cstrNew :: (MonadCData m) => ByteString -> m CStrPtr+cstrNew bytes =+  cdataIO . BSU.unsafeUseAsCStringLen bytes $ \(ptr, len) ->+    checkedStr =<< c_nn_str_new ptr (fromIntegral len)++-- | Copy text's UTF-8 bytes into a new string: a path, or a store path's+-- hash or name or an output name in a string's context.+cstrFromText :: (MonadCData m) => Text -> m CStrPtr+cstrFromText text =+  cdataIO . TF.withCStringLen text $ \(ptr, len) ->+    checkedStr =<< c_nn_str_new ptr (fromIntegral len)++-- | Reject the NULL @nn_str_new@ answers, outside the arena's window, for+-- a string longer than its uint32 length can say, or when the allocator+-- refuses a block.+checkedStr :: CStrPtr -> IO CStrPtr+checkedStr s+  | s == nullPtr = cStatusFailure "nn_str_new" "the string cannot be held (allocation failure, or longer than 4 GiB)"+  | otherwise = pure s++-- ---------------------------------------------------------------------------+-- Reading+-- ---------------------------------------------------------------------------++-- | A copy of a string's bytes.+cstrBytes :: (MonadCData m) => CStrPtr -> m ByteString+cstrBytes s = cdataIO $ do+  len <- c_nn_str_len s+  if len == 0+    then pure BS.empty+    else do+      bytes <- c_nn_str_bytes s+      BS.packCStringLen (bytes, fromIntegral len)++-- | The text of a string made from text ('cstrFromText').  Its bytes are+-- decoded where they lie and copied once, into the result, before the+-- action returns.  Bytes that are not UTF-8 are a string no text made,+-- which only a defect in this library stores where text is read back.+cstrText :: (MonadCData m) => CStrPtr -> m Text+cstrText s = cdataIO $ do+  len <- c_nn_str_len s+  if len == 0+    then pure T.empty+    else do+      bytes <- c_nn_str_bytes s+      view <- BSU.unsafePackCStringLen (bytes, fromIntegral len)+      case TE.decodeUtf8' view of+        Right text -> pure text+        Left _ -> cInvariantViolated "nn_str_bytes" "a string stored from text holds bytes that are not UTF-8"
src/Nix/Eval/CThunk.hs view
@@ -1,36 +1,33 @@ -- | C-backed thunk memoization cells via FFI. -- -- Wraps @cbits/nn_thunk.c@ - an arena-allocated mutable cell that--- holds either a pending expression (StablePtr to (Expr, Env)) or a--- computed value (StablePtr to NixValue).  Replaces Haskell's--- @IORef ThunkCell@ (~56 bytes on GHC heap, all GC-traced) with a--- 16-byte C struct in an arena (invisible to GHC GC).+-- holds either pending work (a bytecode index and the C env it runs in,+-- or a deferred application's cells) or a computed value (an inline+-- scalar or builtin index, or a pointer to a C object).  Each cell is a 16-byte C struct in an arena, invisible to+-- GHC's GC. -- -- Includes blackhole detection: a thunk being forced is marked -- BLACKHOLE; if forced again before completion, infinite recursion -- is detected (matching C++ Nix behavior). --+-- In an evaluation session ('Nix.Eval.IO.withEvalSession'):+-- -- @--- cthunkInit 0--- ptr <- cthunkNew pendingStablePtr+-- ptr <- cthunkNewBc bcIdx envPtr -- cthunkState ptr  -- 0 (PENDING) -- cthunkMarkBlackhole ptr  -- True (was PENDING)--- cthunkSetComputed ptr valueStablePtr  -- True (was not yet COMPUTED)+-- cthunkSetComputedInt ptr 42  -- True (was not yet COMPUTED) -- cthunkState ptr  -- 1 (COMPUTED)--- cthunkDestroy -- @ module Nix.Eval.CThunk   ( -- * Opaque handle     NnThunk,     CThunkPtr, -    -- * Lifecycle-    cthunkInit,-    cthunkDestroy,-     -- * Allocation     cthunkNewBc,-    cthunkNewComputed,+    cthunkNewApply1,+    cthunkNewApply2,     cthunkNewComputedInt,     cthunkNewComputedFloat,     cthunkNewComputedStr,@@ -39,31 +36,31 @@     cthunkNewComputedAttrs,     cthunkNewComputedCtxStr,     cthunkNewComputedLambda,+    cthunkNewComputedPrimop,+    cthunkNewComputedPrimopApp,      -- * Shared constants     cthunkNull,     cthunkBool,+    cthunkEmptyList,+    cthunkPrimop,      -- * State queries     cthunkState,     cthunkPayload,     cthunkValueTag,     cthunkGetBcIdx,-    cthunkSetPayload,+    noCode,+    cthunkPendingForm,+    cthunkApplyCell,     cthunkGetInt,     cthunkGetFloat,     cthunkGetBool,-    cthunkGetStr,-    cthunkGetPath,-    cthunkGetList,-    cthunkGetAttrs,-    cthunkGetCtxStr,-    cthunkGetLambda,+    cthunkGetPrimop,      -- * State transitions     cthunkMarkBlackhole,     cthunkMarkPending,-    cthunkSetComputed,     cthunkSetComputedInt,     cthunkSetComputedFloat,     cthunkSetComputedBool,@@ -74,10 +71,8 @@     cthunkSetComputedAttrs,     cthunkSetComputedCtxStr,     cthunkSetComputedLambda,--    -- * Arena diagnostics / cleanup-    cthunkCount,-    cthunkGet,+    cthunkSetComputedPrimop,+    cthunkSetComputedPrimopApp,   ) where @@ -85,7 +80,9 @@ import Data.Word (Word32, Word8) import Foreign.C.Types (CDouble (..), CInt (..)) import Foreign.Ptr (Ptr, nullPtr)-import Nix.Eval.CStatus (checkedCPtr)+import Nix.Eval.CData (MonadCData, cdataIO)+import Nix.Eval.CStatus (cInvariantViolated, checkedCPtr)+import Nix.Eval.CStr (CStrPtr)  -- | Phantom type for C-side @nn_thunk_t@. data NnThunk@@ -97,23 +94,23 @@ -- FFI imports (all unsafe - no callbacks, fast data access) -- --------------------------------------------------------------------------- -foreign import ccall unsafe "nn_thunk_init"-  c_nn_thunk_init :: Word32 -> IO ()--foreign import ccall unsafe "nn_thunk_destroy"-  c_nn_thunk_destroy :: IO ()- foreign import ccall unsafe "nn_thunk_new_bc"   c_nn_thunk_new_bc :: Word32 -> Ptr () -> IO CThunkPtr +foreign import ccall unsafe "nn_thunk_new_apply1"+  c_nn_thunk_new_apply1 :: CThunkPtr -> CThunkPtr -> IO CThunkPtr++foreign import ccall unsafe "nn_thunk_new_apply2"+  c_nn_thunk_new_apply2 :: CThunkPtr -> CThunkPtr -> CThunkPtr -> IO CThunkPtr+ foreign import ccall unsafe "nn_thunk_get_bc_idx"   c_nn_thunk_get_bc_idx :: CThunkPtr -> IO Word32 -foreign import ccall unsafe "nn_thunk_set_payload"-  c_nn_thunk_set_payload :: CThunkPtr -> Ptr () -> IO CInt+foreign import ccall unsafe "nn_thunk_pending_form"+  c_nn_thunk_pending_form :: CThunkPtr -> IO Word8 -foreign import ccall unsafe "nn_thunk_new_computed"-  c_nn_thunk_new_computed :: Ptr () -> IO CThunkPtr+foreign import ccall unsafe "nn_thunk_apply_cell"+  c_nn_thunk_apply_cell :: CThunkPtr -> Word32 -> IO CThunkPtr  foreign import ccall unsafe "nn_thunk_new_computed_int"   c_nn_thunk_new_computed_int :: Int64 -> IO CThunkPtr@@ -122,10 +119,10 @@   c_nn_thunk_new_computed_float :: CDouble -> IO CThunkPtr  foreign import ccall unsafe "nn_thunk_new_computed_str"-  c_nn_thunk_new_computed_str :: Word32 -> IO CThunkPtr+  c_nn_thunk_new_computed_str :: CStrPtr -> IO CThunkPtr  foreign import ccall unsafe "nn_thunk_new_computed_path"-  c_nn_thunk_new_computed_path :: Word32 -> IO CThunkPtr+  c_nn_thunk_new_computed_path :: CStrPtr -> IO CThunkPtr  foreign import ccall unsafe "nn_thunk_new_computed_list"   c_nn_thunk_new_computed_list :: Ptr () -> IO CThunkPtr@@ -139,6 +136,12 @@ foreign import ccall unsafe "nn_thunk_new_computed_lambda"   c_nn_thunk_new_computed_lambda :: Ptr () -> IO CThunkPtr +foreign import ccall unsafe "nn_thunk_new_computed_primop"+  c_nn_thunk_new_computed_primop :: Word32 -> IO CThunkPtr++foreign import ccall unsafe "nn_thunk_new_computed_primop_app"+  c_nn_thunk_new_computed_primop_app :: Ptr () -> IO CThunkPtr+ -- The shared cells are C statics, one address for the life of the -- process, so these imports are pure: no arena window, nor its absence, -- changes what they return.@@ -147,9 +150,17 @@ foreign import ccall unsafe "nn_thunk_null"   cthunkNull :: CThunkPtr +-- | The shared COMPUTED empty list thunk.+foreign import ccall unsafe "nn_thunk_empty_list"+  cthunkEmptyList :: CThunkPtr+ foreign import ccall unsafe "nn_thunk_bool"   c_nn_thunk_bool :: Word8 -> CThunkPtr +-- Fills the static cell the first time it is asked for, so an action.+foreign import ccall unsafe "nn_thunk_primop"+  c_nn_thunk_primop :: Word32 -> IO CThunkPtr+ foreign import ccall unsafe "nn_thunk_state"   c_nn_thunk_state :: CThunkPtr -> IO Word8 @@ -168,23 +179,8 @@ foreign import ccall unsafe "nn_thunk_get_bool"   c_nn_thunk_get_bool :: CThunkPtr -> IO Word8 -foreign import ccall unsafe "nn_thunk_get_str"-  c_nn_thunk_get_str :: CThunkPtr -> IO Word32--foreign import ccall unsafe "nn_thunk_get_path"-  c_nn_thunk_get_path :: CThunkPtr -> IO Word32--foreign import ccall unsafe "nn_thunk_get_list"-  c_nn_thunk_get_list :: CThunkPtr -> IO (Ptr ())--foreign import ccall unsafe "nn_thunk_get_attrs"-  c_nn_thunk_get_attrs :: CThunkPtr -> IO (Ptr ())--foreign import ccall unsafe "nn_thunk_get_ctxstr"-  c_nn_thunk_get_ctxstr :: CThunkPtr -> IO (Ptr ())--foreign import ccall unsafe "nn_thunk_get_lambda"-  c_nn_thunk_get_lambda :: CThunkPtr -> IO (Ptr ())+foreign import ccall unsafe "nn_thunk_get_primop"+  c_nn_thunk_get_primop :: CThunkPtr -> IO Word32  foreign import ccall unsafe "nn_thunk_mark_blackhole"   c_nn_thunk_mark_blackhole :: CThunkPtr -> IO CInt@@ -192,9 +188,6 @@ foreign import ccall unsafe "nn_thunk_mark_pending"   c_nn_thunk_mark_pending :: CThunkPtr -> IO CInt -foreign import ccall unsafe "nn_thunk_set_computed"-  c_nn_thunk_set_computed :: CThunkPtr -> Ptr () -> IO CInt- foreign import ccall unsafe "nn_thunk_set_computed_int"   c_nn_thunk_set_computed_int :: CThunkPtr -> Int64 -> IO CInt @@ -208,10 +201,10 @@   c_nn_thunk_set_computed_null :: CThunkPtr -> IO CInt  foreign import ccall unsafe "nn_thunk_set_computed_str"-  c_nn_thunk_set_computed_str :: CThunkPtr -> Word32 -> IO CInt+  c_nn_thunk_set_computed_str :: CThunkPtr -> CStrPtr -> IO CInt  foreign import ccall unsafe "nn_thunk_set_computed_path"-  c_nn_thunk_set_computed_path :: CThunkPtr -> Word32 -> IO CInt+  c_nn_thunk_set_computed_path :: CThunkPtr -> CStrPtr -> IO CInt  foreign import ccall unsafe "nn_thunk_set_computed_list"   c_nn_thunk_set_computed_list :: CThunkPtr -> Ptr () -> IO CInt@@ -225,90 +218,109 @@ foreign import ccall unsafe "nn_thunk_set_computed_lambda"   c_nn_thunk_set_computed_lambda :: CThunkPtr -> Ptr () -> IO CInt -foreign import ccall unsafe "nn_thunk_count"-  c_nn_thunk_count :: IO Word32--foreign import ccall unsafe "nn_thunk_get"-  c_nn_thunk_get :: Word32 -> IO CThunkPtr---- ------------------------------------------------------------------------------ Lifecycle--- ------------------------------------------------------------------------------- | Initialize the global thunk arena.  Call once before evaluation.--- @capacity@ is a hint for thunks per block (0 uses default: 65536).-cthunkInit :: Word32 -> IO ()-cthunkInit = c_nn_thunk_init+foreign import ccall unsafe "nn_thunk_set_computed_primop"+  c_nn_thunk_set_computed_primop :: CThunkPtr -> Word32 -> IO CInt --- | Destroy the global thunk arena, freeing all C-side memory.--- Caller must free all payload StablePtrs first.--- All 'CThunkPtr' values become invalid after this call.-cthunkDestroy :: IO ()-cthunkDestroy = c_nn_thunk_destroy+foreign import ccall unsafe "nn_thunk_set_computed_primop_app"+  c_nn_thunk_set_computed_primop_app :: CThunkPtr -> Ptr () -> IO CInt  -- --------------------------------------------------------------------------- -- Allocation -- ---------------------------------------------------------------------------  -- Every allocator below rejects the C side's NULL through 'checkedCPtr':--- outside the 'cthunkInit' .. 'cthunkDestroy' window that is the only+-- outside the arena's init .. destroy window that is the only -- answer the arena gives, and a NULL that flowed on would fault at the -- next state read instead of raising 'Nix.Eval.CStatus.ArenaNotInitialized'.  -- | Allocate a new PENDING thunk with a bytecode index + C env pointer.+-- The index is never 'noCode', which the C side asserts. -- No Haskell heap references - zero GC pressure for pending thunks.-cthunkNewBc :: Word32 -> Ptr () -> IO CThunkPtr-cthunkNewBc bcIdx envPtr = checkedCPtr "nn_thunk_new_bc" =<< c_nn_thunk_new_bc bcIdx envPtr+-- The pointer is an @nn_env_t *@, untyped here because "Nix.Eval.CEnv"+-- imports this module for the slots it stores.+cthunkNewBc :: (MonadCData m) => Word32 -> Ptr () -> m CThunkPtr+cthunkNewBc bcIdx envPtr = cdataIO (checkedCPtr "nn_thunk_new_bc" =<< c_nn_thunk_new_bc bcIdx envPtr) --- | Read the bytecode index from a PENDING thunk.-cthunkGetBcIdx :: CThunkPtr -> IO Word32-cthunkGetBcIdx = c_nn_thunk_get_bc_idx+-- | Allocate a new PENDING thunk deferring the application of the+-- function in one cell to the argument in another, as upstream's app+-- value holds a function and its argument.  Its cells live in the env+-- pages, beside no env.  Neither cell is 'Foreign.Ptr.nullPtr', which+-- the C side asserts.+cthunkNewApply1 :: (MonadCData m) => CThunkPtr -> CThunkPtr -> m CThunkPtr+cthunkNewApply1 fn arg = cdataIO (checkedCPtr "nn_thunk_new_apply1" =<< c_nn_thunk_new_apply1 fn arg) --- | Set the payload of a PENDING thunk (deferred env fixup for--- knot-tying).  'False' when the thunk is not PENDING and was left as it--- was, which keeps the shared constant cells unwritten.-cthunkSetPayload :: CThunkPtr -> Ptr () -> IO Bool-cthunkSetPayload ptr payload = accepted <$> c_nn_thunk_set_payload ptr payload+-- | 'cthunkNewApply1' applying the function to a first argument, and the+-- result to a second, as upstream's @mapAttrs@ nests two app values.+cthunkNewApply2 :: (MonadCData m) => CThunkPtr -> CThunkPtr -> CThunkPtr -> m CThunkPtr+cthunkNewApply2 fn first second = cdataIO (checkedCPtr "nn_thunk_new_apply2" =<< c_nn_thunk_new_apply2 fn first second) --- | Allocate a new pre-COMPUTED thunk with StablePtr payload (complex types).-cthunkNewComputed :: Ptr () -> IO CThunkPtr-cthunkNewComputed value = checkedCPtr "nn_thunk_new_computed" =<< c_nn_thunk_new_computed value+-- | Read the bytecode index of a PENDING or BLACKHOLE code thunk, or+-- 'noCode' for an application.+cthunkGetBcIdx :: (MonadCData m) => CThunkPtr -> m Word32+cthunkGetBcIdx = cdataIO . c_nn_thunk_get_bc_idx --- | Allocate a pre-COMPUTED thunk with an inline int64 (no StablePtr).-cthunkNewComputedInt :: Int64 -> IO CThunkPtr-cthunkNewComputedInt n = checkedCPtr "nn_thunk_new_computed_int" =<< c_nn_thunk_new_computed_int n+-- | @NN_THUNK_NO_CODE@ of @cbits/nn_thunk.h@: the index of no+-- instruction, which 'cthunkGetBcIdx' answers for a thunk that runs+-- none.+noCode :: Word32+noCode = maxBound --- | Allocate a pre-COMPUTED thunk with an inline double (no StablePtr).-cthunkNewComputedFloat :: Double -> IO CThunkPtr-cthunkNewComputedFloat d = checkedCPtr "nn_thunk_new_computed_float" =<< c_nn_thunk_new_computed_float (CDouble d)+-- | Read the form of a PENDING or BLACKHOLE thunk: @NN_PENDING_CODE@,+-- @NN_PENDING_APPLY1@ or @NN_PENDING_APPLY2@ of @cbits/nn_thunk.h@.+cthunkPendingForm :: (MonadCData m) => CThunkPtr -> m Word8+cthunkPendingForm = cdataIO . c_nn_thunk_pending_form --- | Allocate a pre-COMPUTED thunk with an interned string symbol (no StablePtr).--- For context-free strings only (tag 4).-cthunkNewComputedStr :: Word32 -> IO CThunkPtr-cthunkNewComputedStr sym = checkedCPtr "nn_thunk_new_computed_str" =<< c_nn_thunk_new_computed_str sym+-- | Cell @i@ of a PENDING or BLACKHOLE application, the function's at+-- 0.  The caller reads the form first ('cthunkPendingForm'); a thunk of+-- another state or form, or an index past its cells, aborts in C.+cthunkApplyCell :: (MonadCData m) => CThunkPtr -> Word32 -> m CThunkPtr+cthunkApplyCell ptr i = cdataIO (c_nn_thunk_apply_cell ptr i) --- | Allocate a pre-COMPUTED thunk with an interned path symbol (no StablePtr).-cthunkNewComputedPath :: Word32 -> IO CThunkPtr-cthunkNewComputedPath sym = checkedCPtr "nn_thunk_new_computed_path" =<< c_nn_thunk_new_computed_path sym+-- | Allocate a pre-COMPUTED thunk with an inline int64.+cthunkNewComputedInt :: (MonadCData m) => Int64 -> m CThunkPtr+cthunkNewComputedInt n = cdataIO (checkedCPtr "nn_thunk_new_computed_int" =<< c_nn_thunk_new_computed_int n) --- | Allocate a pre-COMPUTED thunk with a CList pointer (no StablePtr).-cthunkNewComputedList :: Ptr () -> IO CThunkPtr-cthunkNewComputedList list = checkedCPtr "nn_thunk_new_computed_list" =<< c_nn_thunk_new_computed_list list+-- | Allocate a pre-COMPUTED thunk with an inline double.+cthunkNewComputedFloat :: (MonadCData m) => Double -> m CThunkPtr+cthunkNewComputedFloat d = cdataIO (checkedCPtr "nn_thunk_new_computed_float" =<< c_nn_thunk_new_computed_float (CDouble d)) --- | Allocate a pre-COMPUTED thunk with a CAttrSet pointer (no StablePtr).-cthunkNewComputedAttrs :: Ptr () -> IO CThunkPtr-cthunkNewComputedAttrs attrs = checkedCPtr "nn_thunk_new_computed_attrs" =<< c_nn_thunk_new_computed_attrs attrs+-- | Allocate a pre-COMPUTED thunk pointing at a string's bytes.  For+-- context-free strings only (tag 4).+cthunkNewComputedStr :: (MonadCData m) => CStrPtr -> m CThunkPtr+cthunkNewComputedStr str = cdataIO (checkedCPtr "nn_thunk_new_computed_str" =<< c_nn_thunk_new_computed_str str) --- | Allocate a pre-COMPUTED thunk with a CCtxStr pointer (no StablePtr).--- For strings with non-empty context (tag 8).-cthunkNewComputedCtxStr :: Ptr () -> IO CThunkPtr-cthunkNewComputedCtxStr ctxstr = checkedCPtr "nn_thunk_new_computed_ctxstr" =<< c_nn_thunk_new_computed_ctxstr ctxstr+-- | Allocate a pre-COMPUTED thunk pointing at a path's bytes.+cthunkNewComputedPath :: (MonadCData m) => CStrPtr -> m CThunkPtr+cthunkNewComputedPath str = cdataIO (checkedCPtr "nn_thunk_new_computed_path" =<< c_nn_thunk_new_computed_path str) --- | Allocate a pre-COMPUTED thunk with a CLambda pointer (no StablePtr).--- For lambda closures (tag 9).-cthunkNewComputedLambda :: Ptr () -> IO CThunkPtr-cthunkNewComputedLambda lambda = checkedCPtr "nn_thunk_new_computed_lambda" =<< c_nn_thunk_new_computed_lambda lambda+-- | Allocate a pre-COMPUTED thunk with a CList pointer.+cthunkNewComputedList :: (MonadCData m) => Ptr () -> m CThunkPtr+cthunkNewComputedList list = cdataIO (checkedCPtr "nn_thunk_new_computed_list" =<< c_nn_thunk_new_computed_list list) +-- | Allocate a pre-COMPUTED thunk with a CAttrSet pointer.+cthunkNewComputedAttrs :: (MonadCData m) => Ptr () -> m CThunkPtr+cthunkNewComputedAttrs attrs = cdataIO (checkedCPtr "nn_thunk_new_computed_attrs" =<< c_nn_thunk_new_computed_attrs attrs)++-- | Allocate a pre-COMPUTED thunk with a CCtxStr pointer.  For strings+-- with non-empty context (tag 8).+cthunkNewComputedCtxStr :: (MonadCData m) => Ptr () -> m CThunkPtr+cthunkNewComputedCtxStr ctxstr = cdataIO (checkedCPtr "nn_thunk_new_computed_ctxstr" =<< c_nn_thunk_new_computed_ctxstr ctxstr)++-- | Allocate a pre-COMPUTED thunk with a CLambda pointer.  For lambda+-- closures (tag 9).+cthunkNewComputedLambda :: (MonadCData m) => Ptr () -> m CThunkPtr+cthunkNewComputedLambda lambda = cdataIO (checkedCPtr "nn_thunk_new_computed_lambda" =<< c_nn_thunk_new_computed_lambda lambda)++-- | Allocate a pre-COMPUTED thunk holding a builtin's index inline, for a+-- builtin with no argument taken (tag 10).+cthunkNewComputedPrimop :: (MonadCData m) => Word32 -> m CThunkPtr+cthunkNewComputedPrimop primop = cdataIO (checkedCPtr "nn_thunk_new_computed_primop" =<< c_nn_thunk_new_computed_primop primop)++-- | Allocate a pre-COMPUTED thunk with a CPrimopApp pointer, for a+-- builtin's partial application (tag 11).+cthunkNewComputedPrimopApp :: (MonadCData m) => Ptr () -> m CThunkPtr+cthunkNewComputedPrimopApp app = cdataIO (checkedCPtr "nn_thunk_new_computed_primop_app" =<< c_nn_thunk_new_computed_primop_app app)+ -- --------------------------------------------------------------------------- -- Shared constants -- ---------------------------------------------------------------------------@@ -321,62 +333,54 @@ trueCell = c_nn_thunk_bool 1 falseCell = c_nn_thunk_bool 0 +-- | The shared COMPUTED cell of the builtin at an index: a C static, one+-- per builtin, the same in every arena window and outside all of them.+-- An index from @NN_PRIMOP_CELLS@ on has no cell, which only a builtin+-- table grown past that bound would ask for.+cthunkPrimop :: (MonadCData m) => Word32 -> m CThunkPtr+cthunkPrimop primop = cdataIO $ do+  cell <- c_nn_thunk_primop primop+  if cell == nullPtr+    then cInvariantViolated "nn_thunk_primop" ("builtin index " ++ show primop ++ " is past the static cells (NN_PRIMOP_CELLS)")+    else pure cell+ -- --------------------------------------------------------------------------- -- State queries -- ---------------------------------------------------------------------------  -- | Read the current state: 0 = PENDING, 1 = COMPUTED, 2 = BLACKHOLE.-cthunkState :: CThunkPtr -> IO Word8-cthunkState = c_nn_thunk_state+cthunkState :: (MonadCData m) => CThunkPtr -> m Word8+cthunkState = cdataIO . c_nn_thunk_state --- | Read the payload pointer.  Returns 'nullPtr' for NULL payloads.-cthunkPayload :: CThunkPtr -> IO (Ptr ())-cthunkPayload ptr = do-  p <- c_nn_thunk_payload ptr-  pure (if p == nullPtr then nullPtr else p)+-- | Read the payload pointer.  For a COMPUTED thunk of a C object (value+-- tags 4 to 9 and 11) it is that object, cast at the use to the type its+-- tag names (a t'CStrPtr' for a string or a path); for a PENDING or+-- BLACKHOLE one, its env or its application's cells.+cthunkPayload :: (MonadCData m) => CThunkPtr -> m (Ptr ())+cthunkPayload = cdataIO . c_nn_thunk_payload --- | Read the value tag (valid when state == COMPUTED).--- 0=INT, 1=FLOAT, 2=BOOL, 3=NULL, 255=PTR (StablePtr).-cthunkValueTag :: CThunkPtr -> IO Word8-cthunkValueTag = c_nn_thunk_value_tag+-- | Read the value tag (valid when state == COMPUTED): the+-- @NN_VALUE_*@ constants of @cbits\/nn_thunk.h@.+cthunkValueTag :: (MonadCData m) => CThunkPtr -> m Word8+cthunkValueTag = cdataIO . c_nn_thunk_value_tag  -- | Read an inline int64 from a COMPUTED thunk (val_tag == 0).-cthunkGetInt :: CThunkPtr -> IO Int64-cthunkGetInt = c_nn_thunk_get_int+cthunkGetInt :: (MonadCData m) => CThunkPtr -> m Int64+cthunkGetInt = cdataIO . c_nn_thunk_get_int  -- | Read an inline double from a COMPUTED thunk (val_tag == 1).-cthunkGetFloat :: CThunkPtr -> IO Double-cthunkGetFloat ptr = do+cthunkGetFloat :: (MonadCData m) => CThunkPtr -> m Double+cthunkGetFloat ptr = cdataIO $ do   CDouble d <- c_nn_thunk_get_float ptr   pure d  -- | Read an inline bool from a COMPUTED thunk (val_tag == 2).-cthunkGetBool :: CThunkPtr -> IO Word8-cthunkGetBool = c_nn_thunk_get_bool---- | Read an interned string symbol from a COMPUTED thunk (val_tag == 4).-cthunkGetStr :: CThunkPtr -> IO Word32-cthunkGetStr = c_nn_thunk_get_str---- | Read an interned path symbol from a COMPUTED thunk (val_tag == 5).-cthunkGetPath :: CThunkPtr -> IO Word32-cthunkGetPath = c_nn_thunk_get_path---- | Read a CList pointer from a COMPUTED thunk (val_tag == 6).-cthunkGetList :: CThunkPtr -> IO (Ptr ())-cthunkGetList = c_nn_thunk_get_list---- | Read a CAttrSet pointer from a COMPUTED thunk (val_tag == 7).-cthunkGetAttrs :: CThunkPtr -> IO (Ptr ())-cthunkGetAttrs = c_nn_thunk_get_attrs---- | Read a CCtxStr pointer from a COMPUTED thunk (val_tag == 8).-cthunkGetCtxStr :: CThunkPtr -> IO (Ptr ())-cthunkGetCtxStr = c_nn_thunk_get_ctxstr+cthunkGetBool :: (MonadCData m) => CThunkPtr -> m Word8+cthunkGetBool = cdataIO . c_nn_thunk_get_bool --- | Read a CLambda pointer from a COMPUTED thunk (val_tag == 9).-cthunkGetLambda :: CThunkPtr -> IO (Ptr ())-cthunkGetLambda = c_nn_thunk_get_lambda+-- | Read a builtin's index from a COMPUTED thunk (val_tag == 10).+cthunkGetPrimop :: (MonadCData m) => CThunkPtr -> m Word32+cthunkGetPrimop = cdataIO . c_nn_thunk_get_primop  -- --------------------------------------------------------------------------- -- State transitions@@ -384,78 +388,69 @@  -- | Mark a PENDING thunk as BLACKHOLE (being evaluated). -- Returns 'True' on success, 'False' if not PENDING.-cthunkMarkBlackhole :: CThunkPtr -> IO Bool-cthunkMarkBlackhole ptr = accepted <$> c_nn_thunk_mark_blackhole ptr+cthunkMarkBlackhole :: (MonadCData m) => CThunkPtr -> m Bool+cthunkMarkBlackhole ptr = cdataIO (accepted <$> c_nn_thunk_mark_blackhole ptr)  -- | Restore a BLACKHOLE thunk to PENDING after a caught throw during its force, -- so a later force re-evaluates instead of misreporting infinite recursion. -- Returns 'True' on success, 'False' if the thunk was not BLACKHOLE.-cthunkMarkPending :: CThunkPtr -> IO Bool-cthunkMarkPending ptr = accepted <$> c_nn_thunk_mark_pending ptr+cthunkMarkPending :: (MonadCData m) => CThunkPtr -> m Bool+cthunkMarkPending ptr = cdataIO (accepted <$> c_nn_thunk_mark_pending ptr)  -- The setters below store a value in a thunk that is not yet COMPUTED and -- answer 'True', or leave a COMPUTED thunk as it was and answer 'False'.--- They do not hand back the pending payload: the forcing caller read it--- to evaluate the thunk, and frees that StablePtr itself.---- | Store a StablePtr value (complex types).-cthunkSetComputed :: CThunkPtr -> Ptr () -> IO Bool-cthunkSetComputed ptr value = accepted <$> c_nn_thunk_set_computed ptr value+-- The pending payload they overwrite is an env or an application's+-- cells, which the env pages own, so nothing is handed back. --- | Store an inline int64 (no StablePtr).-cthunkSetComputedInt :: CThunkPtr -> Int64 -> IO Bool-cthunkSetComputedInt ptr n = accepted <$> c_nn_thunk_set_computed_int ptr n+-- | Store an inline int64.+cthunkSetComputedInt :: (MonadCData m) => CThunkPtr -> Int64 -> m Bool+cthunkSetComputedInt ptr n = cdataIO (accepted <$> c_nn_thunk_set_computed_int ptr n) --- | Store an inline double (no StablePtr).-cthunkSetComputedFloat :: CThunkPtr -> Double -> IO Bool-cthunkSetComputedFloat ptr d = accepted <$> c_nn_thunk_set_computed_float ptr (CDouble d)+-- | Store an inline double.+cthunkSetComputedFloat :: (MonadCData m) => CThunkPtr -> Double -> m Bool+cthunkSetComputedFloat ptr d = cdataIO (accepted <$> c_nn_thunk_set_computed_float ptr (CDouble d)) --- | Store an inline bool (no StablePtr).-cthunkSetComputedBool :: CThunkPtr -> Word8 -> IO Bool-cthunkSetComputedBool ptr b = accepted <$> c_nn_thunk_set_computed_bool ptr b+-- | Store an inline bool.+cthunkSetComputedBool :: (MonadCData m) => CThunkPtr -> Word8 -> m Bool+cthunkSetComputedBool ptr b = cdataIO (accepted <$> c_nn_thunk_set_computed_bool ptr b) --- | Store null (no StablePtr).-cthunkSetComputedNull :: CThunkPtr -> IO Bool-cthunkSetComputedNull ptr = accepted <$> c_nn_thunk_set_computed_null ptr+-- | Store null.+cthunkSetComputedNull :: (MonadCData m) => CThunkPtr -> m Bool+cthunkSetComputedNull ptr = cdataIO (accepted <$> c_nn_thunk_set_computed_null ptr) --- | Store an interned string symbol.-cthunkSetComputedStr :: CThunkPtr -> Word32 -> IO Bool-cthunkSetComputedStr ptr sym = accepted <$> c_nn_thunk_set_computed_str ptr sym+-- | Store a pointer to a string's bytes.+cthunkSetComputedStr :: (MonadCData m) => CThunkPtr -> CStrPtr -> m Bool+cthunkSetComputedStr ptr str = cdataIO (accepted <$> c_nn_thunk_set_computed_str ptr str) --- | Store an interned path symbol.-cthunkSetComputedPath :: CThunkPtr -> Word32 -> IO Bool-cthunkSetComputedPath ptr sym = accepted <$> c_nn_thunk_set_computed_path ptr sym+-- | Store a pointer to a path's bytes.+cthunkSetComputedPath :: (MonadCData m) => CThunkPtr -> CStrPtr -> m Bool+cthunkSetComputedPath ptr str = cdataIO (accepted <$> c_nn_thunk_set_computed_path ptr str)  -- | Store a CList pointer.-cthunkSetComputedList :: CThunkPtr -> Ptr () -> IO Bool-cthunkSetComputedList ptr list = accepted <$> c_nn_thunk_set_computed_list ptr list+cthunkSetComputedList :: (MonadCData m) => CThunkPtr -> Ptr () -> m Bool+cthunkSetComputedList ptr list = cdataIO (accepted <$> c_nn_thunk_set_computed_list ptr list)  -- | Store a CAttrSet pointer.-cthunkSetComputedAttrs :: CThunkPtr -> Ptr () -> IO Bool-cthunkSetComputedAttrs ptr attrs = accepted <$> c_nn_thunk_set_computed_attrs ptr attrs+cthunkSetComputedAttrs :: (MonadCData m) => CThunkPtr -> Ptr () -> m Bool+cthunkSetComputedAttrs ptr attrs = cdataIO (accepted <$> c_nn_thunk_set_computed_attrs ptr attrs)  -- | Store a CCtxStr pointer.-cthunkSetComputedCtxStr :: CThunkPtr -> Ptr () -> IO Bool-cthunkSetComputedCtxStr ptr ctxstr = accepted <$> c_nn_thunk_set_computed_ctxstr ptr ctxstr+cthunkSetComputedCtxStr :: (MonadCData m) => CThunkPtr -> Ptr () -> m Bool+cthunkSetComputedCtxStr ptr ctxstr = cdataIO (accepted <$> c_nn_thunk_set_computed_ctxstr ptr ctxstr)  -- | Store a CLambda pointer.-cthunkSetComputedLambda :: CThunkPtr -> Ptr () -> IO Bool-cthunkSetComputedLambda ptr lambda = accepted <$> c_nn_thunk_set_computed_lambda ptr lambda+cthunkSetComputedLambda :: (MonadCData m) => CThunkPtr -> Ptr () -> m Bool+cthunkSetComputedLambda ptr lambda = cdataIO (accepted <$> c_nn_thunk_set_computed_lambda ptr lambda) +-- | Store a builtin's index inline.+cthunkSetComputedPrimop :: (MonadCData m) => CThunkPtr -> Word32 -> m Bool+cthunkSetComputedPrimop ptr primop = cdataIO (accepted <$> c_nn_thunk_set_computed_primop ptr primop)++-- | Store a CPrimopApp pointer.+cthunkSetComputedPrimopApp :: (MonadCData m) => CThunkPtr -> Ptr () -> m Bool+cthunkSetComputedPrimopApp ptr app = cdataIO (accepted <$> c_nn_thunk_set_computed_primop_app ptr app)+ -- | A transition's C answer: 1 when it ran, 0 when the thunk's state -- refused it. accepted :: CInt -> Bool accepted = (/= 0)---- ------------------------------------------------------------------------------ Arena diagnostics / cleanup--- ------------------------------------------------------------------------------- | Total thunks allocated in the arena.-cthunkCount :: IO Word32-cthunkCount = c_nn_thunk_count---- | Get a thunk by global index (for cleanup iteration).--- Returns 'nullPtr' if index is out of range.-cthunkGet :: Word32 -> IO CThunkPtr-cthunkGet = c_nn_thunk_get
src/Nix/Eval/CallDepth.hs view
@@ -31,7 +31,6 @@     defaultMaxCallDepth,     topLevelCallDepth,     enterCallFrame,-    maxCallDepthExceeded,   ) where 
src/Nix/Eval/CanonPath.hs view
@@ -46,7 +46,7 @@ -- and passes through untouched - upstream's semantics - while on -- Windows it is a separator and folds to @/@.  Every site that -- produces a 'Nix.Eval.Types.VPath' from platform-tainted text (literal resolution,--- base-dir joins, fetcher scratch dirs, search-path entries) goes+-- base-dir joins, search-path entries) goes -- through this gate; store-path text is canonical by construction. canonPathValue :: Text -> Text canonPathValue t = canonPath (if T.any needsFold t then T.map foldSeparator t else t)
src/Nix/Eval/Compile.hs view
@@ -9,16 +9,49 @@ -- instructions; a binding refers to its position there by the index -- "Nix.Eval.SourcePos" records it at. ----- Must be called after 'Nix.Eval.CBytecode.cbcInit' and 'Nix.Eval.Symbol.symbolInit'.+-- The operator, formals and capture decoders and the binding fold answer+-- a tag this module never writes, which only a corrupt store holds, with+-- a failure for the evaluator to report.  The store hands each tag back+-- as a whole byte or word, so no type on the decoding side can rule such+-- a tag out.+--+-- A set's or a let's bindings and a closure's captured slots are read by+-- folds over the data buffer each time their code runs, so no list of+-- them is built.  A binding list's words start with the names it binds+-- counted, so the evaluator knows a frame's layout and a set's size+-- before it reads a binding, and then the frame's shares, which the+-- compiler decides once ('siblingShares') for the evaluator to copy each+-- time it fills the frame.+--+-- Compiling writes the bytecode store and interns names, so it runs in an+-- evaluation session ('Nix.Eval.IO.withEvalSession'). module Nix.Eval.Compile   ( compileExpr,+    compileParsed,     compileFormalsToEval,+    encodeUnaryOp,+    decodeUnaryOp,+    encodeBinaryOp,+    decodeBinaryOp,     decodeBcFormals,+    BcCaptureInfo (..),+    BcCapturedSlots (..),     decodeBcCaptureInfo,+    foldBcCapturedSlots,+    BcBindings (..),+    BcBindingCounts (..),+    BcShares (..),+    decodeBcBindings,+    foldBcShares,+    SiblingVar (..),+    siblingShares,+    formalDefaultWords,+    formalDefaultFromWords,     BcBinding (..),+    BcInheritedNames (..),     BcInheritedName (..),-    BcAttrKey (..),-    decodeBcBindings,+    foldBcBindings,+    foldBcInheritedNames,     reassembleInt64,     reassembleDouble,   )@@ -26,14 +59,19 @@  import Data.Bits (shiftL, shiftR, (.&.), (.|.)) import Data.Int (Int64)+import Data.List (sortOn)+import qualified Data.Map.Strict as Map+import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text.Encoding as TE import Data.Word (Word16, Word32, Word64, Word8) import GHC.Float (castDoubleToWord64, castWord64ToDouble) import Nix.Eval.CBytecode-  ( appDirect,-    attrkeyDynamic,+  ( attrkeyDynamic,     attrkeyStatic,+    attrsPlain,+    attrsRec,+    attrsRecOverrides,     binaryAdd,     binaryAnd,     binaryConcat,@@ -58,9 +96,14 @@     cbcData,     cbcEmit,     cbcEmitData,+    cbcEmitString,+    cbcEmitText,+    formalDefault,     formalName,     formalNamedSet,+    formalNoDefault,     formalSet,+    formalSharedDefault,     spilledCountSentinel,     strpartEsc,     strpartInterp,@@ -84,8 +127,8 @@     pattern OpLitPath,     pattern OpLitUri,     pattern OpPathStr,+    pattern OpPos,     pattern OpResolvedVar,-    pattern OpSearchPath,     pattern OpSelect,     pattern OpStr,     pattern OpUnary,@@ -93,9 +136,10 @@     pattern OpWith,     pattern OpWithVar,   )-import Nix.Eval.EvalFormals (EvalFormal (..), EvalFormals (..))+import Nix.Eval.CData (MonadCData)+import Nix.Eval.EvalFormals (EvalFormal (..), EvalFormals (..), FormalDefault (..), LambdaName (..), lambdaNameFromSymbol, lambdaNameSymbol) import Nix.Eval.SourcePos (PosIdx (..), PosRecorder, newPosRecorder, recordPos)-import Nix.Eval.Symbol (Symbol (..), symbolIntern, symbolInternBytes, symbolText)+import Nix.Eval.Symbol (Symbol (..), symbolIntern) import Nix.Expr.Types   ( AttrKey (..),     BinaryOp (..),@@ -110,14 +154,24 @@     StringPart (..),     UnaryOp (..),   )+import Nix.Parser (ParsedSource, parsedExpr, parsedNames)  -- | Compile an 'Expr' tree to bytecode, returning the root instruction index.--- The bytecode is stored in the global @nn_bytecode@ arena.+-- The bytecode is stored in the global @nn_bytecode@ arena.  The names in+-- it are interned in the order this module meets them. compileExpr :: Expr -> IO Word32 compileExpr expr = do   recorder <- newPosRecorder   compileWith recorder expr +-- | 'compileExpr' for parsed source, its names interned first in the order+-- upstream's parser interns them ('parsedNames'), so that compiling, which+-- meets them in its own order, finds each already in its place.+compileParsed :: ParsedSource -> IO Word32+compileParsed parsed = do+  mapM_ symbolIntern (parsedNames parsed)+  compileExpr (parsedExpr parsed)+ -- | 'compileExpr' recording positions with one recorder for the whole tree. compileWith :: PosRecorder -> Expr -> IO Word32 compileWith recorder = go@@ -131,15 +185,18 @@     go (EWithVar name) = compileSymbolOp OpWithVar name     go (EResolvedVar level idx) =       cbcEmit OpResolvedVar 0 0 (fi level) (fi idx) 0-    go (EAttrs isRec bindings captureInfo) =-      compileAttrs isRec bindings captureInfo+    go (EAttrs False bindings captureInfo) =+      compileAttrs attrsPlain NothingShares bindings captureInfo+    go (EAttrs True bindings captureInfo)+      | bindsOverrides bindings = compileAttrs attrsRecOverrides NothingShares bindings captureInfo+      | otherwise = compileAttrs attrsRec SiblingsShare bindings captureInfo     go (EList exprs) = compileList exprs     go (ESelect target path defExpr) =       compileSelect target path defExpr     go (EHasAttr target path) = compileHasAttr target path     go (EApp func arg) = compileApp func arg     go (ELambda formals body captureInfo) =-      compileLambda formals body captureInfo+      compileLambda AnonymousLambda formals body captureInfo     go (ELet bindings body captureInfo) =       compileLet bindings body captureInfo     go (EIf cond thenExpr elseExpr) = do@@ -162,7 +219,9 @@       leftIdx <- go left       rightIdx <- go right       cbcEmit OpBinary (encodeBinaryOp op) 0 leftIdx rightIdx 0-    go (ESearchPath name) = compileSymbolOp OpSearchPath name+    go (EPos pos) = do+      posWord <- positionWord pos+      cbcEmit OpPos 0 0 posWord 0 0      -- -----------------------------------------------------------------     -- Literals@@ -179,8 +238,8 @@       cbcEmit OpLitBool 0 (if b then 1 else 0) 0 0 0     compileLit NixNull =       cbcEmit OpLitNull 0 0 0 0 0-    compileLit (NixUri u) = compileSymbolOp OpLitUri u-    compileLit (NixPath p) = compileSymbolOp OpLitPath p+    compileLit (NixUri u) = compileTextOp OpLitUri u+    compileLit (NixPath p) = compileTextOp OpLitPath p      -- \| Emit an instruction whose only operand is an interned symbol.     compileSymbolOp :: Word8 -> Text -> IO Word32@@ -188,6 +247,15 @@       Symbol sym <- symbolIntern name       cbcEmit op 0 0 sym 0 0 +    -- \| Emit an instruction whose only operand is a string of the code's:+    -- a URI or a path, each a value upstream's parser makes (an+    -- @ExprString@ or an @ExprPath@, in the @expr_simple@ and @path_start@+    -- rules of parser.y), not a name it interns.+    compileTextOp :: Word8 -> Text -> IO Word32+    compileTextOp op text = do+      index <- cbcEmitText text+      cbcEmit op 0 0 index 0 0+     -- -----------------------------------------------------------------     -- Applications (EApp)     -- -----------------------------------------------------------------@@ -196,7 +264,7 @@     compileApp func arg = do       funcIdx <- go func       argIdx <- go arg-      cbcEmit OpApp appDirect 0 funcIdx argIdx 0+      cbcEmit OpApp 0 0 funcIdx argIdx 0      -- -----------------------------------------------------------------     -- Strings (EStr / EIndStr)@@ -208,13 +276,16 @@       (partCount, dataOff) <- emitCounted "string with parts" (length parts) (pairWords compiled)       cbcEmit op 0 partCount dataOff 0 0 +    -- \| A literal part's bytes are a string of the code's, which a value+    -- the part makes alone points at, as upstream's @ExprString@ holds+    -- the value its bytes make (nixexpr.hh).     compileOnePart :: StringPart -> IO (Word32, Word32)     compileOnePart (StrLit bytes) = do-      Symbol sym <- symbolInternBytes bytes-      pure (strpartLit, sym)+      index <- cbcEmitString bytes+      pure (strpartLit, index)     compileOnePart (StrEsc bytes) = do-      Symbol sym <- symbolInternBytes bytes-      pure (strpartEsc, sym)+      index <- cbcEmitString bytes+      pure (strpartEsc, index)     compileOnePart (StrInterp expr) = do       idx <- go expr       pure (strpartInterp, idx)@@ -223,12 +294,15 @@     -- Attribute sets (EAttrs)     -- ----------------------------------------------------------------- -    compileAttrs :: Bool -> [Binding] -> CaptureInfo -> IO Word32-    compileAttrs isRec bindings captureInfo = do-      bindingWords <- compileBindingWords bindings+    -- \| A set whose instruction holds the flag given ('attrsPlain',+    -- 'attrsRec' or 'attrsRecOverrides'), its values sharing as+    -- @sharing@ says.+    compileAttrs :: Word8 -> FrameSharing -> [Binding] -> CaptureInfo -> IO Word32+    compileAttrs kind sharing bindings captureInfo = do+      bindingWords <- compileBindingWords sharing bindings       capOff <- compileCaptureInfo captureInfo       (bindingCount, dataOff) <- emitCounted "attribute set with bindings" (length bindings) bindingWords-      cbcEmit OpAttrs (if isRec then 1 else 0) bindingCount dataOff capOff 0+      cbcEmit OpAttrs kind bindingCount dataOff capOff 0      -- -----------------------------------------------------------------     -- Lists (EList)@@ -278,40 +352,53 @@     -- Lambda (ELambda)     -- ----------------------------------------------------------------- -    compileLambda :: Formals -> Expr -> CaptureInfo -> IO Word32-    compileLambda formals body captureInfo = do-      bodyIdx <- go body-      formalsOff <- compileFormals formals+    -- \| A function and, when its body is a function too, the body under+    -- the same name, as upstream's @ExprLambda::setName@ names the body+    -- (nixexpr.cc).+    compileLambda :: LambdaName -> Formals -> Expr -> CaptureInfo -> IO Word32+    compileLambda name formals body captureInfo = do+      bodyIdx <- compileNamed name body+      formalsOff <- compileFormals name formals       capOff <- compileCaptureInfo captureInfo       cbcEmit OpLambda (encodeFormalType formals) 0 formalsOff bodyIdx capOff -    compileFormals :: Formals -> IO Word32-    compileFormals (FormalName name) = do+    -- \| An expression whose value a binding names: a function there+    -- takes the name, anything else compiles as it would anywhere.+    compileNamed :: LambdaName -> Expr -> IO Word32+    compileNamed name (ELambda formals body captureInfo) = compileLambda name formals body captureInfo+    compileNamed _ expr = go expr++    -- \| A set pattern's words start with the function's name+    -- ('lambdaNameSymbol').+    compileFormals :: LambdaName -> Formals -> IO Word32+    compileFormals _ (FormalName name) = do       Symbol sym <- symbolIntern name       emitWordList [sym]-    compileFormals (FormalSet formals ellipsis) = do-      formalWords <- compileFormalEntries formals+    compileFormals name (FormalSet formals ellipsis) = do+      formalWords <- compileFormalEntries setFirstFormalSlot formals       emitWordList $-        [fi (length formals), if ellipsis then 1 else 0]+        [lambdaNameSymbol name, fi (length formals), if ellipsis then 1 else 0]           ++ formalWords-    compileFormals (FormalNamedSet name formals ellipsis) = do-      Symbol nameSym <- symbolIntern name-      formalWords <- compileFormalEntries formals+    compileFormals name (FormalNamedSet argName formals ellipsis) = do+      Symbol argSym <- symbolIntern argName+      formalWords <- compileFormalEntries namedSetFirstFormalSlot formals       emitWordList $-        [nameSym, fi (length formals), if ellipsis then 1 else 0]+        [lambdaNameSymbol name, argSym, fi (length formals), if ellipsis then 1 else 0]           ++ formalWords -    compileFormalEntries :: [Formal] -> IO [Word32]-    compileFormalEntries = fmap concat . mapM compileFormalEntry+    -- \| A set pattern's formal entries, the first formal in the slot+    -- given, each three words: the name, the kind of its default and the+    -- default's code ('formalDefaultWords').+    compileFormalEntries :: Int -> [Formal] -> IO [Word32]+    compileFormalEntries firstFormal formals = do+      pending <- mapM compilePendingFormal formals+      entries <- shareFormalDefaults firstFormal pending+      pure (concat [[unSymbol name, kind, code] | EvalFormal name def <- entries, let (kind, code) = formalDefaultWords def]) -    compileFormalEntry :: Formal -> IO [Word32]-    compileFormalEntry (Formal name defExpr) = do-      Symbol nameSym <- symbolIntern name-      case defExpr of-        Nothing -> pure [nameSym, 0, 0]-        Just d -> do-          defIdx <- go d-          pure [nameSym, 1, defIdx]+    compilePendingFormal :: Formal -> IO PendingFormal+    compilePendingFormal (Formal name defExpr) = do+      sym <- symbolIntern name+      PendingFormal sym <$> pendingDefault go defExpr      -- -----------------------------------------------------------------     -- Let (ELet)@@ -320,7 +407,7 @@     compileLet :: [Binding] -> Expr -> CaptureInfo -> IO Word32     compileLet bindings body captureInfo = do       bodyIdx <- go body-      bindingWords <- compileBindingWords bindings+      bindingWords <- compileBindingWords SiblingsShare bindings       capOff <- compileCaptureInfo captureInfo       (bindingCount, dataOff) <- emitCounted "let with bindings" (length bindings) bindingWords       cbcEmit OpLet 0 bindingCount dataOff bodyIdx capOff@@ -329,18 +416,44 @@     -- Bindings (shared by EAttrs and ELet)     -- ----------------------------------------------------------------- -    -- \| The flat data words for a binding list; the caller emits them-    -- (with the count, via emitCounted) so a spilled count can precede-    -- them contiguously.-    compileBindingWords :: [Binding] -> IO [Word32]-    compileBindingWords bindings = concat <$> mapM compileOneBinding bindings+    -- \| The flat data words for a binding list: the names it binds+    -- statically and the bindings with a dynamic name, counted+    -- ('bindingNameCounts'), then its frame's shares, counted, then each+    -- binding's words.  The caller emits them (with the count, via+    -- emitCounted) so a spilled count can precede them contiguously.  The+    -- shares are decided once the bindings are compiled, so every name+    -- they read is interned where compiling interns it.+    compileBindingWords :: FrameSharing -> [Binding] -> IO [Word32]+    compileBindingWords sharing bindings = do+      let BcBindingCounts names dynamics = bindingNameCounts bindings+      namesWord <- countArg "binding set with static names" names+      dynamicsWord <- countArg "binding set with dynamic names" dynamics+      bindingWords <- mapM compileOneBinding bindings+      shares <- case sharing of+        NothingShares -> pure []+        SiblingsShare+          | dynamics == 0 -> slotShares bindings+          | otherwise -> nameShares bindings+      sharesWord <- countArg "binding set with shares" (length shares)+      pure (namesWord : dynamicsWord : sharesWord : concat [[slot, target] | (slot, target) <- shares] ++ concat bindingWords) +    -- \| A function bound to a static name is named by it, as upstream's+    -- @addAttr@ names the value of an attribute path's last name+    -- (parser-state.hh).  Upstream names a function under a dynamic key too,+    -- with the name the key evaluates to, each time it evaluates the set+    -- (@ExprAttrs::eval@ in eval.cc); a name the compiler cannot know, so+    -- such a function is anonymous here.     compileOneBinding :: Binding -> IO [Word32]-    compileOneBinding (NamedBinding pos key expr) = do-      (keyKind, keyWord) <- compileAttrKey key+    compileOneBinding (NamedBinding pos (StaticKey name) expr) = do+      sym <- symbolIntern name+      valIdx <- compileNamed (NamedLambda sym) expr+      posWord <- positionWord pos+      pure [bindNamed, attrkeyStatic, unSymbol sym, valIdx, posWord]+    compileOneBinding (NamedBinding pos (DynamicKey keyExpr) expr) = do+      keyIdx <- go keyExpr       valIdx <- go expr       posWord <- positionWord pos-      pure [bindNamed, keyKind, keyWord, valIdx, posWord]+      pure [bindNamed, attrkeyDynamic, keyIdx, valIdx, posWord]     compileOneBinding (Inherit pos name var) = do       sym <- internName name       valIdx <- go var@@ -391,30 +504,9 @@           ++ concatMap (\(level, idx) -> [fi level, fi idx]) pairs      -- ------------------------------------------------------------------    -- Operator encoding+    -- Formal type encoding     -- ----------------------------------------------------------------- -    encodeUnaryOp :: UnaryOp -> Word8-    encodeUnaryOp OpNot = unaryNot-    encodeUnaryOp OpNegate = unaryNegate--    encodeBinaryOp :: BinaryOp -> Word8-    encodeBinaryOp OpAdd = binaryAdd-    encodeBinaryOp OpSub = binarySub-    encodeBinaryOp OpMul = binaryMul-    encodeBinaryOp OpDiv = binaryDiv-    encodeBinaryOp OpAnd = binaryAnd-    encodeBinaryOp OpOr = binaryOr-    encodeBinaryOp OpImpl = binaryImpl-    encodeBinaryOp OpEq = binaryEq-    encodeBinaryOp OpNeq = binaryNeq-    encodeBinaryOp OpLt = binaryLt-    encodeBinaryOp OpLte = binaryLte-    encodeBinaryOp OpGt = binaryGt-    encodeBinaryOp OpGte = binaryGte-    encodeBinaryOp OpConcat = binaryConcat-    encodeBinaryOp OpUpdate = binaryUpdate-     encodeFormalType :: Formals -> Word8     encodeFormalType (FormalName {}) = formalName     encodeFormalType (FormalSet {}) = formalSet@@ -485,165 +577,481 @@ -- ---------------------------------------------------------------------------  -- | Compile parser 'Formals' (with 'Maybe Expr' defaults) to eval-time--- 'EvalFormals' (with 'Maybe Word32' bc_idx defaults).+-- 'EvalFormals', each default compiled and decided as a set pattern's+-- entries hold it ('shareFormalDefaults'), for a function no binding+-- names, interning each name. compileFormalsToEval :: Formals -> IO EvalFormals-compileFormalsToEval (FormalName name) = pure (EFName name)+compileFormalsToEval (FormalName name) = EFName <$> symbolIntern name compileFormalsToEval (FormalSet formals ellipsis) =-  EFSet <$> mapM compileOneFormal formals <*> pure ellipsis+  EFSet AnonymousLambda <$> (mapM compileOneFormal formals >>= shareFormalDefaults setFirstFormalSlot) <*> pure ellipsis compileFormalsToEval (FormalNamedSet name formals ellipsis) =-  EFNamedSet name <$> mapM compileOneFormal formals <*> pure ellipsis+  EFNamedSet AnonymousLambda <$> symbolIntern name <*> (mapM compileOneFormal formals >>= shareFormalDefaults namedSetFirstFormalSlot) <*> pure ellipsis -compileOneFormal :: Formal -> IO EvalFormal+-- | The slot of a set pattern's frame its first formal fills, the rest+-- following it: the first, or for a pattern with an \@-pattern the one+-- after the \@-pattern's name, which upstream's @callFunction@ fills+-- first (eval.cc) and the resolver numbers first+-- ('Nix.Expr.Resolve.lexicalScopeFromFormals').+setFirstFormalSlot, namedSetFirstFormalSlot :: Int+setFirstFormalSlot = 0+namedSetFirstFormalSlot = 1++-- | A formal with its default compiled, its name interned after the+-- default's names, as upstream's parser interns them (the @formal@ rule+-- of parser.y).+compileOneFormal :: Formal -> IO PendingFormal compileOneFormal (Formal name defExpr) = do-  defBcIdx <- case defExpr of-    Nothing -> pure Nothing-    Just expr -> Just <$> compileExpr expr-  pure (EvalFormal name defBcIdx)+  pending <- pendingDefault compileExpr defExpr+  (`PendingFormal` pending) <$> symbolIntern name +-- | A formal whose default is compiled but for a variable of the call's+-- own frame, which waits for the formals' shares to be decided.+data PendingFormal = PendingFormal !Symbol !PendingDefault++-- | A formal's default before the formals' shares are decided.+data PendingDefault+  = -- | None.+    NoPendingDefault+  | -- | Compiled, at a bytecode index.+    CompiledDefault !Word32+  | -- | A variable naming a slot of the call's own frame, not compiled+    -- yet.  Compiling it interns no name.+    FrameSlotDefault !Int++-- | A default compiled as a pending one: a variable of level 0, which+-- names a slot of the call's own frame, is left for+-- 'shareFormalDefaults', and anything else is compiled by @compileDefault@.+pendingDefault :: (Expr -> IO Word32) -> Maybe Expr -> IO PendingDefault+pendingDefault _ Nothing = pure NoPendingDefault+pendingDefault _ (Just (EResolvedVar 0 slot)) = pure (FrameSlotDefault slot)+pendingDefault compileDefault (Just defExpr) = CompiledDefault <$> compileDefault defExpr++-- | Formals with their defaults decided, the first formal in the slot+-- given, as upstream's @callFunction@ fills a set pattern's frame through+-- @maybeThunk@ (eval.cc): the @-pattern's slot first, then the formals'+-- in symbol order (@validateFormals@ in parser-state.hh).  A default that+-- is a variable naming the @-pattern, or a formal 'siblingShares' says is+-- filled before its own, shares that slot's cell ('SharedDefault'); one+-- naming a formal filled after its own is a variable of its own+-- ('Default').  Either stays a variable naming the slot it names: which+-- cell a formal's slot holds depends on whether a call's argument holds the+-- formal, so a chain of shared defaults ends where the call finds it.+shareFormalDefaults :: Int -> [PendingFormal] -> IO [EvalFormal]+shareFormalDefaults firstFormal pending = mapM decide (zip [firstFormal ..] pending)+  where+    names = Map.fromList (zip [firstFormal ..] [name | PendingFormal name _ <- pending])+    shared = Set.fromList (map fst (siblingShares (`Map.lookup` names) [SiblingVar name slot target | (slot, PendingFormal name (FrameSlotDefault target)) <- zip [firstFormal ..] pending, target >= firstFormal]))+    decide (slot, PendingFormal name pendingDef) =+      EvalFormal name <$> case pendingDef of+        NoPendingDefault -> pure NoDefault+        CompiledDefault code -> pure (Default code)+        FrameSlotDefault target+          | target < firstFormal || Set.member slot shared -> SharedDefault <$> frameSlotVar target+          | otherwise -> Default <$> frameSlotVar target+    frameSlotVar slot = cbcEmit OpResolvedVar 0 0 0 (fromIntegral slot) 0++-- | The kind and code words of a formal's default, as a set pattern's+-- entries and a C lambda's hold them.+formalDefaultWords :: FormalDefault -> (Word32, Word32)+formalDefaultWords NoDefault = (formalNoDefault, 0)+formalDefaultWords (Default code) = (formalDefault, code)+formalDefaultWords (SharedDefault code) = (formalSharedDefault, code)++-- | The default 'formalDefaultWords' writes as a kind and a code word,+-- or 'Nothing' for a kind it never writes.+formalDefaultFromWords :: Word32 -> Word32 -> Maybe FormalDefault+formalDefaultFromWords kind code+  | kind == formalNoDefault = Just NoDefault+  | kind == formalDefault = Just (Default code)+  | kind == formalSharedDefault = Just (SharedDefault code)+  | otherwise = Nothing+ -- ---------------------------------------------------------------------------+-- Operator tags (the flags byte of OpUnary and OpBinary)+-- ---------------------------------------------------------------------------++-- | The flags byte an @OpUnary@ instruction carries for its operator.+encodeUnaryOp :: UnaryOp -> Word8+encodeUnaryOp OpNot = unaryNot+encodeUnaryOp OpNegate = unaryNegate++-- | The operator an @OpUnary@ flags byte names: the inverse of+-- 'encodeUnaryOp', and 'Nothing' for a byte it never writes.+decodeUnaryOp :: Word8 -> Maybe UnaryOp+decodeUnaryOp tag+  | tag == unaryNot = Just OpNot+  | tag == unaryNegate = Just OpNegate+  | otherwise = Nothing++-- | The flags byte an @OpBinary@ instruction carries for its operator.+encodeBinaryOp :: BinaryOp -> Word8+encodeBinaryOp OpAdd = binaryAdd+encodeBinaryOp OpSub = binarySub+encodeBinaryOp OpMul = binaryMul+encodeBinaryOp OpDiv = binaryDiv+encodeBinaryOp OpAnd = binaryAnd+encodeBinaryOp OpOr = binaryOr+encodeBinaryOp OpImpl = binaryImpl+encodeBinaryOp OpEq = binaryEq+encodeBinaryOp OpNeq = binaryNeq+encodeBinaryOp OpLt = binaryLt+encodeBinaryOp OpLte = binaryLte+encodeBinaryOp OpGt = binaryGt+encodeBinaryOp OpGte = binaryGte+encodeBinaryOp OpConcat = binaryConcat+encodeBinaryOp OpUpdate = binaryUpdate++-- | The operator an @OpBinary@ flags byte names: the inverse of+-- 'encodeBinaryOp', and 'Nothing' for a byte it never writes.+decodeBinaryOp :: Word8 -> Maybe BinaryOp+decodeBinaryOp tag+  | tag == binaryAdd = Just OpAdd+  | tag == binarySub = Just OpSub+  | tag == binaryMul = Just OpMul+  | tag == binaryDiv = Just OpDiv+  | tag == binaryAnd = Just OpAnd+  | tag == binaryOr = Just OpOr+  | tag == binaryImpl = Just OpImpl+  | tag == binaryEq = Just OpEq+  | tag == binaryNeq = Just OpNeq+  | tag == binaryLt = Just OpLt+  | tag == binaryLte = Just OpLte+  | tag == binaryGt = Just OpGt+  | tag == binaryGte = Just OpGte+  | tag == binaryConcat = Just OpConcat+  | tag == binaryUpdate = Just OpUpdate+  | otherwise = Nothing++-- --------------------------------------------------------------------------- -- Bytecode decoding (eval-time: read from C data buffer) -- --------------------------------------------------------------------------- --- | Decode formals from the bytecode data buffer.--- @flags@ is the formal type (0=Name, 1=Set, 2=NamedSet).--- @dataOff@ is the offset into the data buffer.-decodeBcFormals :: Word8 -> Word32 -> IO EvalFormals-decodeBcFormals flags dataOff = case flags of-  0 {- FormalName -} -> do-    sym <- cbcData dataOff-    pure (EFName (symbolText (Symbol sym)))-  1 {- FormalSet -} -> do-    count <- cbcData dataOff-    ellipsis <- cbcData (dataOff + 1)-    formals <- decodeFormalEntries (fromIntegral count) (dataOff + 2)-    pure (EFSet formals (ellipsis /= 0))-  2 {- FormalNamedSet -} -> do-    nameSym <- cbcData dataOff+-- | Decode formals from the bytecode data buffer: @flags@ is the lambda's+-- formal type ('formalName', 'formalSet' or 'formalNamedSet'), @dataOff@+-- the offset of its words.  'Nothing' for any other type, and a formal's+-- default kind the compiler never writes ('formalDefaultFromWords') is+-- handed to @unknownKind@.  The offset is strict, though an unknown type+-- never reads it, so a caller passes it evaluated rather than as a thunk.+decodeBcFormals :: (MonadCData m) => (Word32 -> m FormalDefault) -> Word8 -> Word32 -> m (Maybe EvalFormals)+decodeBcFormals unknownKind flags !dataOff+  | flags == formalName = Just . EFName . Symbol <$> cbcData dataOff+  | flags == formalSet = do+      lambdaSym <- cbcData dataOff       count <- cbcData (dataOff + 1)       ellipsis <- cbcData (dataOff + 2)-    formals <- decodeFormalEntries (fromIntegral count) (dataOff + 3)-    pure (EFNamedSet (symbolText (Symbol nameSym)) formals (ellipsis /= 0))-  -- Unreachable: the flag is written only by this module's formals compiler,-  -- which emits 0, 1, or 2 - all matched above.-  _ -> error "decodeBcFormals: invalid formal type flag"+      formals <- decodeFormalEntries unknownKind (fromIntegral count) (dataOff + 3)+      pure (Just (EFSet (lambdaNameFromSymbol lambdaSym) formals (ellipsis /= 0)))+  | flags == formalNamedSet = do+      lambdaSym <- cbcData dataOff+      nameSym <- cbcData (dataOff + 1)+      count <- cbcData (dataOff + 2)+      ellipsis <- cbcData (dataOff + 3)+      formals <- decodeFormalEntries unknownKind (fromIntegral count) (dataOff + 4)+      pure (Just (EFNamedSet (lambdaNameFromSymbol lambdaSym) (Symbol nameSym) formals (ellipsis /= 0)))+  | otherwise = pure Nothing  -- | Decode a list of formal entries from the data buffer.--- Each entry is 3 words: [name_sym, has_default, default_bc_idx].-decodeFormalEntries :: Int -> Word32 -> IO [EvalFormal]-decodeFormalEntries 0 _ = pure []-decodeFormalEntries n off = do+-- Each entry is 3 words: the name's symbol, then the default's kind and+-- code ('formalDefaultFromWords'), a kind the compiler never writes+-- handed to @unknownKind@.+decodeFormalEntries :: (MonadCData m) => (Word32 -> m FormalDefault) -> Int -> Word32 -> m [EvalFormal]+decodeFormalEntries _ 0 _ = pure []+decodeFormalEntries unknownKind n off = do   nameSym <- cbcData off-  hasDef <- cbcData (off + 1)-  defBcIdx <- cbcData (off + 2)-  let defMaybe = if hasDef /= 0 then Just defBcIdx else Nothing-  rest <- decodeFormalEntries (n - 1) (off + 3)-  pure (EvalFormal (symbolText (Symbol nameSym)) defMaybe : rest)+  kind <- cbcData (off + 1)+  code <- cbcData (off + 2)+  def <- maybe (unknownKind kind) pure (formalDefaultFromWords kind code)+  rest <- decodeFormalEntries unknownKind (n - 1) (off + 3)+  pure (EvalFormal (Symbol nameSym) def : rest) --- | Decode capture info from the bytecode data buffer.-decodeBcCaptureInfo :: Word32 -> IO CaptureInfo-decodeBcCaptureInfo dataOff = do-  tag <- cbcData dataOff-  case tag of-    0 {- NoCaptureInfo -} -> pure NoCaptureInfo-    1 {- Captures -} -> do-      count <- cbcData (dataOff + 1)-      pairs <- decodePairs (fromIntegral count) (dataOff + 2)-      pure (Captures pairs)-    2 {- CapturesWithScopes -} -> do+-- ---------------------------------------------------------------------------+-- Capture info reading (for evalBcLambda, evalBcAttrs and evalBcLet)+-- ---------------------------------------------------------------------------++-- | A closure's or frame's capture info, its captured slots left in the+-- data buffer for 'foldBcCapturedSlots' to read.+data BcCaptureInfo+  = -- | The closure runs in the env it is made in ('NoCaptureInfo').+    BcNoCaptureInfo+  | -- | The closure runs in an env of the captured slots alone+    -- ('Captures').+    BcCaptures !BcCapturedSlots+  | -- | The closure runs in an env of the captured slots that sees the+    -- with-scopes of the env it is made in ('CapturesWithScopes').+    BcCapturesWithScopes !BcCapturedSlots++-- | The slots a closure captures: their count and the data offset of the+-- first one's (level, index) pair.+data BcCapturedSlots = BcCapturedSlots !Int !Word32++-- | The capture info at a data offset, or the tag there when it is none+-- of 'captureNone', 'captureSlots' and 'captureWithScopes'.+decodeBcCaptureInfo :: (MonadCData m) => Word32 -> m (Either Word32 BcCaptureInfo)+decodeBcCaptureInfo dataOff = cbcData dataOff >>= decodeTagged+  where+    decodeTagged tag+      | tag == captureNone = pure (Right BcNoCaptureInfo)+      | tag == captureSlots = Right . BcCaptures <$> capturedSlots+      | tag == captureWithScopes = Right . BcCapturesWithScopes <$> capturedSlots+      | otherwise = pure (Left tag)+    capturedSlots = do       count <- cbcData (dataOff + 1)-      pairs <- decodePairs (fromIntegral count) (dataOff + 2)-      pure (CapturesWithScopes pairs)-    -- Unreachable: the tag is written only by this module's capture compiler,-    -- which emits 0, 1, or 2 - all matched above.-    _ -> error "decodeBcCaptureInfo: invalid capture type tag"+      pure (BcCapturedSlots (fromIntegral count) (dataOff + 2)) --- | Decode (level, idx) pairs from the data buffer.-decodePairs :: Int -> Word32 -> IO [(Int, Int)]-decodePairs 0 _ = pure []-decodePairs n off = do+-- | Fold over captured slots, first to last, each given as the resolved+-- level and index the slot is read from in the env the closure is made+-- in.  Each pair's words are read as the fold reaches them.+{-# INLINE foldBcCapturedSlots #-}+foldBcCapturedSlots :: (MonadCData m) => (acc -> Word32 -> Word32 -> m acc) -> acc -> BcCapturedSlots -> m acc+foldBcCapturedSlots step start (BcCapturedSlots count dataOff) = go start count dataOff+  where+    go !acc 0 !_ = pure acc+    go !acc n !off = do       level <- cbcData off       idx <- cbcData (off + 1)-  rest <- decodePairs (n - 1) (off + 2)-  pure ((fromIntegral level, fromIntegral idx) : rest)+      next <- step acc level idx+      go next (n - 1) (off + 2)  -- ------------------------------------------------------------------------------ Binding decoding (for evalBcAttrs / evalBcLet)+-- Binding reading (for evalBcAttrs and evalBcLet) -- --------------------------------------------------------------------------- --- | A decoded binding from the bytecode data buffer, each name at the--- position it was defined at.+-- | The bindings of a set or a let: their names counted, the frame's+-- shares, then their count, resolved through the short_arg spill, and the+-- data offset of the first.+data BcBindings = BcBindings !BcBindingCounts !BcShares !Int !Word32++-- | How many names bindings bind statically, one for each static key and+-- inherited variable and one for each name of an @inherit (from)@, and+-- how many bindings have a dynamic name.+data BcBindingCounts = BcBindingCounts !Int !Int++-- | The names of a binding list counted, as the compiler writes them at+-- the head of its words.  The bindings' variables are resolved by slot+-- exactly when none has a dynamic name, one slot per static name in+-- declaration order: this must stay in sync with @allStaticSingleKey@+-- and @lexicalScopeFromBindings@ in "Nix.Expr.Resolve".+bindingNameCounts :: [Binding] -> BcBindingCounts+bindingNameCounts = foldl' countOne (BcBindingCounts 0 0)+  where+    countOne (BcBindingCounts names dynamics) binding = case binding of+      NamedBinding _ (StaticKey _) _ -> BcBindingCounts (names + 1) dynamics+      NamedBinding _ (DynamicKey _) _ -> BcBindingCounts names (dynamics + 1)+      Inherit {} -> BcBindingCounts (names + 1) dynamics+      InheritFrom _ inherited -> BcBindingCounts (names + length inherited) dynamics++-- | Whether a recursive set's bindings bind 'overridesName' statically,+-- as upstream looks for it among a recursive set's static attributes, an+-- inherited one included (@ExprAttrs::eval@ in eval.cc).  Its instruction+-- then holds 'attrsRecOverrides' rather than 'attrsRec'.+bindsOverrides :: [Binding] -> Bool+bindsOverrides = any bindsName+  where+    bindsName binding = case binding of+      NamedBinding _ (StaticKey name) _ -> name == overridesName+      NamedBinding _ (DynamicKey _) _ -> False+      Inherit _ name _ -> name == overridesName+      InheritFrom _ inherited -> overridesName `elem` [name | InheritedName _ name <- inherited]++-- | The attribute a recursive set overrides its own attributes with+-- upstream (@sOverrides@ in eval.cc at 2.24.9, @StaticEvalSymbols@'s+-- @overrides@ in eval.hh at 2.36.0).+overridesName :: Text+overridesName = "__overrides"++-- | Whether a binding list's values may share the cells of its own names:+-- a recursive set's and a let's, but not a recursive set's that binds+-- @__overrides@, whose values upstream makes thunks of their own+-- (@ExprAttrs::eval@ in eval.cc), or a plain set's, which binds no name+-- its values read.+data FrameSharing = SiblingsShare | NothingShares++-- | A binding of a frame being tied whose whole value is a variable naming+-- another binding of the same frame: the name the binding binds, the key+-- its cell is kept under, and the key of the binding the variable names.+data SiblingVar k = SiblingVar !Symbol !k !k++-- | Of a frame's sibling variables, each a t'SiblingVar', the ones that+-- share a sibling's cell where upstream's do, each as its binding's key+-- and the key of the binding whose cell it takes, in the order the frame+-- fills them.  Upstream fills a frame's slots in symbol order, from an+-- env whose slots start empty (@allocEnv@ in eval-inline.hh), and+-- @ExprVar::maybeThunk@ binds a variable to its slot's cell when the slot+-- is filled and to a thunk of its own when it is not+-- (eval.cc).  So a variable shares the cell of a sibling whose name has the+-- lesser symbol, and keeps its own thunk otherwise, as a variable naming its+-- own binding does.  A sibling that shares holds the cell it takes, so each+-- pair names the binding at the end of the chain, whose cell is its own, and+-- the pairs can be copied in any order.  @nameOf@ gives the name the binding+-- under a key binds.+siblingShares :: (Ord k) => (k -> Maybe Symbol) -> [SiblingVar k] -> [(k, k)]+siblingShares nameOf siblings = reverse shares+  where+    SharesMade _ shares = foldl' share (SharesMade Map.empty []) (sortOn bindingName siblings)+    bindingName (SiblingVar name _ _) = name+    share made@(SharesMade roots found) (SiblingVar name key target) = case nameOf target of+      Just targetName+        | targetName < name ->+            let root = Map.findWithDefault target target roots+             in SharesMade (Map.insert key root roots) ((key, root) : found)+      _ -> made++-- | The shares 'siblingShares' has made so far: the binding at the end of+-- each sharing binding's chain, and the pairs, last first.+data SharesMade k = SharesMade !(Map.Map k k) ![(k, k)]++-- | Each slot a binding list's static names fill, in declaration order:+-- the name, and the slot of the frame its value names when that value is+-- a variable of the frame's own slots.+staticSlots :: [Binding] -> [(Text, Maybe Int)]+staticSlots = concatMap slotsOf+  where+    slotsOf (NamedBinding _ (StaticKey name) value) = [(name, frameSlot value)]+    slotsOf (NamedBinding _ (DynamicKey _) _) = []+    slotsOf (Inherit _ name _) = [(name, Nothing)]+    slotsOf (InheritFrom _ inherited) = [(name, Nothing) | InheritedName _ name <- inherited]+    frameSlot (EResolvedVar 0 slot) = Just slot+    frameSlot _ = Nothing++-- | The shares of a binding list whose names are in slots, as slot pairs+-- ('siblingShares').  Its names are interned by then.+slotShares :: [Binding] -> IO [(Word32, Word32)]+slotShares bindings = do+  let slots = staticSlots bindings+  names <- traverse (symbolIntern . fst) slots+  let siblings = [SiblingVar sym slot target | (slot, sym, Just target) <- zip3 [0 ..] names (map snd slots)]+  pure [(fromIntegral slot, fromIntegral target) | (slot, target) <- siblingShares (`Map.lookup` Map.fromList (zip [0 ..] names)) siblings]++-- | The shares of a binding list whose static names are in a name table,+-- as symbol pairs ('siblingShares'): a static name's value that is a+-- variable the resolver left to the table names another static name.+-- Its names are interned by then.+nameShares :: [Binding] -> IO [(Word32, Word32)]+nameShares bindings = do+  let staticNames = Set.fromList (map fst (staticSlots bindings))+  siblings <-+    sequence+      [ (\sym target -> SiblingVar sym sym target) <$> symbolIntern own <*> symbolIntern name+      | NamedBinding _ (StaticKey own) (EVar name) <- bindings,+        Set.member name staticNames+      ]+  pure [(unSymbol key, unSymbol target) | (key, target) <- siblingShares Just siblings]++-- | The shares of a frame's bindings, in the order the frame fills them:+-- their count and the data offset of the first one's pair of words, each+-- pair the slot or the symbol of a binding whose whole value is a+-- variable naming another of the frame's names and the one whose cell it+-- takes ('siblingShares').+data BcShares = BcShares !Int !Word32++-- | The bindings in an instruction's counted payload: @count@ bindings,+-- resolved through the short_arg spill, whose words start at @dataOff@+-- with their names counted and their shares after the counts.+decodeBcBindings :: (MonadCData m) => Int -> Word32 -> m BcBindings+decodeBcBindings count dataOff = do+  names <- cbcData dataOff+  dynamics <- cbcData (dataOff + 1)+  shares <- cbcData (dataOff + 2)+  let firstShare = dataOff + 3+  pure+    ( BcBindings+        (BcBindingCounts (fromIntegral names) (fromIntegral dynamics))+        (BcShares (fromIntegral shares) firstShare)+        count+        (firstShare + 2 * shares)+    )++-- | Fold over a frame's shares, first to last, each given as the slot or+-- symbol that takes a cell and the one whose cell it takes.  Each pair's+-- words are read as the fold reaches them.+{-# INLINE foldBcShares #-}+foldBcShares :: (MonadCData m) => (acc -> Word32 -> Word32 -> m acc) -> acc -> BcShares -> m acc+foldBcShares step start (BcShares count dataOff) = go start count dataOff+  where+    go !acc 0 !_ = pure acc+    go !acc n !off = do+      key <- cbcData off+      target <- cbcData (off + 1)+      next <- step acc key target+      go next (n - 1) (off + 2)++-- | A binding of a set or a let, each name at the position it was+-- defined at. data BcBinding-  = -- | @key = expr@: its position, the key and the value's bc_idx-    BcNamed !PosIdx !BcAttrKey !Word32+  = -- | @name = expr@: its position, the name's symbol and the value's+    -- bc_idx+    BcNamed !PosIdx !Word32 !Word32+  | -- | @${key} = expr@: its position, the bc_idx of the expression the+    -- name is computed by and the value's bc_idx+    BcDynamic !PosIdx !Word32 !Word32   | -- | One name of @inherit x@: its position, its symbol and the bc_idx     -- of the variable it copies, which is evaluated in the env around the     -- binding set     BcInherit !PosIdx !Word32 !Word32-  | -- | @inherit (from) names@ with from-expr bc_idx and the names-    BcInheritFrom !Word32 ![BcInheritedName]+  | -- | @inherit (from) names@: the from-expr's bc_idx and the names,+    -- which 'foldBcInheritedNames' reads+    BcInheritFrom !Word32 !BcInheritedNames +-- | The names of an @inherit (from) names@ binding: their count and the+-- data offset of the first.+data BcInheritedNames = BcInheritedNames !Int !Word32+ -- | One name of an @inherit (from) names@ binding: its position, its -- symbol and the bc_idx of the select that reads it from slot 0 of an env -- holding the from-value. data BcInheritedName = BcInheritedName !PosIdx !Word32 !Word32 --- | A binding's attribute key.-data BcAttrKey-  = -- | Static key (interned symbol)-    BcStaticKey !Word32-  | -- | Dynamic key (bc_idx of expression to evaluate)-    BcDynamicKey !Word32---- | Decode all bindings from the bytecode data buffer.--- @bindCount@ is the number of bindings (already resolved through the--- short_arg spill by the caller), @dataOff@ is the start offset.-decodeBcBindings :: Int -> Word32 -> IO [BcBinding]-decodeBcBindings 0 _ = pure []-decodeBcBindings count dataOff = do-  (binding, nextOff) <- decodeOneBinding dataOff-  rest <- decodeBcBindings (count - 1) nextOff-  pure (binding : rest)---- | Decode a single binding, returning it and the offset past it.-decodeOneBinding :: Word32 -> IO (BcBinding, Word32)-decodeOneBinding off = do-  tag <- cbcData off-  case tag of-    0 {- NamedBinding -} -> do-      key <- decodeAttrKey (off + 1)+-- | Fold over bindings, first to last, each read from the data buffer as+-- the fold reaches it.  The data buffer only grows, so a step may compile+-- code.  A binding tag that is none of 'bindNamed', 'bindInherit' and+-- 'bindInheritFrom' ends the fold with @unknownTag@ applied to it.+--+-- It is inlined wherever it is given its two functions, as a partial+-- application of it is.  Each binding is built where the step is applied+-- to it, so a step that is inlined too (an INLINE pragma on it) takes+-- the binding's fields apart without allocating it.+{-# INLINE foldBcBindings #-}+foldBcBindings :: (MonadCData m) => (Word32 -> m acc) -> (acc -> BcBinding -> m acc) -> acc -> BcBindings -> m acc+foldBcBindings unknownTag step = foldFrom+  where+    foldFrom start (BcBindings _ _ count dataOff) = go start count dataOff+    go !acc 0 !_ = pure acc+    go !acc n !off = cbcData off >>= stepTagged+      where+        stepTagged tag+          | tag == bindNamed = do+              isExpr <- cbcData (off + 1)+              keyWord <- cbcData (off + 2)               valBcIdx <- cbcData (off + 3)-      pos <- cbcData (off + 4)-      pure (BcNamed (PosIdx pos) key valBcIdx, off + 5)-    1 {- Inherit -} -> do+              pos <- PosIdx <$> cbcData (off + 4)+              if isExpr /= 0+                then step acc (BcDynamic pos keyWord valBcIdx) >>= continueAt (off + 5)+                else step acc (BcNamed pos keyWord valBcIdx) >>= continueAt (off + 5)+          | tag == bindInherit = do               sym <- cbcData (off + 1)               valBcIdx <- cbcData (off + 2)-      pos <- cbcData (off + 3)-      pure (BcInherit (PosIdx pos) sym valBcIdx, off + 4)-    2 {- InheritFrom -} -> do+              pos <- PosIdx <$> cbcData (off + 3)+              step acc (BcInherit pos sym valBcIdx) >>= continueAt (off + 4)+          | tag == bindInheritFrom = do               fromBcIdx <- cbcData (off + 1)               nameCount <- cbcData (off + 2)-      names <- decodeInheritedNames (fromIntegral nameCount) (off + 3)-      pure (BcInheritFrom fromBcIdx names, off + 3 + 3 * nameCount)-    -- Unreachable: the tag is written only by this module's binding compiler,-    -- which emits 0, 1 or 2 - all matched above.-    _ -> error "decodeOneBinding: invalid binding type tag"---- | Decode a binding's key: the pair (is_expr, key_or_bc_idx).-decodeAttrKey :: Word32 -> IO BcAttrKey-decodeAttrKey off = do-  isExpr <- cbcData off-  val <- cbcData (off + 1)-  pure (if isExpr /= 0 then BcDynamicKey val else BcStaticKey val)+              step acc (BcInheritFrom fromBcIdx (BcInheritedNames (fromIntegral nameCount) (off + 3)))+                >>= continueAt (off + 3 + 3 * nameCount)+          | otherwise = unknownTag tag+        continueAt nextOff next = go next (n - 1) nextOff --- | Decode inherited names: triples of (name_sym, select_bc_idx, pos).-decodeInheritedNames :: Int -> Word32 -> IO [BcInheritedName]-decodeInheritedNames 0 _ = pure []-decodeInheritedNames n off = do+-- | Fold over the names of an @inherit (from)@ binding, first to last.+{-# INLINE foldBcInheritedNames #-}+foldBcInheritedNames :: (MonadCData m) => (acc -> BcInheritedName -> m acc) -> acc -> BcInheritedNames -> m acc+foldBcInheritedNames step start (BcInheritedNames count dataOff) = go start count dataOff+  where+    go !acc 0 !_ = pure acc+    go !acc n !off = do       sym <- cbcData off       selectBcIdx <- cbcData (off + 1)       pos <- cbcData (off + 2)-  rest <- decodeInheritedNames (n - 1) (off + 3)-  pure (BcInheritedName (PosIdx pos) sym selectBcIdx : rest)+      next <- step acc (BcInheritedName (PosIdx pos) sym selectBcIdx)+      go next (n - 1) (off + 3)  -- --------------------------------------------------------------------------- -- Numeric reassembly (from two uint32 halves)
src/Nix/Eval/Context.hs view
@@ -13,7 +13,10 @@      -- * Queries     contextIsEmpty,-    firstContextEncoded,+    firstContextDisplayed,+    inUpstreamOrder,+    encodedElement,+    contextRequest,      -- * Extraction (for derivation building)     extractInputSrcs,@@ -27,6 +30,7 @@ where  import Data.Foldable (minimumBy)+import Data.List (sortOn) import qualified Data.List.NonEmpty as NE import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map@@ -34,8 +38,9 @@ import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T+import Nix.Eval.RealiseContext (ContextRequest (..)) import Nix.Eval.Types (StringContext (..), StringContextElement (..))-import Nix.Store.Path (StorePath (spHash, spName))+import Nix.Store.Path (StorePath (spHash, spName), defaultStoreDir, storePathToText)  -- --------------------------------------------------------------------------- -- Construction@@ -61,25 +66,62 @@ contextIsEmpty :: StringContext -> Bool contextIsEmpty (StringContext s) = Set.null s --- | The element of a context upstream names first, in the encoding it--- prints (@NixStringContextElem::to_string@ at 2.24.9): a plain path as--- its base name, all outputs of a derivation as @=@ and the .drv's, one--- output as @!output!@ and the .drv's.  Upstream keeps a context in a--- @std::set@ of a variant ordered plain, all outputs, one output, which--- is not this type's constructor order, so that order is searched here.-firstContextEncoded :: StringContext -> Maybe Text-firstContextEncoded (StringContext elems) =-  encoded . minimumBy (comparing upstreamOrder) <$> NE.nonEmpty (Set.toList elems)+-- | The element of a context upstream names first, as it displays one+-- (@NixStringContextElem::display@ at 2.36.0): a plain path as its store+-- path, all outputs of a derivation as the .drv's store path and+-- @ (deep)@, and one output as the .drv's store path, @^@ and the+-- output.  Upstream keeps a context in a @std::set@ of a variant ordered+-- plain, all outputs, one output, which is not this type's constructor+-- order, so that order is searched here.+firstContextDisplayed :: StringContext -> Maybe Text+firstContextDisplayed (StringContext elems) =+  displayedElement . minimumBy (comparing upstreamOrder) <$> NE.nonEmpty (Set.toList elems)   where-    upstreamOrder element = case element of-      SCPlain sp -> (0 :: Int, sp, T.empty)-      SCAllOutputs sp -> (1, sp, T.empty)-      SCDrvOutput sp output -> (2, sp, output)-    encoded element = case element of+    displayedElement element = case element of+      SCPlain sp -> storePathToText defaultStoreDir sp+      SCAllOutputs sp -> storePathToText defaultStoreDir sp <> " (deep)"+      SCDrvOutput sp output -> storePathToText defaultStoreDir sp <> "^" <> output++-- | A context's elements in the order upstream keeps them+-- ('upstreamOrder').+inUpstreamOrder :: StringContext -> [StringContextElement]+inUpstreamOrder (StringContext elems) = sortOn upstreamOrder (Set.toList elems)++-- | An element in the encoding upstream prints: a plain path as its base+-- name, all outputs of a derivation as @=@ and the .drv's, one output as+-- @!output!@ and the .drv's.+encodedElement :: StringContextElement -> Text+encodedElement element = case element of   SCPlain sp -> baseName sp   SCAllOutputs sp -> "=" <> baseName sp   SCDrvOutput sp output -> "!" <> output <> "!" <> baseName sp+  where     baseName sp = spHash sp <> "-" <> spName sp++-- | What realising a context asks of the store, in upstream's order of+-- its elements ('upstreamOrder'): every path that must be valid, the+-- derivation of each output among them, and each output named.+contextRequest :: StringContext -> ContextRequest+contextRequest (StringContext elems) =+  ContextRequest+    { crPaths = map elementPath ordered,+      crOutputs = [(drv, output) | SCDrvOutput drv output <- ordered]+    }+  where+    ordered = inUpstreamOrder (StringContext elems)+    elementPath element = case element of+      SCPlain sp -> sp+      SCAllOutputs sp -> sp+      SCDrvOutput sp _ -> sp++-- | The position of a context element in upstream's @std::set@ of a+-- variant ordered plain, all outputs, one output, each by its fields,+-- which is not this type's constructor order.+upstreamOrder :: StringContextElement -> (Int, StorePath, Text)+upstreamOrder element = case element of+  SCPlain sp -> (0, sp, T.empty)+  SCAllOutputs sp -> (1, sp, T.empty)+  SCDrvOutput sp output -> (2, sp, output)  -- --------------------------------------------------------------------------- -- Extraction
src/Nix/Eval/EvalFormals.hs view
@@ -5,29 +5,91 @@ -- t'Nix.Expr.Types.Expr').  This avoids circular dependencies: both "Nix.Eval.Types" -- (for 'Nix.Eval.Types.VLambda') and "Nix.Eval.Compile" (for encoding\/decoding) -- import this leaf module.+--+-- Every name here is the t'Symbol' the bytecode and a C lambda hold, as+-- upstream's @Formal@ and @ExprLambda@ hold theirs (nixexpr.hh): a call+-- finds its formals in its argument by symbol, and a name becomes text only+-- where a message or a printed value spells it. module Nix.Eval.EvalFormals   ( EvalFormals (..),     EvalFormal (..),+    FormalDefault (..),+    hasDefault,+    LambdaName (..),+    lambdaNameText,+    lambdaNameSymbol,+    lambdaNameFromSymbol,   ) where  import Data.Text (Text) import Data.Word (Word32)+import Nix.Eval.Symbol (Symbol (..), invalidSymbolId, symbolText) --- | A single formal parameter with an optional default (bytecode index).+-- | A single formal parameter and its default. data EvalFormal = EvalFormal-  { efName :: !Text,-    efDefault :: !(Maybe Word32)+  { efName :: !Symbol,+    efDefault :: !FormalDefault   }   deriving (Eq, Show) +-- | A formal's default, as the compiler decides it.+data FormalDefault+  = -- | None: a call's argument must hold the formal.+    NoDefault+  | -- | The code at a bytecode index, made in the call's frame.+    Default !Word32+  | -- | A variable naming a slot of the call's frame, the code at a+    -- bytecode index, whose cell the formal's slot shares once the frame+    -- is filled, as upstream's @maybeThunk@ shares the cell of a slot it+    -- has filled before the formal's (@ExprVar::maybeThunk@ and+    -- @callFunction@ in eval.cc).+    SharedDefault !Word32+  deriving (Eq, Show)++-- | Whether a call can leave the formal out of its argument.+hasDefault :: FormalDefault -> Bool+hasDefault NoDefault = False+hasDefault (Default _) = True+hasDefault (SharedDefault _) = True++-- | The name a function's call errors give it.  Upstream names a function+-- after the attribute a set or @let@ binds it to, and names a function+-- that is its body the same (@addAttr@ in parser-state.hh, and+-- @ExprLambda::setName@ in nixexpr.cc).  Only a set pattern raises such an+-- error, so only its formals carry the name.+data LambdaName+  = -- | Bound to no static attribute name.+    AnonymousLambda+  | -- | Bound to this attribute name.+    NamedLambda !Symbol+  deriving (Eq, Show)++-- | The name as a call error spells it (@callFunction@ in eval.cc).+lambdaNameText :: LambdaName -> Text+lambdaNameText AnonymousLambda = "anonymous lambda"+lambdaNameText (NamedLambda name) = symbolText name++-- | The symbol a set pattern's bytecode and a C lambda hold for the name:+-- the name's own, or the invalid symbol for an anonymous function, which+-- no name interns to.+lambdaNameSymbol :: LambdaName -> Word32+lambdaNameSymbol AnonymousLambda = invalidSymbolId+lambdaNameSymbol (NamedLambda name) = unSymbol name++-- | The name 'lambdaNameSymbol' stored as a symbol.+lambdaNameFromSymbol :: Word32 -> LambdaName+lambdaNameFromSymbol sid+  | sid == invalidSymbolId = AnonymousLambda+  | otherwise = NamedLambda (Symbol sid)+ -- | Formal parameter specification for a lambda.--- Mirrors 'Nix.Expr.Types.Formals' but with bytecode indices for defaults.+-- Mirrors 'Nix.Expr.Types.Formals' but with each default as compiled. data EvalFormals   = -- | @x: body@ - single named parameter-    EFName !Text+    EFName !Symbol   | -- | @{ a, b, ... }: body@ - destructuring set pattern-    EFSet ![EvalFormal] !Bool+    EFSet !LambdaName ![EvalFormal] !Bool   | -- | @args\@{ a, b, ... }: body@ - named set pattern-    EFNamedSet !Text ![EvalFormal] !Bool+    EFNamedSet !LambdaName !Symbol ![EvalFormal] !Bool   deriving (Eq, Show)
src/Nix/Eval/IO.hs view
@@ -1,1316 +1,1954 @@-{-# LANGUAGE GeneralizedNewtypeDeriving #-}-{-# LANGUAGE LambdaCase #-}-{-# LANGUAGE PatternSynonyms #-}-{-# LANGUAGE ScopedTypeVariables #-}---- | IO-based Nix evaluator.------ Provides t'EvalIO', a concrete 'MonadEval' instance that performs--- real file-system access.  The @import@ builtin reads, parses, and--- evaluates @.nix@ files with a per-process import cache.------ @--- st <- newEvalState "/path/to/project"--- result <- runEvalIO st (eval (builtinEnv unrestrictedPolicy 0 []) expr)--- @-module Nix.Eval.IO-  ( -- * Evaluator-    EvalIO,-    runEvalIO,-    runEvalIOTraced,--    -- * State-    EvalState (..),-    newEvalState,-    allowEvalPath,--    -- * Errors-    EvalErrorKind (..),-    EvalFailure (..),-    renderEvalFailure,-    NixEvalError (..),-    NixAbortError (..),-  )-where--import Control.Exception (Exception, Handler (..), IOException, SomeAsyncException, SomeException, catch, catches, displayException, fromException, onException, throwIO, try)-import Control.Monad (unless, void, when)-import Control.Monad.IO.Class (liftIO)-import Control.Monad.Reader (ReaderT (..), ask, asks, local)-import Crypto.Random (getRandomBytes)-import qualified Data.ByteString as BS-import Data.Either (fromRight, isRight)-import Data.IORef (IORef, modifyIORef', newIORef, readIORef)-import Data.Int (Int64)-import Data.Map.Strict (Map)-import qualified Data.Map.Strict as Map-import Data.Maybe (isJust)-import qualified Data.Set as Set-import Data.Text (Text)-import qualified Data.Text as T-import qualified Data.Text.Encoding as TE-import Data.Time.Clock.POSIX (getPOSIXTime)-import Foreign.Ptr (castPtr)-import Foreign.StablePtr (castPtrToStablePtr, castStablePtrToPtr, deRefStablePtr, freeStablePtr, newStablePtr)-import Nix.Builtins (builtinEnv, builtinEnvWithScope, parseNixPath, rootScopeNames)-import Nix.Derivation (fromATerm)-import Nix.Environment (EnvLookup (..), lookupEnvBytes)-import Nix.Eval (eval)-import Nix.Eval.CList (CList (..))-import Nix.Eval.CStatus (cInvariantViolated)-import Nix.Eval.CThunk (CThunkPtr, cthunkGetAttrs, cthunkGetBcIdx, cthunkGetBool, cthunkGetCtxStr, cthunkGetFloat, cthunkGetInt, cthunkGetLambda, cthunkGetList, cthunkGetPath, cthunkGetStr, cthunkMarkBlackhole, cthunkMarkPending, cthunkPayload, cthunkSetComputed, cthunkSetComputedAttrs, cthunkSetComputedBool, cthunkSetComputedCtxStr, cthunkSetComputedFloat, cthunkSetComputedInt, cthunkSetComputedLambda, cthunkSetComputedList, cthunkSetComputedNull, cthunkSetComputedPath, cthunkSetComputedStr, cthunkState, cthunkValueTag)-import Nix.Eval.CallDepth (CallDepth, defaultMaxCallDepth, enterCallFrame, topLevelCallDepth)-import Nix.Eval.CanonPath (canonBaseName, canonPath, canonPathValue)-import Nix.Eval.Policy (AllowedPaths, EvalPolicy (..), allowPathIn, forbiddenPathMessage, isAbsolutePath, isAllowedPath, isAllowedPrefix, joinComponents, noAllowedPaths, pathComponents, pathsRestricted, unrestrictedPolicy, uriAccess)-import Nix.Eval.SourceError (SourceAccess (..), sourceErrorMessage)-import Nix.Eval.Symbol (Symbol (..), symbolBytes, symbolIntern, symbolInternBytes, symbolText)-import Nix.Eval.Types (AttrSet (..), Env (..), MonadEval (..), NixValue (..), PathExistence (..), Thunk (..), attrSetSize, bytesToTextLossy, emptyContext, marshalLambda, marshalStringContext, storePathOrThrow, unmarshalLambdaValue, unmarshalStringContext, pattern ThunkBlackhole, pattern ThunkComputed, pattern ThunkPending, pattern ValueAttrs, pattern ValueBool, pattern ValueCtxStr, pattern ValueFloat, pattern ValueInt, pattern ValueLambda, pattern ValueList, pattern ValueNull, pattern ValuePath, pattern ValueStr)-import Nix.Expr.Resolve (undefinedVariableMessage)-import Nix.Hash (bytesToHexText, makeFixedOutputPath, makeTextPath, sha256Digest)-import Nix.Parser (SourceError (..), SourceOrigin (..), parseNixWithScope)-import Nix.Store (unpackNarEntry)-import Nix.Store.CaseSensitive (probeCaseSensitivity, processCaseHack, volumeCaseHack)-import qualified Nix.Store.ExecBit as ExecBit-import qualified Nix.Store.Path as SP-import qualified NovaCache.NAR as NAR-import qualified System.Directory as Dir-import System.Exit (ExitCode (..))-import System.FilePath (isAbsolute, isPathSeparator, isRelative, takeDirectory, (</>))-import System.IO (hPutStrLn, stderr)-import qualified System.Process as Proc---- ------------------------------------------------------------------------------ Error type--- ------------------------------------------------------------------------------- | How an eval-time failure interacts with @builtins.tryEval@:--- 'ErrorThrown' (@builtins.throw@, a failed @assert@) is catchable,--- matching upstream's ThrownError\/AssertionError; 'ErrorUncatchable'--- (type errors, missing attributes, IO failures) escapes tryEval like--- every other upstream EvalError.-data EvalErrorKind = ErrorThrown | ErrorUncatchable-  deriving (Eq, Show)---- | A failure's message and the lines of context it gathered unwinding--- ('addErrorTrace'), outermost first: upstream's @ErrorInfo@ message and--- traces, without positions.-data EvalFailure = EvalFailure-  { failureTrace :: ![Text],-    failureMessage :: !Text-  }-  deriving (Eq, Show)---- | A failure with nothing gathered yet.-untracedFailure :: Text -> EvalFailure-untracedFailure = EvalFailure []---- | Evaluation error surfaced as an IO exception.-data NixEvalError = NixEvalError !EvalErrorKind !EvalFailure-  deriving (Show)--instance Exception NixEvalError---- | Abort error - NOT catchable by tryEval (matches real Nix semantics).-newtype NixAbortError = NixAbortError EvalFailure-  deriving (Show)--instance Exception NixAbortError---- | A failure as upstream's @showErrorInfo@ prints it (error.cc at--- 2.24.9) when no line has a position: each line of context after an--- ellipsis and a blank line, then the message after an @error:@ of its--- own.  The report is upstream's @indent@: the first line follows--- @error: @, every later line is indented to align with it, and each line--- loses its trailing whitespace.-renderEvalFailure :: EvalFailure -> Text-renderEvalFailure (EvalFailure trace msg) =-  T.intercalate "\n" (zipWith indentLine (errorPrefix : repeat continuation) (T.splitOn "\n" (chomp report)))-  where-    report = foldMap traceLine trace <> (if null trace then "" else "\n" <> errorPrefix) <> msg-    traceLine line = "\n\x2026 " <> line <> "\n"-    indentLine prefix line = chomp (prefix <> line)-    continuation = T.replicate (T.length errorPrefix) " "-    chomp = T.dropWhileEnd (`elem` [' ', '\n', '\r', '\t'])---- | What upstream prints before an error's message.-errorPrefix :: Text-errorPrefix = "error: "---- ------------------------------------------------------------------------------ State--- ------------------------------------------------------------------------------- | Shared state for IO evaluation.------ 'esImportCache' is a shared mutable cache (global across all frames).--- Single-threaded only - switch to @MVar@ or @TVar@ if concurrent--- evaluation is ever added.------ 'esBaseDir' is immutable per frame - @import@ uses 'local' to set it--- for nested evaluations, so it is exception-safe with no save\/restore.------ 'esSearchPaths' holds parsed @NIX_PATH@ entries as thunks, populating--- @builtins.nixPath@.-data EvalState = EvalState-  { esImportCache :: !(IORef (Map FilePath NixValue)),-    -- | Cache of derivation modulo-hashes (drv store path to hex), populated-    -- bottom-up by @builtinDerivationStrict@ so input derivations can be-    -- substituted by their content hashes when computing output paths.-    esDrvModuloCache :: !(IORef (Map Text Text)),-    -- | Accumulated @.drv@ closure (drv store path text to its ATerm bytes),-    -- recorded bottom-up by @builtinDerivationStrict@.  The build driver reads-    -- this after evaluation to write every input @.drv@ to the store before-    -- building.-    esDrvClosure :: !(IORef (Map Text BS.ByteString)),-    -- | Cache of source path to its store path (recursive NAR hash), so a path-    -- literal used across many derivations is hashed only once.-    esSourcePathCache :: !(IORef (Map Text Text)),-    -- | Every store object evaluation wrote (store path to its-    -- references), for the build driver to register before building --    -- eval has no store DB handle.  All of them, not only-    -- @builtins.toFile@: an unrecorded write reaches @drvInputSrcs@ as-    -- an unregistered path and fails the build that names it.-    esStoreWriteCache :: !(IORef (Map Text ([SP.StorePath], SP.StoreWriteMode))),-    esBaseDir :: !FilePath,-    -- | Where store objects live on this machine, so eval's own reads and-    -- writes honor @--store@ the same way the builder does.-    esStoreDir :: !SP.StoreDir,-    esTimestamp :: !Int64,-    esSearchPaths :: ![Thunk],-    -- | The call frames active around the current evaluation and the-    -- @max-call-depth@ ceiling.  Per frame like 'esBaseDir':-    -- 'withCallFrame' scopes it with 'local', so a failure unwinding-    -- through a frame leaves the count it found, upstream's RAII guard-    -- with nothing to restore.-    esCallDepth :: !CallDepth,-    -- | What this evaluation may reach: upstream's @restrict-eval@ and-    -- @pure-eval@ settings and the @allowed-uris@ list, and its-    -- @trace-verbose@ setting.  Unrestricted unless the caller says-    -- otherwise, as upstream's defaults are.-    esPolicy :: !EvalPolicy,-    -- | The allowed path prefixes under a restricting policy: the search-    -- path roots the caller seeded with 'allowEvalPath', plus every store-    -- object this evaluation copies, fetches or writes (upstream's-    -- @allowPath@ after each such step), plus the fetchers' scratch-    -- directories.  Mutable because it grows as evaluation proceeds, like-    -- the import cache.-    esAllowedPaths :: !(IORef AllowedPaths)-  }---- | Create a fresh evaluation state rooted at the given directory, reading--- and writing store objects under the given store directory.--- Reads @NIX_PATH@ from the environment to populate search paths, its--- bytes unchanged, as upstream's @initGC@ reads it--- (src/libexpr/eval-gc.cc at Nix 2.24.9).  The one refusal is a Windows--- @NIX_PATH@ holding an unpaired UTF-16 surrogate, which has no UTF-8--- form and raises an 'IOException'.  The call-depth ceiling starts at--- upstream's default; a caller with a configured one replaces--- 'esCallDepth'.------ The state is unrestricted.  A restricting policy is set on 'esPolicy',--- and the roots it should admit are seeded with 'allowEvalPath' before--- evaluation starts, as upstream's constructor allows its lookup path.-newEvalState :: SP.StoreDir -> FilePath -> IO EvalState-newEvalState storeDir baseDir = do-  cache <- newIORef Map.empty-  drvCache <- newIORef Map.empty-  drvClosure <- newIORef Map.empty-  srcCache <- newIORef Map.empty-  storeWriteCache <- newIORef Map.empty-  allowedPaths <- newIORef noAllowedPaths-  now <- floor <$> getPOSIXTime :: IO Int64-  nixPath <- lookupEnvBytes nixPathVar-  searchPaths <- case nixPath of-    EnvUnset -> pure []-    EnvValue value -> pure (parseNixPath value)-    EnvUnpairedSurrogate ->-      ioError (userError "NIX_PATH holds an unpaired UTF-16 surrogate, which has no UTF-8 form")-  pure-    EvalState-      { esImportCache = cache,-        esDrvModuloCache = drvCache,-        esDrvClosure = drvClosure,-        esSourcePathCache = srcCache,-        esStoreWriteCache = storeWriteCache,-        esBaseDir = baseDir,-        esStoreDir = storeDir,-        esTimestamp = now,-        esSearchPaths = searchPaths,-        esCallDepth = topLevelCallDepth defaultMaxCallDepth,-        esPolicy = unrestrictedPolicy,-        esAllowedPaths = allowedPaths-      }---- | Grant access to a path prefix (upstream @EvalState::allowPath@): the--- caller seeds the search path roots before evaluation, and the instance--- adds every store object the evaluation produces.  Like upstream's, this--- is a no-op when nothing restricts access, so an unrestricted evaluation--- does not accumulate a set it never consults.  The prefix is allowed on--- the drive its reads open ('locatedPath'), the form every check uses.-allowEvalPath :: EvalState -> Text -> IO ()-allowEvalPath st path =-  when (pathsRestricted (esPolicy st)) $-    modifyIORef' (esAllowedPaths st) (allowPathIn (locatedPath st path))---- | Path-value text as the policy checks it: canonical, and on the drive--- this evaluation's store directory puts it on ('SP.qualifyPathText'),--- so a check and the read it guards ('evalStoreTextPath') name one file.-locatedPath :: EvalState -> Text -> Text-locatedPath st = SP.qualifyPathText (esStoreDir st) . canonPathValue---- ------------------------------------------------------------------------------ EvalIO newtype--- ------------------------------------------------------------------------------- | IO evaluation monad.  Wraps @ReaderT EvalState IO@.-newtype EvalIO a = EvalIO {unEvalIO :: ReaderT EvalState IO a}-  deriving (Functor, Applicative, Monad)---- ------------------------------------------------------------------------------ MonadEval instance--- -----------------------------------------------------------------------------instance MonadEval EvalIO where-  throwEvalError msg = EvalIO (liftIO (throwIO (NixEvalError ErrorUncatchable (untracedFailure msg))))-  throwCatchableError msg = EvalIO (liftIO (throwIO (NixEvalError ErrorThrown (untracedFailure msg))))-  abortEvaluation msg = EvalIO (liftIO (throwIO (NixAbortError (untracedFailure msg))))--  -- tryEval semantics: recover from a throw/assert only; an uncatchable-  -- eval error is rethrown (aborts are a separate exception type and-  -- never enter the 'try').-  catchEvalError (EvalIO action) = EvalIO $ do-    st <- ask-    result <- liftIO (try (runReaderT action st))-    case result of-      Left (NixEvalError ErrorThrown failure) -> pure (Left (failureMessage failure))-      Left err@(NixEvalError ErrorUncatchable _) -> liftIO (throwIO err)-      Right val -> pure (Right val)--  -- Over IO exceptions, so eval errors, aborts, and IO failures-  -- crossing 'wrapIO' all trigger the cleanup before propagating.-  onEvalError (EvalIO action) (EvalIO cleanup) = EvalIO $ do-    st <- ask-    liftIO (runReaderT action st `onException` runReaderT cleanup st)--  addErrorTrace line (EvalIO action) = EvalIO $ do-    st <- ask-    liftIO-      ( runReaderT action st-          `catches` [ Handler (\(NixEvalError kind failure) -> throwIO (NixEvalError kind (traced failure))),-                      Handler (\(NixAbortError failure) -> throwIO (NixAbortError (traced failure)))-                    ]-      )-    where-      traced (EvalFailure trace msg) = EvalFailure (line : trace) msg--  withCallFrame (EvalIO action) = EvalIO $ do-    depth <- asks esCallDepth-    either-      (unEvalIO . throwEvalError)-      (\deeper -> local (\s -> s {esCallDepth = deeper}) action)-      (enterCallFrame depth)--  -- A refused path reads as absent, as upstream's pathExists turns a-  -- RestrictedPathError into false.  The query decides the walk and the-  -- stat as prim_pathExists does: a plain path is resolved through its-  -- ancestors only and lstat'ed in place, so a symlink exists whatever-  -- it points at; a path that must be a directory is resolved fully and-  -- must stat as one.-  doesPathExist query path = do-    allowed <- pathAllowed (existenceResolution query) path-    if allowed-      then evalStoreTextPath path >>= \resolved -> wrapIO (existsAs query resolved)-      else pure False--  listDirectory path = do-    accessPath path-    dir <- evalStoreTextPath path-    sourceIOWith ReadDirectory (resolvedForMessage path dir) $ do-      entries <- Dir.listDirectory dir-      mapM (classifyEntry dir) entries--  importFile rawPath = do-    baseDir <- EvalIO (asks esBaseDir)-    timestamp <- EvalIO (asks esTimestamp)-    searchPaths <- EvalIO (asks esSearchPaths)-    policy <- EvalIO (asks esPolicy)-    -- Resolved, and so checked, before the cache is consulted, as-    -- upstream resolves the file before its fileEvalCache lookup: a-    -- cached import is no more readable than a fresh one.-    (target, ioTarget) <- resolveImportTarget baseDir rawPath-    -- Check import cache (readIORef cannot throw, no wrapIO needed)-    cacheRef <- EvalIO (asks esImportCache)-    cache <- EvalIO (liftIO (readIORef cacheRef))-    case Map.lookup target cache of-      Just cached -> pure cached-      Nothing -> do-        source <- sourceIO ReadFile (T.pack target) (BS.readFile ioTarget)-        let fileDir = takeDirectory target-        case parseNixWithScope (rootScopeNames policy) fileDir (SourceFile (T.pack target)) source of-          Left err -> rejectSource "import" target err-          Right expr -> do-            -- local sets new base dir for nested imports - pure, exception-safe-            let nested =-                  EvalIO-                    ( local-                        (\s -> s {esBaseDir = fileDir})-                        (unEvalIO (eval (builtinEnv policy timestamp searchPaths) expr))-                    )-            result <- nested-            -- Skip caching very large attr sets (e.g. all-packages.nix-            -- with 30k+ entries) so GC can reclaim them.  nixpkgs only-            -- imports all-packages.nix once at the top level, so skipping-            -- the cache for it has zero performance cost.-            let shouldCache = case result of-                  VAttrs attrs -> attrSetSize attrs < importCacheMaxAttrs-                  _ -> True-            when shouldCache $-              wrapIO (modifyIORef' cacheRef (Map.insert target result))-            pure result--  -- Upstream's getEnv answers empty under either setting-  -- (@prim_getEnv@: @restrictEval || pureEval ? "" : getEnv(name)@).-  -- The read cannot throw, so it needs no wrapIO.-  getEnvVar name = do-    policy <- EvalIO (asks esPolicy)-    if pathsRestricted policy-      then pure BS.empty-      else do-        found <- EvalIO (liftIO (lookupEnvBytes name))-        case found of-          EnvUnset -> pure BS.empty-          EnvValue value -> pure value-          EnvUnpairedSurrogate ->-            throwEvalError ("builtins.getEnv: the value of '" <> bytesToTextLossy name <> "' holds an unpaired UTF-16 surrogate, which has no UTF-8 form")--  lookupDrvHash key = EvalIO $ do-    ref <- asks esDrvModuloCache-    liftIO (Map.lookup key <$> readIORef ref)--  cacheDrvHash key val = EvalIO $ do-    ref <- asks esDrvModuloCache-    liftIO (modifyIORef' ref (Map.insert key val))--  recordDrvAterm key aterm = EvalIO $ do-    ref <- asks esDrvClosure-    liftIO (modifyIORef' ref (Map.insert key aterm))--  -- Read a .drv from the store on a modulo-hash cache miss (a cross-session or-  -- appendContext reference).  Mirrors the build side's readDrvFromStore: map-  -- to the on-disk path, read the raw bytes, parse the ATerm byte-level (env-  -- values keep arbitrary bytes).  A file that cannot be read or does not-  -- parse is 'Nothing', which the caller turns into a loud modulo-hash error.-  readStoreDerivation sp = EvalIO $ do-    filePath <- asks ((`storeFilePath` sp) . esStoreDir)-    result <- liftIO (try (BS.readFile filePath) :: IO (Either IOException BS.ByteString))-    pure $ case result of-      Left _ -> Nothing-      Right bytes -> either (const Nothing) Just (fromATerm bytes)--  -- Look up a derivation recorded earlier this session by its .drv path,-  -- reusing the esDrvClosure ATerm map (populated bottom-up by recordDrvAterm).-  -- This recovers an in-session all-outputs reference's output names without a-  -- disk read - the .drv is not written to the store until after evaluation.-  lookupSessionDrv drvPathText = EvalIO $ do-    ref <- asks esDrvClosure-    closure <- liftIO (readIORef ref)-    pure (Map.lookup drvPathText closure >>= either (const Nothing) Just . fromATerm)--  lookupSessionReferences sp = EvalIO $ do-    ref <- asks esStoreWriteCache-    writes <- liftIO (readIORef ref)-    pure (fst <$> Map.lookup (canonicalStorePathText sp) writes)--  storeSourcePath rawPath = do-    ref <- EvalIO (asks esSourcePathCache)-    cached <- EvalIO (liftIO (Map.lookup rawPath <$> readIORef ref))-    case cached of-      Just hit -> pure hit-      Nothing -> do-        -- Upstream names the copy baseNameOf(canonicalized path); path-        -- values arrive canonicalized, so the last segment is the name.-        -- A root, which has none, is refused before its tree is read.-        -- A name the store-path rules refuse is refused only once the tree-        -- is hashed, as upstream's is: the refusal names the path the copy-        -- would have had.-        let name = canonBaseName rawPath-        when (T.null name) $-          throwEvalError ("cannot copy '" <> rawPath <> "' to the store: the path has no base name")-        accessPath rawPath-        -- The tree behind the path's symlinks, under the path's own name:-        -- upstream's copyPathToStore stores path.resolveSymlinks() under-        -- path.baseName() (eval.cc:2393 at 2.24.9), so a path that is a-        -- link copies what it points to, not the link.-        resolvedText <- resolveSymlinks rawPath-        resolvedSource <- evalStoreTextPath resolvedText-        -- A path already in the store never reaches here (it coerces to-        -- itself), so this is a source, read as the build driver's-        -- restore reads it again.-        entry <- serialiseSource resolvedText processCaseHack resolvedSource-        let narDigest = sha256Digest (NAR.serialise entry)-        sp <- storePathOrThrow (makeFixedOutputPath name "sha256" "recursive" narDigest)-        let spText = canonicalStorePathText sp-        EvalIO (liftIO (modifyIORef' ref (Map.insert rawPath spText)))-        -- The copy is readable afterwards, as upstream's copyPathToStore-        -- allows its destination.-        allowPath spText-        pure spText--  getCurrentTime = EvalIO (asks esTimestamp)--  writeToStore name contents refs = do-    -- Upstream's text-path scheme via makeTextPath - the same scheme .drv-    -- paths use, so it is parity-validated: type @text:<refs>@, flat-    -- sha256 of the contents, canonical store dir.  Construction also-    -- validates the name, so the write below never targets a path-    -- outside the store root.  The contents are the string's RAW BYTES,-    -- hashed and written as-is: no encoding step, and no text-mode IO-    -- (which would CRLF-translate on Windows and store bytes that no-    -- longer match the hash that named the path).-    sp <- storePathOrThrow (makeTextPath name (sha256Digest contents) refs)-    filePath <- evalFilePath sp-    let storePath = canonicalStorePathText sp-    wrapIO $ do-      Dir.createDirectoryIfMissing True (takeDirectory filePath)-      -- Adopt an existing file only when its bytes are these bytes: an-      -- interrupted earlier run can leave a truncated file here, and-      -- skipping on bare existence adopted it under this path's hash.-      -- 'Dir.removePathForcibly' clears read-only marks and accepts a-      -- missing path, so a sealed or squatting leftover rewrites too.-      existing <- readBytesIfPresent filePath-      unless (existing == Just contents) $ do-        Dir.removePathForcibly filePath-        BS.writeFile filePath contents-    recordStoreWrite storePath refs SP.WriteText-    -- Upstream's toFile returns the path through allowAndSetStorePathString.-    allowPath storePath-    pure storePath--  scopedImportFile scope rawPath = do-    baseDir <- EvalIO (asks esBaseDir)-    timestamp <- EvalIO (asks esTimestamp)-    searchPaths <- EvalIO (asks esSearchPaths)-    policy <- EvalIO (asks esPolicy)-    (target, ioTarget) <- resolveImportTarget baseDir rawPath-    source <- sourceIO ReadFile (T.pack target) (BS.readFile ioTarget)-    let fileDir = takeDirectory target-    case parseNixWithScope (Set.union (Set.fromList (map fst scope)) (rootScopeNames policy)) fileDir (SourceFile (T.pack target)) source of-      Left err -> rejectSource "scopedImport" target err-      Right expr -> do-        -- No import cache for scoped imports (different scopes = different results)-        let scopedEnv = builtinEnvWithScope policy timestamp searchPaths scope-        EvalIO-          ( local-              (\s -> s {esBaseDir = fileDir})-              (unEvalIO (eval scopedEnv expr))-          )--  readFileBytes path = do-    accessPath path-    evalStoreTextPath path >>= \resolved -> sourceIOWith ReadFile (resolvedForMessage path resolved) (BS.readFile resolved)--  -- An lstat of the path itself, no symlink walk: upstream's readFileType-  -- realises its argument without resolution, the allow list checks the-  -- path it is handed (so a refusal names the path asked for), and the-  -- posix accessor beneath refuses a symlink anywhere above it, in every-  -- mode, so the type of a path reached through a symlinked directory is-  -- never revealed.-  getFileType path = do-    accessPathDirect path-    refuseSymlinkedAncestor path-    evalStoreTextPath path >>= \resolved -> sourceIO StatPath path (classifyPath resolved)--  runProcess cmd cmdArgs stdinText = wrapIO $ do-    let cp =-          (Proc.proc (T.unpack cmd) (map T.unpack cmdArgs))-            { Proc.std_in = Proc.CreatePipe,-              Proc.std_out = Proc.CreatePipe,-              Proc.std_err = Proc.CreatePipe-            }-    (exitCode, stdoutStr, stderrStr) <--      Proc.readCreateProcessWithExitCode cp (T.unpack stdinText)-    let code = case exitCode of-          ExitSuccess -> 0-          ExitFailure n -> n-    pure (code, T.pack stdoutStr, T.pack stderrStr)--  createScratchDir prefix = do-    dir <- wrapIO $ do-      tmpBase <- Dir.getTemporaryDirectory-      suffix <- getRandomBytes scratchSuffixBytes-      -- Forward-slash join: the scratch path feeds sh pipelines (tar -C)-      -- and store copies, both of which accept '/' on every host.-      let dir = tmpBase <> "/" <> T.unpack (prefix <> bytesToHexText suffix)-      -- createDirectory is exclusive: an already-existing path fails the-      -- fetch rather than being silently adopted.-      Dir.createDirectory dir-      pure (T.pack dir)-    -- The evaluator's own scratch area, not ambient filesystem: what a-    -- fetch lands there is read back under the same rule that makes a-    -- fetched store path readable afterwards.  Allowed under its resolved-    -- spelling too, because the walk follows symlinks and a temp dir can-    -- sit behind one (macOS's /var is /private/var), and under the given-    -- spelling so the walk may traverse the link's own ancestors.-    resolved <- wrapIO (Dir.canonicalizePath (T.unpack dir))-    allowPath dir-    allowPath (T.pack resolved)-    pure dir--  removeScratchDir dir = wrapIO (Dir.removePathForcibly (T.unpack dir))--  copyPathToStore srcPath name expectedSha256 = do-    -- Content-addressed like upstream addToStore: recursive NAR sha256-    -- under the caller's name.  Same content means same path, so the-    -- existence check in 'unpackToStoreVerified' is sound: changed source-    -- content can never serve stale bytes from an earlier copy.-    -- The tree behind the root's symlinks, under the root's own name, as-    -- upstream's copyPathToStore and addPath store path.resolveSymlinks()-    -- under path.baseName(); the walk checks the policy on the way.-    resolvedText <- resolveSymlinks srcPath-    caseHack <- readCaseHack resolvedText-    resolvedSource <- evalStoreTextPath resolvedText-    entry <- serialiseSource resolvedText caseHack resolvedSource-    let narDigest = sha256Digest (NAR.serialise entry)-    case expectedSha256 of-      Just (subject, expected)-        | expected /= narDigest ->-            throwEvalError-              ( subject-                  <> ": hash mismatch: expected sha256:"-                  <> bytesToHexText expected-                  <> ", got sha256:"-                  <> bytesToHexText narDigest-              )-      _ -> pure ()-    -- The name is refused only once the tree is hashed, as upstream's is:-    -- the refusal names the path the copy would have had.-    sp <- storePathOrThrow (makeFixedOutputPath name "sha256" "recursive" narDigest)-    destFilePath <- evalFilePath sp-    let destPath = canonicalStorePathText sp-    -- Restored from the entry just hashed, not copied from the source:-    -- the store's volume may fold a pair the source's keeps apart, and-    -- the tree that lands is exactly the one the address names.-    wrapIO (unpackToStoreVerified destFilePath entry narDigest) >>= either throwEvalError pure-    recordStoreWrite destPath [] SP.WriteRecursive-    allowPath destPath-    pure destPath--  narHashOfPath path = do-    accessPath path-    caseHack <- readCaseHack path-    resolved <- evalStoreTextPath path-    wrapIO (sha256Digest . NAR.serialise <$> ExecBit.serialiseFromPath caseHack resolved)--  isExecutableFile path = do-    accessPath path-    evalStoreTextPath path >>= \resolved -> wrapIO (ExecBit.isExecutable resolved)--  setExecutableFile path = do-    accessPath path-    evalStoreTextPath path >>= \resolved -> wrapIO (ExecBit.markExecutable resolved)--  lookupFetchCache key = wrapIO $ do-    file <- fetchCacheFile key-    there <- Dir.doesFileExist file-    if not there-      then pure Nothing-      else do-        recorded <- try (BS.readFile file) :: IO (Either IOException BS.ByteString)-        pure $ case recorded of-          Left _ -> Nothing-          Right bytes -> either (const Nothing) Just (TE.decodeUtf8' bytes)--  adoptStorePath path = do-    resolved <- evalStoreTextPath path-    there <- wrapIO (Dir.doesPathExist resolved)-    -- Same recording the uncached fetch's copyPathToStore would have done.-    -- materializeEvalStoreWrites skips a path that is already valid, so-    -- re-recording one costs nothing and closes the case where the row is-    -- missing.-    when there $ do-      recordStoreWrite path [] SP.WriteRecursive-      -- A fetch result, whether fetched now or remembered: upstream-      -- allows the store path every fetcher returns.-      allowPath path-    pure there--  writeFetchCache key value = wrapIO $ do-    file <- fetchCacheFile key-    -- The cache is an optimisation: a machine that cannot write one still-    -- has to be able to build.-    _ <--      try-        ( do-            Dir.createDirectoryIfMissing True (takeDirectory file)-            -- Written beside the entry and renamed onto it, so a reader-            -- sees either the whole entry or none of it. A plain write can-            -- be cut short and leave a torn file behind, and an entry is-            -- trusted for as long as its store path survives.-            let staging = file ++ ".tmp"-            BS.writeFile staging (TE.encodeUtf8 value)-            Dir.renameFile staging file-        ) ::-        IO (Either IOException ())-    pure ()--  -- The two checks of getFileType: upstream's readLink asserts no-  -- symlink above the path it is handed as well.-  readSymlinkTarget path = do-    accessPathDirect path-    refuseSymlinkedAncestor path-    evalStoreTextPath path >>= \resolved -> wrapIO (T.pack <$> Dir.getSymbolicLinkTarget resolved)--  addSourceNar name narBytes =-    case NAR.deserialise narBytes of-      -- Unreachable in practice: the bytes come from NAR.serialise of a-      -- tree this process just built.  Kept total for the FFI-adjacent-      -- boundary rather than trusting the round trip.-      Left err -> throwEvalError ("builtins.path: internal NAR round-trip error: " <> T.pack err)-      Right entry -> do-        sp <- storePathOrThrow (makeFixedOutputPath name "sha256" "recursive" (sha256Digest narBytes))-        destFilePath <- evalFilePath sp-        let destPath = canonicalStorePathText sp-        -- Raised here rather than inside 'wrapIO', which would render-        -- the refusal through an exception's own text ("user error (...)").-        wrapIO (unpackToStoreVerified destFilePath entry (sha256Digest narBytes)) >>= either throwEvalError pure-        recordStoreWrite destPath [] SP.WriteRecursive-        allowPath destPath-        pure destPath--  addFixedOutputFile name bytes = do-    -- Canonical fixed-output path: a sha256-pinned fetch must land at the same-    -- store path C++ Nix computes, so it stays reproducible and cache-compatible.-    sp <- storePathOrThrow (makeFixedOutputPath name "sha256" "flat" (sha256Digest bytes))-    filePath <- evalFilePath sp-    let storePath = canonicalStorePathText sp-    wrapIO $ do-      Dir.createDirectoryIfMissing True (takeDirectory filePath)-      -- Same verified adoption as the other writers: this one used to-      -- write unconditionally, which both adopted nothing (fine) and-      -- crashed on a sealed leftover (the write hits read-only).-      existing <- readBytesIfPresent filePath-      unless (existing == Just bytes) $ do-        Dir.removePathForcibly filePath-        BS.writeFile filePath bytes-    recordStoreWrite storePath [] SP.WriteFlat-    allowPath storePath-    pure storePath--  traceMessage msg = EvalIO (liftIO (hPutStrLn stderr (T.unpack msg)))--  evalPolicy = EvalIO (asks esPolicy)--  checkUri uri = do-    st <- EvalIO ask-    allowed <- EvalIO (liftIO (readIORef (esAllowedPaths st)))-    either throwEvalError pure (uriAccess (esStoreDir st) (esPolicy st) allowed uri)--  qualifyPath path = EvalIO (asks ((`SP.qualifyPathText` path) . esStoreDir))--  -- Store text stays canonical in the value domain, as it does for an-  -- import target ('resolveImportTarget' says why); every other path-  -- resolves as the platform path it opens, the policy walk having-  -- followed the same links first.-  resolveSymlinks path = do-    accessPath path-    if SP.isCanonicalStoreText path-      then pure (canonPath path)-      else evalStoreTextPath path >>= \native -> wrapIO (canonPathValue . T.pack <$> Dir.canonicalizePath native)--  resolvePathLiteral path = do-    baseDir <- EvalIO (asks esBaseDir)-    policy <- EvalIO (asks esPolicy)-    -- ~/x resolves against the home directory (upstream lexes HPATH and-    -- expands it at eval); everything else relative joins the base dir.-    -- Both end at the producer gate ('canonPathValue'): the value is-    -- absolute, lexically canonical, and slash-spelled regardless of-    -- the base dir's native spelling - platform separators exist only-    -- at the filesystem boundary.  Under pure-eval the home directory is-    -- ambient state, and upstream's parser refuses the literal outright-    -- (parser.y, the HPATH rule); the same refusal lands here, where the-    -- expansion is.-    expanded <- case T.stripPrefix "~/" path of-      Just below-        | epPureEval policy ->-            throwEvalError ("the path '" <> path <> "' can not be resolved in pure mode")-        | otherwise -> do-            home <- wrapIO Dir.getHomeDirectory-            pure (home </> T.unpack below)-      Nothing -> pure (T.unpack path)-    let absolute = if isRelative expanded then baseDir </> expanded else expanded-    pure (canonPathValue (T.pack absolute))--  forceThunk evalFn (Thunk ptr) = do-    -- Force protocol: PENDING to BLACKHOLE to COMPUTED with memoization.-    -- Scalar values (int/float/bool/null) are stored inline in the-    -- thunk payload (no StablePtr), dispatched via val_tag.-    ---    -- Blackhole detection: PENDING thunks are marked BLACKHOLE before-    -- evaluation begins.  If evaluation re-enters the same thunk, it-    -- sees BLACKHOLE and reports infinite recursion.  This is safe with-    -- knot-tying (evalRecAttrs, evalLet, matchFormalSet) because those-    -- patterns create distinct thunks sharing an env - no thunk ever-    -- forces itself.-    state <- EvalIO (liftIO (cthunkState ptr))-    case state of-      ThunkComputed ->-        EvalIO (liftIO (readComputed ptr))-      ThunkBlackhole ->-        -- Infinite recursion is non-catchable (like abort), matching C++ Nix.-        -- tryEval must NOT catch blackholes - using abortEvaluation ensures-        -- the error propagates through tryEval/catchEvalError.-        abortEvaluation "infinite recursion encountered"-      ThunkPending -> do-        -- Bytecode thunks: read bc_idx + StablePtr Env.-        -- The Expr is gone (replaced by bc_idx in the struct).-        -- The Env is still a StablePtr (for knot-tying laziness).-        bcIdx <- EvalIO (liftIO (cthunkGetBcIdx ptr))-        envSp <- EvalIO (liftIO (cthunkPayload ptr))-        let pendingSp = castPtrToStablePtr envSp-        env <- EvalIO (liftIO (deRefStablePtr pendingSp))-        -- Mark blackhole BEFORE evaluation - any re-entry hits the-        -- BLACKHOLE branch above.-        EvalIO . liftIO $ do-          marked <- cthunkMarkBlackhole ptr-          unless marked (cInvariantViolated "nn_thunk_mark_blackhole" "a thunk read as PENDING was not PENDING")-        -- If the force throws (a builtins.throw caught by an upstream tryEval,-        -- a type error, a failed import), restore the thunk to PENDING and-        -- rethrow, so a later force of this shared thunk re-evaluates instead of-        -- taking the BLACKHOLE branch above and aborting with a bogus "infinite-        -- recursion".  Mirrors C++ Nix forceValue: catch (...) { restore; throw }.-        -- A genuine self-recursion still rethrows its NixAbortError, which-        -- escapes tryEval exactly as before.  Storing the value is inside the-        -- restore too, since interning or marshalling it can fail.  The-        -- restore's own answer is not needed: it refuses only a thunk that is-        -- no longer BLACKHOLE, which a later force already handles, and the-        -- exception in flight is the one to report.-        val <- EvalIO $ do-          st <- ask-          liftIO-            ( ( do-                  result <- runReaderT (unEvalIO (evalFn env bcIdx)) st-                  storeComputed ptr result-                  pure result-              )-                `onException` cthunkMarkPending ptr-            )-        -- The value is stored, so nothing reads the pending env again.-        EvalIO (liftIO (freeStablePtr pendingSp))-        pure val-      other ->-        EvalIO (liftIO (cInvariantViolated "nn_thunk_state" ("no thunk has state " ++ show other)))---- | Store a forced thunk's NixValue in its C cell.--- Scalars (int, float, bool, null) are stored inline (no StablePtr).--- Complex values use StablePtr.  The cell is BLACKHOLE while its force--- runs, which keeps every other path from computing it, so a setter's--- refusal is an invariant violation rather than a value to drop.-storeComputed :: CThunkPtr -> NixValue -> IO ()-storeComputed ptr val = do-  stored <- case val of-    VInt n -> cthunkSetComputedInt ptr n-    VFloat d -> cthunkSetComputedFloat ptr d-    VBool b -> cthunkSetComputedBool ptr (if b then 1 else 0)-    VNull -> cthunkSetComputedNull ptr-    VAttrs (AttrSet cset) -> cthunkSetComputedAttrs ptr (castPtr cset)-    VPath p -> do-      Symbol sym <- symbolIntern p-      cthunkSetComputedPath ptr sym-    VStr t ctx-      | ctx == emptyContext -> do-          Symbol sym <- symbolInternBytes t-          cthunkSetComputedStr ptr sym-      | otherwise -> do-          csptr <- marshalStringContext t ctx-          cthunkSetComputedCtxStr ptr (castPtr csptr)-    VList (CList clistPtr) -> cthunkSetComputedList ptr (castPtr clistPtr)-    VLambda (Env envPtr) formals bodyBcIdx -> do-      lamPtr <- marshalLambda envPtr formals bodyBcIdx-      cthunkSetComputedLambda ptr lamPtr-    _ -> do-      valSp <- newStablePtr val-      kept <- cthunkSetComputed ptr (castStablePtrToPtr valSp)-      unless kept (freeStablePtr valSp)-      pure kept-  unless stored (cInvariantViolated "nn_thunk_set_computed" "a thunk being forced was already COMPUTED")---- | Read a computed NixValue from a C thunk.--- Dispatches on val_tag: scalars are read inline, complex via StablePtr.-readComputed :: CThunkPtr -> IO NixValue-readComputed ptr = do-  tag <- cthunkValueTag ptr-  case tag of-    ValueInt -> VInt <$> cthunkGetInt ptr-    ValueFloat -> VFloat <$> cthunkGetFloat ptr-    ValueBool -> (\b -> VBool (b /= 0)) <$> cthunkGetBool ptr-    ValueNull -> pure VNull-    ValueStr -> do-      sym <- cthunkGetStr ptr-      pure (VStr (symbolBytes (Symbol sym)) emptyContext)-    ValuePath -> VPath . symbolText . Symbol <$> cthunkGetPath ptr-    ValueList -> do-      listPtr <- cthunkGetList ptr-      pure (VList (CList (castPtr listPtr)))-    ValueAttrs -> VAttrs . AttrSet . castPtr <$> cthunkGetAttrs ptr-    ValueCtxStr -> do-      csptr <- cthunkGetCtxStr ptr-      uncurry VStr <$> unmarshalStringContext (castPtr csptr)-    ValueLambda -> do-      lamPtr <- cthunkGetLambda ptr-      unmarshalLambdaValue lamPtr-    _ {- PTR -} -> do-      payloadPtr <- cthunkPayload ptr-      deRefStablePtr (castPtrToStablePtr payloadPtr)---- ------------------------------------------------------------------------------ Constants--- ------------------------------------------------------------------------------- | Maximum attribute set size for import caching.  Results larger than this--- are not cached, allowing GC to reclaim them.  Prevents the import cache--- from retaining huge attr sets like nixpkgs' 30k-entry all-packages.nix.-importCacheMaxAttrs :: Int-importCacheMaxAttrs = 1000---- | The variable upstream reads its lookup path from.-nixPathVar :: BS.ByteString-nixPathVar = "NIX_PATH"---- | Random bytes in a scratch-dir name suffix (hex-encoded).  128 bits:--- unguessable by another local process, collision-free in practice.-scratchSuffixBytes :: Int-scratchSuffixBytes = 16---- ------------------------------------------------------------------------------ Helpers--- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------ Access policy--- ------------------------------------------------------------------------------- | Admit a store object this evaluation produced (upstream's @allowPath@--- after a copy, fetch or write).-allowPath :: Text -> EvalIO ()-allowPath path = do-  st <- EvalIO ask-  EvalIO (liftIO (allowEvalPath st path))---- | Refuse a read unless the whole path, symlinks resolved, lies in the--- allowed prefixes.  Upstream's accessor checks every prefix as its--- symlink walk pushes it (@SourceAccessor::resolveSymlinks@ through--- @FilteringSourceAccessor::maybeLstat@, which throws at 2.24.9), so the--- refusal names the first prefix outside the allow list - @/etc@ for--- @/etc/passwd@ when nothing under @/etc@ is allowed - and a symlink's--- target is checked where the walk follows it.  A no-op when nothing--- restricts access.-accessPath :: Text -> EvalIO ()-accessPath path = do-  st <- EvalIO ask-  when (pathsRestricted (esPolicy st)) $ do-    allowed <- EvalIO (liftIO (readIORef (esAllowedPaths st)))-    walkAllowed ResolveFull st allowed path >>= either throwEvalError pure---- | Refuse a read unless the path itself is allowed, no symlink walk: the--- check upstream's accessor makes on an lstat or readlink of the path it--- is handed.  The refusal names the path asked for.-accessPathDirect :: Text -> EvalIO ()-accessPathDirect path = do-  st <- EvalIO ask-  when (pathsRestricted (esPolicy st)) $ do-    allowed <- EvalIO (liftIO (readIORef (esAllowedPaths st)))-    let canonical = locatedPath st path-    unless (isAbsolutePath canonical) $ throwEvalError (relativePathMessage path)-    unless (isAllowedPath allowed canonical) $-      throwEvalError (forbiddenPathMessage (esPolicy st) canonical)---- | Whether the walk would admit the path, for the one reader that--- answers a Boolean instead of refusing.-pathAllowed :: SymlinkResolution -> Text -> EvalIO Bool-pathAllowed mode path = do-  st <- EvalIO ask-  if pathsRestricted (esPolicy st)-    then do-      allowed <- EvalIO (liftIO (readIORef (esAllowedPaths st)))-      isRight <$> walkAllowed mode st allowed path-    else pure True---- | Refuse a path with a symlink anywhere above it, naming the deepest--- one: upstream's posix accessor asserts this on an lstat or readlink of--- the path it is handed (@PosixSourceAccessor::assertNoSymlinks@ over--- the parent, at 2.24.9), in every mode, and names the first symlink it--- meets walking up from the parent.-refuseSymlinkedAncestor :: Text -> EvalIO ()-refuseSymlinkedAncestor path = do-  st <- EvalIO ask-  mapM_ (check st) (strictAncestors (canonPathValue path))-  where-    check st ancestor = do-      target <- EvalIO (liftIO (symlinkTargetAt st ancestor))-      when (isJust target) $-        throwEvalError ("path '" <> ancestor <> "' is a symlink")---- | A canonical path's ancestors below the root, deepest first.-strictAncestors :: Text -> [Text]-strictAncestors path =-  [joinComponents (take n components) | n <- [length components - 1, length components - 2 .. 1]]-  where-    components = pathComponents path---- | How a 'PathExistence' query walks the path: a directory is demanded--- through the final symlink, an entry is found in place.-existenceResolution :: PathExistence -> SymlinkResolution-existenceResolution ExistsAsDirectory = ResolveFull-existenceResolution ExistsAsEntry = ResolveAncestors---- | The stat a 'PathExistence' query ends in: a directory through every--- symlink, or an entry of any kind in place.-existsAs :: PathExistence -> FilePath -> IO Bool-existsAs ExistsAsDirectory = Dir.doesDirectoryExist-existsAs ExistsAsEntry = lstatExists---- | Whether an entry is at the path, a dangling symlink included: an--- lstat, as upstream's @maybeLstat@ is.  'Dir.pathIsSymbolicLink' is the--- lstat the directory package exposes, and it throws for a missing path,--- so any failure is absence, as it is for 'Dir.doesPathExist'.-lstatExists :: FilePath -> IO Bool-lstatExists fp = do-  outcome <- try (Dir.pathIsSymbolicLink fp) :: IO (Either IOException Bool)-  pure (isRight outcome)---- | Upstream's @coerceToPath@ refusal of a relative string.  The builtins--- refuse one before it gets here; the gate repeats the refusal because--- its soundness depends on it.-relativePathMessage :: Text -> Text-relativePathMessage path = "string '" <> path <> "' doesn't represent an absolute path"---- | Which symlinks a walk follows, upstream's @SymlinkResolution@: every--- one, or every one but the last component's, which is then checked in--- place.-data SymlinkResolution = ResolveFull | ResolveAncestors-  deriving (Eq, Show)---- | The symlink-resolving prefix walk of upstream's--- @SourceAccessor::resolveSymlinks@ at 2.24.9, with the allow list--- consulted where its @maybeLstat@ would be: each component is pushed,--- the prefix so far must be allowed, and a symlink at that prefix has--- its target spliced in front of what remains (an absolute target--- restarts at the root).  'Left' carries the refusal for the first--- prefix outside the allow list.  Under 'ResolveAncestors' the last--- component's own symlink is left alone, as upstream consults--- @maybeLstat@ only while something remains to resolve.  The path is--- walked on the drive its read opens ('locatedPath'), the form the allow--- list holds.-walkAllowed :: SymlinkResolution -> EvalState -> AllowedPaths -> Text -> EvalIO (Either Text ())-walkAllowed mode st allowed path-  | not (isAbsolutePath canonical) = pure (Left (relativePathMessage path))-  | otherwise = go symlinkFollowLimit [] (pathComponents canonical)-  where-    canonical = locatedPath st path-    policy = esPolicy st-    go _ _ [] = pure (Right ())-    go linksLeft done (component : rest)-      | component == "." = go linksLeft done rest-      | component == ".." = go linksLeft (drop 1 done) rest-      | not (isAllowedPrefix allowed prefix) = pure (Left (forbiddenPathMessage policy prefixText))-      | otherwise = do-          target <- if followsLinkAt rest then EvalIO (liftIO (symlinkTargetAt st prefixText)) else pure Nothing-          case target of-            Nothing -> go linksLeft prefixReversed rest-            Just _-              | linksLeft == 0 ->-                  throwEvalError ("infinite symlink recursion in path '" <> canonical <> "'")-            Just link ->-              let linkComponents = filter (not . T.null) (T.split isPathSeparator link)-                  -- Spliced in front of the remainder; the walk resumes from-                  -- the root for an absolute target and from the link's own-                  -- directory otherwise.-                  resumeFrom = if isAbsoluteTarget link then [] else done-               in go (linksLeft - 1) resumeFrom (linkComponents ++ rest)-      where-        prefixReversed = component : done-        prefix = reverse prefixReversed-        prefixText = joinComponents prefix-    followsLinkAt rest = mode == ResolveFull || not (null rest)-    isAbsoluteTarget link = T.isPrefixOf "/" link || isAbsolute (T.unpack link)---- | The target of the symlink at a path value, read through the store--- mapping, or 'Nothing' when there is no symlink there.  A path that--- does not exist is simply not a symlink; the read that follows reports--- it missing.-symlinkTargetAt :: EvalState -> Text -> IO (Maybe Text)-symlinkTargetAt st pathText = do-  let fsPath = SP.storeTextToFilePath (esStoreDir st) pathText-  outcome <--    try-      ( do-          isLink <- Dir.pathIsSymbolicLink fsPath-          if isLink then Just . T.pack <$> Dir.getSymbolicLinkTarget fsPath else pure Nothing-      ) ::-      IO (Either IOException (Maybe Text))-  pure (fromRight Nothing outcome)---- | Upstream's bound on symlinks followed while resolving one path.-symlinkFollowLimit :: Int-symlinkFollowLimit = 1024---- | Where a recorded fetch is kept: one file per key, under this user's--- cache directory, named by the key's own hash. Outside the store on--- purpose - it's a note about work already done, not a derivation input.-fetchCacheFile :: Text -> IO FilePath-fetchCacheFile key = do-  dir <- Dir.getXdgDirectory Dir.XdgCache "nova-nix/fetch"-  pure (dir </> T.unpack (bytesToHexText (sha256Digest (TE.encodeUtf8 key))))---- | Where a store path lives on this machine: this evaluation's store dir--- mapped to a filesystem path.  This is the 'SP.StorePath' direction;--- path-value text goes through 'evalStoreTextPath'.  Both must read the--- same store dir, since a store honored on one side and not the other--- writes to one directory and reads from another.-storeFilePath :: SP.StoreDir -> SP.StorePath -> FilePath-storeFilePath = SP.storePathToFilePath---- | Record a store object evaluation just wrote, so the build driver--- registers it before a derivation naming it is built.  Every eval-time--- writer goes through this: a write that skips it lands in--- @drvInputSrcs@ with no registration row and fails the build with--- \"path \'...\' is not valid\".  The mode names the scheme that--- constructed the path, so materialization can verify the on-disk--- content reproduces it before registering.-recordStoreWrite :: Text -> [SP.StorePath] -> SP.StoreWriteMode -> EvalIO ()-recordStoreWrite storePath refs mode = do-  cacheRef <- EvalIO (asks esStoreWriteCache)-  EvalIO (liftIO (modifyIORef' cacheRef (Map.insert storePath (refs, mode))))---- | The file's bytes, 'Nothing' when nothing readable is there: absent,--- or something unreadable squatting on the name; either way the writer--- must replace rather than adopt.-readBytesIfPresent :: FilePath -> IO (Maybe BS.ByteString)-readBytesIfPresent path = do-  result <- try (BS.readFile path) :: IO (Either IOException BS.ByteString)-  pure (either (const Nothing) Just result)---- | The NAR serialisation of what is on disk, 'Nothing' when nothing--- serialisable is there.  Through 'ExecBit.serialiseFromPath', the--- same walk every producer and verifier uses, so the comparison sees--- the executable flags the store's model records, not the platform's--- permission guesses.-narBytesIfPresent :: NAR.CaseHack -> FilePath -> IO (Maybe BS.ByteString)-narBytesIfPresent caseHack path = do-  onDisk <- Dir.doesPathExist path-  if not onDisk-    then pure Nothing-    else do-      result <- try (ExecBit.serialiseFromPath caseHack path) :: IO (Either IOException NAR.NarEntry)-      pure (either (const Nothing) (Just . NAR.serialise) result)---- | The case-hack mode a read of path-value text runs under.  Store--- text names a tree on the store's volume, read back as the store--- reads its own paths ('volumeCaseHack' of the probed volume); any--- other path is a source, read under the process's setting--- ('processCaseHack').-readCaseHack :: Text -> EvalIO NAR.CaseHack-readCaseHack path-  | SP.isCanonicalStoreText path = do-      storeRoot <- EvalIO (asks (SP.unStoreDir . esStoreDir))-      wrapIO (volumeCaseHack <$> probeCaseSensitivity storeRoot)-  | otherwise = pure processCaseHack---- | 'storeFilePath' against the store this evaluation was given.-evalFilePath :: SP.StorePath -> EvalIO FilePath-evalFilePath sp = EvalIO (asks ((`storeFilePath` sp) . esStoreDir))---- | Resolve path-value text to a filesystem location against the store--- this evaluation was given.  The read counterpart of 'evalFilePath':--- both sides of every eval-time store access must agree on the store--- dir, or a redirected store is written to and read from two places.-evalStoreTextPath :: Text -> EvalIO FilePath-evalStoreTextPath txt = EvalIO (asks ((`SP.storeTextToFilePath` txt) . esStoreDir))---- | A store path's identity: the canonical @/nix/store@ spelling every--- platform shares.  Hashes and eval-visible strings carry this form; it--- never names a location on disk.-canonicalStorePathText :: SP.StorePath -> Text-canonicalStorePathText = SP.storePathToText SP.defaultStoreDir---- | Fail an import whose file does not parse or bind.  Both are uncatchable,--- as upstream's ParseError and UndefinedVarError are to @builtins.tryEval@.--- An unbound variable reads exactly as upstream's message does; a syntax--- error keeps the parser's detail behind the builtin and file it came from.-rejectSource :: Text -> FilePath -> SourceError -> EvalIO a-rejectSource builtinName target err = throwEvalError $ case err of-  SyntaxError syntax -> builtinName <> " " <> T.pack target <> ": " <> T.pack (show syntax)-  UndefinedVariable name -> undefinedVariableMessage name---- | Resolve an import's raw path to the value-domain target (the import--- cache key, the parse name, and the base dir the file's relative path--- literals resolve against) and the filesystem location to read, with--- both the path named and the file resolved checked against the policy:--- upstream's @resolveExprPath@ walks the path it is handed, and--- @parseExprFromFile@ walks the file it reads after @default.nix@ has--- been appended, so a directory whose @default.nix@ is a symlink is--- refused at the link's target.------ Store text stays canonical in the value domain: 'Dir.canonicalizePath'--- would attach the working drive to the rooted @/nix@ prefix on Windows,--- so store text gets lexical canonicalization ('canonPath') only, and--- its reads resolve through 'evalStoreTextPath'.  Every other path--- resolves and canonicalizes as the platform path 'evalStoreTextPath'--- gives it, where the two returned forms coincide.-resolveImportTarget :: FilePath -> Text -> EvalIO (FilePath, FilePath)-resolveImportTarget baseDir rawPath = do-  accessPath rawPath-  (target, ioTarget) <- locate-  accessPath (T.pack target)-  pure (target, ioTarget)-  where-    locate-      | SP.isCanonicalStoreText rawPath = do-          let valueBase = T.unpack (canonPath rawPath)-          resolvedBase <- evalStoreTextPath (T.pack valueBase)-          isDir <- sourceIO StatPath (T.pack valueBase) (statSource resolvedBase >> Dir.doesDirectoryExist resolvedBase)-          -- The value-domain join stays "/" so the canonical spelling survives.-          let valueTarget = if isDir then valueBase <> "/default.nix" else valueBase-          resolvedTarget <- evalStoreTextPath (T.pack valueTarget)-          pure (valueTarget, resolvedTarget)-      | otherwise = do-          raw <- evalStoreTextPath rawPath-          let resolved = if isRelative raw then baseDir </> raw else raw-          canonical <- wrapIO (Dir.canonicalizePath resolved)-          -- Directory import: append /default.nix if target is a-          -- directory, which upstream's resolveExprPath learns from an-          -- lstat, so an absent target is a stat failure.-          isDir <- sourceIO StatPath (T.pack canonical) (statSource canonical >> Dir.doesDirectoryExist canonical)-          let target = if isDir then canonical </> "default.nix" else canonical-          pure (target, target)---- | Classify a filesystem path as @"regular"@, @"directory"@, @"symlink"@,--- or @"unknown"@ - matching Nix's @builtins.readDir@ / @readFileType@.-classifyPath :: FilePath -> IO Text-classifyPath fp =-  firstMatch-    "unknown"-    [ (Dir.pathIsSymbolicLink fp, "symlink"),-      (Dir.doesDirectoryExist fp, "directory"),-      (Dir.doesFileExist fp, "regular")-    ]---- | Return the label of the first predicate that holds, or the default.-firstMatch :: Text -> [(IO Bool, Text)] -> IO Text-firstMatch def [] = pure def-firstMatch def ((test, label) : rest) =-  test >>= \case-    True -> pure label-    False -> firstMatch def rest---- | Classify a directory entry (name relative to parent).-classifyEntry :: FilePath -> FilePath -> IO (Text, Text)-classifyEntry parentDir name = do-  ty <- classifyPath (parentDir </> name)-  pure (T.pack name, ty)---- | Convert IO exceptions to eval errors.--- Guards against double-wrapping: if the exception is already a--- t'NixEvalError', it is re-thrown as-is.-wrapIO :: IO a -> EvalIO a-wrapIO action = EvalIO $ liftIO $ do-  result <- try action-  case result of-    Right val -> pure val-    Left (err :: SomeException)-      | Just (_ :: SomeAsyncException) <- fromException err -> throwIO err-      | Just abortErr <- fromException err -> throwIO (abortErr :: NixAbortError)-      | Just nixErr <- fromException err -> throwIO (nixErr :: NixEvalError)-      | otherwise -> throwIO (NixEvalError ErrorUncatchable (untracedFailure (T.pack (displayException err))))---- | 'wrapIO' for an access to a source path: an 'IOException' becomes--- the message upstream gives that access ('sourceErrorMessage'), naming--- the path as given.-sourceIO :: SourceAccess -> Text -> IO a -> EvalIO a-sourceIO access path = sourceIOWith access (pure path)---- | 'sourceIO' with the path to name computed once the access has failed,--- so a successful read pays nothing for it.-sourceIOWith :: SourceAccess -> IO Text -> IO a -> EvalIO a-sourceIOWith access shownPath action =-  wrapIO $-    action `catch` \(err :: IOException) -> do-      shown <- shownPath-      throwIO (NixEvalError ErrorUncatchable (untracedFailure (sourceErrorMessage access shown err)))---- | A path with its symlinks resolved, as upstream names one it reached--- through realisePath (readFile, hashFile and readDir resolve fully),--- given the value and the native path it opens.  A path the resolution--- itself cannot walk keeps the spelling given.-resolvedForMessage :: Text -> FilePath -> IO Text-resolvedForMessage path native-  | SP.isCanonicalStoreText path = pure (canonPath path)-  | otherwise =-      (canonPathValue . T.pack <$> Dir.canonicalizePath native)-        `catch` \(_ :: IOException) -> pure path---- | An lstat that raises for an absent path: 'Dir.pathIsSymbolicLink' is--- the portable lstat, as 'lstatExists' says.-statSource :: FilePath -> IO ()-statSource = void . Dir.pathIsSymbolicLink---- | A source path's NAR, its root lstat'ed first as upstream's dumpPath--- begins.  A regular file's only access in the walk is its read, so a--- failure there is the read's.  A failure below a directory keeps GHC's--- text until nova-cache's walk names the access that failed--- (Novavero-AI/nova-cache#80).-serialiseSource :: Text -> NAR.CaseHack -> FilePath -> EvalIO NAR.NarEntry-serialiseSource path caseHack resolved = do-  isLink <- sourceIO StatPath path (Dir.pathIsSymbolicLink resolved)-  isFile <- wrapIO (Dir.doesFileExist resolved)-  let walk = ExecBit.serialiseFromPath caseHack resolved-  if not isLink && isFile then sourceIO ReadFile path walk else wrapIO walk---- | Run an IO evaluation, returning @Left@ with the failure's message on--- error.-runEvalIO :: EvalState -> EvalIO a -> IO (Either Text a)-runEvalIO st action = either (Left . failureMessage) Right <$> runEvalIOTraced st action---- | Run an IO evaluation, returning @Left@ with the whole failure on--- error, its lines of context included, for a caller that reports it--- ('renderEvalFailure').------ Catches t'NixEvalError' (throw) and t'NixAbortError' (abort).--- Async exceptions (@StackOverflow@, @ThreadKilled@, etc.) propagate uncaught.-runEvalIOTraced :: EvalState -> EvalIO a -> IO (Either EvalFailure a)-runEvalIOTraced st (EvalIO action) = do-  result <- try (runReaderT action st)-  case result of-    Right val -> pure (Right val)-    Left (err :: SomeException)-      | Just (_ :: SomeAsyncException) <- fromException err -> throwIO err-      | Just (NixEvalError _ failure) <- fromException err -> pure (Left failure)-      | Just (NixAbortError failure) <- fromException err -> pure (Left failure)-      | otherwise -> pure (Left (untracedFailure (T.pack (displayException err))))---- ------------------------------------------------------------------------------ Store copy helpers--- ------------------------------------------------------------------------------- | Unpack a NAR entry at its content-addressed destination.  An--- existing destination is adopted only when its NAR digest is the--- expected one - same content means same path, so a matching tree is--- byte-identical by construction; anything else (an interrupted--- earlier unpack, a squatter) is cleared and unpacked afresh.  The--- entry is the one evaluation hashed to name the path, so the tree--- that lands is the one the address names, with the store volume's--- own sibling-name handling.-unpackToStoreVerified :: FilePath -> NAR.NarEntry -> BS.ByteString -> IO (Either Text ())-unpackToStoreVerified dest entry expectedDigest = do-  Dir.createDirectoryIfMissing True (takeDirectory dest)-  -- Probed per write rather than carried in 'EvalState': the store-  -- directory need not exist when evaluation starts, and the probe-  -- answers for a path on disk.  It was created just above, and the-  -- cost is one pathconf call per tree.-  sensitivity <- probeCaseSensitivity (takeDirectory dest)-  onDiskNar <- narBytesIfPresent (volumeCaseHack sensitivity) dest-  if (sha256Digest <$> onDiskNar) == Just expectedDigest-    then pure (Right ())-    else do-      Dir.removePathForcibly dest-      unpackNarEntry sensitivity dest entry+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | IO-based Nix evaluator.+--+-- Provides t'EvalIO', a concrete 'MonadEval' instance that performs+-- real file-system access.  The @import@ builtin reads, parses, and+-- evaluates @.nix@ files with a per-session import cache.  Source parsed+-- by 'Nix.Parser.parseNix' evaluates in a session ('withEvalSession'),+-- here a read-only one, as @nova-nix eval@ runs:+--+-- @+-- withLocalStore logger (defaultBuildConfig storeDir) {bcSubstitution = RefuseSubstitution} $ \\ops ->+--   withEvalSession (SessionSettings unrestrictedPolicy nixPathSearchPath storeDir "/path/to/project" RegionsCollect (ReadOnlySession (localQueries storeDir) ops) logger) $ \\st ->+--     runEvalIO st (evalParsed (pure (evalBaseEnv st)) parsed)+-- @+module Nix.Eval.IO+  ( -- * Evaluator+    EvalIO,+    runEvalIO,+    runEvalIOTraced,++    -- * Sessions+    SessionSettings (..),+    SessionStore (..),+    withEvalSession,+    nixPathSearchPath,++    -- * Source files+    resolveImportTarget,+    readImportTarget,++    -- * State+    EvalState+      ( esDrvModuloCache,+        esDrvClosure,+        esSourcePathCache,+        esStoreWriteCache,+        esBaseDir,+        esStoreDir,+        esCallDepth,+        esFetchRetry,+        esAllowedPaths,+        esAdded+      ),+    SourceCopy (..),+    sourceCopies,+    evalBaseEnv,+    evalSearchPath,+    newEvalStateWith,+    nixPathValue,+    allowEvalPath,++    -- * Errors+    EvalFailure (..),+    renderEvalFailure,+  )+where++import Control.Exception (Exception, Handler (..), IOException, SomeAsyncException, SomeException, bracket, bracket_, catch, catchJust, catches, displayException, fromException, onException, throwIO, toException, try, tryJust)+import Control.Monad (mfilter, unless, void, when)+import Control.Monad.Except (ExceptT (..), runExceptT)+import Control.Monad.IO.Class (liftIO)+import Control.Monad.Reader (ReaderT (..), ask, asks, local)+import Crypto.Random (getRandomBytes)+import Data.Bifunctor (first)+import qualified Data.ByteString as BS+import Data.Either (fromRight, isRight)+import Data.Foldable (traverse_)+import Data.IORef (IORef, modifyIORef', newIORef, readIORef)+import Data.Int (Int64)+import Data.List (find)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (catMaybes, isJust)+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Time.Clock.POSIX (getPOSIXTime)+import Data.Void (absurd)+import Data.Word (Word32)+import Foreign.C.Error (Errno (..), eACCES, ePERM)+import Foreign.Ptr (castPtr)+import GHC.Exts (oneShot)+import GHC.IO.Exception (ioe_errno)+import Nix.Builtins (builtinEnv, builtinEnvWithScope, parseNixPath, rootScopeNames)+import Nix.Derivation (Derivation (..), DerivationOutput (..), fromATerm)+import Nix.Environment (EnvLookup (..), lookupEnvBytes)+import Nix.Eval (deepForce, eval, evalBytecode, evalParsed, findInSearchPath)+import Nix.Eval.Arena (arenaDestroy, arenaInit)+import Nix.Eval.AttrPath (selectAttrPath)+import Nix.Eval.AutoCall (AutoArgs, autoCallFunction)+import Nix.Eval.CData (MonadCData (..), runCData)+import Nix.Eval.CList (CList (..))+import Nix.Eval.CRegion (Regions (..), inRegion, regionsRunning, withRegions)+import Nix.Eval.CRoots (crootsAddEnv, crootsAddThunk, crootsMark, crootsRelease)+import Nix.Eval.CStatus (arenaLive, cInvariantViolated)+import Nix.Eval.CThunk (CThunkPtr, cthunkMarkBlackhole, cthunkMarkPending, cthunkSetComputedAttrs, cthunkSetComputedBool, cthunkSetComputedCtxStr, cthunkSetComputedFloat, cthunkSetComputedInt, cthunkSetComputedLambda, cthunkSetComputedList, cthunkSetComputedNull, cthunkSetComputedPath, cthunkSetComputedPrimop, cthunkSetComputedPrimopApp, cthunkSetComputedStr, cthunkState)+import Nix.Eval.CallDepth (CallDepth, defaultMaxCallDepth, enterCallFrame, topLevelCallDepth)+import Nix.Eval.CanonPath (canonBaseName, canonPath, canonPathValue)+import Nix.Eval.Context (contextRequest)+import Nix.Eval.Policy (AllowedPaths, EvalPolicy (..), SymlinkResolution (..), WalkStop (..), allowPathIn, fileUrlPath, forbiddenPathMessage, hostPathRules, isAbsolutePath, isAllowedPath, isAllowedPrefix, joinComponents, linkTarget, noAllowedPaths, pathComponents, pathsRestricted, storeRootPrefix, uriAccess, walkPath)+import Nix.Eval.RealiseContext (ContextRefusal (..), ContextRequest (..), PendingOrigin (..), Plan (..), SessionMode (..), contextRefusalMessage, firstInvalidPath, planRealisation, readableIn, referenceClosure)+import Nix.Eval.SourceError (SourceAccess (..), sourceErrorMessage)+import Nix.Eval.Types (AttrSet (..), Env (..), MonadEval (..), NixValue (..), PathExistence (..), PrimopCell (..), StringCell (..), Thunk (..), attrSetKeys, bytesToTextLossy, evaluated, marshalLambda, pathCell, primopCell, readComputed, readPending, storePathOrThrow, stringCell, warnMessage, pattern ThunkBlackhole, pattern ThunkComputed, pattern ThunkPending)+import Nix.Expr.Resolve (undefinedVariableMessage)+import Nix.Expr.Types (Expr)+import Nix.Fetch.Archive (FetchFailure (..), unpackArchive)+import Nix.Fetch.Download (DownloadSource (..), downloadBytes, withUrlBody)+import Nix.Fetch.Tree (Blob, Tree, treeNarBytes, treeNarHash, withTreeNarSource)+import Nix.Hash (FileIngestionMethod (..), bytesToHexText, makeFixedOutputPath, makeTextPath, sha256Digest)+import Nix.Http (FetchRetryPolicy, attemptFailureMessage, defaultFetchRetryPolicy, fileUrlFailure)+import Nix.Logger (Logger, logMessage)+import Nix.Parser (ParsedSource, SourceError (..), SourceOrigin (..), parseNixWithScope)+import Nix.Store (ArchiveEnd (..), NarStreamFailure (..), UpstreamHazard (..), abortNarUnpack, canonicalizeMetadata, finishNarUnpack, newNarUnpackSink, sinkNarStream, unpackNarEntry, upstreamManagedRefusal)+import Nix.Store.Access (createStoreDirectory)+import Nix.Store.CaseSensitive (pathCaseHack, probeCaseSensitivity, volumeCaseHack)+import qualified Nix.Store.ExecBit as ExecBit+import Nix.Store.Ops (EvalObjects (..), EvalWrite (..), EvalWrites (..), MadeOps (..), StoreOps (..), StoreQueries (..), madeAnotherPath, nothingToAdd, stopReported)+import qualified Nix.Store.Path as SP+import qualified NovaCache.Hash as Hash+import qualified NovaCache.NAR as NAR+import qualified System.Directory as Dir+import System.Exit (ExitCode (..))+import System.FilePath (isRelative, takeDirectory, (</>))+import System.IO.Error (ioeGetErrorString, isUserError)+import qualified System.Process as Proc++-- ---------------------------------------------------------------------------+-- Error type+-- ---------------------------------------------------------------------------++-- | How an eval-time failure interacts with @builtins.tryEval@:+-- 'ErrorThrown' (@builtins.throw@, a failed @assert@) is catchable,+-- matching upstream's ThrownError\/AssertionError; 'ErrorUncatchable'+-- (type errors, missing attributes, IO failures) escapes tryEval like+-- every other upstream EvalError.+data EvalErrorKind = ErrorThrown | ErrorUncatchable+  deriving (Eq, Show)++-- | A failure's message and the lines of context it gathered unwinding+-- ('Nix.Eval.Types.addErrorTrace'), outermost first: upstream's+-- @ErrorInfo@ message and traces, without positions.+data EvalFailure = EvalFailure+  { failureTrace :: ![Text],+    failureMessage :: !Text+  }+  deriving (Eq, Show)++-- | A failure with nothing gathered yet.+untracedFailure :: Text -> EvalFailure+untracedFailure = EvalFailure []++-- | Evaluation error surfaced as an IO exception.+data NixEvalError = NixEvalError !EvalErrorKind !EvalFailure+  deriving (Show)++instance Exception NixEvalError++-- | Abort error - NOT catchable by tryEval (matches real Nix semantics).+newtype NixAbortError = NixAbortError EvalFailure+  deriving (Show)++instance Exception NixAbortError++-- | A failure as upstream's @showErrorInfo@ prints it (error.cc at+-- 2.24.9) when no line has a position: each line of context after an+-- ellipsis and a blank line, then the message after an @error:@ of its+-- own.  An empty line of context prints nothing, as upstream passes over a+-- trace whose text is empty, and the message still follows an @error:@ of+-- its own, as upstream's follows one whenever the failure has a trace.  The+-- report is upstream's @indent@: the first line follows @error: @, every+-- later line is indented to align with it, and each line loses its trailing+-- whitespace.+renderEvalFailure :: EvalFailure -> Text+renderEvalFailure (EvalFailure trace msg) =+  T.intercalate "\n" (zipWith indentLine (errorPrefix : repeat continuation) (T.splitOn "\n" (chomp report)))+  where+    shown = filter (not . T.null) trace+    report = foldMap traceLine shown <> (if null trace then "" else "\n" <> errorPrefix) <> msg+    traceLine line = "\n\x2026 " <> line <> "\n"+    indentLine prefix line = chomp (prefix <> line)+    continuation = T.replicate (T.length errorPrefix) " "+    chomp = T.dropWhileEnd (`elem` [' ', '\n', '\r', '\t'])++-- | What upstream prints before an error's message.+errorPrefix :: Text+errorPrefix = "error: "++-- ---------------------------------------------------------------------------+-- State+-- ---------------------------------------------------------------------------++-- | A path value's copy: the store path it is copied to, and the+-- path-value text of the tree evaluation read for it, the path with the+-- symlinks among its ancestors resolved and its own last component left+-- alone, which the build driver restores the copy from.+data SourceCopy = SourceCopy+  { scStorePath :: !SP.StorePath,+    scSource :: !Text+  }+  deriving (Eq, Show)++-- | Each copy's store path with the text of the tree it is restored+-- from: the sources of the t'EvalObjects' a session hands its store.+sourceCopies :: Map Text SourceCopy -> Map SP.StorePath Text+sourceCopies copies = Map.fromList [(scStorePath copy, scSource copy) | copy <- Map.elems copies]++-- | Shared state for IO evaluation: an evaluation session.+--+-- The policy, the time and the search path are fixed as the session+-- starts ('withEvalSession'), when its base environment is built over them,+-- as upstream's @EvalState@ takes its settings and lookup path as it is+-- constructed; the module exports no way to change one after.+--+-- 'esImportCache' is a shared mutable cache (global across all frames),+-- holding each file's value in a cell registered as a root+-- ("Nix.Eval.CRoots").  Single-threaded only - switch to @MVar@ or+-- @TVar@ if concurrent evaluation is ever added.+--+-- 'esBaseDir' is immutable per frame - @import@ uses 'local' to set it+-- for nested evaluations, so it is exception-safe with no save\/restore.+data EvalState = EvalState+  { esImportCache :: !(IORef (Map FilePath Thunk)),+    -- | The base environment every file the session evaluates is+    -- evaluated in, @builtins.nixPath@ the search path in it.+    esBaseEnv :: !Env,+    -- | Cache of derivation modulo-hashes (drv store path to hex), populated+    -- bottom-up by @builtinDerivationStrict@ so input derivations can be+    -- substituted by their content hashes when computing output paths.+    esDrvModuloCache :: !(IORef (Map Text Text)),+    -- | Accumulated @.drv@ closure (drv store path text to its ATerm bytes),+    -- recorded bottom-up by @builtinDerivationStrict@.  The build driver reads+    -- this after evaluation to write every input @.drv@ to the store before+    -- building.+    esDrvClosure :: !(IORef (Map Text BS.ByteString)),+    -- | Each path value coerced so far, by its text, with its copy, so a+    -- path literal used across many derivations is hashed only once.+    esSourcePathCache :: !(IORef (Map Text SourceCopy)),+    -- | Every store object evaluation made but a path value's copy+    -- ('esSourcePathCache') and a derivation ('esDrvClosure'), store path+    -- to its references, written or, in a read-only session, only named, for+    -- the build driver to register before building.  All of them, not+    -- only @builtins.toFile@: an unrecorded write reaches @drvInputSrcs@+    -- as an unregistered path and fails the build that names it.+    esStoreWriteCache :: !(IORef (Map Text ([SP.StorePath], SP.StoreWriteMode))),+    -- | The store paths of the writes a fetcher made, which upstream's+    -- fetchers add to the store in any mode, so a read-only session+    -- reads them where it refuses what evaluation computed.+    esFetched :: !(IORef (Set Text)),+    esBaseDir :: !FilePath,+    -- | Where store objects live on this machine, so eval's own reads and+    -- writes honor @--store@ the same way the builder does.+    esStoreDir :: !SP.StoreDir,+    esTimestamp :: !Int64,+    esSearchPaths :: ![Thunk],+    -- | The call frames active around the current evaluation and the+    -- @max-call-depth@ ceiling.  Per frame like 'esBaseDir':+    -- 'withCallFrame' scopes it with 'local', so a failure unwinding+    -- through a frame leaves the count it found, upstream's RAII guard+    -- with nothing to restore.+    esCallDepth :: !CallDepth,+    -- | How a fetcher's download is tried ('fetchUrlBytes' and+    -- 'fetchArchiveToStore'): upstream's default unless the caller+    -- replaces it with what @download-attempts@ says.+    esFetchRetry :: !FetchRetryPolicy,+    -- | What this evaluation may reach: upstream's @restrict-eval@ and+    -- @pure-eval@ settings and the @allowed-uris@ list, and its+    -- @trace-verbose@ setting.  Unrestricted unless the caller says+    -- otherwise, as upstream's defaults are.+    esPolicy :: !EvalPolicy,+    -- | What the session's regions run for, a region opened around each+    -- force while any run ("Nix.Eval.CRegion").  Every session in the+    -- arena runs what the outermost one started.+    esRegions :: !Regions,+    -- | The allowed path prefixes under a restricting policy: the search+    -- path roots the caller seeded with 'allowEvalPath', plus every store+    -- object this evaluation copies, fetches or writes (upstream's+    -- @allowPath@ after each such step), plus the closures of the outputs a+    -- realised context names, plus the fetchers' scratch directories.  Mutable+    -- because it grows as evaluation proceeds, like the import cache.+    esAllowedPaths :: !(IORef AllowedPaths),+    -- | The store contexts are realised against.+    esStore :: !SessionStore,+    -- | The store paths of what evaluation made that a read-write session+    -- has added to its store, so a later realisation adds only what came+    -- after.+    esAdded :: !(IORef (Set Text)),+    -- | Where @builtins.trace@ and an evaluation warning go.+    esLogger :: !Logger+  }++-- | What an evaluation session starts with: upstream's settings and+-- lookup path, which its @EvalState@ takes as it is constructed.+data SessionSettings = SessionSettings+  { -- | What the evaluation may reach.+    sessionPolicy :: !EvalPolicy,+    -- | The search path, made once the session's arena is live; for+    -- the one @NIX_PATH@ gives, 'nixPathSearchPath'.+    sessionSearchPath :: !(IO [Thunk]),+    -- | Where store objects live.+    sessionStoreDir :: !SP.StoreDir,+    -- | The directory relative paths in the evaluated source resolve+    -- against.+    sessionBaseDir :: !FilePath,+    -- | What to run regions for ("Nix.Eval.CRegion"): the collector, a+    -- census, or nothing.  Only a session that sets up the arena starts+    -- them; a nested session runs whatever the arena's run.+    sessionRegions :: !Regions,+    -- | The store a path reader's context is realised against.+    sessionStore :: !SessionStore,+    -- | Where @builtins.trace@ and an evaluation warning go.+    sessionLogger :: !Logger+  }++-- | The store a session realises contexts against+-- ("Nix.Eval.RealiseContext").+data SessionStore+  = -- | One the session asks what it holds through queries that write+    -- no row, as @nova-nix eval@ asks it ('Nix.Store.Ops.localQueries'),+    -- and whose operations write and add what a fetcher fetched, as+    -- upstream's fetchers add theirs in any mode, and realise an output a+    -- context names.  What evaluation computed is named and never+    -- written.  The operations' build refuses every substitution and+    -- builds an output that may not be substituted, as upstream's+    -- read-only evaluation realises one: a 'Nix.Store.Ops.withLocalStore'+    -- under 'Nix.Builder.RefuseSubstitution'.  What a fetcher fetched+    -- reaches the store as 'soEvalWrites' says: written in its directory+    -- by the session, or handed to the store as it is made.+    ReadOnlySession !(StoreQueries IO) !(StoreOps IO)+  | -- | One the session also adds what evaluation made to, and builds what+    -- a context names in, as @nova-nix build@ does.  What evaluation+    -- writes reaches the store as 'soEvalWrites' says: written in the+    -- store's directory by the session and added with the rest, or handed+    -- to the store as it is made.+    ReadWriteSession !(StoreOps IO)++-- | Run an action in an evaluation session: the C data layer's arena is+-- set up when no session holds it already, the session's state is made+-- over the settings ('newEvalStateWith'), and the action runs with it.+-- As the session ends, by returning or by an exception, it forgets the+-- roots it registered, and the outermost session tears the arena down,+-- freeing every C object its evaluations made.  A nested session shares+-- the arena of the session around it.  Nothing made in a session is used+-- after it ends: no value, environment or thunk outlives its arena.+withEvalSession :: SessionSettings -> (EvalState -> IO a) -> IO a+withEvalSession settings action = withArena (bracket crootsMark crootsRelease (const session))+  where+    session = do+      searchPaths <- sessionSearchPath settings+      newEvalStateWith (sessionLogger settings) (sessionPolicy settings) searchPaths (sessionStore settings) (sessionStoreDir settings) (sessionBaseDir settings) >>= action+    withArena body = do+      live <- arenaLive+      if live then body else withRegions (sessionRegions settings) (bracket_ arenaInit arenaDestroy body)++-- | The search path @NIX_PATH@ gives ('nixPathValue').+nixPathSearchPath :: IO [Thunk]+nixPathSearchPath = nixPathValue >>= parseNixPath++-- | The base environment a session evaluates a file in: every name+-- upstream's base environment binds ('Nix.Builtins.builtinEnv').+evalBaseEnv :: EvalState -> Env+evalBaseEnv = esBaseEnv++-- | The search path the session was started with, the one+-- @builtins.nixPath@ holds.+evalSearchPath :: EvalState -> [Thunk]+evalSearchPath = esSearchPaths++-- | The bytes of @NIX_PATH@, unchanged, as upstream's @initGC@ reads them+-- (src/libexpr/eval-gc.cc at Nix 2.24.9), and empty when it is unset.  The+-- one refusal is a Windows @NIX_PATH@ holding an unpaired UTF-16+-- surrogate, which has no UTF-8 form and raises an 'IOException'.+nixPathValue :: IO BS.ByteString+nixPathValue =+  lookupEnvBytes nixPathVar >>= \case+    EnvUnset -> pure BS.empty+    EnvValue value -> pure value+    EnvUnpairedSurrogate ->+      ioError (userError "NIX_PATH holds an unpaired UTF-16 surrogate, which has no UTF-8 form")++-- | The state of a session, made in the session already open: what+-- 'withEvalSession' makes for a new one, and a caller already inside one+-- can make another with.  The call-depth ceiling and the download retry+-- policy start at upstream's defaults; a caller with configured ones+-- replaces 'esCallDepth' and 'esFetchRetry'.+--+-- Under a restricting policy, the roots it should admit are seeded with+-- 'allowEvalPath' before evaluation starts, as upstream's constructor+-- allows its lookup path.  The base environment is built here, in the C+-- data layer, so this runs in a session ('withEvalSession'), whose roots+-- the base environment joins, and the search path with it, through+-- @builtins.nixPath@.+newEvalStateWith :: Logger -> EvalPolicy -> [Thunk] -> SessionStore -> SP.StoreDir -> FilePath -> IO EvalState+newEvalStateWith logger policy searchPaths store storeDir baseDir = do+  cache <- newIORef Map.empty+  drvCache <- newIORef Map.empty+  drvClosure <- newIORef Map.empty+  srcCache <- newIORef Map.empty+  storeWriteCache <- newIORef Map.empty+  fetched <- newIORef Set.empty+  allowedPaths <- newIORef noAllowedPaths+  added <- newIORef Set.empty+  now <- floor <$> getPOSIXTime :: IO Int64+  baseEnv@(Env baseEnvPtr) <- builtinEnv policy now searchPaths+  crootsAddEnv baseEnvPtr+  regions <- regionsRunning+  pure+    EvalState+      { esImportCache = cache,+        esBaseEnv = baseEnv,+        esDrvModuloCache = drvCache,+        esDrvClosure = drvClosure,+        esSourcePathCache = srcCache,+        esStoreWriteCache = storeWriteCache,+        esFetched = fetched,+        esBaseDir = baseDir,+        esStoreDir = storeDir,+        esTimestamp = now,+        esSearchPaths = searchPaths,+        esCallDepth = topLevelCallDepth defaultMaxCallDepth,+        esFetchRetry = defaultFetchRetryPolicy,+        esPolicy = policy,+        esRegions = regions,+        esAllowedPaths = allowedPaths,+        esStore = store,+        esAdded = added,+        esLogger = logger+      }++-- | Grant access to a path prefix, as upstream Nix grants one: the+-- caller seeds the search path roots before evaluation, and the instance+-- adds every store object the evaluation copies, fetches or writes, and+-- the closures of the outputs it realises.  Like upstream's, this+-- is a no-op when nothing restricts access, so an unrestricted evaluation+-- does not accumulate a set it never consults.  The prefix is allowed on+-- the drive its reads open ('locatedPath'), the form every check uses.+allowEvalPath :: EvalState -> Text -> IO ()+allowEvalPath st path =+  when (pathsRestricted (esPolicy st)) $+    modifyIORef' (esAllowedPaths st) (allowPathIn (locatedPath st path))++-- | Path-value text as the policy checks it: canonical, and on the drive+-- this evaluation's store directory puts it on ('SP.qualifyPathText'),+-- so a check and the read it guards ('evalStoreTextPath') name one file.+locatedPath :: EvalState -> Text -> Text+locatedPath st = SP.qualifyPathText (esStoreDir st) . canonPathValue++-- ---------------------------------------------------------------------------+-- EvalIO newtype+-- ---------------------------------------------------------------------------++-- | IO evaluation monad.  Wraps @ReaderT EvalState IO@.+newtype EvalIO a = MkEvalIO (ReaderT EvalState IO a)++-- Every action is built through this pattern, never through MkEvalIO+-- itself, so that its state argument is marked one-shot: an evaluator+-- action runs once, so GHC may take the state and the IO world as+-- arguments together instead of returning a closure that waits for them,+-- and may move work into the action instead of keeping it outside to share+-- between runs that never happen.  This is the one-shot state monad trick+-- GHC's own IOEnv uses (Note [The one-shot state monad trick] in+-- GHC.Utils.Monad).  A derived instance would bypass the builder, so the+-- instances below are written out.  Under the specialisation below it+-- cuts the time of the benchmarks the cabal file names by 8 to 12% and+-- their allocation by 12 to 13%; on the unspecialised evaluator it+-- changes nothing, since every bind there is an unknown call through the+-- instance dictionary.+pattern EvalIO :: ReaderT EvalState IO a -> EvalIO a+pattern EvalIO {unEvalIO} <- MkEvalIO unEvalIO+  where+    EvalIO (ReaderT run) = MkEvalIO (ReaderT (oneShot run))++{-# COMPLETE EvalIO #-}++instance Functor EvalIO where+  fmap f (EvalIO m) = EvalIO (fmap f m)+  a <$ EvalIO m = EvalIO (a <$ m)++instance Applicative EvalIO where+  pure a = EvalIO (pure a)+  EvalIO f <*> EvalIO m = EvalIO (f <*> m)+  EvalIO m *> EvalIO k = EvalIO (m *> k)++instance Monad EvalIO where+  EvalIO m >>= k = EvalIO (m >>= unEvalIO . k)++  -- Not the default, which goes through '>>=' and loses its one-shot+  -- marking unless '>>=' is INLINE (Note [INLINE pragmas and (>>)] in+  -- GHC.Utils.Monad).+  (>>) = (*>)++-- ---------------------------------------------------------------------------+-- Specialisation+-- ---------------------------------------------------------------------------++-- The evaluator is written over any MonadEval and compiled that way, so+-- each of its binds and class methods is a call through the instance+-- dictionary.  These compile the entry points a caller runs in EvalIO+-- (evalParsed for this module's import and scopedImport and for the+-- executable's evaluation, evalBytecode for the executable's evaluation+-- that keeps its root environment for a census, eval for an expression+-- built by hand, --strict and attribute selection, and the lookup and the+-- call of a command line's target) for EvalIO alone, and the library's+-- specialisation flags carry that through everything they reach.  Each+-- pragma exports a rule that sends a call at EvalIO in any module+-- importing this one to that code.  The flags alone leave no rule for an+-- entry point small enough to be inlined here rather than specialised, as+-- eval is, so a caller in another module, the executable among them, would+-- run the dictionary-passing evaluator.+{-# SPECIALIZE evalParsed :: EvalIO Env -> ParsedSource -> EvalIO NixValue #-}++{-# SPECIALIZE eval :: Env -> Expr -> EvalIO NixValue #-}++{-# SPECIALIZE evalBytecode :: Env -> Word32 -> EvalIO NixValue #-}++{-# SPECIALIZE deepForce :: NixValue -> EvalIO () #-}++{-# SPECIALIZE selectAttrPath :: (NixValue -> EvalIO NixValue) -> Text -> NixValue -> EvalIO (Either Text NixValue) #-}++{-# SPECIALIZE autoCallFunction :: AutoArgs -> NixValue -> EvalIO NixValue #-}++{-# SPECIALIZE findInSearchPath :: [Thunk] -> BS.ByteString -> EvalIO Text #-}++-- ---------------------------------------------------------------------------+-- MonadEval instance+-- ---------------------------------------------------------------------------++instance MonadCData EvalIO where+  liftCData act = EvalIO (liftIO (runCData act))+  {-# INLINE liftCData #-}++instance MonadEval EvalIO where+  throwEvalError msg = EvalIO (liftIO (throwIO (NixEvalError ErrorUncatchable (untracedFailure msg))))+  throwCatchableError msg = EvalIO (liftIO (throwIO (NixEvalError ErrorThrown (untracedFailure msg))))+  abortEvaluation msg = EvalIO (liftIO (throwIO (NixAbortError (untracedFailure msg))))++  -- tryEval semantics: recover from a throw/assert only; an uncatchable+  -- eval error is rethrown (aborts are a separate exception type and+  -- never enter the 'try').+  catchEvalError (EvalIO action) = EvalIO $ do+    st <- ask+    result <- liftIO (try (runReaderT action st))+    case result of+      Left (NixEvalError ErrorThrown failure) -> pure (Left (failureMessage failure))+      Left err@(NixEvalError ErrorUncatchable _) -> liftIO (throwIO err)+      Right val -> pure (Right val)++  -- Over IO exceptions, so eval errors, aborts, and IO failures+  -- crossing 'wrapIO' all trigger the cleanup before propagating.+  onEvalError (EvalIO action) (EvalIO cleanup) = EvalIO $ do+    st <- ask+    liftIO (runReaderT action st `onException` runReaderT cleanup st)++  -- The line is made after the failure is caught, not in a handler,+  -- which would run it with asynchronous exceptions masked.+  addEvaluatedTrace onFailedLine (EvalIO line) (EvalIO action) = EvalIO $ do+    st <- ask+    result <- liftIO (try (try (runReaderT action st)))+    case result of+      Right (Right val) -> pure val+      Right (Left (NixAbortError failure)) -> retrace st (throwIO . NixAbortError) failure+      Left (NixEvalError kind failure) -> retrace st (throwIO . NixEvalError kind) failure+    where+      retrace st rethrow (EvalFailure trace msg) = do+        made <- liftIO (try (try (runReaderT line st)))+        let !context = case made of+              Right (Right text) -> text+              Right (Left (NixAbortError (EvalFailure _ failed))) -> onFailedLine failed+              Left (NixEvalError _ (EvalFailure _ failed)) -> onFailedLine failed+        liftIO (rethrow (EvalFailure (context : trace) msg))++  withCallFrame (EvalIO action) = EvalIO $ do+    depth <- asks esCallDepth+    either+      (unEvalIO . throwEvalError)+      (\deeper -> local (\s -> s {esCallDepth = deeper}) action)+      (enterCallFrame depth)++  -- A refused path reads as absent, as upstream's pathExists turns a+  -- RestrictedPathError into false.  The query decides the walk and the+  -- stat as prim_pathExists does: a plain path is resolved through its+  -- ancestors only and lstat'ed in place, so a symlink exists whatever+  -- it points at; a path that must be a directory is resolved fully and+  -- must stat as one.+  doesPathExist query path = do+    allowed <- pathAllowed (existenceResolution query) path+    if allowed+      then evalStoreTextPath path >>= \resolved -> wrapIO (existsAs query resolved)+      else pure False++  listDirectory path = do+    accessPath path+    dir <- evalStoreTextPath path+    sourceIOWith ReadDirectory (resolvedForMessage path dir) $ do+      entries <- Dir.listDirectory dir+      mapM (classifyEntry dir) entries++  importFile rawPath = do+    baseDir <- EvalIO (asks esBaseDir)+    baseEnv <- EvalIO (asks esBaseEnv)+    policy <- EvalIO (asks esPolicy)+    -- Resolved, and so checked, before the cache is consulted, as+    -- upstream resolves the file before its fileEvalCache lookup: a+    -- cached import is no more readable than a fresh one.+    (target, ioTarget) <- resolveImportTarget baseDir rawPath+    -- Check import cache (readIORef cannot throw, no wrapIO needed)+    cacheRef <- EvalIO (asks esImportCache)+    cache <- EvalIO (liftIO (readIORef cacheRef))+    case Map.lookup target cache of+      Just (Thunk cell) -> readComputed cell+      Nothing -> do+        source <- readImportTarget (target, ioTarget)+        let fileDir = takeDirectory target+        case parseNixWithScope (rootScopeNames policy) fileDir (SourceFile (T.pack target)) source of+          Left err -> rejectSource "import" target err+          Right parsed -> do+            -- local sets new base dir for nested imports - pure, exception-safe+            let nested =+                  EvalIO+                    ( local+                        (\s -> s {esBaseDir = fileDir})+                        (unEvalIO (evalParsed (pure baseEnv) parsed))+                    )+            result <- nested+            -- Every file's value is cached, kept in a cell registered as+            -- a root, as upstream's fileEvalCache keeps every file it+            -- evaluates (evalFile in eval.cc): a later import of the+            -- file is the same value.+            cell <- evaluated result+            crootsAddThunk (unThunk cell)+            wrapIO (modifyIORef' cacheRef (Map.insert target cell))+            pure result++  -- Upstream's getEnv answers empty under either setting+  -- (@prim_getEnv@: @restrictEval || pureEval ? "" : getEnv(name)@).+  -- The read cannot throw, so it needs no wrapIO.+  getEnvVar name = do+    policy <- EvalIO (asks esPolicy)+    if pathsRestricted policy+      then pure BS.empty+      else do+        found <- EvalIO (liftIO (lookupEnvBytes name))+        case found of+          EnvUnset -> pure BS.empty+          EnvValue value -> pure value+          EnvUnpairedSurrogate ->+            throwEvalError ("builtins.getEnv: the value of '" <> bytesToTextLossy name <> "' holds an unpaired UTF-16 surrogate, which has no UTF-8 form")++  lookupDrvHash key = EvalIO $ do+    ref <- asks esDrvModuloCache+    liftIO (Map.lookup key <$> readIORef ref)++  cacheDrvHash key val = EvalIO $ do+    ref <- asks esDrvModuloCache+    liftIO (modifyIORef' ref (Map.insert key val))++  recordDrvAterm key aterm = EvalIO $ do+    ref <- asks esDrvClosure+    liftIO (modifyIORef' ref (Map.insert key aterm))++  -- Read a .drv from the store on a modulo-hash cache miss (a cross-session or+  -- appendContext reference).  Mirrors the build side's readDrvFromStore: map+  -- to the on-disk path, read the raw bytes, parse the ATerm byte-level (env+  -- values keep arbitrary bytes).  A file that cannot be read or does not+  -- parse is 'Nothing', which the caller turns into a loud modulo-hash error.+  readStoreDerivation sp = EvalIO $ do+    filePath <- asks ((`storeFilePath` sp) . esStoreDir)+    result <- liftIO (try (BS.readFile filePath) :: IO (Either IOException BS.ByteString))+    pure $ case result of+      Left _ -> Nothing+      Right bytes -> either (const Nothing) Just (fromATerm bytes)++  -- Look up a derivation recorded earlier this session by its .drv path,+  -- reusing the esDrvClosure ATerm map (populated bottom-up by recordDrvAterm).+  -- This recovers an in-session all-outputs reference's output names without a+  -- disk read - the .drv is not written to the store until after evaluation.+  lookupSessionDrv drvPathText = EvalIO $ do+    ref <- asks esDrvClosure+    closure <- liftIO (readIORef ref)+    pure (Map.lookup drvPathText closure >>= either (const Nothing) Just . fromATerm)++  lookupSessionReferences sp = EvalIO $ do+    ref <- asks esStoreWriteCache+    writes <- liftIO (readIORef ref)+    pure (fst <$> Map.lookup (canonicalStorePathText sp) writes)++  -- The store is asked about each path the session cannot answer itself:+  -- what evaluation fetched, or made in a read-write session, needs no+  -- answer.  A path that is not valid is refused before any derivation is+  -- read; each output's path is then read from its derivation, the one+  -- this session recorded or the store's, and the plan carried out+  -- ("Nix.Eval.RealiseContext"), after the warning it gives, as upstream+  -- warns before it builds.+  realiseContext ctx = do+    st <- EvalIO ask+    pending <- pendingPaths+    let request = contextRequest ctx+        (mode, queries) = sessionQueries (esStore st)+        asked = Set.fromList [path | path <- crPaths request, maybe True (\origin -> mode == ReadOnly && origin == Computed) (Map.lookup path pending)]+    valid <- validAmong queries asked+    case firstInvalidPath mode pending valid request of+      Just path -> pure (Left (PathNotValid path))+      Nothing -> do+        outputPaths <- Map.fromList . catMaybes <$> traverse outputPathOf (crOutputs request)+        validOutputs <- validAmong queries (Set.fromList (Map.elems outputPaths))+        case planRealisation (epImportFromDerivation (esPolicy st)) mode pending (valid <> validOutputs) outputPaths request of+          Left refusal -> pure (Left refusal)+          Right plan -> do+            mapM_ warnMessage (planWarning plan)+            realisePlan (esStore st) queries plan+    where+      outputPathOf named@(drv, output) = do+        recorded <- lookupSessionDrv (canonicalStorePathText drv)+        derivation <- maybe (readStoreDerivation drv) (pure . Just) recorded+        pure ((,) named . doPath <$> (derivation >>= find ((== output) . doName) . drvOutputs))++  storeSourcePath rawPath = do+    ref <- EvalIO (asks esSourcePathCache)+    cached <- EvalIO (liftIO (Map.lookup rawPath <$> readIORef ref))+    case cached of+      Just hit -> pure (canonicalStorePathText (scStorePath hit))+      Nothing -> do+        -- Upstream names the copy baseNameOf(canonicalized path); path+        -- values arrive canonicalized, so the last segment is the name.+        -- A root, which has none, is refused before its tree is read.+        -- A name the store-path rules refuse is refused only once the tree+        -- is hashed, as upstream's is: the refusal names the path the copy+        -- would have had.+        let name = canonBaseName rawPath+        when (T.null name) $+          throwEvalError ("cannot copy '" <> rawPath <> "' to the store: the path has no base name")+        -- The path with the links among its ancestors followed and its+        -- own left alone, under the path's own name, inside the store+        -- too: upstream's copyPathToStore stores+        -- path.resolveSymlinks(SymlinkResolution::Ancestors) under+        -- path.baseName() (eval.cc, 2.34.9 and later), so a path that is a+        -- link is copied as the link, and the policy walks no further, since+        -- upstream's accessor reads the link rather than following it.+        -- 2.24.9 resolved the path in full (copyPathToStore in eval.cc) and+        -- copied what a link points to; nova-nix follows the newest release.+        accessPathResolving ResolveAncestors rawPath+        resolvedText <- resolvedAncestors rawPath+        -- Read where the text names it and under the case-hack its+        -- volume needs, as copyPathToStore reads: a path inside the+        -- store is copied too, and store text names the store this+        -- evaluation was given, not the canonical directory.+        caseHack <- readCaseHack resolvedText+        resolvedSource <- evalStoreTextPath resolvedText+        entry <- serialiseSource resolvedText caseHack resolvedSource+        let narDigest = sha256Digest (NAR.serialise entry)+        sp <- storePathOrThrow (makeFixedOutputPath name "sha256" NarIngestion narDigest)+        let spText = canonicalStorePathText sp+        -- The copy records the tree it was hashed from, so the build+        -- driver restores that tree rather than the path as written.+        EvalIO (liftIO (modifyIORef' ref (Map.insert rawPath (SourceCopy sp resolvedText))))+        -- The copy is readable afterwards, as upstream's copyPathToStore+        -- allows its destination.+        allowPath spText+        pure spText++  getCurrentTime = EvalIO (asks esTimestamp)++  writeToStore name contents refs = do+    -- Upstream's text-path scheme via makeTextPath - the same scheme .drv+    -- paths use, so it is parity-validated: type @text:<refs>@, flat+    -- sha256 of the contents, canonical store dir.  Construction also+    -- validates the name, so the write below never targets a path+    -- outside the store root.  The contents are the string's RAW BYTES,+    -- hashed and written as-is: no encoding step, and no text-mode IO+    -- (which would CRLF-translate on Windows and store bytes that no+    -- longer match the hash that named the path).+    sp <- storePathOrThrow (makeTextPath name (sha256Digest contents) refs)+    let storePath = canonicalStorePathText sp+    writtenFor Computed sp (pure (TextWrite name (Set.fromList refs) contents)) $ do+      filePath <- evalFilePath sp+      wrapIO $ do+        -- Adopt an existing file only when its bytes are these bytes: an+        -- interrupted earlier run can leave a truncated file here, and+        -- skipping on bare existence adopted it under this path's hash.+        -- 'Dir.removePathForcibly' clears read-only marks and accepts a+        -- missing path, so a sealed or squatting leftover rewrites too.+        existing <- readBytesIfPresent filePath+        unless (existing == Just contents) $ do+          Dir.removePathForcibly filePath+          BS.writeFile filePath contents+        -- Adopted or written, the file takes the metadata upstream's+        -- LocalStore::addToStoreFromDump gives what it adds (local-store.cc),+        -- which builtins.toFile calls (prim_toFile in primops.cc).+        canonicalizeMetadata filePath+    recordStoreWrite Computed storePath refs SP.WriteText+    -- Upstream's toFile returns the path through allowAndSetStorePathString.+    allowPath storePath+    pure storePath++  scopedImportFile scope rawPath = do+    baseDir <- EvalIO (asks esBaseDir)+    baseEnv <- EvalIO (asks esBaseEnv)+    policy <- EvalIO (asks esPolicy)+    located@(target, _) <- resolveImportTarget baseDir rawPath+    source <- readImportTarget located+    scopeNames <- attrSetKeys scope+    let fileDir = takeDirectory target+    case parseNixWithScope (Set.union (Set.fromList scopeNames) (rootScopeNames policy)) fileDir (SourceFile (T.pack target)) source of+      Left err -> rejectSource "scopedImport" target err+      Right parsed -> do+        -- No import cache for scoped imports (different scopes = different results)+        EvalIO+          ( local+              (\s -> s {esBaseDir = fileDir})+              (unEvalIO (evalParsed (builtinEnvWithScope baseEnv scope) parsed))+          )++  readFileBytes path = do+    accessPath path+    evalStoreTextPath path >>= \resolved -> sourceIOWith ReadFile (resolvedForMessage path resolved) (BS.readFile resolved)++  -- An lstat of the path itself, no symlink walk: upstream's readFileType+  -- realises its argument without resolution, the allow list checks the+  -- path it is handed (so a refusal names the path asked for), and the+  -- posix accessor beneath refuses a symlink anywhere above it, in every+  -- mode, so the type of a path reached through a symlinked directory is+  -- never revealed.+  getFileType path = do+    accessPathDirect path+    refuseSymlinkedAncestor path+    evalStoreTextPath path >>= \resolved -> sourceIO StatPath path (classifyPath resolved)++  runProcess cmd cmdArgs stdinText = wrapIO $ do+    let cp =+          (Proc.proc (T.unpack cmd) (map T.unpack cmdArgs))+            { Proc.std_in = Proc.CreatePipe,+              Proc.std_out = Proc.CreatePipe,+              Proc.std_err = Proc.CreatePipe+            }+    (exitCode, stdoutStr, stderrStr) <-+      Proc.readCreateProcessWithExitCode cp (T.unpack stdinText)+    let code = case exitCode of+          ExitSuccess -> 0+          ExitFailure n -> n+    pure (code, T.pack stdoutStr, T.pack stderrStr)++  createScratchDir prefix = do+    dir <- T.pack <$> wrapIO (newScratchDirectory prefix)+    -- The evaluator's own scratch area, not ambient filesystem: what a+    -- fetch lands there is read back under the same rule that makes a+    -- fetched store path readable afterwards.  Allowed under its resolved+    -- spelling too, because the walk follows symlinks and a temp dir can+    -- sit behind one (macOS's /var is /private/var), and under the given+    -- spelling so the walk may traverse the link's own ancestors.+    resolved <- wrapIO (Dir.canonicalizePath (T.unpack dir))+    allowPath dir+    allowPath (T.pack resolved)+    pure dir++  removeScratchDir dir = wrapIO (Dir.removePathForcibly (T.unpack dir))++  copyPathToStore origin srcPath name pin = do+    -- Content-addressed like upstream addToStore: recursive NAR sha256+    -- under the caller's name.  Same content means same path, so the+    -- existence check in 'unpackToStoreVerified' is sound: changed source+    -- content can never serve stale bytes from an earlier copy.+    -- The tree behind the root's symlinks, under the root's own name, as+    -- upstream's copyPathToStore and addPath store path.resolveSymlinks()+    -- under path.baseName(); the walk checks the policy on the way.+    resolvedText <- resolveSymlinks srcPath+    caseHack <- readCaseHack resolvedText+    resolvedSource <- evalStoreTextPath resolvedText+    entry <- serialiseSource resolvedText caseHack resolvedSource+    let nar = NAR.serialise entry+        narDigest = sha256Digest nar+    case pin of+      Just (expected, mismatch) | expected /= narDigest -> throwEvalError (mismatch narDigest)+      _ -> pure ()+    -- The name is refused only once the tree is hashed, as upstream's is:+    -- the refusal names the path the copy would have had.+    sp <- storePathOrThrow (makeFixedOutputPath name "sha256" NarIngestion narDigest)+    let destPath = canonicalStorePathText sp+    -- Restored from the entry just hashed, not copied from the source:+    -- the store's volume may fold a pair the source's keeps apart, and+    -- the tree that lands is exactly the one the address names.+    writtenFor origin sp (pure (NarWrite name nar)) $ do+      destFilePath <- evalFilePath sp+      wrapIO (unpackToStoreVerified destFilePath entry narDigest) >>= either throwEvalError pure+    recordStoreWrite origin destPath [] SP.WriteRecursive+    allowPath destPath+    pure destPath++  narHashOfPath path = do+    accessPath path+    caseHack <- readCaseHack path+    resolved <- evalStoreTextPath path+    wrapIO (sha256Digest . NAR.serialise <$> ExecBit.serialiseFromPath caseHack resolved)++  isExecutableFile path = do+    accessPath path+    evalStoreTextPath path >>= \resolved -> wrapIO (ExecBit.isExecutable resolved)++  setExecutableFile path = do+    accessPath path+    evalStoreTextPath path >>= \resolved -> wrapIO (ExecBit.markExecutable resolved)++  lookupFetchCache key = wrapIO $ do+    file <- fetchCacheFile key+    there <- Dir.doesFileExist file+    if not there+      then pure Nothing+      else do+        recorded <- try (BS.readFile file) :: IO (Either IOException BS.ByteString)+        pure $ case recorded of+          Left _ -> Nothing+          Right bytes -> either (const Nothing) Just (TE.decodeUtf8' bytes)++  -- A store that takes writes as they are made holds what a fetch wrote+  -- there, and the disk, which evaluation never wrote, says nothing of+  -- it: the store is asked.  Otherwise the path is adopted from the+  -- store's directory.+  adoptStorePath path = do+    st <- EvalIO ask+    case soEvalWrites (sessionOps (esStore st)) of+      WrittenInDirectory -> adoptFromDirectory path+      AddedAsMade made -> adoptHeldPath made path++  pinnedFetchHeld sp = do+    st <- EvalIO ask+    pending <- pendingPaths+    let (mode, queries) = sessionQueries (esStore st)+    valid <- validAmong queries (Set.singleton sp)+    let held = readableIn mode pending valid sp+    held <$ when held (allowPath (canonicalStorePathText sp))++  writeFetchCache key value = wrapIO $ do+    file <- fetchCacheFile key+    -- The cache is an optimisation: a machine that cannot write one still+    -- has to be able to build.+    _ <-+      try+        ( do+            Dir.createDirectoryIfMissing True (takeDirectory file)+            -- Written beside the entry and renamed onto it, so a reader+            -- sees either the whole entry or none of it. A plain write can+            -- be cut short and leave a torn file behind, and an entry is+            -- trusted for as long as its store path survives.+            let staging = file ++ ".tmp"+            BS.writeFile staging (TE.encodeUtf8 value)+            Dir.renameFile staging file+        ) ::+        IO (Either IOException ())+    pure ()++  -- The two checks of getFileType: upstream's readLink asserts no+  -- symlink above the path it is handed as well.+  readSymlinkTarget path = do+    accessPathDirect path+    refuseSymlinkedAncestor path+    evalStoreTextPath path >>= \resolved -> wrapIO (T.pack <$> Dir.getSymbolicLinkTarget resolved)++  addSourceNar name narBytes =+    case NAR.deserialise narBytes of+      -- The bytes are the NAR of a tree the filter walk just built, so+      -- they fail to parse only when the tree holds what a filesystem can+      -- hold and the parser refuses, such as a name past the length the+      -- parser holds names to: on Windows a name of 255 UTF-16 units can+      -- pass 255 bytes of UTF-8.  Upstream's restore of its own dump+      -- refuses such an archive in its parser's words, and the refusal+      -- here is the parser's too.+      Left err -> throwEvalError (T.pack err)+      Right entry -> do+        sp <- storePathOrThrow (makeFixedOutputPath name "sha256" NarIngestion (sha256Digest narBytes))+        let destPath = canonicalStorePathText sp+        writtenFor Computed sp (pure (NarWrite name narBytes)) $ do+          destFilePath <- evalFilePath sp+          wrapIO (unpackToStoreVerified destFilePath entry (sha256Digest narBytes)) >>= either throwEvalError pure+        recordStoreWrite Computed destPath [] SP.WriteRecursive+        allowPath destPath+        pure destPath++  addFixedOutputFile origin name bytes = do+    -- Canonical fixed-output path: a sha256-pinned fetch must land at the same+    -- store path C++ Nix computes, so it stays reproducible and cache-compatible.+    sp <- storePathOrThrow (makeFixedOutputPath name "sha256" FlatIngestion (sha256Digest bytes))+    let storePath = canonicalStorePathText sp+    writtenFor origin sp (pure (FlatWrite name bytes)) $ do+      filePath <- evalFilePath sp+      wrapIO $ do+        -- Same verified adoption as the other writers: an unconditional+        -- write would crash on a sealed leftover (the write hits+        -- read-only).+        existing <- readBytesIfPresent filePath+        unless (existing == Just bytes) $ do+          Dir.removePathForcibly filePath+          BS.writeFile filePath bytes+        -- The metadata upstream gives a downloaded file it adds+        -- (LocalStore::addToStore in local-store.cc).+        canonicalizeMetadata filePath+    recordStoreWrite origin storePath [] SP.WriteFlat+    allowPath storePath+    pure storePath++  fetchUrlBytes url = do+    st <- EvalIO ask+    case downloadSourceOf (esStoreDir st) url of+      Left refusal -> pure (Left refusal)+      Right source -> wrapIO (downloadBytes (esLogger st) (esFetchRetry st) url source)++  fetchArchiveToStore url name pin = do+    st <- EvalIO ask+    case downloadSourceOf (esStoreDir st) url of+      Left refusal -> pure (Left (FetchFailure [] refusal))+      Right source -> do+        refusal <- wrapIO (localArchiveRefusal source)+        case refusal of+          Just failure -> pure (Left failure)+          Nothing -> withScratchDirectory tarballScratchPrefix $ \scratch -> do+            downloaded <- wrapIO (withUrlBody (esLogger st) (esFetchRetry st) url source (unpackArchive scratch))+            case downloaded of+              Left message -> pure (Left (FetchFailure [] message))+              Right (warnings, unpacked) -> do+                mapM_ warnMessage warnings+                either (pure . Left) (storeArchive scratch name pin) unpacked++  traceMessage msg = do+    logger <- EvalIO (asks esLogger)+    EvalIO (liftIO (logMessage logger msg))++  evalPolicy = EvalIO (asks esPolicy)++  checkUri uri = do+    st <- EvalIO ask+    allowed <- EvalIO (liftIO (readIORef (esAllowedPaths st)))+    either throwEvalError pure (uriAccess (esStoreDir st) (esPolicy st) allowed uri)++  qualifyPath path = EvalIO (asks ((`SP.qualifyPathText` path) . esStoreDir))++  -- Every path is resolved in the value domain, as upstream resolves+  -- one over the union of the host's file system and the store+  -- (rootFS in EvalState's constructor, eval.cc, 2.34.9 and later): each+  -- link is read through the store this evaluation was given, so a host+  -- link into the store is followed on inside it, and store text keeps its+  -- canonical spelling, as an import target's does ('resolveImportTarget'+  -- says why).+  resolveSymlinks path = do+    accessPath path+    st <- EvalIO ask+    either absurd id <$> walkLinks ResolveFull (\_ _ -> Right ()) st (locatedPath st path)++  resolvePathLiteral path = do+    baseDir <- EvalIO (asks esBaseDir)+    policy <- EvalIO (asks esPolicy)+    -- ~/x resolves against the home directory here, at eval, while+    -- upstream's parser expands it as it reads the literal; everything+    -- else relative joins the base dir.  Both end at the producer gate+    -- ('canonPathValue'): the value is absolute, lexically canonical, and+    -- slash-spelled regardless of the base dir's native spelling -+    -- platform separators exist only at the filesystem boundary.  Under+    -- pure-eval the home directory is ambient state, and upstream's parser+    -- refuses the literal outright; the same refusal lands here, where the+    -- expansion is.+    expanded <- case T.stripPrefix "~/" path of+      Just below+        | epPureEval policy ->+            throwEvalError ("the path '" <> path <> "' can not be resolved in pure mode")+        | otherwise -> do+            home <- wrapIO Dir.getHomeDirectory+            pure (home </> T.unpack below)+      Nothing -> pure (T.unpack path)+    let absolute = if isRelative expanded then baseDir </> expanded else expanded+    pure (canonPathValue (T.pack absolute))++  forceThunk evalFn (Thunk ptr) = do+    -- Force protocol: PENDING to BLACKHOLE to COMPUTED with memoization.+    -- Scalar values (int/float/bool/null) are stored inline in the+    -- thunk payload, dispatched via val_tag.+    --+    -- Blackhole detection: PENDING thunks are marked BLACKHOLE before+    -- evaluation begins.  If evaluation re-enters the same thunk, it+    -- sees BLACKHOLE and reports infinite recursion.  This is safe with+    -- knot-tying (evalBcRecAttrs, evalBcLet, matchFormalSet) because those+    -- patterns create distinct thunks sharing an env - no thunk ever+    -- forces itself.+    state <- cthunkState ptr+    case state of+      ThunkComputed -> readComputed ptr+      ThunkBlackhole ->+        -- Infinite recursion is non-catchable (like abort), matching C++ Nix.+        -- tryEval must NOT catch blackholes - using abortEvaluation ensures+        -- the error propagates through tryEval/catchEvalError.+        abortEvaluation "infinite recursion encountered"+      ThunkPending -> do+        pending <- readPending ptr+        -- Mark blackhole BEFORE evaluation - any re-entry hits the+        -- BLACKHOLE branch above.+        marked <- cthunkMarkBlackhole ptr+        unless marked $+          EvalIO (liftIO (cInvariantViolated "nn_thunk_mark_blackhole" "a thunk read as PENDING was not PENDING"))+        -- If the force throws (a builtins.throw caught by an upstream tryEval,+        -- a type error, a failed import), restore the thunk to PENDING and+        -- rethrow, so a later force of this shared thunk re-evaluates instead of+        -- taking the BLACKHOLE branch above and aborting with a bogus "infinite+        -- recursion".  Mirrors C++ Nix forceValue: catch (...) { restore; throw }.+        -- A genuine self-recursion still rethrows its NixAbortError, which+        -- escapes tryEval.  Storing the value is inside the restore too,+        -- since copying or marshalling it can fail.  The+        -- restore's own answer is not needed: it refuses only a thunk that is+        -- no longer BLACKHOLE, which a later force already handles, and the+        -- exception in flight is the one to report.+        -- While regions run the force is a region, closed once its value+        -- is stored or it throws, so the store, which can allocate, is+        -- inside it.  Whatever in the C data layer the value handed back+        -- points at, the cell reaches too, so a collecting close, which+        -- frees only what nothing older reaches, leaves it.+        EvalIO $ do+          st <- ask+          liftIO+            ( inRegion+                (esRegions st)+                ( ( do+                      result <- runReaderT (unEvalIO (evalFn pending)) st+                      storeComputed ptr result+                      pure result+                  )+                    `onException` cthunkMarkPending ptr+                )+            )+      other ->+        EvalIO (liftIO (cInvariantViolated "nn_thunk_state" ("no thunk has state " ++ show other)))++-- | Store a forced thunk's NixValue in its C cell.+-- Scalars (int, float, bool, null) and a builtin with no argument taken+-- are stored inline; strings and paths (over the C object their bytes are+-- held in, or a copy), lists, sets, lambdas and partial applications as+-- their C objects.  The cell is BLACKHOLE while its force runs, which+-- keeps every other path from computing it, so a setter's refusal is an+-- invariant violation rather than a value to drop.+storeComputed :: CThunkPtr -> NixValue -> IO ()+storeComputed ptr val = do+  stored <- case val of+    VInt n -> cthunkSetComputedInt ptr n+    VFloat d -> cthunkSetComputedFloat ptr d+    VBool b -> cthunkSetComputedBool ptr (if b then 1 else 0)+    VNull -> cthunkSetComputedNull ptr+    VAttrs (AttrSet cset) -> cthunkSetComputedAttrs ptr (castPtr cset)+    VPathHeld p held -> pathCell p held >>= cthunkSetComputedPath ptr+    VStrHeld t ctx held ->+      stringCell t ctx held >>= \case+        StrCell str -> cthunkSetComputedStr ptr str+        CtxStrCell csptr -> cthunkSetComputedCtxStr ptr (castPtr csptr)+    VList (CList clistPtr) -> cthunkSetComputedList ptr (castPtr clistPtr)+    VLambda (Env envPtr) formals bodyBcIdx -> do+      lamPtr <- marshalLambda envPtr formals bodyBcIdx+      cthunkSetComputedLambda ptr lamPtr+    VBuiltin builtin args ->+      primopCell builtin args >>= \case+        PrimopCell primop -> cthunkSetComputedPrimop ptr primop+        PrimopAppCell app -> cthunkSetComputedPrimopApp ptr (castPtr app)+  unless stored (cInvariantViolated "nn_thunk_set_computed_*" "a thunk being forced was already COMPUTED")++-- ---------------------------------------------------------------------------+-- Constants+-- ---------------------------------------------------------------------------++-- | The variable upstream reads its lookup path from.+nixPathVar :: BS.ByteString+nixPathVar = "NIX_PATH"++-- | Random bytes in a scratch-dir name suffix (hex-encoded).  128 bits:+-- unguessable by another local process, collision-free in practice.+scratchSuffixBytes :: Int+scratchSuffixBytes = 16++-- ---------------------------------------------------------------------------+-- Helpers+-- ---------------------------------------------------------------------------++-- ---------------------------------------------------------------------------+-- Access policy+-- ---------------------------------------------------------------------------++-- | Admit a store object this evaluation produced (upstream's @allowPath@+-- after a copy, fetch or write).+allowPath :: Text -> EvalIO ()+allowPath path = do+  st <- EvalIO ask+  EvalIO (liftIO (allowEvalPath st path))++-- | The operations of a session's store, whichever kind of session it is.+sessionOps :: SessionStore -> StoreOps IO+sessionOps (ReadOnlySession _ ops) = ops+sessionOps (ReadWriteSession ops) = ops++-- | What a session's store says about what it holds, and whether the+-- session may add to it.+sessionQueries :: SessionStore -> (SessionMode, StoreQueries IO)+sessionQueries (ReadOnlySession queries _) = (ReadOnly, queries)+sessionQueries (ReadWriteSession ops) = (ReadWrite, soQueries ops)++-- | Which of the paths the store holds, asking it nothing when there are+-- none: a read-write session's store opens with its first question.+validAmong :: StoreQueries IO -> Set SP.StorePath -> EvalIO (Set SP.StorePath)+validAmong queries paths+  | Set.null paths = pure Set.empty+  | otherwise = wrapIO (sqValidPaths queries paths)++-- | The store paths of what evaluation has made and the session has not+-- added to its store, each with how it came to be: the sources it named,+-- the trees it wrote, a fetcher's among them, and the derivations it+-- recorded.  What has been added the store answers for, except what a+-- fetcher fetched, which is readable whether or not it has been added+-- and so needs no answer.+pendingPaths :: EvalIO (Map SP.StorePath PendingOrigin)+pendingPaths = do+  st <- EvalIO ask+  EvalIO . liftIO $ do+    sources <- readIORef (esSourcePathCache st)+    writes <- readIORef (esStoreWriteCache st)+    drvs <- readIORef (esDrvClosure st)+    fetched <- readIORef (esFetched st)+    added <- readIORef (esAdded st)+    let originOf path = if path `Set.member` fetched then Fetched else Computed+        copies = map (canonicalStorePathText . scStorePath) (Map.elems sources)+        made = filter (\path -> path `Set.notMember` added || path `Set.member` fetched) (copies <> Map.keys writes <> Map.keys drvs)+    pure (Map.fromList [(sp, originOf path) | path <- made, Just sp <- [SP.parseStorePath SP.defaultStoreDir path]])++-- | Carry a realisation's plan out: in a read-write session add what+-- evaluation made, then in either session realise the outputs through+-- its build, then make their closures readable.+realisePlan :: SessionStore -> StoreQueries IO -> Plan -> EvalIO (Either ContextRefusal ())+realisePlan store queries plan = runExceptT $ do+  case store of+    ReadOnlySession _ ops -> realiseThrough (soBuild ops)+    ReadWriteSession ops -> do+      when (planAdd plan) (ExceptT (addMade ops))+      realiseThrough (soBuild ops)+  ExceptT (allowClosures queries (planOutputs plan))+  where+    realiseThrough build =+      unless (null (planBuilds plan)) $+        ExceptT (first stopped <$> wrapIO (build (planBuilds plan)))+    stopped = RealisationFailed . fst . stopReported++-- | Add to a read-write session's store what evaluation has made and not+-- yet added there, references first ('soAddEvalObjects').  A store that+-- refuses the add, or a write that fails, is a failed realisation, worded+-- as the build command reports it.+addMade :: StoreOps IO -> EvalIO (Either ContextRefusal ())+addMade ops = do+  st <- EvalIO ask+  objects <- EvalIO . liftIO $ do+    added <- readIORef (esAdded st)+    let notAdded = (`Set.notMember` added)+    (EvalObjects . Map.filterWithKey (const . notAdded . canonicalStorePathText) . sourceCopies <$> readIORef (esSourcePathCache st))+      <*> (Map.filterWithKey (const . notAdded) <$> readIORef (esStoreWriteCache st))+      <*> (Map.filterWithKey (const . notAdded) <$> readIORef (esDrvClosure st))+  if nothingToAdd objects then pure (Right ()) else addAll st objects+  where+    addAll st objects = do+      outcome <- wrapIO (try (soAddEvalObjects ops objects))+      recordAdded st objects outcome+    recordAdded st objects outcome = case outcome of+      Left (failure :: IOException) -> pure (Left (RealisationFailed (exceptionText (toException failure))))+      Right (Left reason) -> pure (Left (RealisationFailed reason))+      Right (Right ()) -> do+        let paths = map canonicalStorePathText (Map.keys (eoSources objects)) <> Map.keys (eoStoreWrites objects) <> Map.keys (eoDerivations objects)+        Right () <$ EvalIO (liftIO (modifyIORef' (esAdded st) (<> Set.fromList paths)))++-- | Under a restricting policy, make readable every path in the closures+-- of a realisation's outputs, as upstream's @allowClosure@ does+-- (eval.cc at 2.34.9).  A no-op otherwise, and nothing is asked.+allowClosures :: StoreQueries IO -> [SP.StorePath] -> EvalIO (Either ContextRefusal ())+allowClosures queries outputs = do+  st <- EvalIO ask+  if not (pathsRestricted (esPolicy st)) || null outputs+    then pure (Right ())+    else do+      closure <- wrapIO (referenceClosure (sqReferences queries) outputs)+      case closure of+        Left failure -> pure (Left (RealisationFailed failure))+        Right paths -> Right () <$ mapM_ (allowPath . canonicalStorePathText) (Set.toList paths)++-- | Refuse a read unless the whole path, symlinks resolved, lies in the+-- allowed prefixes.  Upstream's accessor checks every prefix as its+-- symlink walk pushes it (@SourceAccessor::resolveSymlinks@ through+-- @FilteringSourceAccessor::maybeLstat@, which throws at 2.24.9), so the+-- refusal names the first prefix outside the allow list - @/etc@ for+-- @/etc/passwd@ when nothing under @/etc@ is allowed - and a symlink's+-- target is checked where the walk follows it.  A no-op when nothing+-- restricts access.+accessPath :: Text -> EvalIO ()+accessPath = accessPathResolving ResolveFull++-- | 'accessPath' walking as the given resolution does: under+-- 'ResolveAncestors' the last component is checked in place and its+-- link not followed, for a read of the link itself.+accessPathResolving :: SymlinkResolution -> Text -> EvalIO ()+accessPathResolving mode path = do+  st <- EvalIO ask+  when (pathsRestricted (esPolicy st)) $ do+    allowed <- EvalIO (liftIO (readIORef (esAllowedPaths st)))+    walkAllowed mode st allowed path >>= either throwEvalError pure++-- | Path-value text with the links among its ancestors followed and its+-- own last component left alone, upstream's+-- @resolveSymlinks(SymlinkResolution::Ancestors)@, walked in the value+-- domain ('walkLinks'): each link is read through the store mapping, so+-- store text stays canonical, and every other path is walked on the+-- drive its read opens ('locatedPath').+resolvedAncestors :: Text -> EvalIO Text+resolvedAncestors path = do+  st <- EvalIO ask+  either absurd id <$> walkLinks ResolveAncestors (\_ _ -> Right ()) st (locatedPath st path)++-- | Refuse a read unless the path itself is allowed, no symlink walk: the+-- check upstream's accessor makes on an lstat or readlink of the path it+-- is handed.  The refusal names the path asked for.+accessPathDirect :: Text -> EvalIO ()+accessPathDirect path = do+  st <- EvalIO ask+  when (pathsRestricted (esPolicy st)) $ do+    allowed <- EvalIO (liftIO (readIORef (esAllowedPaths st)))+    let canonical = locatedPath st path+    unless (isAbsolutePath canonical) $ throwEvalError (relativePathMessage path)+    unless (isAllowedPath allowed canonical) $+      throwEvalError (forbiddenPathMessage (esPolicy st) canonical)++-- | Whether the walk would admit the path, for the one reader that+-- answers a Boolean instead of refusing.+pathAllowed :: SymlinkResolution -> Text -> EvalIO Bool+pathAllowed mode path = do+  st <- EvalIO ask+  if pathsRestricted (esPolicy st)+    then do+      allowed <- EvalIO (liftIO (readIORef (esAllowedPaths st)))+      isRight <$> walkAllowed mode st allowed path+    else pure True++-- | Refuse a path with a symlink anywhere above it, naming the deepest+-- one: upstream's posix accessor asserts this on an lstat or readlink of+-- the path it is handed (@PosixSourceAccessor::assertNoSymlinks@ over+-- the parent, at 2.24.9), in every mode, and names the first symlink it+-- meets walking up from the parent.  It looks only beneath its root, and+-- the store's accessor has the store directory for its root+-- (@PosixDirectorySourceAccessor::openParent@ in posix-source-accessor.cc+-- at 2.35.4, @openParentAndUpsert@ at 2.36.0), so the store directory and+-- its ancestors are not looked at for a path in the store+-- ('storeRootPrefix').+refuseSymlinkedAncestor :: Text -> EvalIO ()+refuseSymlinkedAncestor path = do+  st <- EvalIO ask+  let canonical = canonPathValue path+      beneathRoot ancestor = not (storeRootPrefix (pathComponents canonical) (pathComponents ancestor))+  mapM_ (check st) (filter beneathRoot (strictAncestors canonical))+  where+    check st ancestor = do+      target <- EvalIO (liftIO (symlinkTargetAt st ancestor))+      when (isJust target) $+        throwEvalError ("path '" <> ancestor <> "' is a symlink")++-- | A canonical path's ancestors below the root, deepest first.+strictAncestors :: Text -> [Text]+strictAncestors path =+  [joinComponents (take n components) | n <- [length components - 1, length components - 2 .. 1]]+  where+    components = pathComponents path++-- | How a 'PathExistence' query walks the path: a directory is demanded+-- through the final symlink, an entry is found in place.+existenceResolution :: PathExistence -> SymlinkResolution+existenceResolution ExistsAsDirectory = ResolveFull+existenceResolution ExistsAsEntry = ResolveAncestors++-- | The stat a 'PathExistence' query ends in: a directory through every+-- symlink, or an entry of any kind in place.+existsAs :: PathExistence -> FilePath -> IO Bool+existsAs ExistsAsDirectory = Dir.doesDirectoryExist+existsAs ExistsAsEntry = lstatExists++-- | Whether an entry is at the path, a dangling symlink included: an+-- lstat, as upstream's @maybeLstat@ is.  'Dir.pathIsSymbolicLink' is the+-- lstat the directory package exposes, and it throws for a missing path,+-- so any failure is absence, as it is for 'Dir.doesPathExist'.+lstatExists :: FilePath -> IO Bool+lstatExists fp = do+  outcome <- try (Dir.pathIsSymbolicLink fp) :: IO (Either IOException Bool)+  pure (isRight outcome)++-- | Upstream's @coerceToPath@ refusal of a relative string.  The builtins+-- refuse one before it gets here; the gate repeats the refusal because+-- its soundness depends on it.+relativePathMessage :: Text -> Text+relativePathMessage path = "string '" <> path <> "' doesn't represent an absolute path"++-- | The allow list consulted along upstream's symlink walk+-- ('walkLinks'): the prefix so far must be allowed, and 'Left' carries+-- the refusal for the first prefix outside it.  The path is walked on+-- the drive its read opens ('locatedPath'), the form the allow list+-- holds.+walkAllowed :: SymlinkResolution -> EvalState -> AllowedPaths -> Text -> EvalIO (Either Text ())+walkAllowed mode st allowed path+  | not (isAbsolutePath canonical) = pure (Left (relativePathMessage path))+  | otherwise = void <$> walkLinks mode refusalAt st canonical+  where+    canonical = locatedPath st path+    refusalAt prefix prefixText+      | isAllowedPrefix allowed prefix = Right ()+      | otherwise = Left (forbiddenPathMessage (esPolicy st) prefixText)++-- | The walk of a path through its symlinks ('walkPath') under the+-- host's rules, each link read through the store mapping+-- ('symlinkTargetAt').  A chain of links past upstream's bound is+-- refused as upstream refuses it.+walkLinks :: SymlinkResolution -> ([Text] -> Text -> Either e ()) -> EvalState -> Text -> EvalIO (Either e Text)+walkLinks mode refusalAt st canonical =+  walkPath hostPathRules mode refusalAt (EvalIO . liftIO . symlinkTargetAt st) canonical >>= \case+    Left WalkLoops -> throwEvalError ("infinite symlink recursion in path '" <> canonical <> "'")+    Left (WalkRefused refusal) -> pure (Left refusal)+    Right resolved -> pure (Right resolved)++-- | The target of the symlink at a path value, read through the store+-- mapping, or 'Nothing' when there is no symlink there.  A path that+-- does not exist is simply not a symlink; the read that follows reports+-- it missing.  On Windows a reparse point whose target no path value+-- spells, a volume mount point among them, is not taken for a link+-- ('linkTarget'): the read that follows lets Windows resolve it, as a+-- POSIX read crosses a mount.+symlinkTargetAt :: EvalState -> Text -> IO (Maybe Text)+symlinkTargetAt st pathText = do+  let fsPath = SP.storeTextToFilePath (esStoreDir st) pathText+  outcome <-+    try+      ( do+          isLink <- Dir.pathIsSymbolicLink fsPath+          if isLink then Just . T.pack <$> Dir.getSymbolicLinkTarget fsPath else pure Nothing+      ) ::+      IO (Either IOException (Maybe Text))+  pure (mfilter (isJust . linkTarget hostPathRules) (fromRight Nothing outcome))++-- | Where a recorded fetch is kept: one file per key, under this user's+-- cache directory, named by the key's own hash. Outside the store on+-- purpose - it's a note about work already done, not a derivation input.+fetchCacheFile :: Text -> IO FilePath+fetchCacheFile key = do+  dir <- Dir.getXdgDirectory Dir.XdgCache "nova-nix/fetch"+  pure (dir </> T.unpack (bytesToHexText (sha256Digest (TE.encodeUtf8 key))))++-- | Where a store path lives on this machine: this evaluation's store dir+-- mapped to a filesystem path.  This is the 'SP.StorePath' direction;+-- path-value text goes through 'evalStoreTextPath'.  Both must read the+-- same store dir, since a store honored on one side and not the other+-- writes to one directory and reads from another.+storeFilePath :: SP.StoreDir -> SP.StorePath -> FilePath+storeFilePath = SP.storePathToFilePath++-- | Make an object evaluation made reach the session's store unless the+-- session only names it.  A read-only session writes what a fetcher+-- fetched, as upstream's fetchers add their results in any mode, and+-- computes the path of everything else without writing it, as upstream's+-- read-only evaluation does.  A read-write session writes everything.  An+-- evaluation that writes nothing never makes the store.+--+-- How it reaches the store is the store's own ('soEvalWrites').  For a+-- store whose directory evaluation writes, the given action runs.  A+-- store that takes each tree as it is made is handed the t'EvalWrite'+-- instead, and answers the path it made, which must be the one evaluation+-- computed for the object, the given path.  It needs every reference of+-- a text valid, and a reference may be a copy or a derivation evaluation+-- only named so far, so a read-write session adds what evaluation has+-- made and not added first, as a realisation adds it.  A read-only+-- session adds nothing of its own, so a reference the store does not hold+-- is the store's to refuse.  The t'EvalWrite' is made only for a store+-- that takes it, so a tree that is written from its own pieces is never+-- held whole for a store whose directory evaluation writes.+writtenFor :: PendingOrigin -> SP.StorePath -> EvalIO EvalWrite -> EvalIO () -> EvalIO ()+writtenFor origin sp makeWrite inDirectory = do+  st <- EvalIO ask+  case (esStore st, origin) of+    (ReadOnlySession _ _, Computed) -> pure ()+    (ReadOnlySession _ ops, Fetched) -> placed st ops (const (pure ()))+    (ReadWriteSession ops, _) -> placed st ops (addReferencedFirst ops)+  where+    placed :: EvalState -> StoreOps IO -> (EvalWrite -> EvalIO ()) -> EvalIO ()+    placed st ops beforeAdding = case soEvalWrites ops of+      WrittenInDirectory -> inDirectory+      AddedAsMade made -> do+        write <- makeWrite+        beforeAdding write+        stored <- wrapIO (moAdd made write) >>= either throwEvalError pure+        when (stored /= sp) $ throwEvalError (madeAnotherPath stored sp)+        EvalIO (liftIO (modifyIORef' (esAdded st) (Set.insert (canonicalStorePathText sp))))+    addReferencedFirst ops write = case write of+      TextWrite _ refs _ | not (Set.null refs) -> addMade ops >>= either (throwEvalError . contextRefusalMessage) pure+      _ -> pure ()++-- | Record a store object evaluation just made, written or only named,+-- so the build driver registers it before a derivation naming it is+-- built.  Every eval-time writer goes through this: a write that skips+-- it lands in @drvInputSrcs@ with no registration row and fails the+-- build with \"path \'...\' is not valid\".  The mode names the scheme+-- that constructed the path, so materialization can verify the on-disk+-- content reproduces it before registering.  A fetcher's write is+-- remembered as one ('esFetched'), and stays one when a computation+-- makes the same path again.+--+-- A read-only session adds what a fetcher fetched to its store at once,+-- as upstream's local store adds a fetch the moment it lands, whatever+-- the mode (@addToStore@ in tarball.cc's @downloadFile@), making its database+-- if it has none: a later read in this evaluation or a later evaluation+-- finds it valid, even if this one fails.  A read-write session adds+-- everything it made before a realisation and once evaluation is done.+recordStoreWrite :: PendingOrigin -> Text -> [SP.StorePath] -> SP.StoreWriteMode -> EvalIO ()+recordStoreWrite origin storePath refs mode = do+  st <- EvalIO ask+  EvalIO . liftIO $ do+    modifyIORef' (esStoreWriteCache st) (Map.insert storePath (refs, mode))+    when (origin == Fetched) (modifyIORef' (esFetched st) (Set.insert storePath))+  case (esStore st, origin) of+    (ReadOnlySession _ ops, Fetched) -> do+      wrapIO (soAddEvalObjects ops (EvalObjects Map.empty (Map.singleton storePath (refs, mode)) Map.empty)) >>= either throwEvalError pure+      EvalIO (liftIO (modifyIORef' (esAdded st) (Set.insert storePath)))+    _ -> pure ()++-- | Take over a store path an earlier evaluation wrote into the store's+-- directory, when it is still there.+adoptFromDirectory :: Text -> EvalIO Bool+adoptFromDirectory path = do+  resolved <- evalStoreTextPath path+  there <- wrapIO (Dir.doesPathExist resolved)+  -- Same recording the uncached fetch's copyPathToStore would have done.+  -- materializeEvalStoreWrites skips a path that is already valid, so+  -- re-recording one costs nothing and closes the case where the row is+  -- missing.+  when there $ do+    -- What is on disk may carry other modes and times than a fetch+    -- writes, so the remembered tree is made canonical as the uncached+    -- fetch's copyPathToStore makes the tree it writes.+    wrapIO (canonicalizeMetadata resolved)+    recordStoreWrite Fetched path [] SP.WriteRecursive+    -- A fetch result, whether fetched now or remembered: upstream+    -- allows the store path every fetcher returns.+    allowPath path+  pure there++-- | Take over a store path an earlier evaluation fetched into a store+-- that takes writes as they are made, when the store holds it.  Its+-- directory is the store's, so nothing is read from the disk or changed+-- there.  The path is held before the store is asked whether it has it,+-- since the answer is relied on without adding the path, and a text that+-- names no store path is not one.+adoptHeldPath :: MadeOps IO -> Text -> EvalIO Bool+adoptHeldPath made path = do+  st <- EvalIO ask+  case SP.parseStorePath SP.defaultStoreDir path of+    Nothing -> pure False+    Just sp -> do+      wrapIO (moHold made sp) >>= either throwEvalError pure+      held <- Set.member sp <$> validAmong (snd (sessionQueries (esStore st))) (Set.singleton sp)+      when held $ do+        recordStoreWrite Fetched path [] SP.WriteRecursive+        EvalIO (liftIO (modifyIORef' (esAdded st) (Set.insert path)))+        allowPath path+      pure held++-- | The file's bytes, 'Nothing' when nothing readable is there: absent,+-- or something unreadable squatting on the name; either way the writer+-- must replace rather than adopt.+readBytesIfPresent :: FilePath -> IO (Maybe BS.ByteString)+readBytesIfPresent path = do+  result <- try (BS.readFile path) :: IO (Either IOException BS.ByteString)+  pure (either (const Nothing) Just result)++-- | The NAR serialisation of what is on disk, 'Nothing' when nothing+-- serialisable is there.  Through 'ExecBit.serialiseIfReadable', the+-- same walk every producer and verifier uses, so the comparison sees+-- the executable flags the store's model records, not the platform's+-- permission guesses.+narBytesIfPresent :: NAR.CaseHack -> FilePath -> IO (Maybe BS.ByteString)+narBytesIfPresent caseHack path = do+  onDisk <- Dir.doesPathExist path+  if not onDisk+    then pure Nothing+    else fmap NAR.serialise <$> ExecBit.serialiseIfReadable caseHack path++-- | The case-hack mode a read of path-value text runs under+-- ('pathCaseHack'), against the volume of the store this evaluation+-- was given.+readCaseHack :: Text -> EvalIO NAR.CaseHack+readCaseHack path = do+  storeRoot <- EvalIO (asks (SP.unStoreDir . esStoreDir))+  wrapIO ((`pathCaseHack` path) <$> probeCaseSensitivity storeRoot)++-- | Where an eval-time store write of a path lands: 'storeFilePath'+-- against the store this evaluation was given.  Every eval-time writer+-- asks here before it writes, so a store upstream Nix's database may+-- also manage is refused at the first write, uncatchably+-- ("Nix.Store.Upstream"): a writer clears a tree there that does not+-- reproduce its address, which may be one upstream registered.  The+-- store's directory is made here too, where it is missing, as the+-- store's open makes it ('createStoreDirectory'): a write can come+-- before the store is opened, and on Windows a directory made any other+-- way takes what its parent passes down.  A store a directory on the way+-- to it makes untrustworthy is refused the same way, in the open's+-- words.  An evaluation that writes nothing never asks.+evalFilePath :: SP.StorePath -> EvalIO FilePath+evalFilePath sp = do+  storeDir <- EvalIO (asks esStoreDir)+  refusal <- wrapIO (upstreamManagedRefusal ReplacesUpstreamPaths storeDir)+  traverse_ throwEvalError refusal+  made <- wrapIO (tryJust refusedStore (createStoreDirectory (SP.unStoreDir storeDir)))+  either throwEvalError (const (pure (storeFilePath storeDir sp))) made+  where+    refusedStore err+      | isUserError err = Just (T.pack (ioeGetErrorString err))+      | otherwise = Nothing++-- | Resolve path-value text to a filesystem location against the store+-- this evaluation was given.  The read counterpart of 'evalFilePath':+-- both sides of every eval-time store access must agree on the store+-- dir, or a redirected store is written to and read from two places.+evalStoreTextPath :: Text -> EvalIO FilePath+evalStoreTextPath txt = EvalIO (asks ((`SP.storeTextToFilePath` txt) . esStoreDir))++-- | A store path's identity: the canonical @/nix/store@ spelling every+-- platform shares.  Hashes and eval-visible strings carry this form; it+-- never names a location on disk.+canonicalStorePathText :: SP.StorePath -> Text+canonicalStorePathText = SP.storePathToText SP.defaultStoreDir++-- | Fail an import whose file does not parse or bind.  Both are uncatchable,+-- as upstream's ParseError and UndefinedVarError are to @builtins.tryEval@.+-- An unbound variable reads exactly as upstream's message does; a syntax+-- error keeps the parser's detail behind the builtin and file it came from.+rejectSource :: Text -> FilePath -> SourceError -> EvalIO a+rejectSource builtinName target err = throwEvalError $ case err of+  SyntaxError syntax -> builtinName <> " " <> T.pack target <> ": " <> T.pack (show syntax)+  UndefinedVariable name -> undefinedVariableMessage name++-- | Resolve an import's raw path to the value-domain target (the import+-- cache key, the parse name, and the base dir the file's relative path+-- literals resolve against) and the filesystem location to read, as+-- @import@, @scopedImport@ and a command line's @\<NAME\>@ target find+-- their file, with both the path named and the file resolved checked+-- against the policy: upstream's @resolveExprPath@ walks the path it is+-- handed, and @parseExprFromFile@ walks the file it reads after+-- @default.nix@ has been appended, so a directory whose @default.nix@ is+-- a symlink is refused at the link's target.+--+-- Store text stays canonical in the value domain: 'Dir.canonicalizePath'+-- would attach the working drive to the rooted @/nix@ prefix on Windows,+-- so store text gets lexical canonicalization ('canonPath') only, and+-- its reads resolve through 'evalStoreTextPath'.  Every other path+-- resolves and canonicalizes as the platform path 'evalStoreTextPath'+-- gives it, where the two returned forms coincide.+resolveImportTarget :: FilePath -> Text -> EvalIO (FilePath, FilePath)+resolveImportTarget baseDir rawPath = do+  accessPath rawPath+  (target, ioTarget) <- locate+  accessPath (T.pack target)+  pure (target, ioTarget)+  where+    locate+      | SP.isCanonicalStoreText rawPath = do+          let valueBase = T.unpack (canonPath rawPath)+          resolvedBase <- evalStoreTextPath (T.pack valueBase)+          isDir <- sourceIO StatPath (T.pack valueBase) (statSource resolvedBase >> Dir.doesDirectoryExist resolvedBase)+          -- The value-domain join stays "/" so the canonical spelling survives.+          let valueTarget = if isDir then valueBase <> "/default.nix" else valueBase+          resolvedTarget <- evalStoreTextPath (T.pack valueTarget)+          pure (valueTarget, resolvedTarget)+      | otherwise = do+          raw <- evalStoreTextPath rawPath+          let resolved = if isRelative raw then baseDir </> raw else raw+          canonical <- wrapIO (Dir.canonicalizePath resolved)+          -- Directory import: append /default.nix if target is a+          -- directory, which upstream's resolveExprPath learns from an+          -- lstat, so an absent target is a stat failure.+          isDir <- sourceIO StatPath (T.pack canonical) (statSource canonical >> Dir.doesDirectoryExist canonical)+          let target = if isDir then canonical </> "default.nix" else canonical+          pure (target, target)++-- | Read the file 'resolveImportTarget' located, failing as an import+-- that cannot read its file fails.+readImportTarget :: (FilePath, FilePath) -> EvalIO BS.ByteString+readImportTarget (target, ioTarget) = sourceIO ReadFile (T.pack target) (BS.readFile ioTarget)++-- | Classify a filesystem path as @"regular"@, @"directory"@, @"symlink"@,+-- or @"unknown"@ - matching Nix's @builtins.readDir@ / @readFileType@.+classifyPath :: FilePath -> IO Text+classifyPath fp =+  firstMatch+    "unknown"+    [ (Dir.pathIsSymbolicLink fp, "symlink"),+      (Dir.doesDirectoryExist fp, "directory"),+      (Dir.doesFileExist fp, "regular")+    ]++-- | Return the label of the first predicate that holds, or the default.+firstMatch :: Text -> [(IO Bool, Text)] -> IO Text+firstMatch def [] = pure def+firstMatch def ((test, label) : rest) =+  test >>= \case+    True -> pure label+    False -> firstMatch def rest++-- | Classify a directory entry (name relative to parent) as upstream's+-- @readDirectory@ types one (@PosixSourceAccessor::readDirectory@ in+-- posix-source-accessor.cc at 2.24.9): an entry whose lstat is refused with+-- @EACCES@ or @EPERM@ (@permission_denied@, @operation_not_permitted@) has+-- no type, and any other failure fails the listing.  A directory that can+-- be read but not searched refuses every entry's lstat this way.+classifyEntry :: FilePath -> FilePath -> IO (Text, Maybe Text)+classifyEntry parentDir name = do+  ty <- catchJust refusedStat (Just <$> classifyPath (parentDir </> name)) (\() -> pure Nothing)+  pure (T.pack name, ty)+  where+    refusedStat err+      | fmap Errno (ioe_errno err) `elem` [Just eACCES, Just ePERM] = Just ()+      | otherwise = Nothing++-- | Convert IO exceptions to eval errors.+-- Guards against double-wrapping: if the exception is already a+-- t'NixEvalError', it is re-thrown as-is.+wrapIO :: IO a -> EvalIO a+wrapIO action = EvalIO $ liftIO $ do+  result <- try action+  case result of+    Right val -> pure val+    Left (err :: SomeException)+      | Just (_ :: SomeAsyncException) <- fromException err -> throwIO err+      | Just abortErr <- fromException err -> throwIO (abortErr :: NixAbortError)+      | Just nixErr <- fromException err -> throwIO (nixErr :: NixEvalError)+      | otherwise -> throwIO (NixEvalError ErrorUncatchable (untracedFailure (exceptionText err)))++-- | An exception as the user reads it.  A 'userError' is a refusal the+-- code raised in its own words (a tree the walk refuses to archive, a+-- path the store refuses to register), so it is its message alone,+-- which 'displayException' would wrap in @user error (...)@.+exceptionText :: SomeException -> Text+exceptionText err = case fromException err of+  Just ioErr | isUserError ioErr -> T.pack (ioeGetErrorString ioErr)+  _ -> T.pack (displayException err)++-- | 'wrapIO' for an access to a source path: an 'IOException' becomes+-- the message upstream gives that access ('sourceErrorMessage'), naming+-- the path as given.  A 'userError' is no failed access but a refusal in+-- its own words, such as the walk's of an entry a NAR cannot hold, so it+-- reaches 'wrapIO' as it was raised.+sourceIO :: SourceAccess -> Text -> IO a -> EvalIO a+sourceIO access path = sourceIOWith access (pure path)++-- | 'sourceIO' with the path to name computed once the access has failed,+-- so a successful read pays nothing for it.+sourceIOWith :: SourceAccess -> IO Text -> IO a -> EvalIO a+sourceIOWith access shownPath action = wrapIO (action `catch` reworded)+  where+    reworded :: IOException -> IO b+    reworded err+      | isUserError err = throwIO err+      | otherwise = do+          shown <- shownPath+          throwIO (NixEvalError ErrorUncatchable (untracedFailure (sourceErrorMessage access shown err)))++-- | A path with its symlinks resolved, as upstream names one it reached+-- through realisePath (readFile, hashFile and readDir resolve fully),+-- given the value and the native path it opens.  A path the resolution+-- itself cannot walk keeps the spelling given.+resolvedForMessage :: Text -> FilePath -> IO Text+resolvedForMessage path native+  | SP.isCanonicalStoreText path = pure (canonPath path)+  | otherwise =+      (canonPathValue . T.pack <$> Dir.canonicalizePath native)+        `catch` \(_ :: IOException) -> pure path++-- | An lstat that raises for an absent path: 'Dir.pathIsSymbolicLink' is+-- the portable lstat, as 'lstatExists' says.+statSource :: FilePath -> IO ()+statSource = void . Dir.pathIsSymbolicLink++-- | A source path's NAR, its root lstat'ed first as upstream's dumpPath+-- begins.  A regular file's only access in the walk is its read, so a+-- failure there is the read's.  A failure below a directory keeps GHC's+-- text until nova-cache's walk names the access that failed.+serialiseSource :: Text -> NAR.CaseHack -> FilePath -> EvalIO NAR.NarEntry+serialiseSource path caseHack resolved = do+  isLink <- sourceIO StatPath path (Dir.pathIsSymbolicLink resolved)+  isFile <- wrapIO (Dir.doesFileExist resolved)+  let walk = ExecBit.serialiseFromPath caseHack resolved+  if not isLink && isFile then sourceIO ReadFile path walk else wrapIO walk++-- | Run an IO evaluation, returning @Left@ with the failure's message on+-- error.+runEvalIO :: EvalState -> EvalIO a -> IO (Either Text a)+runEvalIO st action = either (Left . failureMessage) Right <$> runEvalIOTraced st action++-- | Run an IO evaluation, returning @Left@ with the whole failure on+-- error, its lines of context included, for a caller that reports it+-- ('renderEvalFailure').+--+-- Catches t'NixEvalError' (throw) and t'NixAbortError' (abort).+-- Async exceptions (@StackOverflow@, @ThreadKilled@, etc.) propagate uncaught.+runEvalIOTraced :: EvalState -> EvalIO a -> IO (Either EvalFailure a)+runEvalIOTraced st (EvalIO action) = do+  result <- try (runReaderT action st)+  case result of+    Right val -> pure (Right val)+    Left (err :: SomeException)+      | Just (_ :: SomeAsyncException) <- fromException err -> throwIO err+      | Just (NixEvalError _ failure) <- fromException err -> pure (Left failure)+      | Just (NixAbortError failure) <- fromException err -> pure (Left failure)+      | otherwise -> pure (Left (untracedFailure (exceptionText err)))++-- ---------------------------------------------------------------------------+-- Downloads+-- ---------------------------------------------------------------------------++-- | Where a fetch reads a URL from: the file a @file:\/\/@ URL names, as+-- 'fileUrlPath' reads it (the same path restricted evaluation checks), or+-- the HTTP client for any other URL.  A @file:\/\/@ URL that names no file+-- here is refused in the words a failed download of it takes.+downloadSourceOf :: SP.StoreDir -> Text -> Either Text DownloadSource+downloadSourceOf storeDir url = case fileUrlPath storeDir url of+  Just (Right path) -> Right (LocalFile (T.unpack path))+  Just (Left reason) -> Left (attemptFailureMessage (fileUrlFailure url (T.unpack reason)))+  Nothing -> Right (RemoteUrl url)++-- | What a tarball fetch refuses of a local file before reading it: a+-- path with nothing there, and a directory, named as a repository when it+-- holds Git's or Mercurial's metadata.+localArchiveRefusal :: DownloadSource -> IO (Maybe FetchFailure)+localArchiveRefusal source = case source of+  RemoteUrl _ -> pure Nothing+  LocalFile path -> do+    there <- Dir.doesPathExist path+    directory <- Dir.doesDirectoryExist path+    git <- Dir.doesPathExist (path </> ".git")+    hg <- Dir.doesPathExist (path </> ".hg")+    let quoted = "\"" <> T.pack path <> "\""+        repository scheme = refused ("tarball " <> quoted <> " is a repository, not a tarball. Please use `" <> scheme <> "` as the scheme.")+    pure $ case (there, directory) of+      (False, _) -> refused ("tarball " <> quoted <> " does not exist.")+      (True, True)+        | git -> repository "git+file"+        | hg -> repository "hg+file"+        | otherwise -> refused ("tarball " <> quoted <> " is a directory, not a file.")+      (True, False) -> Nothing+  where+    refused = Just . FetchFailure []++-- ---------------------------------------------------------------------------+-- Store copy helpers+-- ---------------------------------------------------------------------------++-- | A new scratch directory under the system temp dir: the prefix and an+-- unpredictable suffix, created exclusively, so an existing path fails the+-- fetch rather than being adopted.  The join is a forward slash, which git+-- and the store's copies accept on every host.+newScratchDirectory :: Text -> IO FilePath+newScratchDirectory prefix = do+  tmpBase <- Dir.getTemporaryDirectory+  suffix <- getRandomBytes scratchSuffixBytes+  let dir = tmpBase <> "/" <> T.unpack (prefix <> bytesToHexText suffix)+  dir <$ Dir.createDirectory dir++-- | The prefix of a tarball fetch's scratch directory.+tarballScratchPrefix :: Text+tarballScratchPrefix = "nova-nix-tarball-"++-- | Run an action with a scratch directory of its own ('newScratchDirectory'),+-- removed however the action ends.+withScratchDirectory :: Text -> (FilePath -> EvalIO a) -> EvalIO a+withScratchDirectory prefix use = EvalIO $ do+  st <- ask+  liftIO (bracket (newScratchDirectory prefix) Dir.removePathForcibly (\dir -> let EvalIO action = use dir in runReaderT action st))++-- | Hash a fetched tree's NAR, hold it to the pin, and restore it at the+-- store path its name and hash give, as a fetch result.  The tree's files+-- are read from the scratch directory the fetch wrote them to.+storeArchive :: FilePath -> Text -> Maybe (BS.ByteString, BS.ByteString -> Text) -> Tree Blob -> EvalIO (Either FetchFailure Text)+storeArchive scratch name pin tree = do+  Hash.NixHash digest <- wrapIO (treeNarHash scratch tree)+  case pin of+    Just (expected, mismatch) | expected /= digest -> pure (Left (FetchFailure [] (mismatch digest)))+    _ -> do+      sp <- storePathOrThrow (makeFixedOutputPath name "sha256" NarIngestion digest)+      let destPath = canonicalStorePathText sp+      writtenFor Fetched sp (NarWrite name <$> wrapIO (treeNarBytes scratch tree)) $ do+        dest <- evalFilePath sp+        wrapIO (restoreFetchedTree scratch dest tree (Hash.NixHash digest)) >>= either throwEvalError pure+      recordStoreWrite Fetched destPath [] SP.WriteRecursive+      allowPath destPath+      pure (Right destPath)++-- | Restore a fetched tree at its content-addressed destination from its+-- NAR, streamed into the store's unpack sink so its names are spelled for+-- the volume, and make its metadata canonical.  A tree already there whose+-- NAR is the one the address names is kept, as 'unpackToStoreVerified'+-- keeps one; anything else there is cleared first, and a restore that+-- fails leaves nothing.  The tree's files are read from the scratch+-- directory the fetch wrote them to.+restoreFetchedTree :: FilePath -> FilePath -> Tree Blob -> Hash.NixHash -> IO (Either Text ())+restoreFetchedTree scratch dest tree digest = do+  sensitivity <- probeCaseSensitivity (takeDirectory dest)+  held <- heldTree (volumeCaseHack sensitivity)+  if held+    then Right () <$ canonicalizeMetadata dest+    else do+      Dir.removePathForcibly dest+      outcome <- restore sensitivity `onException` Dir.removePathForcibly dest+      either (\reason -> Left reason <$ Dir.removePathForcibly dest) (\() -> Right () <$ canonicalizeMetadata dest) outcome+  where+    heldTree caseHack = do+      there <- Dir.doesPathExist dest+      if not there+        then pure False+        else+          ((== digest) <$> ExecBit.narHashOfPath caseHack dest)+            `catches` [Handler (\(_ :: IOException) -> pure False), Handler (\(_ :: NAR.NarWalkError) -> pure False)]+    restore sensitivity = do+      sink <- newNarUnpackSink sensitivity dest+      streamed <- withTreeNarSource scratch tree (sinkNarStream AtEndOfInput sink)+      case streamed of+        Left (NarStreamRefused reason) -> pure (Left reason)+        Left (NarStreamMalformed reason) -> pure (Left ("the fetched tree's NAR does not parse: " <> reason))+        Right (written, _)+          | written /= digest -> do+              abortNarUnpack sink+              pure (Left "the fetched tree changed while it was written to the store")+          | otherwise -> finishNarUnpack sink++-- | Unpack a NAR entry at its content-addressed destination and make the+-- tree's metadata canonical ('canonicalizeMetadata'), as upstream's+-- @addToStoreFromDump@ does to what it restores (local-store.cc).  An+-- existing destination is adopted only when its NAR digest is the expected+-- one - same content means same path, so a matching tree is byte-identical+-- by construction; anything else (an interrupted earlier unpack, a+-- squatter) is cleared and unpacked afresh.  The entry is the one+-- evaluation hashed to name the path, so the tree that lands is the one the+-- address names, with the store volume's own sibling-name handling.+unpackToStoreVerified :: FilePath -> NAR.NarEntry -> BS.ByteString -> IO (Either Text ())+unpackToStoreVerified dest entry expectedDigest = do+  -- Probed per write rather than carried in 'EvalState': the store+  -- directory need not exist when evaluation starts, and the probe+  -- answers for a path on disk.  'evalFilePath' made it before this+  -- destination was named, and the cost is one pathconf call per tree.+  sensitivity <- probeCaseSensitivity (takeDirectory dest)+  onDiskNar <- narBytesIfPresent (volumeCaseHack sensitivity) dest+  placed <-+    if (sha256Digest <$> onDiskNar) == Just expectedDigest+      then pure (Right ())+      else do+        Dir.removePathForcibly dest+        unpackNarEntry sensitivity dest entry+  traverse (\() -> canonicalizeMetadata dest) placed
src/Nix/Eval/Operator.hs view
@@ -1,12 +1,17 @@+{-# LANGUAGE LambdaCase #-}+ -- | Binary and unary operator evaluation for Nix. ----- Short-circuiting operators ('OpAnd', 'OpOr', 'OpImpl') are handled--- directly in @Nix.Eval.eval@ because they must not evaluate both--- operands.  Everything else lives here.+-- Short-circuiting operators ('OpAnd', 'OpOr', 'OpImpl') are handled in+-- "Nix.Eval" because they must not evaluate both operands, and so is @+@+-- ('OpAdd'), which coerces strings and paths through the evaluator and+-- comes here for its numeric cases ('addToInteger', 'addToFloat').+-- Everything else lives here. module Nix.Eval.Operator   ( evalBinary,     evalUnary,     evalUpdate,+    evalUpdateChain,     addToInteger,     addToFloat,     nixCompare,@@ -16,13 +21,19 @@     primMul,     primDiv,     expectInt,+    expectedFailure,   ) where +import Control.Monad (foldM) import Data.Int (Int64)+import Data.List.NonEmpty (NonEmpty (..))+import qualified Data.List.NonEmpty as NE import Data.Text (Text) import qualified Data.Text as T-import Nix.Eval.CAttrSet (cattrsetUnion)+import Nix.Eval.AllocSite (SetSite (SetUpdate))+import Nix.Eval.CAttrSet (cattrsetUpdate)+import Nix.Eval.CData (MonadCData) import Nix.Eval.CList (clistFromThunks, clistLen, clistThunks) import Nix.Eval.Print (PrintOptions (..), printValue) import Nix.Eval.Types@@ -30,15 +41,13 @@     MonadEval (..),     NixValue (..),     Thunk (..),-    attrSetElems,-    attrSetKeys,+    attrSetAllPairs,     attrSetLookup,-    thunkSameRef,+    attrSetSize,     typeName,     typeOfValue,   ) import Nix.Expr.Types (BinaryOp (..), UnaryOp (..))-import System.IO.Unsafe (unsafePerformIO)  -- | Force function passed by the caller to break the import cycle. -- Needed for deep equality on lists and attribute sets.@@ -49,8 +58,9 @@ -- The caller must handle 'OpAdd' and the short-circuit operators -- ('OpAnd', 'OpOr', 'OpImpl') before calling this: each looks at its left -- operand before the right is evaluated, and @+@ coerces through the--- evaluator.  The @Force@ function is used only for deep structural--- equality on compound values.+-- evaluator.  The @Force@ function is used only to force the elements of+-- compound values: for deep structural equality, and for the element-wise+-- ordering of lists. evalBinary :: (MonadEval m) => Force m -> BinaryOp -> NixValue -> NixValue -> m NixValue evalBinary forceFn op left right = case op of   OpSub -> primSub left right@@ -139,17 +149,20 @@ -- | Upstream's @forceInt@ on a forced value (eval.cc at 2.24.9). expectInt :: (MonadEval m) => NixValue -> m Int64 expectInt (VInt n) = pure n-expectInt other = throwEvalError (expectedMessage "an integer" other)+expectInt other = expectedFailure "an integer" other  -- | Upstream's @forceFloat@ on a forced value: an integer widens. expectFloat :: (MonadEval m) => NixValue -> m Double expectFloat (VInt n) = pure (fromIntegral n) expectFloat (VFloat x) = pure x-expectFloat other = throwEvalError (expectedMessage "a float" other)+expectFloat other = expectedFailure "a float" other -expectedMessage :: Text -> NixValue -> Text-expectedMessage wanted other =-  "expected " <> wanted <> " but found " <> typeName other <> ": " <> printValue PrintForError other+-- | Upstream's refusal of a value of the wrong type: the type wanted, the+-- type found, and the value as an error prints it.+expectedFailure :: (MonadEval m) => Text -> NixValue -> m a+expectedFailure wanted other = do+  shown <- printValue PrintForError other+  throwEvalError ("expected " <> wanted <> " but found " <> typeName other <> ": " <> shown)  isFloat :: NixValue -> Bool isFloat (VFloat _) = True@@ -214,8 +227,10 @@ -- Paths compare as their string representation (Nix semantics). nixCompare _ (VPath a) (VPath b) = pure (a < b) -- Lists compare lexicographically, element by element (Nix semantics).-nixCompare forceFn (VList clA) (VList clB) =-  listCompare forceFn (map Thunk (clistThunks clA)) (map Thunk (clistThunks clB))+nixCompare forceFn (VList clA) (VList clB) = do+  as <- map Thunk <$> clistThunks clA+  bs <- map Thunk <$> clistThunks clB+  listCompare forceFn as bs -- Upstream's @CompareValues@ (primops.cc at 2.24.9).  2.33.2 appends the -- two values; 2.24.9 does not. nixCompare _ left right@@ -227,20 +242,19 @@  -- | Lexicographic comparison of two thunk lists for the @<@ operator: -- the first NON-EQUAL element pair decides via @<@ on that pair, as--- upstream does (eqValues, then CompareValues on the first difference).--- An unequal pair where @<@ holds in neither direction (NaN) therefore--- decides False rather than being skipped as equal.  A proper prefix is--- less than the longer list.  Mirrors 'listEqual'.+-- upstream does (eqValues, then CompareValues on the first difference,+-- in primops.cc).  An unequal pair where @<@ holds in neither+-- direction (NaN) therefore decides False rather than being skipped as+-- equal.  A proper prefix is less than the longer list.  Mirrors+-- 'listEqual'. listCompare :: (MonadEval m) => Force m -> [Thunk] -> [Thunk] -> m Bool listCompare _ [] [] = pure False listCompare _ [] (_ : _) = pure True listCompare _ (_ : _) [] = pure False-listCompare forceFn (a : as) (b : bs)-  | thunkSameRef a b = listCompare forceFn as bs-  | otherwise = do+listCompare forceFn (a : as) (b : bs) = do   va <- forceFn a   vb <- forceFn b-      equal <- nixEqual forceFn va vb+  equal <- forcedPairEqual forceFn (a, va) (b, vb)   if equal     then listCompare forceFn as bs     else nixCompare forceFn va vb@@ -257,27 +271,47 @@ -- String equality ignores context (matching real Nix). nixEqual _ (VStr a _) (VStr b _) = pure (a == b) nixEqual _ (VPath a) (VPath b) = pure (a == b)-nixEqual forceFn (VList clA) (VList clB)-  | clistLen clA /= clistLen clB = pure False-  | otherwise = listEqual forceFn (map Thunk (clistThunks clA)) (map Thunk (clistThunks clB))+nixEqual forceFn (VList clA) (VList clB) = do+  lenA <- clistLen clA+  lenB <- clistLen clB+  if lenA /= lenB+    then pure False+    else do+      as <- map Thunk <$> clistThunks clA+      bs <- map Thunk <$> clistThunks clB+      listEqual forceFn as bs+-- Upstream's @eqValues@ on two sets (eval.cc): two derivations by their+-- outPaths, then sets of different sizes unequal with no value forced, then+-- 'attrsEqual'. nixEqual forceFn (VAttrs as) (VAttrs bs) = do   drvOutPaths <- derivationOutPathPair forceFn as bs   case drvOutPaths of     Just outPathPair -> thunkPairEqual forceFn outPathPair-    Nothing-      | attrSetKeys as /= attrSetKeys bs -> pure False-      | otherwise ->-          -- Short-circuit on the first mismatch: later pairs are never-          -- forced, so errors past the deciding pair cannot surface-          -- (upstream stops comparing there too).-          allPairsEqual (zip (attrSetElems as) (attrSetElems bs))-  where-    allPairsEqual [] = pure True-    allPairsEqual (pair : rest) = do-      eq <- thunkPairEqual forceFn pair-      if eq then allPairsEqual rest else pure False+    Nothing -> do+      sizeA <- attrSetSize as+      sizeB <- attrSetSize bs+      if sizeA /= sizeB then pure False else attrsEqual forceFn as bs nixEqual _ _ _ = pure False +-- | Upstream's walk over two sets of one size (@eqValues@ in eval.cc):+-- both in symbol order, each pair's names compared and then its+-- values, stopping at the first difference, so no value past it is forced+-- ('attrSetAllPairs').  Upstream's @Bindings@ are sorted by @Symbol@,+-- whose id is the order its table interned the name in (attr-set.hh and+-- symbol-table.hh), and a set here walks in symbol id order the same way.+-- Two sets therefore compare in upstream's order wherever the two tables+-- interned the sets' names in one order: the startup names first+-- ('Nix.Eval.StartupSymbols'), each name in source where upstream's+-- parser interns it, and each name @listToAttrs@, @groupBy@ and+-- @fromJSON@ make where those builtins intern it upstream.  No string+-- value takes a symbol in either.+attrsEqual :: (MonadEval m) => Force m -> AttrSet -> AttrSet -> m Bool+attrsEqual forceFn = attrSetAllPairs samePair+  where+    samePair (nameA, a) (nameB, b)+      | nameA /= nameB = pure False+      | otherwise = thunkPairEqual forceFn (a, b)+ -- | When both attr sets are derivations (a @type@ attr forcing to the string -- @"derivation"@) and both carry an @outPath@, the pair of outPath thunks. --@@ -294,17 +328,19 @@     then pure Nothing     else do       rightIsDrv <- isDerivationSet forceFn bs-      pure $       if rightIsDrv-          then (,) <$> attrSetLookup "outPath" as <*> attrSetLookup "outPath" bs-          else Nothing+        then do+          outPathA <- attrSetLookup "outPath" as+          outPathB <- attrSetLookup "outPath" bs+          pure ((,) <$> outPathA <*> outPathB)+        else pure Nothing  -- | Does the set carry @type = "derivation"@?  Forces only the @type@ attr -- (as upstream's isDerivation does); a non-string type is simply not a -- derivation, not an error. isDerivationSet :: (MonadEval m) => Force m -> AttrSet -> m Bool isDerivationSet forceFn attrs =-  case attrSetLookup "type" attrs of+  attrSetLookup "type" attrs >>= \case     Nothing -> pure False     Just typeThunk -> do       typeVal <- forceFn typeThunk@@ -315,66 +351,92 @@ -- | Pairwise equality of two thunk lists (for list comparison). listEqual :: (MonadEval m) => Force m -> [Thunk] -> [Thunk] -> m Bool listEqual _ [] [] = pure True-listEqual forceFn (a : as) (b : bs)-  | thunkSameRef a b = listEqual forceFn as bs-  | otherwise = do-      va <- forceFn a-      vb <- forceFn b-      eq <- nixEqual forceFn va vb+listEqual forceFn (a : as) (b : bs) = do+  eq <- thunkPairEqual forceFn (a, b)   if eq then listEqual forceFn as bs else pure False listEqual _ _ _ = pure False --- | Compare two thunks for equality by forcing both.--- Short-circuits on thunk identity (same IORef = same value).+-- | Upstream's @eqValues@ on two thunks (eval.cc): both are forced, the left+-- first, before one is taken as equal to itself, so an error in a value both+-- sides share surfaces. thunkPairEqual :: (MonadEval m) => Force m -> (Thunk, Thunk) -> m Bool-thunkPairEqual forceFn (a, b)-  | thunkSameRef a b = pure True-  | otherwise = do+thunkPairEqual forceFn (a, b) = do   va <- forceFn a   vb <- forceFn b-      nixEqual forceFn va vb+  forcedPairEqual forceFn (a, va) (b, vb) +-- | Equality of two thunks already forced, each with its value.  One thunk+-- is equal to itself whatever its value, as upstream's @&v1 == &v2@ makes+-- a function or NaN that both sides share equal; two thunks compare their+-- values.+forcedPairEqual :: (MonadEval m) => Force m -> (Thunk, NixValue) -> (Thunk, NixValue) -> m Bool+forcedPairEqual forceFn (a, va) (b, vb)+  | a == b = pure True+  | otherwise = nixEqual forceFn va vb+ -- --------------------------------------------------------------------------- -- List / attrset operators -- ---------------------------------------------------------------------------  -- | List concatenation (++). evalConcat :: (MonadEval m) => NixValue -> NixValue -> m NixValue-evalConcat (VList clA) (VList clB) =-  pure (VList (clistFromThunks (clistThunks clA ++ clistThunks clB)))+evalConcat (VList clA) (VList clB) = do+  as <- clistThunks clA+  bs <- clistThunks clB+  VList <$> clistFromThunks (as ++ bs) evalConcat left right =   throwEvalError ("cannot concatenate " <> typeName left <> " and " <> typeName right)  -- | Attribute set merge (//).  Right-biased: keys in the right--- operand shadow keys in the left.------ Each operand is evaluated and checked for a set in turn, the left--- first, as @ExprOpUpdate::eval@ calls @evalAttrs@ on each (eval.cc at--- 2.24.9): a non-set left fails before the right is evaluated at all, and--- the refusal is @evalAttrs@'s message.  2.33.2 checks the right first;--- 2.24.9 is followed.  Upstream adds a trace line naming the operand ("in--- the left operand of the update (//) operator") above the message;--- nova-nix's errors carry no trace, so only the final line is reproduced.+-- operand shadow keys in the left.  The chain of the two+-- ('evalUpdateChain'). evalUpdate :: (MonadEval m) => m NixValue -> m NixValue -> m NixValue-evalUpdate evalLeft evalRight = do-  leftSet <- evalLeft >>= expectSet-  rightSet <- evalRight >>= expectSet-  pure (VAttrs (mergeAttrSets leftSet rightSet))+evalUpdate evalLeft evalRight = evalUpdateChain (evalLeft :| [evalRight])++-- | A chain of @//@, given its operands first to last.+--+-- Each operand is evaluated and checked for a set in turn, last to+-- first, as upstream Nix gathers a chain: each update evaluates its right+-- operand and then its left.  A non-set fails before an operand before it+-- is evaluated at all, and the refusal is upstream's message for a value+-- that is not a set.  Older upstream releases evaluate and check the left+-- operand first; the newest pinned release is followed.  Upstream adds a+-- trace line naming the operand ("in the left operand of the update (//)+-- operator") above the message; this refusal adds no line of context, so+-- only the final line is reproduced.+--+-- Once every operand is a set, the sets are merged from the first, each+-- into the result of those before it, as the update queue folds a chain+-- from its leftmost operand once it has evaluated them all+-- (@ExprOpUpdate::eval@ in eval.cc): each small operand layers on the sets+-- before it ('mergeAttrSets'), and a chain one of whose operands fails+-- merges none.+evalUpdateChain :: (MonadEval m) => NonEmpty (m NixValue) -> m NixValue+evalUpdateChain operands = do+  lastFirst <- traverse (>>= expectSet) (NE.reverse operands)+  case NE.reverse lastFirst of+    start :| rest -> VAttrs <$> foldM mergeAttrSets start rest   where     expectSet (VAttrs set) = pure set-    expectSet other =-      throwEvalError ("expected a set but found " <> typeName other <> ": " <> printValue PrintForError other)+    expectSet other = expectedFailure "a set" other --- | Merge two t'AttrSet's, right-biased (@//@).--- Delegates to C-side @nn_attrset_union@ which performs a linear merge--- of two sorted arrays - O(n+m) on contiguous, cache-friendly memory.------ 'unsafePerformIO' safety: @nn_attrset_union@ is a pure C function--- that allocates a new result set from its two inputs without side--- effects, callbacks to Haskell, or dependency on mutable state--- beyond the C allocator.  The NOINLINE pragma prevents float-out--- from sharing results across distinct call sites.-{-# NOINLINE mergeAttrSets #-}-mergeAttrSets :: AttrSet -> AttrSet -> AttrSet-mergeAttrSets (AttrSet a) (AttrSet b) =-  AttrSet (unsafePerformIO (cattrsetUnion a b))+-- | Merge two t'AttrSet's, right-biased (@//@).  An empty operand gives+-- the other operand's set itself, the left checked first, as upstream's+-- @ExprOpUpdate::eval@ copies the other operand's @Value@ (eval.cc): no set+-- is made, and a printer, which enters a set by its bindings, finds the+-- operand's.  Otherwise C-side @nn_attrset_update@ makes the set as+-- upstream 2.34 does: a layer on the left holding the right's entries alone+-- when the right is small and the left's chain of layers short, else a+-- merge of the two into a new set, O(n+m)+-- ('Nix.Eval.CAttrSet.cattrsetUpdate').  The census counts the entries+-- either copies, as upstream adds them to @nrOpUpdateValuesCopied@+-- (@ExprOpUpdate::eval@ in eval.cc at 2.34.9).  An empty operand copies and+-- counts nothing in either.+mergeAttrSets :: (MonadCData m) => AttrSet -> AttrSet -> m AttrSet+mergeAttrSets left@(AttrSet a) right@(AttrSet b) = do+  leftSize <- attrSetSize left+  rightSize <- attrSetSize right+  case (leftSize, rightSize) of+    (0, _) -> pure right+    (_, 0) -> pure left+    _ -> AttrSet <$> cattrsetUpdate SetUpdate a b
src/Nix/Eval/Policy.hs view
@@ -1,29 +1,34 @@ -- | The evaluation policy: upstream's @restrict-eval@ and @pure-eval@ -- settings, the @allowed-uris@ list, and the pure decisions they drive, -- plus the @trace-verbose@ setting, which decides what--- @builtins.traceVerbose@ does.+-- @builtins.traceVerbose@ does, @allow-import-from-derivation@ and+-- @trace-import-from-derivation@, which decide whether a path reader may+-- build what its argument's context names, and @experimental-features@,+-- which decides what a flake reference may name. ----- Upstream gates evaluation in two layers (@src/libexpr/eval.cc@ at--- 2.24.9).  Under either setting the root filesystem is wrapped in an--- @AllowListSourceAccessor@ that admits a path when it lies within an--- allowed prefix or is an ancestor of one (@CanonPath::isAllowed@), and--- the allowed set starts as the search path roots and grows as the--- evaluation copies, fetches or writes store objects (@allowPath@).--- Under @restrict-eval@ alone a fetch is also checked against--- @allowed-uris@ (@checkURI@).  @pure-eval@ additionally empties the+-- Upstream gates evaluation in two layers.  Under either setting the root+-- filesystem is wrapped in an accessor that admits a path when it lies+-- within an allowed prefix or is an ancestor of one, and the allowed set+-- starts as the search path roots and grows as the evaluation copies,+-- fetches or writes store objects.  Under @restrict-eval@ alone a fetch is+-- also checked against @allowed-uris@.  @pure-eval@ additionally empties the -- search path, hides the impure constants, and makes the fetchers demand--- a hash or revision; those decisions live with the builtins and consult--- t'EvalPolicy' through 'Nix.Eval.Types.MonadEval'.+-- a hash or revision.  The search path is the caller's to choose as it+-- starts the session, the constants are left out by+-- 'Nix.Builtins.builtinEnv' from the policy it is given, and the fetchers'+-- demand lives with the builtins and consults t'EvalPolicy' through+-- 'Nix.Eval.Types.MonadEval'. ----- Everything here is pure so each rule can be tested on its own.  The--- filesystem side (walking a path through its symlinks, prefix by--- prefix) lives in "Nix.Eval.IO".+-- Everything here is pure so each rule can be tested on its own, the+-- walk of a path through its symlinks included ('walkPath'), which takes+-- the read of a link as an argument; "Nix.Eval.IO" hands it the+-- filesystem. module Nix.Eval.Policy   ( -- * Policy     EvalPolicy (..),+    ImportFromDerivation (..),     unrestrictedPolicy,     pathsRestricted,-    modeInformation,      -- * Allowed paths     AllowedPaths,@@ -34,24 +39,42 @@     pathComponents,     joinComponents,     isAbsolutePath,+    storeRootPrefix,+    windowsLinkTargetJoins,++    -- * Walking a path's symlinks+    PathRules (..),+    hostPathRules,+    SymlinkResolution (..),+    LinkTarget (..),+    linkTarget,+    WalkStop (..),+    walkPath,     forbiddenPathMessage,      -- * Allowed URIs     isAllowedUri,     uriAccess,     fileUrlPrefix,-    forbiddenUriMessage,+    fileUrlPath,   ) where -import Data.Char (isAsciiLower, isAsciiUpper, isDigit)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BS8+import Data.Char (isAsciiLower, isAsciiUpper, isDigit, ord) import Data.List (inits, isPrefixOf)+import Data.Maybe (isJust) import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T+import qualified Data.Text.Encoding as TE import Nix.Eval.CanonPath (canonPathValue)-import Nix.Store.Path (StoreDir, qualifyPathText)+import Nix.ExperimentalFeature (FeatureSet, noFeatures)+import Nix.Store.Path (StoreDir, defaultStoreDirText, qualifyPathText, storeDirDrive)+import Numeric (readHex)+import qualified System.Info  -- --------------------------------------------------------------------------- -- Policy@@ -77,13 +100,44 @@     -- | Upstream @trace-verbose@: @builtins.traceVerbose@ traces as     -- @builtins.trace@ does, where otherwise it returns its second     -- argument without forcing its first.-    epTraceVerbose :: !Bool+    epTraceVerbose :: !Bool,+    -- | Whether a path reader may build or substitute what its argument's+    -- context names.+    epImportFromDerivation :: !ImportFromDerivation,+    -- | Upstream's @experimental-features@: what reading a flake+    -- reference or a fetcher input may need.+    epExperimentalFeatures :: !FeatureSet   }   deriving (Eq, Show) --- | Upstream's default: every setting off, nothing listed.+-- | What upstream's @allow-import-from-derivation@ and+-- @trace-import-from-derivation@ settings say together+-- (eval-settings.hh at 2.34.9): the second has no effect when the+-- first is off, so the three cases are all there are.+data ImportFromDerivation+  = -- | @allow-import-from-derivation = false@: a context that names an+    -- output is refused before anything is built, even an output that is+    -- valid already.+    RefuseImportFromDerivation+  | -- | The default: an output a context names is realised.+    AllowImportFromDerivation+  | -- | @trace-import-from-derivation = true@ as well: it is realised after+    -- a warning naming the first output.+    TraceImportFromDerivation+  deriving (Eq, Show)++-- | Upstream's default: every confinement off, nothing listed, an import+-- from derivation allowed and not traced, and no experimental feature. unrestrictedPolicy :: EvalPolicy-unrestrictedPolicy = EvalPolicy {epRestrictEval = False, epPureEval = False, epAllowedUris = [], epTraceVerbose = False}+unrestrictedPolicy =+  EvalPolicy+    { epRestrictEval = False,+      epPureEval = False,+      epAllowedUris = [],+      epTraceVerbose = False,+      epImportFromDerivation = AllowImportFromDerivation,+      epExperimentalFeatures = noFeatures+    }  -- | Whether filesystem access goes through the allow list: upstream wraps -- the root filesystem when either setting is on.@@ -133,6 +187,26 @@   where     descendantAllowed = maybe False (path `isPrefixOf`) (Set.lookupGE path allowed) +-- | Whether a prefix of a path, both as components, is the canonical+-- store directory or one of its ancestors while the path lies in the+-- store.  Such a prefix stands for the store an evaluation was given,+-- wherever that is, as upstream's store accessor has the store+-- directory for its root and looks for links only beneath it, so no+-- link is read there; under any other path it is a host directory.+storeRootPrefix :: [Text] -> [Text] -> Bool+storeRootPrefix path prefix = prefix `isPrefixOf` storeDirComponents && storeDirComponents `isPrefixOf` path+  where+    storeDirComponents = pathComponents defaultStoreDirText++-- | Whether a link target as Windows reports it names a place a path+-- value can spell.  Windows answers for every reparse point: a volume+-- mount point's target is the volume's GUID name (@Volume{...}@ once its+-- @\\??\\@ prefix is stripped) and a remote link's a UNC or device path,+-- neither of which a path value names, so a walk leaves such a link in+-- place for the read to follow.+windowsLinkTargetJoins :: Text -> Bool+windowsLinkTargetJoins target = not (any (`T.isPrefixOf` target) ["Volume{", "UNC\\", "\\\\"])+ -- | A canonical path's components: the root has none, and a Windows -- drive designator is the first one. pathComponents :: Text -> [Text]@@ -144,7 +218,9 @@   (drive : rest)     | isDriveDesignator drive -> drive <> "/" <> T.intercalate "/" rest   _ -> "/" <> T.intercalate "/" components-  where++-- | Whether a component is a Windows drive designator, @X:@.+isDriveDesignator :: Text -> Bool isDriveDesignator d = T.length d == driveDesignatorLength && T.isSuffixOf ":" d  -- | @X:@@@ -159,13 +235,134 @@ -- ('Nix.Store.Path.qualifyPathText'), which the gates check and the -- reads open. isAbsolutePath :: Text -> Bool-isAbsolutePath path = T.isPrefixOf "/" path || hasDrive-  where-    hasDrive = case T.unpack (T.take (driveDesignatorLength + 1) path) of+isAbsolutePath path = T.isPrefixOf "/" path || leadsWithDrive path++-- | Whether a path's text begins with a drive designator and a @/@.+leadsWithDrive :: Text -> Bool+leadsWithDrive path = case T.unpack (T.take (driveDesignatorLength + 1) path) of   [letter, ':', '/'] -> isAsciiLetter letter   _ -> False++-- | An ASCII letter, as a drive designator's is.+isAsciiLetter :: Char -> Bool isAsciiLetter c = isAsciiLower c || isAsciiUpper c +-- ---------------------------------------------------------------------------+-- Walking a path's symlinks+-- ---------------------------------------------------------------------------++-- | The path rules a link's target is read under: the host's, since the+-- host's file system wrote it.  A walk takes them as an argument, so the+-- Windows rules are tested on every host.+data PathRules+  = -- | @/@ separates, and a target leading with it is absolute.+    PosixPaths+  | -- | @/@ and @\\@ separate, a target leading with either or with a+    -- drive designator is absolute, and a drive designator met inside a+    -- path starts it again at that drive.+    WindowsPaths+  deriving (Eq, Show)++-- | The rules of the host evaluation runs on.+hostPathRules :: PathRules+hostPathRules+  | System.Info.os == "mingw32" = WindowsPaths+  | otherwise = PosixPaths++-- | Which symlinks a walk follows, upstream's @SymlinkResolution@: every+-- one, or every one but the last component's, which is then checked in+-- place.+data SymlinkResolution = ResolveFull | ResolveAncestors+  deriving (Eq, Show)++-- | A link's target as a walk splices it, as components: an absolute one+-- restarts the walk at the root, a relative one resumes it in the link's+-- own directory.+data LinkTarget = AbsoluteTarget [Text] | RelativeTarget [Text]+  deriving (Eq, Show)++-- | A link's target text under the host's rules, or 'Nothing' for one no+-- path value names ('windowsLinkTargetJoins'), which a walk leaves in+-- place.  A target leading with a separator is absolute on every host,+-- store text among them, where Windows' own @isAbsolute@ wants a drive.+linkTarget :: PathRules -> Text -> Maybe LinkTarget+linkTarget rules target = case rules of+  WindowsPaths+    | not (windowsLinkTargetJoins target) -> Nothing+    | rooted || startsWithDrive -> Just (AbsoluteTarget components)+  PosixPaths+    | rooted -> Just (AbsoluteTarget components)+  _ -> Just (RelativeTarget components)+  where+    separates c = c == '/' || (rules == WindowsPaths && c == '\\')+    components = filter (not . T.null) (T.split separates target)+    rooted = maybe False (separates . fst) (T.uncons target)+    -- @C:@ alone or before a separator; @C:name@ is drive-relative.+    startsWithDrive = case T.unpack (T.take (driveDesignatorLength + 1) target) of+      [letter, ':'] -> isAsciiLetter letter+      [letter, ':', next] -> isAsciiLetter letter && separates next+      _ -> False++-- | Why a walk stopped short of a path: the check's refusal of a prefix,+-- or a chain of links past upstream's bound.+data WalkStop e = WalkRefused e | WalkLoops+  deriving (Eq, Show)++-- | The symlink-resolving prefix walk of upstream's+-- @SourceAccessor::resolveSymlinks@ (source-accessor.cc at 2.35.4) over+-- an absolute canonical path, giving the path it resolves to.  Each+-- component is pushed, the check is asked about the prefix so far where+-- upstream's @maybeLstat@ would be, and a link at that prefix, read with+-- the reader given, has its target ('linkTarget') spliced in front of+-- what remains.  The joining is over path-value text alone: the host's+-- rules decide only how a target reads.  Under 'ResolveAncestors' the+-- last component's own link is left alone, as upstream consults+-- @maybeLstat@ only while something remains to resolve.  For a path in+-- the store the canonical store directory and its ancestors stand for+-- the store an evaluation was given, wherever that is, so no link is+-- read there ('storeRootPrefix').+walkPath ::+  (Monad m) =>+  PathRules ->+  SymlinkResolution ->+  ([Text] -> Text -> Either e ()) ->+  (Text -> m (Maybe Text)) ->+  Text ->+  m (Either (WalkStop e) Text)+walkPath rules mode refusalAt readLink canonical = go symlinkFollowLimit [] (pathComponents canonical)+  where+    go _ done [] = pure (Right (joined (reverse done)))+    go linksLeft done (component : rest)+      | component == "." = go linksLeft done rest+      | component == ".." = go linksLeft (drop 1 done) rest+      -- A rooted value whose first component is a drive (@/C:/...@, as+      -- @/. + "C:\\..."@ spells one) names that drive, so it starts the+      -- path again there rather than nesting under the store's drive.+      | WindowsPaths <- rules, isDriveDesignator component, not (null done) = go linksLeft [] (component : rest)+      | Left refusal <- refusalAt prefix prefixText = pure (Left (WalkRefused refusal))+      | otherwise = do+          target <- if followsLinkAt prefix rest then readLink prefixText else pure Nothing+          case target >>= linkTarget rules of+            Nothing -> go linksLeft prefixReversed rest+            Just _ | linksLeft <= 0 -> pure (Left WalkLoops)+            Just (AbsoluteTarget spliced) -> go (linksLeft - 1) [] (spliced ++ rest)+            Just (RelativeTarget spliced) -> go (linksLeft - 1) done (spliced ++ rest)+      where+        prefixReversed = component : done+        prefix = reverse prefixReversed+        prefixText = joined prefix+    followsLinkAt prefix rest =+      not (storeRootPrefix (prefix ++ rest) prefix) && (mode == ResolveFull || not (null rest))+    -- A drive designator leads only a Windows path; on POSIX @C:@ is a+    -- name like any other.+    joined components = case rules of+      WindowsPaths -> joinComponents components+      PosixPaths -> "/" <> T.intercalate "/" components++-- | Upstream's bound on symlinks followed while resolving one path.+symlinkFollowLimit :: Int+symlinkFollowLimit = 1024+ -- | Upstream's refusal, from the accessor's error callback in @eval.cc@. forbiddenPathMessage :: EvalPolicy -> Text -> Text forbiddenPathMessage policy path =@@ -213,23 +410,25 @@ schemePunctuation :: [Char] schemePunctuation = "+.-" --- | Upstream @EvalState::checkURI@: nothing is checked unless--- @restrict-eval@ is on; an allowed URI passes; a URI that is a path, or--- a @file://@ URL, is checked against the allowed paths instead--- (upstream passes the remainder through @CanonPath@, so a rootless--- remainder is rooted, and one that spells a drive, @file://C:/...@, is--- rooted already); anything else is refused.  The path is checked on the--- drive the given store directory puts it on ('qualifyPathText'), the--- one the fetch reads it from.+-- | Whether restricted evaluation lets a fetch reach a URI, as upstream+-- decides it: nothing is checked unless @restrict-eval@ is on; an allowed+-- URI passes; a URI that is a path is checked against the allowed paths+-- instead, and so is a @file://@ URL upstream's URL parser takes+-- ('fileUrlParses'), by its percent-decoded path, which is the path a+-- fetch of it reads ('fileUrlPath').  Any other @file://@ URL is refused,+-- as is anything else.  The path is checked on the drive the given store+-- directory puts it on ('qualifyPathText'), the one the fetch reads it+-- from. uriAccess :: StoreDir -> EvalPolicy -> AllowedPaths -> Text -> Either Text () uriAccess storeDir policy allowed uri   | not (epRestrictEval policy) = Right ()   | isAllowedUri (epAllowedUris policy) uri = Right ()   | T.isPrefixOf "/" uri = pathAccess uri-  | Just rest <- T.stripPrefix fileUrlPrefix uri = pathAccess (rooted rest)+  | Just located <- fileUrlPath storeDir uri = case located of+      Right path | fileUrlParses storeDir uri -> pathAccess path+      _ -> Left (forbiddenUriMessage uri)   | otherwise = Left (forbiddenUriMessage uri)   where-    rooted rest = if isAbsolutePath rest then rest else "/" <> rest     pathAccess path =       let canonical = qualifyPathText storeDir (canonPathValue path)        in if isAllowedPath allowed canonical then Right () else Left (forbiddenPathMessage policy canonical)@@ -238,6 +437,116 @@ fileUrlPrefix :: Text fileUrlPrefix = "file://" --- | Upstream's refusal from @checkURI@.+-- | The file a @file://@ URL names, as the transfer under upstream's+-- fetchers reads one: 'Nothing' for a URL of any other scheme, and a+-- 'Left' saying why for one that names no file here.  The query and the+-- fragment are not part of the path.  The authority is empty, or names+-- this machine (@localhost@ in any case, or @127.0.0.1@); on a Windows+-- store a drive may stand in its place (@file://C:/...@), as curl reads a+-- file URL on Windows.  The path is percent-decoded, refused when it+-- decodes to a NUL or to bytes that are not UTF-8, and canonicalized+-- lexically, so a dot segment, encoded or not, never steps past what the+-- restricted-mode gate checks ('uriAccess').  A path with no drive is+-- named on the store's drive ('qualifyPathText').+fileUrlPath :: StoreDir -> Text -> Maybe (Either Text Text)+fileUrlPath storeDir url = located . T.takeWhile (`notElem` urlPathEnds) <$> T.stripPrefix fileUrlPrefix url+  where+    located spelled = do+      encoded <- localPart spelled+      decoded <- percentDecoded encoded+      if T.null decoded+        then Left "the URL names no file"+        else Right (qualifyPathText storeDir (canonPathValue decoded))+    localPart spelled+      | isJust (storeDirDrive storeDir) && leadsWithDrive spelled = Right spelled+      | otherwise = case T.break (== '/') spelled of+          (authority, path)+            | T.null authority || T.toLower authority == localHostName || authority == loopbackAddress -> Right path+            | otherwise -> Left ("the URL names the host '" <> authority <> "', not this machine")++-- | Whether upstream's URL parser takes a @file://@ URL as naming a local+-- path, which upstream's restricted evaluation requires before it checks+-- the path: an empty authority, a path, query and fragment spelled in the+-- characters RFC 3986 allows in each or in escapes of two hex digits, and+-- no path segment that decodes to a @/@ or a NUL.  On a Windows store a+-- drive in the authority's place is that drive's path, as 'fileUrlPath'+-- reads it.  The transfer that reads the file is laxer on all three, so a+-- URL this refuses may still be fetched where evaluation is not+-- restricted.+fileUrlParses :: StoreDir -> Text -> Bool+fileUrlParses storeDir url = maybe False parses (T.stripPrefix fileUrlPrefix url)+  where+    parses rest =+      let (beforeFragment, fragment) = T.break (== fragmentStart) rest+          (spelled, query) = T.break (== queryStart) beforeFragment+       in maybe False (all (spelledIn pathChar segmentRefusedBytes) . T.splitOn "/") (pathOf spelled)+            && spelledIn queryChar [] (T.drop 1 query)+            && spelledIn queryChar [] (T.drop 1 fragment)+    pathOf spelled+      | isJust (storeDirDrive storeDir) && leadsWithDrive spelled = Just spelled+      | otherwise = case T.break (== '/') spelled of+          (authority, path) | T.null authority -> Just path+          _ -> Nothing+    pathChar char = isAsciiLower char || isAsciiUpper char || isDigit char || char `elem` urlPathPunctuation+    queryChar char = pathChar char || char `elem` urlQueryPunctuation++-- | Whether a URL component is spelled in the characters it may hold and+-- in escapes of two hex digits, none of which decodes to one of the given+-- bytes.+spelledIn :: (Char -> Bool) -> [Int] -> Text -> Bool+spelledIn allowed refused = go . T.unpack+  where+    go chars = case chars of+      '%' : high : low : rest | [(value, "")] <- readHex [high, low] -> value `notElem` refused && go rest+      '%' : _ -> False+      char : rest -> allowed char && go rest+      [] -> True++-- | What a path segment may not decode to: a separator, or a NUL.+segmentRefusedBytes :: [Int]+segmentRefusedBytes = [ord '/', 0]++-- | The punctuation RFC 3986 allows in a path segment as it is: the+-- unreserved marks, the sub-delimiters, a colon and an at sign.+urlPathPunctuation :: [Char]+urlPathPunctuation = "-._~!$&'()*+,;=:@"++-- | What a query or a fragment may hold beyond a path segment's+-- characters.+urlQueryPunctuation :: [Char]+urlQueryPunctuation = "/?"++-- | Where a URL's query and fragment start.+queryStart, fragmentStart :: Char+queryStart = '?'+fragmentStart = '#'++-- | Where a URL's path ends: at its query or its fragment.+urlPathEnds :: [Char]+urlPathEnds = [queryStart, fragmentStart]++-- | The names of this machine a @file://@ URL's authority may give.+localHostName, loopbackAddress :: Text+localHostName = "localhost"+loopbackAddress = "127.0.0.1"++-- | A URL path with each @%XX@ escape decoded to its byte, read as UTF-8.+-- A @%@ not followed by two hex digits stands for itself.  A NUL, or bytes+-- that are not UTF-8, name no file this layer can open.+percentDecoded :: Text -> Either Text Text+percentDecoded encoded+  | BS.elem 0 bytes = Left "the URL's path decodes to a NUL byte"+  | otherwise = either (const (Left "the URL's path does not decode to UTF-8")) Right (TE.decodeUtf8' bytes)+  where+    -- Each byte as the Latin-1 character of its value, so an escape is+    -- matched on characters and every other byte passes through as it is.+    bytes = BS.pack (decode (BS8.unpack (TE.encodeUtf8 encoded)))+    decode chars = case chars of+      '%' : high : low : rest | [(value, "")] <- readHex [high, low] -> value : decode rest+      char : rest -> fromIntegral (ord char) : decode rest+      [] -> []++-- | Upstream's refusal of a URI restricted evaluation does not let a fetch+-- reach. forbiddenUriMessage :: Text -> Text forbiddenUriMessage uri = "access to URI '" <> uri <> "' is forbidden in restricted mode"
src/Nix/Eval/Print.hs view
@@ -1,3 +1,5 @@+{-# LANGUAGE LambdaCase #-}+ -- | The value printers upstream writes values with. -- -- @printValue@ (print.cc at Nix 2.24.9) quotes a value in a message.@@ -15,26 +17,30 @@ -- literal written in the list or set itself, for a function's argument, -- and for anything already forced.  It is not where upstream hands over a -- value without a thunk and nova-nix makes one (an indented string, a--- @~\/@ path, a variable bound to a literal by @let@ or @rec@, a global--- such as @map@).  A function value carries neither the name nor+-- @~\/@ path).  A function value carries neither the name nor -- the source position upstream prints after @lambda@, so its marker holds--- the word alone.  A set or list reached a second time prints again where--- upstream marks it repeated, which needs value identity this printer--- does not track.+-- the word alone. -- -- Upstream's @printAmbiguous@ (print-ambiguous.cc) writes what -- @nix-instantiate --eval@ prints, and 'printAmbiguous' writes what -- @nova-nix eval@ prints.  It renders to bytes: a string's payload is -- bytes that need not be UTF-8, and upstream writes them as they are.+--+-- Both printers, like upstream's, print a set or list they reach a second+-- time as a repeated marker, so a value that holds itself, as every+-- derivation does through its @all@ and output attributes, prints to an+-- end.  The same means the same set or list, not an equal one: two sets+-- made apart with the same attributes both print in full. module Nix.Eval.Print   ( PrintOptions (..),     printValue,     printAmbiguous,+    printSymbol,     formatXmlFloat,   ) where -import Control.Monad.State.Strict (State, evalState, gets, modify')+import Control.Monad.State.Strict (StateT, evalStateT, gets, lift, modify') import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.ByteString.Builder as BB@@ -42,11 +48,17 @@ import qualified Data.ByteString.Lazy as BL import Data.Char (isAsciiLower, isAsciiUpper, isDigit) import Data.List (partition)+import Data.Set (Set)+import qualified Data.Set as Set import Data.String (IsString) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as TE-import Nix.Eval.Types (AttrSet, NixValue (..), Thunk (..), attrSetToAscList, bytesToTextLossy, clistThunks, readThunkValue, thunkUnderEvaluation)+import Nix.Eval.Builtin (builtinName)+import Nix.Eval.CData (MonadCData)+import Nix.Eval.CList (CListPtr)+import Nix.Eval.CThunk (CThunkPtr)+import Nix.Eval.Types (AttrSet (..), CAttrSet, CList (..), NixValue (..), Thunk (..), attrSetNull, attrSetToAscList, bytesToTextLossy, clistLen, clistThunks, readThunkValue, thunkUnderEvaluation)  -- | Which of upstream's option sets a print follows. data PrintOptions@@ -83,20 +95,33 @@ limitedTo _ PrintInFull = Unlimited limitedTo bound PrintForError = AtMost bound --- | How many attributes and list items one print has shown.  Upstream's--- bounds on them count over the whole print, not per set or list.-data Shown = Shown {shownAttrs :: !Int, shownItems :: !Int}+-- | What one print has done so far: how many attributes and list items it+-- has shown, and which sets and lists it has entered.  Upstream counts+-- toward its bounds, and remembers what it has entered, over the whole+-- print, not per set or list.  'printAmbiguous' bounds nothing, so only+-- what it has entered changes there.+data Shown = Shown+  { shownAttrs :: !Int,+    shownItems :: !Int,+    shownEntered :: !(Set Entered)+  } -type Printer = State Shown+-- | A print in progress, reading the C data layer as it goes.+type Printer m = StateT Shown m +-- | A print that has shown and entered nothing yet.+nothingShown :: Shown+nothingShown = Shown 0 0 Set.empty+ -- | Render a value as upstream's @printValue@ renders it under the given -- options.-printValue :: PrintOptions -> NixValue -> Text-printValue options val = evalState (printAt options 0 val) (Shown 0 0)+printValue :: (MonadCData m) => PrintOptions -> NixValue -> m Text+printValue options val = evalStateT (printAt options 0 Nothing val) nothingShown --- | A value at a nesting depth, the top-level value being at 0.-printAt :: PrintOptions -> Int -> NixValue -> Printer Text-printAt options depth val = case val of+-- | A value at a nesting depth, the top-level value being at 0, with the+-- cell it was read from.  The top-level value is handed over without one.+printAt :: (MonadCData m) => PrintOptions -> Int -> Maybe Thunk -> NixValue -> Printer m Text+printAt options depth cell val = case val of   VInt n -> pure (T.pack (show n))   VFloat f -> pure (formatXmlFloat f)   VBool True -> pure "true"@@ -104,37 +129,38 @@   VNull -> pure "null"   VStr bytes _ -> pure (printString options bytes)   VPath p -> pure p-  VList cl -> printList options depth (map Thunk (clistThunks cl))-  VAttrs attrs -> printAttrs options depth attrs+  VList cl -> do+    key <- lift (printedList cell cl)+    entering repeatedMarker key (printList options depth cl)+  VAttrs attrs -> entering repeatedMarker (Just (printedSet attrs)) (printAttrs options depth attrs)   -- What upstream prints for a lambda whose expression it cannot reach.   VLambda {} -> pure (marker "lambda")-  VBuiltin name [] -> pure (marker ("primop " <> name))-  VBuiltin name _ -> pure (marker ("partially applied primop " <> name))-  -- A compiled pattern exists only among the arguments of a partially-  -- applied match or split and names neither, so it prints as upstream-  -- prints an application whose primop it cannot name.-  VCompiledRegex _ -> pure (marker "partially applied primop")+  VBuiltin builtin [] -> pure (marker ("primop " <> builtinName builtin))+  VBuiltin builtin _ -> pure (marker ("partially applied primop " <> builtinName builtin))  -- | Upstream's @printAttrs@.  A set's attributes count toward the bound -- after the attributes of any set inside them, as upstream counts one -- only once its value has printed.-printAttrs :: PrintOptions -> Int -> AttrSet -> Printer Text+printAttrs :: (MonadCData m) => PrintOptions -> Int -> AttrSet -> Printer m Text printAttrs options depth attrs-  | within depth (depthLimit options) =-      bracketed "{" "}" <$> printBounded (attrLimit options) shownAttrs countAttr elidedAttrs (map printAttr (orderedAttrs options attrs))+  | within depth (depthLimit options) = do+      ordered <- lift (orderedAttrs options attrs)+      bracketed "{" "}" <$> printBounded (attrLimit options) shownAttrs countAttr elidedAttrs (map printAttr ordered)   | otherwise = pure "{ ... }"   where     printAttr (name, thunk) = do       shown <- printThunk options (depth + 1) thunk-      pure (builderText (printIdentifier (TE.encodeUtf8 name)) <> " = " <> shown <> ";")+      pure (printSymbol name <> " = " <> shown <> ";")     countAttr counts = counts {shownAttrs = shownAttrs counts + 1}     elidedAttrs left = elided left "attribute" "attributes" --- | Upstream's @printList@.-printList :: PrintOptions -> Int -> [Thunk] -> Printer Text-printList options depth thunks-  | within depth (depthLimit options) =-      bracketed "[" "]" <$> printBounded (itemLimit options) shownItems countItem elidedItems (map (printThunk options (depth + 1)) thunks)+-- | Upstream's @printList@.  The elements are read only inside the depth+-- bound, so a list past it prints as @[ ... ]@ without reading any.+printList :: (MonadCData m) => PrintOptions -> Int -> CList -> Printer m Text+printList options depth cl+  | within depth (depthLimit options) = do+      thunks <- lift (clistThunks cl)+      bracketed "[" "]" <$> printBounded (itemLimit options) shownItems countItem elidedItems (map (printThunk options (depth + 1) . Thunk) thunks)   | otherwise = pure "[ ... ]"   where     countItem counts = counts {shownItems = shownItems counts + 1}@@ -142,30 +168,26 @@  -- | Print the entries of one set or list while the print's running count -- is inside the bound, then, in place of the rest, how many were left.-printBounded :: Limit -> (Shown -> Int) -> (Shown -> Shown) -> (Int -> Text) -> [Printer Text] -> Printer [Text]-printBounded bound counted count elision = go-  where-    go :: [Printer Text] -> Printer [Text]-    go [] = pure []-    go entries@(entry : rest) = gets counted >>= continueAt-      where-        continueAt sofar-          | within sofar bound = do+printBounded :: (Monad m) => Limit -> (Shown -> Int) -> (Shown -> Shown) -> (Int -> Text) -> [Printer m Text] -> Printer m [Text]+printBounded _ _ _ _ [] = pure []+printBounded bound counted count elision entries@(entry : rest) = do+  sofar <- gets counted+  if within sofar bound+    then do       shown <- entry       modify' count-              (shown :) <$> go rest-          | otherwise = pure [elision (length entries)]+      (shown :) <$> printBounded bound counted count elision rest+    else pure [elision (length entries)]  -- | A set's attributes in upstream's order: by name, with @_type@ and -- @type@ ahead of the rest wherever attributes are bounded (print.cc sorts -- by its @ImportantFirstAttrNameCmp@ then).-orderedAttrs :: PrintOptions -> AttrSet -> [(Text, Thunk)]-orderedAttrs options attrs = case attrLimit options of-  Unlimited -> byName-  AtMost _ -> important <> rest+orderedAttrs :: (MonadCData m) => PrintOptions -> AttrSet -> m [(Text, Thunk)]+orderedAttrs options attrs = inOrder <$> attrSetToAscList attrs   where-    byName = attrSetToAscList attrs-    (important, rest) = partition ((`elem` importantAttrNames) . fst) byName+    inOrder byName = case attrLimit options of+      Unlimited -> byName+      AtMost _ -> uncurry (<>) (partition ((`elem` importantAttrNames) . fst) byName)  -- | Upstream's @isImportantAttrName@. importantAttrNames :: [Text]@@ -174,12 +196,13 @@ -- | An element or attribute value, read without forcing it: its value -- once it has one, and otherwise upstream's marker for a thunk, or for a -- thunk whose force is still running.-printThunk :: PrintOptions -> Int -> Thunk -> Printer Text-printThunk options depth thunk = case readThunkValue thunk of-  Just val -> printAt options depth val-  Nothing-    | thunkUnderEvaluation thunk -> pure (marker "potential infinite recursion")-    | otherwise -> pure (marker "thunk")+printThunk :: (MonadCData m) => PrintOptions -> Int -> Thunk -> Printer m Text+printThunk options depth thunk =+  lift (readThunkValue thunk) >>= \case+    Just val -> printAt options depth (Just thunk) val+    Nothing -> do+      underEvaluation <- lift (thunkUnderEvaluation thunk)+      pure (marker (if underEvaluation then "potential infinite recursion" else "thunk"))  -- | Upstream's @printLiteralString@: quoted and escaped so the lexer reads -- the same string back.  The cut and the count of what it left out are in@@ -235,6 +258,88 @@ builderText = bytesToTextLossy . BL.toStrict . BB.toLazyByteString  -- ---------------------------------------------------------------------------+-- Repeated sets and lists+-- ---------------------------------------------------------------------------++-- | A set or list a print has entered, by the identity upstream's printers+-- remember one by.  Each is a C pointer, reached from the value the print+-- was handed, which is older than every force the print runs, so no close+-- of one frees it ("Nix.Eval.CRegion"), and a pointer names one set, list+-- or cell for the whole print.+data Entered+  = -- | A set, by its C set, as upstream remembers a set by its+    -- @Bindings@: every empty set upstream shares is the one+    -- 'Nix.Eval.Types.emptyAttrSet' here, and an update with an empty+    -- operand is the other operand's set, as upstream's is.+    EnteredSet !CAttrSet+  | -- | A list, by the cell it was read from, as upstream remembers a list+    -- by its @Value@.+    EnteredCell !CThunkPtr+  | -- | A list, by its C list, which every cell holding the list shares.+    EnteredList !CListPtr+  deriving (Eq, Ord)++-- | Print a set or list the first time a print enters it, and the given+-- marker each time after.  One with no identity prints in full each time.+entering :: (Monad m) => a -> Maybe Entered -> Printer m a -> Printer m a+entering _ Nothing body = body+entering repeated (Just key) body = gets (Set.member key . shownEntered) >>= enterUnlessSeen+  where+    enterUnlessSeen True = pure repeated+    enterUnlessSeen False = modify' (\shown -> shown {shownEntered = Set.insert key (shownEntered shown)}) >> body++-- | Upstream's @printRepeated@.+repeatedMarker :: Text+repeatedMarker = marker "repeated"++-- | What 'printValue' enters a set by (@printAttrs@ in print.cc): its+-- bindings, an empty set's included.+printedSet :: AttrSet -> Entered+printedSet = EnteredSet . unAttrSet++-- | What 'printValue' enters a list with elements by (@printList@ in+-- print.cc): the cell holding it.  The top-level value has no cell, so a+-- list there is entered by nothing.  Upstream's top-level @Value@ is the+-- one its caller hands over: a temporary for a coercion+-- (@ExprConcatStrings::eval@ in eval.cc), which nothing else holds either,+-- and for @builtins.trace@ the argument itself (@prim_trace@ in+-- primops.cc), so a traced list that holds itself prints one level deeper+-- here before the marker.+printedList :: (MonadCData m) => Maybe Thunk -> CList -> m (Maybe Entered)+printedList cell cl = do+  len <- clistLen cl+  pure (if len == 0 then Nothing else EnteredCell . unThunk <$> cell)++-- | What 'printAmbiguous' enters a set with attributes by+-- (print-ambiguous.cc): its bindings.  An empty set is entered by nothing and+-- always prints in full.+resultSet :: (MonadCData m) => AttrSet -> m (Maybe Entered)+resultSet attrs = do+  empty <- attrSetNull attrs+  pure (if empty then Nothing else Just (EnteredSet (unAttrSet attrs)))++-- | What 'printAmbiguous' enters a list with elements by+-- (print-ambiguous.cc at 2.24.9): where its elements are.  Upstream keeps a+-- short list's elements inside its @Value@ and a longer one's in an array+-- every copy of that @Value@ shares (@Value::listElems@ in value.hh), so a+-- short list is entered by the cell holding it and a longer one by its C+-- list.  The top-level value has no cell, and upstream's is+-- nix-instantiate's own copy (@processExpr@ in nix-instantiate.cc), which+-- nothing else holds, so a short list there is entered by nothing.+resultList :: (MonadCData m) => Maybe Thunk -> CList -> m (Maybe Entered)+resultList cell cl = enteredBy <$> clistLen cl+  where+    enteredBy len+      | len == 0 = Nothing+      | len <= inlineListElements = EnteredCell . unThunk <$> cell+      | otherwise = Just (EnteredList (unCList cl))++-- | The most elements upstream keeps inside a list's @Value@+-- (@smallList@ in value.hh).+inlineListElements :: Int+inlineListElements = 2++-- --------------------------------------------------------------------------- -- The eval result -- --------------------------------------------------------------------------- @@ -243,26 +348,37 @@ -- newline the command writes after it.  A string prints as its own bytes, -- escaped as 'printValue' escapes it and never cut, and a float in a -- default ostream's six-digit form, as 'formatXmlFloat' writes it.-printAmbiguous :: NixValue -> BB.Builder-printAmbiguous val = case val of-  VInt n -> BB.int64Dec n-  VFloat f -> TE.encodeUtf8Builder (formatXmlFloat f)-  VBool True -> "true"-  VBool False -> "false"-  VNull -> "null"-  VStr bytes _ -> quotedBytes (BS.length bytes) bytes-  VPath p -> TE.encodeUtf8Builder p-  VList cl -> bracketed "[" "]" (map (printElement . Thunk) (clistThunks cl))-  VAttrs attrs -> bracketed "{" "}" (map printAttribute (attrSetToAscList attrs))-  VLambda {} -> "<LAMBDA>"-  VBuiltin _ [] -> "<PRIMOP>"-  VBuiltin _ _ -> "<PRIMOP-APP>"-  -- A compiled pattern exists only among the arguments of a partially-  -- applied match or split, so it prints as that application does.-  VCompiledRegex _ -> "<PRIMOP-APP>"+printAmbiguous :: (MonadCData m) => NixValue -> m BB.Builder+printAmbiguous val = evalStateT (printAmbiguousAt Nothing val) nothingShown+-- The executable prints its result in IO, and a result can be the whole+-- of a large value: left to the library's flags, that print ran on the+-- dictionary-passing code.+{-# SPECIALIZE printAmbiguous :: NixValue -> IO BB.Builder #-}++-- | A value with the cell it was read from, as 'printAt' takes one.+printAmbiguousAt :: (MonadCData m) => Maybe Thunk -> NixValue -> Printer m BB.Builder+printAmbiguousAt cell val = case val of+  VInt n -> pure (BB.int64Dec n)+  VFloat f -> pure (TE.encodeUtf8Builder (formatXmlFloat f))+  VBool True -> pure "true"+  VBool False -> pure "false"+  VNull -> pure "null"+  VStr bytes _ -> pure (quotedBytes (BS.length bytes) bytes)+  VPath p -> pure (TE.encodeUtf8Builder p)+  VList cl -> do+    key <- lift (resultList cell cl)+    entering repeatedBytes key (lift (clistThunks cl) >>= fmap (bracketed "[" "]") . traverse (printElement . Thunk))+  VAttrs attrs -> do+    key <- lift (resultSet attrs)+    entering repeatedBytes key (lift (attrSetToAscList attrs) >>= fmap (bracketed "{" "}") . traverse printAttribute)+  VLambda {} -> pure "<LAMBDA>"+  VBuiltin _ [] -> pure "<PRIMOP>"+  VBuiltin _ _ -> pure "<PRIMOP-APP>"   where-    printAttribute (name, thunk) =-      printIdentifier (TE.encodeUtf8 name) <> " = " <> printElement thunk <> ";"+    repeatedBytes = TE.encodeUtf8Builder repeatedMarker+    printAttribute (name, thunk) = do+      shown <- printElement thunk+      pure (printIdentifier (TE.encodeUtf8 name) <> " = " <> shown <> ";")  -- | Upstream follows the opening bracket and every item with a space, so -- an empty list is @[ ]@.  Both printers bracket this way.@@ -271,8 +387,15 @@  -- | A list element or attribute value: its value when it has one, and -- upstream's marker for a thunk when it was never forced.-printElement :: Thunk -> BB.Builder-printElement thunk = maybe "<CODE>" printAmbiguous (readThunkValue thunk)+printElement :: (MonadCData m) => Thunk -> Printer m BB.Builder+printElement thunk = lift (readThunkValue thunk) >>= maybe (pure "<CODE>") (printAmbiguousAt (Just thunk))++-- | A name as upstream writes a symbol into a message: its @operator<<@ on+-- a @SymbolStr@ writes it through @printIdentifier@ (nixexpr.cc), so a name+-- that is not an identifier, the empty name or a keyword prints as a string+-- literal.+printSymbol :: Text -> Text+printSymbol = builderText . printIdentifier . TE.encodeUtf8  -- | Upstream's @printIdentifier@ (print.cc), which @printAmbiguous@ writes -- an attribute name through (nixexpr.cc's @operator<<@ on a symbol): a
+ src/Nix/Eval/RealiseContext.hs view
@@ -0,0 +1,246 @@+{-# LANGUAGE LambdaCase #-}++-- | Realising a string's context before a path reader reads its path, as+-- upstream's @EvalState::realiseContext@ does (primops.cc): what a context+-- asks of the store, and what a session does about it.+--+-- Every path the context names must be valid, checked in upstream's+-- order, and the first that is not stops the read with upstream's+-- @path \'...\' is not valid@.  Then, unless @allow-import-from-derivation@+-- refuses a context that names an output, each output it names is built or+-- substituted (@EvalState::realiseContext@ in primops.cc).+--+-- A read-write session, a build's, adds what evaluation has fetched,+-- written or named and the store does not hold yet before that, so all+-- of it counts as valid there.  A read-only session, an evaluation as+-- @nix-instantiate --eval@ runs one, adds only what a fetcher fetched, as+-- it is fetched.  What evaluation computed (a coerced source, a+-- @builtins.toFile@, @builtins.path@ or @builtins.filterSource@ result, a+-- derivation) is not valid there unless the store already holds it, since+-- upstream's read-only evaluation computes those paths without writing+-- them.  What a fetcher fetched is valid there, since upstream's fetchers+-- add their results whatever the mode.  A read-only session realises an+-- output as+-- upstream's read-only evaluation does: every substitution is refused, and+-- an output that may not be substituted is built.+module Nix.Eval.RealiseContext+  ( -- * Sessions+    SessionMode (..),+    PendingOrigin (..),++    -- * What a context asks+    ContextRequest (..),++    -- * Planning+    readableIn,+    firstInvalidPath,+    Plan (..),+    planRealisation,+    referenceClosure,++    -- * Refusals+    ContextRefusal (..),+    contextRefusalMessage,+    findFileRefusalMessage,+  )+where++import Data.List (find)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (mapMaybe)+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import Nix.Eval.Policy (ImportFromDerivation (..))+import Nix.Store.Path (StorePath, defaultStoreDir, storePathBasename, storePathToText)++-- ---------------------------------------------------------------------------+-- Sessions+-- ---------------------------------------------------------------------------++-- | What an evaluation session may do to its store.+data SessionMode+  = -- | Add only what a fetcher fetched, as it is fetched, and realise an+    -- output as upstream's read-only evaluation does, as+    -- @nix-instantiate --eval@ does without @--read-write-mode@.+    ReadOnly+  | -- | Add what evaluation made and build what its contexts name, as a+    -- build does.+    ReadWrite+  deriving (Eq, Show)++-- | How an object evaluation made and the store does not hold yet came+-- to be, which decides whether a read-only session can read it.+data PendingOrigin+  = -- | A fetcher fetched it, which upstream adds to its store in any+    -- mode.+    Fetched+  | -- | Evaluation computed it, which upstream's read-only evaluation+    -- names without writing.+    Computed+  deriving (Eq, Show)++-- ---------------------------------------------------------------------------+-- What a context asks+-- ---------------------------------------------------------------------------++-- | What a string's context asks of the store, in the order upstream walks+-- its context set (@NixStringContext@, value/context.hh at 2.24.9): plain+-- paths, then derivations named whole, then outputs, each by path.+data ContextRequest = ContextRequest+  { -- | Each path that must be valid: a plain path, a derivation named+    -- whole, and the derivation of each output named, as upstream's+    -- @ensureValid@ asks about each element in turn (primops.cc).+    crPaths :: ![StorePath],+    -- | Each output named, by its derivation and its name.+    crOutputs :: ![(StorePath, Text)]+  }+  deriving (Eq, Show)++-- ---------------------------------------------------------------------------+-- Planning+-- ---------------------------------------------------------------------------++-- | What a session does for a context it can realise.+data Plan = Plan+  { -- | Whether to add what evaluation has made and the store does not+    -- hold yet first: a read-write session adds it before it builds, and+    -- before a read of something evaluation made.+    planAdd :: !Bool,+    -- | The derivations to realise, each for the outputs named of it that+    -- are not valid, or that it may not have, which the realisation+    -- refuses as upstream's worker does.+    planBuilds :: ![(StorePath, Set Text)],+    -- | Every output the context names, whose closures become readable+    -- once they are realised, as upstream allows them (@allowClosure@ in+    -- @EvalState::realiseContext@, primops.cc, at 2.34.9).+    planOutputs :: ![StorePath],+    -- | The warning @trace-import-from-derivation@ prints before anything+    -- is realised, where it is on and an output is named.+    planWarning :: !(Maybe Text)+  }+  deriving (Eq, Show)++-- | Plan the realisation of a context, given the session's mode, what+-- evaluation has made that the store may not hold, the paths of those+-- asked about that the store holds, and each output's path.  A session+-- asks the store about every path the request names that it cannot+-- answer itself: a read-write session about those evaluation did not+-- make, a read-only one about all but what a fetcher fetched, and about+-- the outputs.+--+-- A path that is not valid is refused first, in the request's order+-- ('PathNotValid').  A request that names an output is then refused when+-- import from derivation is off ('ImportFromDerivationOff'), whether or+-- not the output is valid, and warned of when it is traced, each naming+-- the first output in upstream's order.  Each derivation is then realised+-- for its outputs that are not valid, and for any output name whose path is not known,+-- which the realisation refuses as upstream's worker refuses an output a+-- derivation does not have.  A read-write session adds what evaluation+-- made first when it realises anything or the request names any of it,+-- so the read finds it.+planRealisation ::+  ImportFromDerivation ->+  SessionMode ->+  Map StorePath PendingOrigin ->+  Set StorePath ->+  Map (StorePath, Text) StorePath ->+  ContextRequest ->+  Either ContextRefusal Plan+planRealisation imports mode pending valid outputPaths request =+  case firstInvalidPath mode pending valid request of+    Just path -> Left (PathNotValid path)+    Nothing -> case (imports, crOutputs request) of+      (_, []) -> Right (planned Nothing)+      (RefuseImportFromDerivation, (drv, output) : _) -> Left (ImportFromDerivationOff drv output)+      (AllowImportFromDerivation, _) -> Right (planned Nothing)+      (TraceImportFromDerivation, (drv, output) : _) -> Right (planned (Just (importFromDerivationWarning drv output)))+  where+    planned = Plan (mode == ReadWrite && (namesPending || not (null builds))) builds known+    readable = readableIn mode pending valid+    namesPending = any (`Map.member` pending) (crPaths request)+    resolved = [(named, Map.lookup named outputPaths) | named <- crOutputs request]+    known = mapMaybe snd resolved+    builds =+      Map.toList+        ( Map.fromListWith+            Set.union+            [(drv, Set.singleton output) | ((drv, output), path) <- resolved, maybe True (not . readable) path]+        )++-- | The first path of the request that is not valid, in the request's+-- order, given the session's mode, what evaluation has made and the+-- store's answer for the paths asked about: what upstream's+-- @ensureValid@ refuses first (@EvalState::realiseContext@ in primops.cc).+firstInvalidPath :: SessionMode -> Map StorePath PendingOrigin -> Set StorePath -> ContextRequest -> Maybe StorePath+firstInvalidPath mode pending valid = find (not . readableIn mode pending valid) . crPaths++-- | Whether a session can read a path: the store holds it, a fetcher+-- fetched it, or evaluation computed it and a read-write session adds it+-- before the read.+readableIn :: SessionMode -> Map StorePath PendingOrigin -> Set StorePath -> StorePath -> Bool+readableIn mode pending valid path =+  path `Set.member` valid || case Map.lookup path pending of+    Just Fetched -> True+    Just Computed -> mode == ReadWrite+    Nothing -> False++-- | Each path with every path it references, through the store's answer+-- for one path's references, asking about each once.+referenceClosure :: (Monad m) => (StorePath -> m (Either Text (Set StorePath))) -> [StorePath] -> m (Either Text (Set StorePath))+referenceClosure references = go Set.empty+  where+    go seen [] = pure (Right seen)+    go seen (path : rest)+      | path `Set.member` seen = go seen rest+      | otherwise =+          references path >>= \case+            Left failure -> pure (Left failure)+            Right referenced -> go (Set.insert path seen) (Set.toList referenced <> rest)++-- ---------------------------------------------------------------------------+-- Refusals+-- ---------------------------------------------------------------------------++-- | Why a context could not be realised.+data ContextRefusal+  = -- | This path is not valid, and the session cannot make it so.+    PathNotValid !StorePath+  | -- | This output of this derivation is the first the context names,+    -- and @allow-import-from-derivation@ is off.+    ImportFromDerivationOff !StorePath !Text+  | -- | Adding or realising failed, with the message the failure reports.+    RealisationFailed !Text+  deriving (Eq, Show)++-- | A refusal as upstream words it.  A path is named under the logical+-- store directory, as upstream's @printStorePath@ names it+-- (@InvalidPathError@ in eval-error.cc, 2.35.4 and later; 2.34.9 names the+-- path's base name alone).+contextRefusalMessage :: ContextRefusal -> Text+contextRefusalMessage = \case+  PathNotValid path -> "path '" <> storePathToText defaultStoreDir path <> "' is not valid"+  ImportFromDerivationOff drv output -> "cannot build '" <> builtText drv output <> "' during evaluation because the option 'allow-import-from-derivation' is disabled"+  RealisationFailed message -> message++-- | The warning @trace-import-from-derivation@ gives, naming the first+-- output a context names (@EvalState::realiseContext@ in primops.cc at+-- 2.34.9).+importFromDerivationWarning :: StorePath -> Text -> Text+importFromDerivationWarning drv output = "built '" <> builtText drv output <> "' during evaluation due to an import from derivation"++-- | An output of a derivation as upstream renders a built derived path,+-- the derivation's path, a caret and the output's name+-- (@DerivedPath::Built::to_string@ in derived-path.cc).+builtText :: StorePath -> Text -> Text+builtText drv output = storePathToText defaultStoreDir drv <> "^" <> output++-- | A refusal of a search path entry's context as @builtins.findFile@+-- words it: a path that is not valid names the entry and the path's base+-- name (@prim_findFile@ in primops.cc, 2.34.9 and later, where 2.24.9 names+-- the whole path), and any other refusal is worded as it is anywhere else.+findFileRefusalMessage :: Text -> ContextRefusal -> Text+findFileRefusalMessage entry refusal = case refusal of+  PathNotValid path -> "cannot find '" <> entry <> "', since path '" <> storePathBasename path <> "' is not valid"+  other -> contextRefusalMessage other
src/Nix/Eval/SourcePos.hs view
@@ -1,14 +1,17 @@ -- | Source positions as the evaluator keeps them: a t'PosIdx' stored beside--- an attribute, read back as a file, line and column on demand.+-- an attribute, read back as a file, line and column on demand, and+-- written as upstream's messages write one. -- -- A position is recorded when the construct it belongs to is compiled, as--- three words in the bytecode data buffer: the interned path of the file it--- is in ('noFile' for text with no file behind it), its line and its column.--- Its index is one past the record's offset, so 0 is free to mean no--- position, the bias upstream's @PosIdx@ carries for the same reason--- (@noPos@ in pos-idx.hh, @PosTable::add@ in pos-table.hh, at 2.24.9).--- The record lives as long as the bytecode that refers to it, and is--- never written again.+-- three words in the bytecode data buffer: the file it is in, one past the+-- index of its path among the code's strings ('noFile' for text with no+-- file behind it), its line and its column.  The path is a string and not+-- a symbol, as upstream keeps a file in a position's origin and not in its+-- symbol table (@PosTable::Origin@ in pos-table.hh).  Its index is one+-- past the record's offset, so 0 is free to mean no position, the bias+-- upstream's @PosIdx@ carries for the same reason (@noPos@ in pos-idx.hh,+-- @PosTable::add@ in pos-table.hh, at 2.24.9).  The record lives as long+-- as the bytecode that refers to it, and is never written again. module Nix.Eval.SourcePos   ( -- * Indices     PosIdx (..),@@ -22,16 +25,17 @@     -- * Reading back     RecordedPos (..),     lookupPos,+    printPos,   ) where  import Data.IORef (IORef, newIORef, readIORef, writeIORef) import Data.Text (Text)+import qualified Data.Text as T import Data.Word (Word32)-import Nix.Eval.CBytecode (cbcData, cbcEmitData)-import Nix.Eval.Symbol (Symbol (..), symbolIntern, symbolText)+import Nix.Eval.CBytecode (cbcData, cbcEmitData, cbcEmitText, cbcStringText)+import Nix.Eval.CData (MonadCData) import Nix.Expr.Types (SourceOrigin (..), SrcPos (..))-import System.IO.Unsafe (unsafePerformIO)  -- | Where something was defined: 'noPos', or the index of a recorded -- position.@@ -43,15 +47,15 @@ noPos :: PosIdx noPos = PosIdx 0 --- | The file word of a position in text with no file.  No symbol is 0--- (@NN_SYMBOL_INVALID@), so it cannot be mistaken for a path.+-- | The file word of a position in text with no file.  A file's word is+-- one past its path's string index, so it cannot be mistaken for one. noFile :: Word32 noFile = 0  -- | Records the positions of one compilation.  It remembers the last -- origin it recorded and that origin's file word, because the positions--- of one parse share their origin, and interning the path again for each--- one would copy and hash it as many times.+-- of one parse share their origin, and storing the path again for each+-- one would copy it as many times. newtype PosRecorder = PosRecorder (IORef (Maybe SeenOrigin))  -- | An origin and its file word.@@ -79,11 +83,11 @@       case remembered of         Just (SeenOrigin known word) | known == origin -> pure word         _ -> do-          word <- internedFile origin+          word <- storedFile origin           writeIORef seen (Just (SeenOrigin origin word))           pure word-    internedFile (SourceFile path) = unSymbol <$> symbolIntern path-    internedFile (SourceText _) = pure noFile+    storedFile (SourceFile path) = (+ 1) <$> cbcEmitText path+    storedFile (SourceText _) = pure noFile     toWord32 n       | n >= 0 && toInteger n <= toInteger (maxBound :: Word32) = Just (fromIntegral n)       | otherwise = Nothing@@ -96,17 +100,45 @@     PosInText !Int !Int   deriving (Eq, Show) --- | Read a position back, or 'Nothing' for 'noPos'.  'unsafePerformIO' is--- safe here: the record was written once, when its index was made, and--- no later write touches it, so the read answers the same every time.-lookupPos :: PosIdx -> Maybe RecordedPos-lookupPos (PosIdx 0) = Nothing-lookupPos (PosIdx idx) = Just $ unsafePerformIO $ do+-- | Read a position back, or 'Nothing' for 'noPos'.+lookupPos :: (MonadCData m) => PosIdx -> m (Maybe RecordedPos)+lookupPos (PosIdx 0) = pure Nothing+lookupPos (PosIdx idx) = do   let offset = idx - 1   file <- cbcData offset   line <- fromIntegral <$> cbcData (offset + 1)   column <- fromIntegral <$> cbcData (offset + 2)-  pure $-    if file == noFile-      then PosInText line column-      else PosInFile (symbolText (Symbol file)) line column+  Just+    <$> if file == noFile+      then pure (PosInText line column)+      else (\path -> PosInFile path line column) <$> cbcStringText (file - 1)++-- | A position as upstream's messages write one, @Pos::print@ with its+-- origin (position.cc): its origin, then a colon and its line, then a+-- colon and its column unless that is 0.  The origin of a position in a+-- file is the file's path, as upstream shows a file it reads from the+-- filesystem, and of one in text with no file behind it, such as an+-- @--expr@ string, @string@ in guillemets, upstream's @Pos::String@.+-- 'noPos' is upstream's empty @Pos@, at line 0 of @none@ in guillemets.+printPos :: (MonadCData m) => PosIdx -> m Text+printPos idx = written <$> lookupPos idx+  where+    written (Just (PosInFile path line column)) = located path line column+    written (Just (PosInText line column)) = located stringOrigin line column+    written Nothing = located noOrigin 0 0+    located :: Text -> Int -> Int -> Text+    located origin line column = origin <> ":" <> T.pack (show line) <> columnPart column+    columnPart 0 = ""+    columnPart column = ":" <> T.pack (show column)++-- | The origin upstream writes for a position in text with no file behind+-- it, such as an @--expr@ string (@Pos::String@ in @Pos::print@,+-- position.cc), in guillemets (U+00AB, U+00BB) written as escapes to keep+-- the source ASCII.+stringOrigin :: Text+stringOrigin = "\x00ABstring\x00BB"++-- | The origin upstream writes for a position with none (@Pos::print@ in+-- position.cc), escaped as 'stringOrigin' is.+noOrigin :: Text+noOrigin = "\x00ABnone\x00BB"
+ src/Nix/Eval/StartupSymbols.hs view
@@ -0,0 +1,269 @@+-- | The names upstream's evaluator interns as it starts, in the order it+-- interns them, which the C data layer interns before anything else as+-- the outermost evaluation session sets it up+-- ('Nix.Eval.IO.withEvalSession').+--+-- A set holds its attributes in symbol order, and a symbol's place is the+-- order its name was interned in, so that order decides which failure+-- wins wherever a walk over a set stops at the first, such as the+-- unexpected argument a call names.  Upstream's @EvalState@ interns these+-- names before it parses anything (nix-instantiate 2.24.9 with its+-- default settings): its static symbols as it is constructed, then each+-- name @createBaseEnv@ installs, then the names of the @derivation@+-- wrapper, which @createBaseEnv@ parses last.+module Nix.Eval.StartupSymbols+  ( startupSymbols,+  )+where++import Data.Maybe (maybeToList)+import Data.Text (Text)+import qualified Data.Text as T++-- | Every name upstream's evaluator interns as it starts, in order,+-- repeats included: interning a name already in the table changes+-- nothing.+--+-- The base environment's names are those of the default settings:+-- impure, so the two @impureOnly@ constants are there (@addConstant@ in+-- eval.cc), which @pure-eval@ leaves out; no experimental feature; no+-- native code.  Interning them under @pure-eval@ as well places those+-- four names before a program's where upstream's interns them with the+-- program.+startupSymbols :: [Text]+startupSymbols =+  staticSymbols+    ++ concatMap installedNames baseEnvNames+    ++ derivationWrapperNames++-- | The symbols @EvalState@'s constructor interns, in the order its+-- members are declared (@EvalState@ in eval.hh and eval.cc at 2.24.9;+-- @StaticEvalSymbols@ in eval.hh at 2.36.0), the order C++ initializes them+-- in: its @sWith@ to @sOutputSpecified@, then its @exprSymbols@.+staticSymbols :: [Text]+staticSymbols =+  [ "<with>",+    "outPath",+    "drvPath",+    "type",+    "meta",+    "name",+    "value",+    "system",+    "__overrides",+    "outputs",+    "outputName",+    "__ignoreNulls",+    "file",+    "line",+    "column",+    "__functor",+    "__toString",+    "right",+    "wrong",+    "__structuredAttrs",+    "allowedReferences",+    "allowedRequisites",+    "disallowedReferences",+    "disallowedRequisites",+    "maxSize",+    "maxClosureSize",+    "builder",+    "args",+    "__contentAddressed",+    "__impure",+    "outputHash",+    "outputHashAlgo",+    "outputHashMode",+    "recurseForDerivations",+    "description",+    "self",+    "",+    "startSet",+    "operator",+    "key",+    "path",+    "prefix",+    "outputSpecified",+    "__sub",+    "__lessThan",+    "__mul",+    "__div",+    "or",+    "__findFile",+    "__nixPath",+    "body"+  ]++-- | What @addConstant@ and @addPrimOp@ intern for a name they install: the+-- name, then the name less a @__@ prefix, the one @builtins@ holds it+-- under (eval.cc).+installedNames :: Text -> [Text]+installedNames name = name : maybeToList (T.stripPrefix "__" name)++-- | The names @createBaseEnv@ installs, in order (primops.cc at 2.24.9):+-- its constants, @__traceVerbose@ and @__nixPath@, whose entries' @path@+-- and @prefix@ are static symbols; every registered primop not gated on+-- an experimental feature; then @derivation@.+--+-- The primops register as their translation units initialize, each in+-- the order it defines them: primops.cc, then the files of primops/ in+-- name order, the order 2.24.9's build links them (@libexpr_SOURCES@,+-- src/libexpr/local.mk).  2.35.0 compiles them in that order too, as one+-- unity build of the files its meson.build lists.  The release builds of+-- 2.27.0 through 2.34 link them under GCC's link-time optimization, which+-- runs the files' initializers in the reverse order, primops.cc's last.+-- An experimental feature leaves out @__outputOf@+-- (dynamic-derivations), @__fetchClosure@ (fetch-closure) and @fetchTree@+-- (fetch-tree, which flakes implies).  fetchTree.cc registers the+-- internal @fetchFinalTree@ with no feature, which interns its name alone,+-- as an internal primop is installed nowhere but under it (@addPrimOp@ in+-- eval.cc at 2.36.0).  After every registered primop come the flake+-- primops @__getFlake@, @__parseFlakeRef@ and @__flakeRefToString@, which+-- 2.36.0's @nix@ adds to every evaluator whatever the features (its+-- @extraPrimOps@, from libflake's settings.cc).+baseEnvNames :: [Text]+baseEnvNames =+  [ "builtins",+    "true",+    "false",+    "null",+    "__currentTime",+    "__currentSystem",+    "__nixVersion",+    "__storeDir",+    "__langVersion",+    "__traceVerbose",+    "__nixPath"+  ]+    ++ primopsCc+    ++ contextCc+    ++ ["fetchMercurial"]+    ++ ["fetchFinalTree", "__fetchurl", "fetchTarball", "fetchGit"]+    ++ ["fromTOML"]+    ++ ["__getFlake", "__parseFlakeRef", "__flakeRefToString"]+    ++ ["derivation"]+  where+    -- The RegisterPrimOp entries of primops.cc at 2.24.9.+    primopsCc =+      [ "scopedImport",+        "import",+        "__typeOf",+        "isNull",+        "__isFunction",+        "__isInt",+        "__isFloat",+        "__isString",+        "__isBool",+        "__isPath",+        "__genericClosure",+        "break",+        "abort",+        "throw",+        "__addErrorContext",+        "__ceil",+        "__floor",+        "__tryEval",+        "__getEnv",+        "__seq",+        "__deepSeq",+        "__trace",+        "__warn",+        "derivationStrict",+        "placeholder",+        "__toPath",+        "__storePath",+        "__pathExists",+        "baseNameOf",+        "dirOf",+        "__readFile",+        "__findFile",+        "__hashFile",+        "__readFileType",+        "__readDir",+        "__toXML",+        "__toJSON",+        "__fromJSON",+        "__toFile",+        "__filterSource",+        "__path",+        "__attrNames",+        "__attrValues",+        "__getAttr",+        "__unsafeGetAttrPos",+        "__hasAttr",+        "__isAttrs",+        "removeAttrs",+        "__listToAttrs",+        "__intersectAttrs",+        "__catAttrs",+        "__functionArgs",+        "__mapAttrs",+        "__zipAttrsWith",+        "__isList",+        "__elemAt",+        "__head",+        "__tail",+        "map",+        "__filter",+        "__elem",+        "__concatLists",+        "__length",+        "__foldl'",+        "__any",+        "__all",+        "__genList",+        "__sort",+        "__partition",+        "__groupBy",+        "__concatMap",+        "__add",+        "__sub",+        "__mul",+        "__div",+        "__bitAnd",+        "__bitOr",+        "__bitXor",+        "__lessThan",+        "toString",+        "__substring",+        "__stringLength",+        "__hashString",+        "__convertHash",+        "__match",+        "__split",+        "__concatStringsSep",+        "__replaceStrings",+        "__parseDrvName",+        "__compareVersions",+        "__splitVersion"+      ]+    -- primops/context.cc at 2.24.9.+    contextCc =+      [ "__unsafeDiscardStringContext",+        "__hasContext",+        "__unsafeDiscardOutputDependency",+        "__addDrvOutputDependencies",+        "__getContext",+        "__appendContext"+      ]++-- | The names upstream's @derivation@ wrapper (primops/derivation.nix at+-- 2.24.9) brings that nothing above interns, in the order its parser+-- interns them (the grammar actions of parser.y): @strict@ and @drvAttrs@+-- from its first binding, @commonAttrs@ and @outputsList@ from its second,+-- @x@ from that binding's @x: x.value@, then @outputToAttrListElement@.+-- Every other name the wrapper reads is a static symbol or one the base+-- environment installs.  @createBaseEnv@ evaluates the file once it has+-- installed everything (primops.cc).  This evaluator's own wrapper+-- ("Nix.Builtins") names its values with these names, so compiling it+-- interns none.+derivationWrapperNames :: [Text]+derivationWrapperNames =+  [ "strict",+    "drvAttrs",+    "commonAttrs",+    "outputsList",+    "x",+    "outputToAttrListElement"+  ]
src/Nix/Eval/StringInterp.hs view
@@ -1,3 +1,5 @@+{-# LANGUAGE LambdaCase #-}+ -- | String coercion and indented-string whitespace stripping. -- -- Provides 'coerceToString' (string interpolation and @builtins.toString@),@@ -193,25 +195,27 @@ coerceToString True _ _ _ (VBool True) = pure ("1", emptyContext) coerceToString True _ _ _ (VBool False) = pure ("", emptyContext) coerceToString True forceFn applyFn coercePathFn (VList cl) = do-  parts <- mapM element (clistThunks cl)+  parts <- clistThunks cl >>= mapM element   pure (joinCoercedList [(bytes, isEmptyList) | (bytes, _, isEmptyList) <- parts], mconcat [ctx | (_, ctx, _) <- parts])   where     element thunk = do       val <- forceFn (Thunk thunk)       (bytes, ctx) <- coerceToString True forceFn applyFn coercePathFn val-      pure (bytes, ctx, emptyList val)-    emptyList (VList inner) = clistLen inner == 0-    emptyList _ = False+      isEmptyList <- emptyList val+      pure (bytes, ctx, isEmptyList)+    emptyList (VList inner) = (== 0) <$> clistLen inner+    emptyList _ = pure False -- Attribute sets: try __toString first, then outPath (both modes). -- The recursion carries the caller's path coercion, so a path-valued -- @outPath@ lands on the caller's path case, not a fixed one. coerceToString coerceMore forceFn applyFn coercePathFn (VAttrs attrs) =-  case attrSetLookup "__toString" attrs of+  attrSetLookup "__toString" attrs >>= \case     Just toStrThunk -> do       toStrFn <- forceFn toStrThunk       result <- applyFn toStrFn (VAttrs attrs)       coerceToString coerceMore forceFn applyFn coercePathFn result-    Nothing -> case attrSetLookup "outPath" attrs of+    Nothing ->+      attrSetLookup "outPath" attrs >>= \case         Just outPathThunk -> do           outPathVal <- forceFn outPathThunk           coerceToString coerceMore forceFn applyFn coercePathFn outPathVal@@ -233,12 +237,13 @@  -- | Upstream's refusal of a value no coercion takes (@coerceToString@, -- eval.cc at 2.24.9): its type, then the value as an error prints it.--- The message is built before it is thrown, so a thunk it shows reads as--- it is at the failure, not as it is once the force around the failure--- has been unwound.+-- The value is printed before the error is thrown, so a thunk it shows+-- reads as it is at the failure, not as it is once the force around the+-- failure has been unwound. uncoercible :: (MonadEval m) => NixValue -> m a-uncoercible val =-  throwEvalError $! "cannot coerce " <> typeName val <> " to a string: " <> printValue PrintForError val+uncoercible val = do+  shown <- printValue PrintForError val+  throwEvalError ("cannot coerce " <> typeName val <> " to a string: " <> shown)  -- | Format a float the way C++ Nix's coerceToString does - -- @std::to_string@, i.e. FIXED 6 decimal places with no trimming:@@ -250,9 +255,10 @@   | isInfinite n = if n > 0 then "inf" else "-inf"   | otherwise = T.pack (showFFloat (Just 6) n "") --- | Format a float for value display and JSON: 6 fixed decimal places,--- then strip trailing zeros and an unnecessary decimal point.  E.g.--- @1.0@ becomes @"1"@, @3.14@ becomes @"3.14"@.+-- | Format a float for a message, as @builtins.ceil@ and @builtins.floor@+-- report one out of integer range: 6 fixed decimal places, then strip+-- trailing zeros and an unnecessary decimal point.  E.g. @1.0@ becomes+-- @"1"@, @3.14@ becomes @"3.14"@. formatNixFloat :: Double -> Text formatNixFloat n   | isNaN n = "nan"
src/Nix/Eval/Symbol.hs view
@@ -1,28 +1,29 @@--- | Interned string symbols backed by a C hash table.+-- | Interned names backed by a C hash table. -- -- Attribute names are the most repeated data in Nix evaluation. -- This module interns them via a C-side hash table ('cbits/nn_symbol.c'), -- replacing O(n) string comparison with O(1) integer comparison. --+-- The table holds names alone: attribute names, formals, variables and+-- the names interned at startup, as upstream's symbol table does+-- (@SymbolTable@, symbol-table.hh at 2.24.9).  A name's place is the order+-- it was interned in, which decides the order of a set's attributes, so+-- a string value is never interned: its bytes live in "Nix.Eval.CStr".+--+-- In an evaluation session ('Nix.Eval.IO.withEvalSession'):+-- -- @--- symbolInit 8192 -- sym <- symbolIntern "name" -- symbolText sym   -- "name"--- symbolInit destroys and re-creates; call once per evaluation. -- @ module Nix.Eval.Symbol   ( -- * Symbol type     Symbol (..),--    -- * Lifecycle-    symbolInit,-    symbolDestroy,+    invalidSymbolId,      -- * Core operations     symbolIntern,-    symbolInternBytes,     symbolText,-    symbolBytes,     symbolLen,      -- * Diagnostics@@ -30,17 +31,15 @@   ) where -import Data.ByteString (ByteString)-import qualified Data.ByteString as BS-import qualified Data.ByteString.Unsafe as BSU+import Control.Exception (throwIO) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Foreign as TF import Data.Word (Word32) import Foreign.C.Types (CChar, CSize (..)) import Foreign.Ptr (Ptr, nullPtr)-import Nix.Eval.CStatus (cStatusFailure)-import System.IO.Unsafe (unsafePerformIO)+import Nix.Eval.CData (MonadCData, cdataIO, readImmutable)+import Nix.Eval.CStatus (CStatusError (..), arenaLive, cInvariantViolated, cStatusFailure)  -- | An interned symbol - a 'Word32' index into the global symbol table. -- Two symbols are equal iff their indices are equal (O(1) comparison).@@ -57,12 +56,6 @@ -- FFI imports (unsafe - these never call back to Haskell) -- --------------------------------------------------------------------------- -foreign import ccall unsafe "nn_symbol_init"-  c_nn_symbol_init :: Word32 -> IO ()--foreign import ccall unsafe "nn_symbol_destroy"-  c_nn_symbol_destroy :: IO ()- foreign import ccall unsafe "nn_symbol_intern"   c_nn_symbol_intern :: Ptr CChar -> CSize -> IO Word32 @@ -76,43 +69,15 @@   c_nn_symbol_count :: IO Word32  -- ------------------------------------------------------------------------------ Lifecycle--- ------------------------------------------------------------------------------- | Initialize the global symbol table, destroying a live one first.--- Call once before evaluation.  @capacity@ is a hint for the expected--- number of unique symbols.  Pass 0 to use the default (4096).-symbolInit :: Word32 -> IO ()-symbolInit = c_nn_symbol_init---- | Destroy the global symbol table, freeing all C-side memory.--- All t'Symbol' values become invalid after this call.-symbolDestroy :: IO ()-symbolDestroy = c_nn_symbol_destroy---- --------------------------------------------------------------------------- -- Core operations -- --------------------------------------------------------------------------- --- | Intern a 'Text' value, returning its t'Symbol'.--- If the string was already interned, returns the existing symbol.--- This is the canonical entry point for Text to C conversion; the table--- stores the UTF-8 bytes, so a 'Text' and its 'Data.Text.Encoding.encodeUtf8'--- image intern to the SAME symbol.-symbolIntern :: Text -> IO Symbol+-- | Intern a name, returning its t'Symbol'.+-- If the name was already interned, returns the existing symbol.  The+-- table stores the name's UTF-8 bytes.+symbolIntern :: (MonadCData m) => Text -> m Symbol symbolIntern txt =-  TF.withCStringLen txt $ \(ptr, len) ->-    checkedSymbol =<< c_nn_symbol_intern ptr (fromIntegral len)---- | Intern raw bytes, returning their t'Symbol'.  The C table is--- length-prefixed bytes with no encoding assumption, so arbitrary--- (even invalid-UTF-8) byte strings intern losslessly.  The canonical--- entry point for string VALUES, whose payload is a byte string.--- 'BSU.unsafeUseAsCStringLen' is safe here: @nn_symbol_intern@ copies--- the bytes into its own arena and never retains the pointer.-symbolInternBytes :: ByteString -> IO Symbol-symbolInternBytes bs =-  BSU.unsafeUseAsCStringLen bs $ \(ptr, len) ->+  cdataIO . TF.withCStringLen txt $ \(ptr, len) ->     checkedSymbol =<< c_nn_symbol_intern ptr (fromIntegral len)  -- | Reject the interner's failure sentinel before it can become a@@ -125,38 +90,51 @@   | sid == invalidSymbolId = cStatusFailure "nn_symbol_intern" "the symbol table cannot hold the string (allocation failure or its 4 GiB arena limit)"   | otherwise = pure (Symbol sid) --- | Retrieve the text of an interned symbol.--- Returns the original string.  The result is safe to use - it copies--- from the C arena into a fresh 'Text'.  Only valid for symbols interned--- from 'Text' (attr names, paths, output names); a symbol holding a raw--- byte-string payload must be read with 'symbolBytes' instead.+-- The reads below are pure ('readImmutable'): a symbol's bytes do not+-- change once interned, until arena teardown.  They can move, since the+-- table grows its byte storage with @realloc@ as later strings are+-- interned, and a read takes their address before it copies them, so no+-- intern may run between the two: the layer is used from one thread at a+-- time.++-- | The text of an interned symbol, copied out of the table.  The+-- invalid id reads as no name; an id the table does not hold raises+-- 'CInvariantViolated' in an evaluation session and+-- 'ArenaNotInitialized' outside one. symbolText :: Symbol -> Text symbolText (Symbol sid)   | sid == invalidSymbolId = T.empty-  | otherwise = unsafePerformIO $ do+  | otherwise = readImmutable . cdataIO $ do       ptr <- c_nn_symbol_text sid       if ptr == nullPtr-        then pure T.empty+        then unheldSymbol "nn_symbol_text" sid         else do           len <- c_nn_symbol_len sid           TF.peekCStringLen (ptr, fromIntegral len) --- | Retrieve the raw bytes of an interned symbol - the exact bytes that--- were interned, with no decoding.  The read side of 'symbolInternBytes'.-symbolBytes :: Symbol -> ByteString-symbolBytes (Symbol sid)-  | sid == invalidSymbolId = BS.empty-  | otherwise = unsafePerformIO $ do-      ptr <- c_nn_symbol_text sid-      if ptr == nullPtr-        then pure BS.empty-        else do+-- | Byte length of a symbol's string: 0 for the invalid id, and for an+-- id the table does not hold the failure 'symbolText' raises.+symbolLen :: Symbol -> Int+symbolLen (Symbol sid)+  | sid == invalidSymbolId = 0+  | otherwise = fromIntegral . readImmutable . cdataIO $ do       len <- c_nn_symbol_len sid-          BS.packCStringLen (ptr, fromIntegral len)+      -- The table answers 0 for an id it does not hold, which an empty+      -- name's length also is, so only a 0 asks the table's count.+      held <- if len /= 0 then pure True else (sid <=) <$> c_nn_symbol_count+      if held then pure len else unheldSymbol "nn_symbol_len" sid --- | Byte length of a symbol's string.-symbolLen :: Symbol -> Int-symbolLen (Symbol sid) = fromIntegral (unsafePerformIO (c_nn_symbol_len sid))+-- | Fail for a symbol id the table does not hold, which it reads as an+-- empty name.  Outside an evaluation session the table holds none, and+-- the failure is 'ArenaNotInitialized'; within one only a defect makes+-- such an id, and the failure is 'CInvariantViolated', where the name+-- would otherwise be wrong far from its cause.+unheldSymbol :: String -> Word32 -> IO a+unheldSymbol site sid = do+  live <- arenaLive+  if live+    then cInvariantViolated site ("no symbol " ++ show sid ++ " in the table")+    else throwIO (ArenaNotInitialized site)  -- --------------------------------------------------------------------------- -- Diagnostics
src/Nix/Eval/Types.hs view
@@ -1,1638 +1,1899 @@ {-# LANGUAGE GeneralizedNewtypeDeriving #-}-{-# LANGUAGE PatternSynonyms #-}---- | Shared types for the Nix evaluator.------ Extracted into its own module so that "Nix.Eval.Operator",--- "Nix.Eval.StringInterp", and "Nix.Builtins" can all reference--- 'NixValue', t'Thunk', and t'Env' without creating import cycles.-module Nix.Eval.Types-  ( -- * Values-    NixValue (..),-    BuiltinArg (..),-    CompiledRegex (..),-    Thunk (..),-    readThunkValue,-    thunkUnderEvaluation,--    -- * Attribute sets (C-backed sorted arrays)-    AttrSet (..),-    CAttrSet,-    AttrEntry (..),-    attrSetLookup,-    attrSetLookupEntry,-    attrSetKeys,-    attrSetToMap,-    attrSetFromMap,-    attrSetFromEntries,-    attrSetMember,-    attrSetNull,-    attrSetSize,-    attrSetElems,-    attrSetToAscList,-    attrSetMapWithKey,-    attrSetRemoveKeys,-    attrSetUnionWith,-    buildCAttrSetKeys,-    fillCAttrSetValues,--    -- * Lists (C-backed)-    CList (..),-    emptyCList,-    clistFromThunks,-    clistThunks,-    clistLen,--    -- * String context-    StringContextElement (..),-    StringContext (..),-    emptyContext,-    mkStr,-    mkStrBytes,-    bytesToTextLossy,-    marshalStringContext,-    unmarshalStringContext,--    -- * Environment-    Env (..),-    NnEnv,-    emptyEnv,-    envLookup,-    envLookupResolved,-    envFromSlots,-    pushWithScope,-    lookupWithScopes,-    withScopesForCapture,-    envWithScopesRaw,-    checkedCPtr,-    newCEnv,-    newMinimalEnv,--    -- * Eval-time formals (re-exported from EvalFormals)-    EvalFormals (..),-    EvalFormal (..),--    -- * Thunk operations-    mkThunk,-    mkSyntheticThunk,-    cheapThunk,-    cheapThunkBc,-    mkThunkBc,-    evaluated,-    thunkSameRef,-    thunkToCPtr,-    buildCSlots,-    allocCSlots,-    fillCSlots,--    -- * Lambda marshalling-    marshalLambda,-    unmarshalLambdaValue,--    -- * Display-    typeName,-    typeOfValue,--    -- * C thunk-state and value tags (mirror cbits/nn_thunk.h)-    pattern ThunkPending,-    pattern ThunkComputed,-    pattern ThunkBlackhole,-    pattern ValueInt,-    pattern ValueFloat,-    pattern ValueBool,-    pattern ValueNull,-    pattern ValueStr,-    pattern ValuePath,-    pattern ValueList,-    pattern ValueAttrs,-    pattern ValueCtxStr,-    pattern ValueLambda,--    -- * Evaluation monad-    MonadEval (..),-    PathExistence (..),-    EvalPolicy (..),-    unrestrictedPolicy,-    PureEval,-    runPureEval,-    storePathOrThrow,-  )-where--import Control.Monad (forM_)-import Control.Monad.Reader (ReaderT (..), lift)-import Data.Bits (shiftL, (.&.), (.|.))-import Data.ByteString (ByteString)-import qualified Data.ByteString as BS-import Data.Int (Int64)-import Data.Map.Strict (Map)-import qualified Data.Map.Strict as Map-import Data.Set (Set)-import qualified Data.Set as Set-import Data.Text (Text)-import qualified Data.Text as T-import qualified Data.Text.Encoding as TE-import Data.Text.Encoding.Error (lenientDecode)-import Data.Word (Word32, Word64, Word8)-import Foreign.Ptr (Ptr, castPtr, nullPtr, ptrToWordPtr)-import Foreign.StablePtr (castPtrToStablePtr, castStablePtrToPtr, deRefStablePtr, newStablePtr)-import Foreign.Storable (peekElemOff, pokeElemOff)-import GHC.Float (castWord64ToDouble)-import Nix.Derivation (Derivation)-import Nix.Eval.CAttrSet (CAttrSet, cattrsetFreeze, cattrsetGetKey, cattrsetGetPos, cattrsetGetValue, cattrsetIndex, cattrsetInsert, cattrsetKeys, cattrsetLookup, cattrsetNew, cattrsetRemoveKeys, cattrsetSetValue, cattrsetSize)-import Nix.Eval.CBytecode (cbcArg1, cbcArg2, cbcCountedPayload, cbcData, cbcOpcode, cbcShortArg, pattern OpList, pattern OpLitBool, pattern OpLitFloat, pattern OpLitInt, pattern OpLitNull, pattern OpLitPath, pattern OpLitUri, pattern OpResolvedVar, pattern OpStr)-import Nix.Eval.CCtxStr (CCtxStrPtr, cctxstrCtxCount, cctxstrElemHash, cctxstrElemName, cctxstrElemOutput, cctxstrElemTag, cctxstrNew, cctxstrSetAllOutputs, cctxstrSetDrvOutput, cctxstrSetPlain, cctxstrText)-import Nix.Eval.CEnv (NnEnv, cenvAllocSlots, cenvAllocWithScopes, cenvEmpty, cenvFromSlots, cenvLazyScope, cenvLookupResolved, cenvNew, cenvNewMinimal, cenvParent, cenvPushWith, cenvRootScope, cenvSlotCount, cenvWithCount, cenvWithScopes)-import Nix.Eval.CLambda (clambdaAllowExtra, clambdaBody, clambdaEntryDefault, clambdaEntryHasDefault, clambdaEntryName, clambdaEnv, clambdaFormalCount, clambdaFormalsType, clambdaNameSym, clambdaNew, clambdaSetEntry)-import Nix.Eval.CList (CList (..), clistFromThunks, clistLen, clistThunks, emptyCList)-import Nix.Eval.CStatus (checkedCPtr)-import Nix.Eval.CThunk (CThunkPtr, cthunkBool, cthunkGetAttrs, cthunkGetBcIdx, cthunkGetBool, cthunkGetCtxStr, cthunkGetFloat, cthunkGetInt, cthunkGetList, cthunkGetPath, cthunkGetStr, cthunkNewBc, cthunkNewComputed, cthunkNewComputedAttrs, cthunkNewComputedCtxStr, cthunkNewComputedFloat, cthunkNewComputedInt, cthunkNewComputedLambda, cthunkNewComputedList, cthunkNewComputedPath, cthunkNewComputedStr, cthunkNull, cthunkPayload, cthunkState, cthunkValueTag)-import Nix.Eval.CallDepth (CallDepth, defaultMaxCallDepth, enterCallFrame, topLevelCallDepth)-import Nix.Eval.CanonPath (canonPathValue)-import Nix.Eval.Compile (compileExpr, compileFormalsToEval)-import Nix.Eval.EvalFormals (EvalFormal (..), EvalFormals (..))-import Nix.Eval.Policy (EvalPolicy (..), unrestrictedPolicy)-import Nix.Eval.SourcePos (PosIdx, noPos)-import Nix.Eval.Symbol (Symbol (..), symbolBytes, symbolIntern, symbolInternBytes, symbolText)-import Nix.Expr.Types (CaptureInfo (..), Expr (..), NixAtom (..))-import Nix.Store.Path (BadStorePath, StorePath, badStorePathText)-import Nix.Store.Path.Internal (StorePath (StorePath))-import System.IO.Unsafe (unsafePerformIO)-import qualified Text.Regex.TDFA as RE---- ------------------------------------------------------------------------------ Compiled regex--- ------------------------------------------------------------------------------- | Compiled regex with Eq/Show based on the source pattern bytes.--- Carries the pre-compiled 'RE.Regex' alongside the original pattern--- so that partial application of @builtins.match@ / @builtins.split@--- avoids recompiling the same pattern on every invocation.  The pattern--- is the raw byte string the regex was compiled from: upstream regexes--- run over bytes, so byte-identical patterns are the sharing key.-data CompiledRegex = CompiledRegex !ByteString RE.Regex--instance Eq CompiledRegex where-  CompiledRegex a _ == CompiledRegex b _ = a == b--instance Show CompiledRegex where-  show (CompiledRegex pat _) = "CompiledRegex " <> show pat---- ------------------------------------------------------------------------------ String context--- ------------------------------------------------------------------------------- | A single element of string context, tracking where a string--- references store paths.-data StringContextElement-  = -- | Plain store path reference (inputSrcs).-    SCPlain !StorePath-  | -- | Derivation output reference (inputDrvs): .drv path + output name.-    SCDrvOutput !StorePath !Text-  | -- | All outputs of a derivation (for drvPath itself).-    SCAllOutputs !StorePath-  deriving (Eq, Ord, Show)---- | Context carried by Nix strings, tracking store path dependencies.-newtype StringContext = StringContext {unStringContext :: Set StringContextElement}-  deriving (Eq, Ord, Show, Semigroup, Monoid)---- | Empty string context (alias for 'mempty').-emptyContext :: StringContext-emptyContext = mempty---- | Smart constructor for context-free strings from 'Text'.--- Encodes to the UTF-8 bytes that ARE the string's value: a Nix string--- is a byte string, and every Text-producing site goes through here.-mkStr :: Text -> NixValue-mkStr t = VStr (TE.encodeUtf8 t) emptyContext---- | Smart constructor for context-free strings from raw bytes--- (@builtins.readFile@, substring slices - anything already byte-shaped).-mkStrBytes :: ByteString -> NixValue-mkStrBytes b = VStr b emptyContext---- | Decode string-value bytes for DISPLAY ONLY (trace output, error--- messages, value pretty-printing): invalid UTF-8 becomes U+FFFD.--- Never feed the result back into a value, a hash, or an attr name ---- identity-bearing boundaries decode strictly and error instead.-bytesToTextLossy :: ByteString -> Text-bytesToTextLossy = TE.decodeUtf8With lenientDecode---- ------------------------------------------------------------------------------ Thunks--- ------------------------------------------------------------------------------- | A thunk: a C arena-allocated memoization cell.------ Each thunk points to an @nn_thunk_t@ in the C arena.--- On first force, the cell transitions PENDING to BLACKHOLE to COMPUTED,--- which detects infinite recursion (BLACKHOLE) and drops the Expr/Env--- references - matching real Nix which mutates thunks in-place.------ The C thunk is allocated via 'unsafePerformIO' in 'mkThunk' (same--- pattern as the former IORef-based approach) so that knot-tying works--- unchanged.  Arena pointers remain valid until 'Nix.Eval.CThunk.cthunkDestroy'.-newtype Thunk = Thunk {unThunk :: CThunkPtr}--instance Show Thunk where-  show (Thunk ptr) =-    case unsafePerformIO (cthunkState ptr) of-      ThunkComputed -> case readThunkValue (Thunk ptr) of-        Just val -> "Thunk (" ++ show val ++ ")"-        Nothing -> "Thunk <computed?>"-      ThunkPending -> "Thunk <pending>"-      ThunkBlackhole -> "Thunk <blackhole>"-      _ -> "Thunk <unknown>"---- | Equality: pointer identity fast path, then value comparison for--- COMPUTED thunks.  Only used in tests on non-recursive structures.-instance Eq Thunk where-  (Thunk p1) == (Thunk p2)-    | p1 == p2 = True-    | otherwise = case (readThunkValue (Thunk p1), readThunkValue (Thunk p2)) of-        (Just v1, Just v2) -> v1 == v2-        _ -> False---- | Named constants for the C thunk-state byte and value-tag byte, mirroring--- the @NN_THUNK_*@ / @NN_VALUE_*@ macros in @cbits\/nn_thunk.h@.  Bidirectional--- pattern synonyms over literals, so a @case@ on a tag keeps the jump-table--- compilation a bare-literal @case@ gets, while the three thunk-dispatch sites--- ('readThunkValue', @PureEval@'s 'forceThunk', and @Nix.Eval.IO@'s--- @readComputed@) share one source of truth instead of triplicating literals.--- These MUST stay in lockstep with @cbits\/nn_thunk.h@.  The remaining value--- tag (PTR, a StablePtr payload) is the wildcard at each dispatch site.-pattern ThunkPending, ThunkComputed, ThunkBlackhole :: Word8-pattern ThunkPending = 0-pattern ThunkComputed = 1-pattern ThunkBlackhole = 2---- | Value-kind tags for the C value layout, mirroring @cbits\/nn_thunk.h@.--- The tag selects which payload a computed (VALUE) thunk carries.-pattern ValueInt, ValueFloat, ValueBool, ValueNull, ValueStr, ValuePath, ValueList, ValueAttrs, ValueCtxStr, ValueLambda :: Word8-pattern ValueInt = 0-pattern ValueFloat = 1-pattern ValueBool = 2-pattern ValueNull = 3-pattern ValueStr = 4-pattern ValuePath = 5-pattern ValueList = 6-pattern ValueAttrs = 7-pattern ValueCtxStr = 8-pattern ValueLambda = 9---- | Whether a thunk is being forced right now, so it holds no value yet:--- the cell's BLACKHOLE state.  Pure for the reason 'readThunkValue' is,--- and like it an answer about this moment: the state changes when the--- force finishes or is unwound.-thunkUnderEvaluation :: Thunk -> Bool-thunkUnderEvaluation (Thunk ptr) = unsafePerformIO (cthunkState ptr) == ThunkBlackhole---- | Read a COMPUTED thunk's value without forcing.--- Returns 'Nothing' for PENDING or BLACKHOLE thunks.--- Uses 'unsafePerformIO' - safe because C reads are idempotent.-readThunkValue :: Thunk -> Maybe NixValue-readThunkValue (Thunk ptr) =-  unsafePerformIO $ do-    state <- cthunkState ptr-    if state /= ThunkComputed-      then pure Nothing-      else do-        tag <- cthunkValueTag ptr-        fmap Just $ case tag of-          ValueInt -> VInt <$> cthunkGetInt ptr-          ValueFloat -> VFloat <$> cthunkGetFloat ptr-          ValueBool -> (\b -> VBool (b /= 0)) <$> cthunkGetBool ptr-          ValueNull -> pure VNull-          ValueStr -> (\sym -> VStr (symbolBytes (Symbol sym)) emptyContext) <$> cthunkGetStr ptr-          ValuePath -> VPath . symbolText . Symbol <$> cthunkGetPath ptr-          ValueList -> do-            listPtr <- cthunkGetList ptr-            pure (VList (CList (castPtr listPtr)))-          ValueAttrs -> VAttrs . AttrSet . castPtr <$> cthunkGetAttrs ptr-          ValueCtxStr -> do-            csptr <- cthunkGetCtxStr ptr-            uncurry VStr <$> unmarshalStringContext (castPtr csptr)-          ValueLambda -> do-            lamRaw <- cthunkPayload ptr-            unmarshalLambdaValue (castPtr lamRaw)-          _ {- PTR -} -> do-            payload <- cthunkPayload ptr-            deRefStablePtr (castPtrToStablePtr payload)---- | A Nix value - the result of evaluating an expression.-data NixValue-  = -- | 64-bit signed integer (matching Nix semantics).-    VInt !Int64-  | -- | Floating-point.-    VFloat !Double-  | -- | Boolean.-    VBool !Bool-  | -- | The null value.-    VNull-  | -- | String with dependency context.  The payload is a BYTE string,-    -- as upstream: @stringLength@/@substring@ index bytes, regexes match-    -- bytes, and @readFile@ carries raw file bytes (so invalid UTF-8 is-    -- representable).  Text enters via 'mkStr' (UTF-8 encode) and leaves-    -- through explicit decode at boundaries (attr names strictly, display-    -- lossily via 'bytesToTextLossy').-    VStr !ByteString !StringContext-  | -- | Path.-    VPath !Text-  | -- | List of thunks (lazy elements), backed by C array.-    VList !CList-  | -- | Attribute set: unified lazy/eager representation.-    VAttrs !AttrSet-  | -- | Lambda closure: captures environment, formals, body bytecode index.-    VLambda !Env !EvalFormals !Word32-  | -- | Built-in function, dispatched by name, with the arguments a-    -- partial application has taken so far, first to last.-    VBuiltin !Text ![BuiltinArg]-  | -- | Pre-compiled regex carried in a partially-applied builtin.-    -- Internal only - never exposed to Nix code directly.-    VCompiledRegex !CompiledRegex-  deriving (Eq, Show)---- | An argument a builtin has taken.  A primop that forces an argument--- before anything it does can be observed has it forced as it is--- applied.  One that forces it later, after another argument or only on--- some paths, has it held as the thunk it arrived as, and forces it where--- upstream does.  An argument that arrives already forced is held forced--- either way.-data BuiltinArg-  = ArgForced !NixValue-  | ArgDeferred !Thunk-  deriving (Eq, Show)---- ------------------------------------------------------------------------------ Attribute sets (C-backed sorted arrays)--- ------------------------------------------------------------------------------- | Attribute set backed by a C-allocated sorted key-value array.------ All keys are interned symbols; values are CThunkPtrs in a parallel--- array.  O(log n) binary search on contiguous memory for lookup.--- Replaces the former EagerAttrs\/LazyAttrs\/MappedAttrs\/CAttrs ADT--- with a single C-backed representation - all attr set data lives off--- the GHC heap, dramatically reducing GC pressure for large evaluations.-newtype AttrSet = AttrSet {unAttrSet :: CAttrSet}--instance Eq AttrSet where-  a == b = attrSetToMap a == attrSetToMap b--instance Show AttrSet where-  show (AttrSet cset) =-    let n = unsafePerformIO (cattrsetSize cset)-     in "<attrset " ++ show n ++ " entries>"---- | An attribute's value and the position it was defined at, as a set--- holds them.-data AttrEntry = AttrEntry-  { entryPos :: {-# UNPACK #-} !PosIdx,-    entryThunk :: {-# UNPACK #-} !Thunk-  }---- | Look up a single key via symbol interning + C binary search.--- Uses 'unsafePerformIO' - safe because symbolIntern and cattrsetLookup--- are idempotent (same key always yields same symbol and same result).-attrSetLookup :: Text -> AttrSet -> Maybe Thunk-attrSetLookup key (AttrSet cset) =-  unsafePerformIO $ do-    sym <- symbolIntern key-    mptr <- cattrsetLookup cset sym-    pure (fmap Thunk mptr)---- | 'attrSetLookup' with the attribute's position.  'unsafePerformIO' is--- safe for the reason it is in 'attrSetLookup': the same key reads the--- same entry every time.-attrSetLookupEntry :: Text -> AttrSet -> Maybe AttrEntry-attrSetLookupEntry key (AttrSet cset) =-  unsafePerformIO $ do-    sym <- symbolIntern key-    midx <- cattrsetIndex cset sym-    traverse (\idx -> AttrEntry <$> cattrsetGetPos cset idx <*> (Thunk <$> cattrsetGetValue cset idx)) midx---- | All keys, as symbol text from C, in the C array's order: by interned--- symbol, not by name.-attrSetKeys :: AttrSet -> [Text]-attrSetKeys (AttrSet cset) =-  map symbolText (unsafePerformIO (cattrsetKeys cset))---- | Check key membership without materializing thunks.-attrSetMember :: Text -> AttrSet -> Bool-attrSetMember key (AttrSet cset) =-  unsafePerformIO $ do-    sym <- symbolIntern key-    midx <- cattrsetIndex cset sym-    pure (case midx of Nothing -> False; Just _ -> True)---- | Check if the attribute set is empty.-attrSetNull :: AttrSet -> Bool-attrSetNull (AttrSet cset) =-  unsafePerformIO (cattrsetSize cset) == 0---- | Number of attributes.-attrSetSize :: AttrSet -> Int-attrSetSize (AttrSet cset) =-  fromIntegral (unsafePerformIO (cattrsetSize cset))---- | Full materialization: build a 'Map Text Thunk' from all entries.--- Iterates the C array and builds a Haskell Map.  Expensive on large--- sets - avoid on the hot path.-attrSetToMap :: AttrSet -> Map Text Thunk-attrSetToMap (AttrSet cset) =-  unsafePerformIO $ do-    n <- cattrsetSize cset-    if n == 0-      then pure Map.empty-      else do-        pairs <- mapM materializeEntry [0 .. n - 1]-        pure (Map.fromList pairs)-  where-    materializeEntry i = do-      sym <- cattrsetGetKey cset i-      ptr <- cattrsetGetValue cset i-      pure (symbolText sym, Thunk ptr)---- | All thunk values (materialized).-attrSetElems :: AttrSet -> [Thunk]-attrSetElems = Map.elems . attrSetToMap---- | Sorted key-value pairs (materialized).-attrSetToAscList :: AttrSet -> [(Text, Thunk)]-attrSetToAscList = Map.toAscList . attrSetToMap---- | Map a function over all key-value pairs, building a new CAttrSet.--- Materializes the source set, applies @f@ to each entry, and rebuilds.-attrSetMapWithKey :: (Text -> Thunk -> Thunk) -> AttrSet -> AttrSet-attrSetMapWithKey f attrs = attrSetFromMap (Map.mapWithKey f (attrSetToMap attrs))---- | Remove a list of keys, returning a new CAttrSet.--- Uses the C-side @nn_attrset_remove_keys@ for O(n) removal.-{-# NOINLINE attrSetRemoveKeys #-}-attrSetRemoveKeys :: [Text] -> AttrSet -> AttrSet-attrSetRemoveKeys keys (AttrSet cset) = unsafePerformIO $ do-  syms <- mapM symbolIntern keys-  newSet <- cattrsetRemoveKeys cset syms-  pure (AttrSet newSet)---- | Union two attribute sets with a combining function.--- Materializes both to Maps, applies the combining function, rebuilds.-attrSetUnionWith :: (Thunk -> Thunk -> Thunk) -> AttrSet -> AttrSet -> AttrSet-attrSetUnionWith f a b = attrSetFromMap (Map.unionWith f (attrSetToMap a) (attrSetToMap b))---- | Build a CAttrSet from a Haskell 'Map' of attributes defined nowhere in--- source, as those of a set a builtin makes from scratch are; a builtin--- that copies attributes keeps their positions with 'attrSetFromEntries'.--- Interns all keys as symbols, inserts key-value pairs, freezes (sort +--- dedup).------ Uses 'unsafePerformIO' with @NOINLINE@ - safe because C allocation--- is idempotent and the resulting CAttrSet is referentially transparent.-{-# NOINLINE attrSetFromMap #-}-attrSetFromMap :: Map Text Thunk -> AttrSet-attrSetFromMap m = m `seq` AttrSet (unsafePerformIO (newFrozenAttrSet (const noPos) id m))---- | 'attrSetFromMap' for attributes that keep the positions they were--- defined at, as an attribute set literal's and a copied attribute's do.-{-# NOINLINE attrSetFromEntries #-}-attrSetFromEntries :: Map Text AttrEntry -> AttrSet-attrSetFromEntries m = m `seq` AttrSet (unsafePerformIO (newFrozenAttrSet entryPos entryThunk m))---- | Insert every entry of a map into a new set, at the position and with--- the thunk the projections give it, and freeze it.-{-# INLINE newFrozenAttrSet #-}-newFrozenAttrSet :: (a -> PosIdx) -> (a -> Thunk) -> Map Text a -> IO CAttrSet-newFrozenAttrSet posOf thunkOf m = do-  cset <- cattrsetNew (Map.size m)-  forM_ (Map.toList m) $ \(key, entry) -> do-    sym <- symbolIntern key-    cattrsetInsert cset sym (posOf entry) (unThunk (thunkOf entry))-  cattrsetFreeze cset-  pure cset---- | Allocate a CAttrSet skeleton with keys only (NULL values), for an--- environment's name table.--- Used for two-phase construction in @rec {}@ and @let@ (knot-tying):--- keys are known before thunks, so the CAttrSet is built first, then--- values are filled via 'fillCAttrSetValues'.  The table is never a--- value, so its entries carry no position.-{-# NOINLINE buildCAttrSetKeys #-}-buildCAttrSetKeys :: [Text] -> CAttrSet-buildCAttrSetKeys keys = unsafePerformIO $ do-  cset <- cattrsetNew (length keys)-  forM_ keys $ \key -> do-    sym <- symbolIntern key-    cattrsetInsert cset sym noPos nullPtr-  cattrsetFreeze cset-  pure cset---- | Fill values into a pre-allocated CAttrSet (two-phase construction).--- Looks up each key's index and writes the CThunkPtr at that position.--- Keys not found in the CAttrSet are silently ignored (should not happen--- in correct knot-tying code).-{-# NOINLINE fillCAttrSetValues #-}-fillCAttrSetValues :: CAttrSet -> Map Text Thunk -> ()-fillCAttrSetValues cset thunkMap = unsafePerformIO $-  forM_ (Map.toList thunkMap) $ \(key, Thunk ptr) -> do-    sym <- symbolIntern key-    midx <- cattrsetIndex cset sym-    case midx of-      Just idx -> cattrsetSetValue cset idx ptr-      Nothing -> pure ()---- | Evaluation environment - C-backed scope chain.------ Arena-allocated @nn_env_t@ struct (48 bytes, zero GC overhead).--- All env data (slots, lazy scope, parent, with-scopes) lives in C.--- Haskell holds only the pointer.  Variable lookup has two paths:------ * 'envLookupResolved': single C call for 'EResolvedVar'--- * 'envLookup': name-based walk for 'EVar' (lazy scope + with-scopes)-newtype Env = Env (Ptr NnEnv)---- | Pointer equality: two envs are equal iff they are the same C struct.-instance Eq Env where-  Env p1 == Env p2 = p1 == p2---- | Compact show via C accessors.-instance Show Env where-  show (Env envPtr) =-    let sc = unsafePerformIO (cenvSlotCount envPtr)-        ls = unsafePerformIO (cenvLazyScope envPtr)-        par = unsafePerformIO (cenvParent envPtr)-        wc = unsafePerformIO (cenvWithCount envPtr)-     in "Env{"-          ++ show sc-          ++ " slots"-          ++ (if ls /= nullPtr then ", lazyScope" else "")-          ++ (if par /= nullPtr then ", parent" else "")-          ++ ", "-          ++ show wc-          ++ " withs}"---- | Empty environment (no variables in scope).--- Points to a static global C struct - valid until 'Nix.Eval.Arena.arenaDestroy'.-{-# NOINLINE emptyEnv #-}-emptyEnv :: Env-emptyEnv = Env (unsafePerformIO cenvEmpty)---- | General C-backed env constructor.--- Takes Haskell-level types; converts Maybe to nullPtr internally.-{-# NOINLINE newCEnv #-}-newCEnv :: Ptr CThunkPtr -> Int -> Maybe AttrSet -> Maybe Env -> Ptr (Ptr ()) -> Word32 -> Env-newCEnv slots slotCount lazyScope parent withs withCount =-  Env-    ( unsafePerformIO-        ( checkedCPtr "nn_env_new"-            =<< cenvNew-              slots-              (fromIntegral slotCount)-              (case lazyScope of Nothing -> nullPtr; Just (AttrSet cset) -> castPtr cset)-              (case parent of Nothing -> nullPtr; Just (Env p) -> p)-              withs-              withCount-        )-    )---- | Minimal env: slots only, no parent, no with-scopes, no lazy scope.-{-# NOINLINE newMinimalEnv #-}-newMinimalEnv :: Ptr CThunkPtr -> Int -> Env-newMinimalEnv slots n =-  Env (unsafePerformIO (checkedCPtr "nn_env_new_minimal" =<< cenvNewMinimal slots (fromIntegral n)))---- | Look up a resolved variable by level and index.  Single C call:--- O(level) parent hops in C, then O(1) array read.-envLookupResolved :: Int -> Int -> Env -> Thunk-envLookupResolved level idx (Env envPtr) =-  Thunk (unsafePerformIO (cenvLookupResolved envPtr level idx))---- | Name-based variable lookup: walk the parent chain checking--- lazy scopes; fall back to with-scopes (from the starting env).------ Positional slots are NOT searched here - used only for--- 'EVar' lookups (let\/rec bindings, builtins, with-scopes).-envLookup :: Text -> Env -> Maybe Thunk-envLookup name (Env envPtr) = lexicalLookup envPtr-  where-    -- With-scopes from the STARTING env (C array)-    startWiths = unsafePerformIO (cenvWithScopes envPtr)-    startWithCount = unsafePerformIO (cenvWithCount envPtr)-    lexicalLookup ep =-      let ls = unsafePerformIO (cenvLazyScope ep)-          scopeResult =-            if ls /= nullPtr-              then attrSetLookup name (AttrSet (castPtr ls))-              else Nothing-       in case scopeResult of-            Just val -> Just val-            Nothing ->-              let par = unsafePerformIO (cenvParent ep)-               in if par /= nullPtr-                    then lexicalLookup par-                    else lookupWithScopesC name startWiths startWithCount---- | Walk with-scopes (C array) innermost to outermost.--- Skips tagged lazy entries (bit 0 set) - those are thunk pointers--- that can only be resolved by @evalWithVarScopes@ which has monadic--- 'Nix.Eval.force'.  Defensive: an 'EVar' under a with is either a lexical--- (barrier) binding or a static global, both found on the parent chain--- before this fallback fires ('EVar' also blocks closure trimming, so--- the chain is always intact) - but keep it for safety.-lookupWithScopesC :: Text -> Ptr (Ptr ()) -> Word32 -> Maybe Thunk-lookupWithScopesC _ _ 0 = Nothing-lookupWithScopesC name withArr count = unsafePerformIO $ go 0-  where-    go i-      | i >= fromIntegral count = pure Nothing-      | otherwise = do-          scopePtr <- peekElemOff withArr i-          if ptrToWordPtr scopePtr .&. 1 /= 0-            then go (i + 1) -- skip tagged lazy with-scope-            else case attrSetLookup name (AttrSet (castPtr scopePtr)) of-              Just val -> pure (Just val)-              Nothing -> go (i + 1)---- | Walk with-scopes as a Haskell list (backward-compatible signature).-lookupWithScopes :: Text -> [AttrSet] -> Maybe Thunk-lookupWithScopes _ [] = Nothing-lookupWithScopes name (scope : rest) =-  case attrSetLookup name scope of-    Just val -> Just val-    Nothing -> lookupWithScopes name rest---- | Create a child env with positional slots (for lambda formals).--- Inherits with-scopes from the parent.  Arena-allocated.-{-# NOINLINE envFromSlots #-}-envFromSlots :: Ptr CThunkPtr -> Int -> Env -> Env-envFromSlots slotsPtr slotCount (Env parentPtr) =-  Env (unsafePerformIO (checkedCPtr "nn_env_from_slots" =<< cenvFromSlots slotsPtr (fromIntegral slotCount) parentPtr))---- | Push a with-scope onto the scope chain (innermost position).--- Allocates a new C env struct with extended with-scopes array.-{-# NOINLINE pushWithScope #-}-pushWithScope :: AttrSet -> Env -> Env-pushWithScope (AttrSet cset) (Env envPtr) =-  Env (unsafePerformIO (checkedCPtr "nn_env_push_with" =<< cenvPushWith envPtr (castPtr cset)))---- | Read with-scopes array pointer and count from a C env.-{-# NOINLINE envWithScopesRaw #-}-envWithScopesRaw :: Env -> (Ptr (Ptr ()), Word32)-envWithScopesRaw (Env envPtr) = unsafePerformIO $ do-  withs <- cenvWithScopes envPtr-  count <- cenvWithCount envPtr-  pure (withs, count)---- | Build with-scopes for a trimmed env that needs with-scope access--- ('CapturesWithScopes').  Appends the root scope (builtins) as the--- outermost entry so 'EWithVar' can fall back to builtins without--- retaining the parent chain.  Returns C array + count.-{-# NOINLINE withScopesForCapture #-}-withScopesForCapture :: Env -> (Ptr (Ptr ()), Word32)-withScopesForCapture (Env envPtr) = unsafePerformIO $ do-  rootPtr <- cenvRootScope envPtr-  existingWiths <- cenvWithScopes envPtr-  existingCount <- cenvWithCount envPtr-  if rootPtr == nullPtr-    then pure (existingWiths, existingCount)-    else do-      -- existingCount sits far below 2^32 (the C side caps the array-      -- allocation at UINT32_MAX bytes), so the increment cannot wrap.-      let newCount = existingCount + 1-      arr <- checkedCPtr "nn_env_alloc_with_scopes" =<< cenvAllocWithScopes newCount-      forM_ [0 .. fromIntegral existingCount - 1] $ \i -> do-        val <- peekElemOff existingWiths i-        pokeElemOff arr i val-      -- The root scope goes last: it is the outermost.-      pokeElemOff arr (fromIntegral existingCount) rootPtr-      pure (arr, newCount)---- | Create an unevaluated thunk with a fresh C arena-allocated cell.------ Compiles the Expr to bytecode and stores (bc_idx, env_ptr) in the--- C thunk - no StablePtr, zero GHC heap pressure for pending thunks.--- The cell is allocated via 'unsafePerformIO' - safe because C--- allocation is a pure side effect, and the @NOINLINE@ + @seq@--- pattern prevents GHC from floating the allocation to a shared--- top-level CAF.-mkThunk :: Env -> Expr -> Thunk-mkThunk env thunkExpr =-  Thunk (newBcThunkPtr thunkExpr env)---- | A pending thunk running code that many thunks share, each in an env--- of its own, such as 'Nix.Eval.CBytecode.reservedApply1' for--- 'Nix.Eval.deferApply'.  It takes the index rather than an 'Expr'--- because compiling per thunk adds a copy of the same code to a store--- that only grows until 'Nix.Eval.Arena.arenaDestroy'.  Uses the env--- pointer for cell uniqueness instead of the index, which every such--- thunk shares: keyed on a shared value, GHC's full-laziness transform--- could float the allocation to a CAF and give every thunk one cell.------ Must only be called with freshly-constructed envs (not knot-tied--- recursive envs), since it forces the env pointer to WHNF.-mkSyntheticThunk :: Env -> Word32 -> Thunk-mkSyntheticThunk env@(Env envPtr) bcIdx =-  Thunk (newSyntheticBcThunkPtr envPtr bcIdx env)---- | Like 'mkThunk' but avoids C arena allocation for trivial expressions.--- Resolved variables reuse the existing thunk from the env (no wrapper).--- Literals use inline C scalars (no StablePtr).--- Lambdas compile formals+body to bytecode and produce VLambda directly.--- Everything else falls back to 'mkThunk'.-cheapThunk :: Env -> Expr -> Thunk-cheapThunk env (EResolvedVar level idx) = envLookupResolved level idx env-cheapThunk _ (ELit (NixInt n)) = Thunk (newComputedIntPtr n)-cheapThunk _ (ELit (NixFloat n)) = Thunk (newComputedFloatPtr n)-cheapThunk _ (ELit (NixBool b)) = Thunk (cthunkBool b)-cheapThunk _ (ELit NixNull) = Thunk cthunkNull-cheapThunk env (ELambda formals body NoCaptureInfo) =-  let bodyBcIdx = unsafePerformIO (compileExpr body)-      evalFormals = unsafePerformIO (compileFormalsToEval formals)-   in evaluated (VLambda env evalFormals bodyBcIdx)-cheapThunk env (ELambda formals body (Captures captureList)) =-  let (slotsPtr, slotCount) = buildCSlots [envLookupResolved lvl idx env | (lvl, idx) <- captureList]-      trimmedEnv = newMinimalEnv slotsPtr slotCount-      bodyBcIdx = unsafePerformIO (compileExpr body)-      evalFormals = unsafePerformIO (compileFormalsToEval formals)-   in evaluated (VLambda trimmedEnv evalFormals bodyBcIdx)-cheapThunk env (ELambda formals body (CapturesWithScopes captureList)) =-  let (slotsPtr, slotCount) = buildCSlots [envLookupResolved lvl idx env | (lvl, idx) <- captureList]-      (withArr, withCount) = withScopesForCapture env-      trimmedEnv = newCEnv slotsPtr slotCount Nothing Nothing withArr withCount-      bodyBcIdx = unsafePerformIO (compileExpr body)-      evalFormals = unsafePerformIO (compileFormalsToEval formals)-   in evaluated (VLambda trimmedEnv evalFormals bodyBcIdx)-cheapThunk env expr = mkThunk env expr---- | Create a pending thunk from a bytecode index (no compilation needed).--- Used inside 'Nix.Eval.evalBytecode' where the bc_idx is already known.--- The Env is captured LAZILY (for knot-tying in rec attrs / let / matchFormalSet).-mkThunkBc :: Env -> Word32 -> Thunk-mkThunkBc env bcIdx =-  Thunk (newBcThunkPtrLazy bcIdx env)---- | Like 'cheapThunk' but for bytecode indices (used inside evalBytecode).--- Short-circuits for resolved vars and literals without creating a--- pending thunk.  Everything else falls back to 'mkThunkBc'.-cheapThunkBc :: Env -> Word32 -> Thunk-cheapThunkBc env bcIdx =-  case unsafePerformIO (cbcOpcode bcIdx) of-    OpResolvedVar ->-      let level = fromIntegral (unsafePerformIO (cbcArg1 bcIdx))-          idx = fromIntegral (unsafePerformIO (cbcArg2 bcIdx))-       in envLookupResolved level idx env-    OpLitInt ->-      let lo = unsafePerformIO (cbcArg1 bcIdx)-          hi = unsafePerformIO (cbcArg2 bcIdx)-          w64 = fromIntegral lo .|. (fromIntegral hi `shiftL` 32) :: Word64-       in Thunk (newComputedIntPtr (fromIntegral w64 :: Int64))-    OpLitFloat ->-      let lo = unsafePerformIO (cbcArg1 bcIdx)-          hi = unsafePerformIO (cbcArg2 bcIdx)-          w64 = fromIntegral lo .|. (fromIntegral hi `shiftL` 32) :: Word64-       in Thunk (newComputedFloatPtr (castWord64ToDouble w64))-    OpLitBool ->-      let flag = unsafePerformIO (cbcShortArg bcIdx)-       in Thunk (cthunkBool (flag /= 0))-    OpLitNull -> Thunk cthunkNull-    OpLitUri ->-      let sym = unsafePerformIO (cbcArg1 bcIdx)-       in Thunk (newComputedStrPtr (symbolBytes (Symbol sym)))-    OpStr-      | Just bytes <- literalStrBytes bcIdx -> Thunk (newComputedStrPtr bytes)-    OpLitPath-      | Just resolved <- constantPathValue bcIdx -> Thunk (newComputedPathPtr resolved)-    OpList-      | emptyBcList bcIdx -> Thunk (newComputedThunkPtr (VList emptyCList))-    _ -> mkThunkBc env bcIdx---- | The value of a path literal, when producing it is not work.------ Parsing resolves every relative path literal against the file's directory--- ('Nix.Expr.Resolve.resolveRelativePaths'), so what reaches here is already--- absolute and only wants the lexical canonicalisation every path value--- carries.  The exception is a home-relative literal, which parsing leaves--- alone: expanding it reads @HOME@, and that is an effect this cannot run.-constantPathValue :: Word32 -> Maybe Text-constantPathValue bcIdx-  | T.isPrefixOf "~/" text = Nothing-  | otherwise = Just (canonPathValue text)-  where-    text = symbolText (Symbol (unsafePerformIO (cbcArg1 bcIdx)))---- | Whether a list expression has no elements, and so is the same empty list--- however many times it is written.  Upstream hands back one shared--- @vEmptyList@ for this rather than a thunk.-emptyBcList :: Word32 -> Bool-emptyBcList bcIdx =-  let (count, _) = unsafePerformIO (cbcCountedPayload bcIdx =<< cbcArg1 bcIdx)-   in count == 0---- | @NN_STRPART_LIT@ from @cbits/nn_bytecode.h@: a string part that is--- literal text rather than an interpolation.-strPartLiteral :: Word32-strPartLiteral = 0---- | The bytes of a string expression every part of which is literal, or--- 'Nothing' when one is an interpolation and producing the value is work.------ Upstream draws this line in the parser: a fully literal string folds into--- an @ExprString@ carrying a ready-made value, and only a string with--- interpolation survives as @ExprConcatStrings@.  The split is made here--- instead by reading the parts back, because this compiler emits one opcode--- for both shapes.------ Deliberately not extended to @OpIndStr@, whose common indentation is--- stripped during evaluation rather than in the parser, so its value is not--- yet a constant at this point.  Upstream can treat one as a constant--- because its parser has already done that stripping.-literalStrBytes :: Word32 -> Maybe ByteString-literalStrBytes bcIdx =-  let (count, dataOff) = unsafePerformIO (cbcCountedPayload bcIdx =<< cbcArg1 bcIdx)-   in BS.concat <$> partBytes count dataOff-  where-    partBytes 0 _ = Just []-    partBytes n off-      | unsafePerformIO (cbcData off) /= strPartLiteral = Nothing-      | otherwise =-          let sym = unsafePerformIO (cbcData (off + 1))-           in (symbolBytes (Symbol sym) :) <$> partBytes (n - 1 :: Int) (off + 2)---- | Allocate a fresh C arena thunk cell with bytecode.------ @NOINLINE@ prevents inlining so GHC can't see inside or CSE calls.--- @seq@ on the expr creates a data dependency that prevents float-out--- to a top-level CAF - without this, GHC would hoist the--- @unsafePerformIO@ and share ONE cell across ALL thunks.------ Compiles the Expr to bytecode and stores (bc_idx, StablePtr Env)--- in the C thunk.  The Expr tree is eliminated from the GHC heap ---- only the StablePtr Env (~16 bytes) remains for knot-tying laziness.-{-# NOINLINE newBcThunkPtr #-}-newBcThunkPtr :: Expr -> Env -> CThunkPtr-newBcThunkPtr expr env =-  unsafePerformIO $ expr `seq` do-    bcIdx <- compileExpr expr-    sp <- newStablePtr env-    cthunkNewBc bcIdx (castStablePtrToPtr sp)---- | Like 'newBcThunkPtrLazy' but forces the env's C pointer first, for--- 'mkSyntheticThunk'.-{-# NOINLINE newSyntheticBcThunkPtr #-}-newSyntheticBcThunkPtr :: Ptr NnEnv -> Word32 -> Env -> CThunkPtr-newSyntheticBcThunkPtr envKey bcIdx env =-  unsafePerformIO $ envKey `seq` do-    sp <- newStablePtr env-    cthunkNewBc bcIdx (castStablePtrToPtr sp)---- | Allocate a fresh C arena thunk cell from a known bytecode index.--- No compilation needed - the bc_idx is already available.------ Uses StablePtr for the Env so it stays lazy - essential for--- knot-tying in recursive attrs, let bindings, and matchFormalSet.--- The StablePtr points to an Env (newtype around Ptr NnEnv) - ~16--- bytes on the GHC heap, negligible compared to the Expr trees we--- eliminated.-{-# NOINLINE newBcThunkPtrLazy #-}-newBcThunkPtrLazy :: Word32 -> Env -> CThunkPtr-newBcThunkPtrLazy bcIdx env =-  unsafePerformIO $ bcIdx `seq` do-    sp <- newStablePtr env-    cthunkNewBc bcIdx (castStablePtrToPtr sp)---- | Wrap an already-computed value as a thunk.--- Ints and floats use inline C thunks (no StablePtr); booleans and null--- are the shared static cells, as upstream hands out one @vTrue@,--- @vFalse@ and @vNull@ (eval.cc at 2.24.9, @EvalState::getBool@).--- Attrs, paths, and context-free strings use C-native tags (no StablePtr).--- Other complex values fall back to StablePtr-backed C thunks.-evaluated :: NixValue -> Thunk-evaluated (VInt n) = Thunk (newComputedIntPtr n)-evaluated (VFloat d) = Thunk (newComputedFloatPtr d)-evaluated (VBool b) = Thunk (cthunkBool b)-evaluated VNull = Thunk cthunkNull-evaluated (VAttrs (AttrSet cset)) = Thunk (newComputedAttrsPtr cset)-evaluated (VPath p) = Thunk (newComputedPathPtr p)-evaluated (VStr t ctx)-  | ctx == emptyContext = Thunk (newComputedStrPtr t)-  | otherwise = Thunk (newComputedCtxStrPtr t ctx)-evaluated (VList cl) = Thunk (newComputedListPtrC cl)-evaluated (VLambda env formals bodyBcIdx) = Thunk (newComputedLambdaPtr env formals bodyBcIdx)-evaluated val = Thunk (newComputedThunkPtr val)---- | Check if two thunks share the same memoization cell (C pointer--- equality).  When true, both thunks will always produce the same value,--- so deep equality can short-circuit to 'True' without forcing.-thunkSameRef :: Thunk -> Thunk -> Bool-thunkSameRef (Thunk p1) (Thunk p2) = p1 == p2---- | Extract the C pointer from a thunk (zero-cost, newtype unwrap).-thunkToCPtr :: Thunk -> CThunkPtr-thunkToCPtr (Thunk ptr) = ptr---- | Wrap an already-computed 'NixValue' in a C thunk (StablePtr path).--- Arena-allocated (O(1)).  Used for complex values (string, list, attrs, etc.).-{-# NOINLINE newComputedThunkPtr #-}-newComputedThunkPtr :: NixValue -> CThunkPtr-newComputedThunkPtr val =-  unsafePerformIO $ val `seq` do-    sp <- newStablePtr val-    cthunkNewComputed (castStablePtrToPtr sp)---- | Wrap an int64 in a pre-computed C thunk (inline, no StablePtr).-{-# NOINLINE newComputedIntPtr #-}-newComputedIntPtr :: Int64 -> CThunkPtr-newComputedIntPtr n = unsafePerformIO (cthunkNewComputedInt n)---- | Wrap a double in a pre-computed C thunk (inline, no StablePtr).-{-# NOINLINE newComputedFloatPtr #-}-newComputedFloatPtr :: Double -> CThunkPtr-newComputedFloatPtr d = unsafePerformIO (cthunkNewComputedFloat d)---- | Wrap a context-free string in a pre-computed C thunk (interned symbol, no StablePtr).-{-# NOINLINE newComputedStrPtr #-}-newComputedStrPtr :: ByteString -> CThunkPtr-newComputedStrPtr t =-  unsafePerformIO $ t `seq` do-    Symbol sym <- symbolInternBytes t-    cthunkNewComputedStr sym---- | Wrap a path in a pre-computed C thunk (interned symbol, no StablePtr).-{-# NOINLINE newComputedPathPtr #-}-newComputedPathPtr :: Text -> CThunkPtr-newComputedPathPtr p =-  unsafePerformIO $ p `seq` do-    Symbol sym <- symbolIntern p-    cthunkNewComputedPath sym---- | Wrap a CList in a pre-computed C thunk (no conversion needed).-{-# NOINLINE newComputedListPtrC #-}-newComputedListPtrC :: CList -> CThunkPtr-newComputedListPtrC (CList clistPtr) =-  unsafePerformIO-    $ clistPtr-    `seq` cthunkNewComputedList (castPtr clistPtr)---- | Wrap a string with context in a pre-computed C thunk (no StablePtr).--- Interns the payload bytes and all StorePath fields as symbols, builds nn_ctxstr_t.-{-# NOINLINE newComputedCtxStrPtr #-}-newComputedCtxStrPtr :: ByteString -> StringContext -> CThunkPtr-newComputedCtxStrPtr t ctx =-  unsafePerformIO $-    t `seq`-      ctx `seq` do-        ptr <- marshalStringContext t ctx-        cthunkNewComputedCtxStr (castPtr ptr)---- | Wrap a lambda closure in a pre-computed C thunk (no StablePtr).--- Marshals EvalFormals to nn_lambda_t, stores as tag 9.-{-# NOINLINE newComputedLambdaPtr #-}-newComputedLambdaPtr :: Env -> EvalFormals -> Word32 -> CThunkPtr-newComputedLambdaPtr (Env envPtr) formals bodyBcIdx =-  unsafePerformIO $-    formals `seq` do-      clam <- marshalLambda envPtr formals bodyBcIdx-      cthunkNewComputedLambda clam---- | Marshal Env + EvalFormals + body bc_idx to a C nn_lambda_t.-marshalLambda :: Ptr NnEnv -> EvalFormals -> Word32 -> IO (Ptr ())-marshalLambda envPtr formals bodyBcIdx = case formals of-  EFName name -> do-    Symbol nameSym <- symbolIntern name-    lam <- checkedCPtr "nn_lambda_new" =<< clambdaNew envPtr bodyBcIdx 0 nameSym 0 0-    pure (castPtr lam)-  EFSet entries allowExtra -> do-    let count = fromIntegral (length entries) :: Word32-        extraFlag = if allowExtra then 1 else 0 :: Word8-    lam <- checkedCPtr "nn_lambda_new" =<< clambdaNew envPtr bodyBcIdx 1 0 extraFlag count-    fillEntries lam 0 entries-    pure (castPtr lam)-  EFNamedSet name entries allowExtra -> do-    Symbol nameSym <- symbolIntern name-    let count = fromIntegral (length entries) :: Word32-        extraFlag = if allowExtra then 1 else 0 :: Word8-    lam <- checkedCPtr "nn_lambda_new" =<< clambdaNew envPtr bodyBcIdx 2 nameSym extraFlag count-    fillEntries lam 0 entries-    pure (castPtr lam)-  where-    fillEntries _ _ [] = pure ()-    fillEntries lam !idx (EvalFormal name defBcIdx : rest) = do-      Symbol nameSym <- symbolIntern name-      let (hasDef, defIdx) = case defBcIdx of-            Nothing -> (0, 0)-            Just di -> (1, di)-      clambdaSetEntry lam idx nameSym hasDef defIdx-      fillEntries lam (idx + 1) rest---- | Read a C nn_lambda_t back into VLambda.--- Reconstructs Env (newtype wrap), EvalFormals (from symbol IDs), body bc_idx.-unmarshalLambdaValue :: Ptr () -> IO NixValue-unmarshalLambdaValue rawPtr = do-  let lamPtr = castPtr rawPtr-  envPtr <- clambdaEnv lamPtr-  bodyIdx <- clambdaBody lamPtr-  formalsType <- clambdaFormalsType lamPtr-  formals <- case formalsType of-    0 {- Name -} -> do-      nameSym <- clambdaNameSym lamPtr-      pure (EFName (symbolText (Symbol nameSym)))-    1 {- Set -} -> do-      count <- clambdaFormalCount lamPtr-      extra <- clambdaAllowExtra lamPtr-      entries <- readLambdaEntries lamPtr count-      pure (EFSet entries (extra /= 0))-    _ {- NamedSet -} -> do-      nameSym <- clambdaNameSym lamPtr-      count <- clambdaFormalCount lamPtr-      extra <- clambdaAllowExtra lamPtr-      entries <- readLambdaEntries lamPtr count-      pure (EFNamedSet (symbolText (Symbol nameSym)) entries (extra /= 0))-  pure (VLambda (Env envPtr) formals bodyIdx)-  where-    -- Zero-formal set patterns ({}:, { ... }:) store count 0 and a NULL-    -- entries array; count - 1 would underflow Word32.-    readLambdaEntries lamPtr count-      | count == 0 = pure []-      | otherwise = mapM (readOneEntry lamPtr) [0 .. count - 1]-    readOneEntry lamPtr idx = do-      nameSym <- clambdaEntryName lamPtr idx-      hasDef <- clambdaEntryHasDefault lamPtr idx-      defIdx <- clambdaEntryDefault lamPtr idx-      let defMaybe = if hasDef /= 0 then Just defIdx else Nothing-      pure (EvalFormal (symbolText (Symbol nameSym)) defMaybe)---- | Marshal payload bytes + StringContext to a C nn_ctxstr_t.  The--- payload interns byte-level ('symbolInternBytes'); the StorePath and--- output-name fields are Text and intern as UTF-8.-marshalStringContext :: ByteString -> StringContext -> IO CCtxStrPtr-marshalStringContext textVal (StringContext ctxSet) = do-  Symbol textSym <- symbolInternBytes textVal-  let elems = Set.toAscList ctxSet-      count = fromIntegral (length elems) :: Word32-  ptr <- checkedCPtr "nn_ctxstr_new" =<< cctxstrNew textSym count-  fillElems ptr 0 elems-  pure ptr-  where-    fillElems _ _ [] = pure ()-    fillElems ptr !idx (e : es) = do-      marshalElem ptr idx e-      fillElems ptr (idx + 1) es-    marshalElem eptr eidx (SCPlain (StorePath h n)) = do-      Symbol hashSym <- symbolIntern h-      Symbol nameSym <- symbolIntern n-      cctxstrSetPlain eptr eidx hashSym nameSym-    marshalElem eptr eidx (SCDrvOutput (StorePath h n) out) = do-      Symbol hashSym <- symbolIntern h-      Symbol nameSym <- symbolIntern n-      Symbol outSym <- symbolIntern out-      cctxstrSetDrvOutput eptr eidx hashSym nameSym outSym-    marshalElem eptr eidx (SCAllOutputs (StorePath h n)) = do-      Symbol hashSym <- symbolIntern h-      Symbol nameSym <- symbolIntern n-      cctxstrSetAllOutputs eptr eidx hashSym nameSym---- | Unmarshal a C nn_ctxstr_t back to (payload bytes, StringContext).-unmarshalStringContext :: CCtxStrPtr -> IO (ByteString, StringContext)-unmarshalStringContext ptr = do-  textSym <- cctxstrText ptr-  count <- cctxstrCtxCount ptr-  let textVal = symbolBytes (Symbol textSym)-  -- count - 1 underflows Word32 at 0 (defensive: marshal sites store-  -- only non-empty contexts today).-  elems <--    if count == 0-      then pure []-      else mapM (readElem ptr) [0 .. count - 1]-  pure (textVal, StringContext (Set.fromList elems))-  where-    readElem cptr idx = do-      tag <- cctxstrElemTag cptr idx-      hashSym <- cctxstrElemHash cptr idx-      nameSym <- cctxstrElemName cptr idx-      -- Raw construction (Nix.Store.Path.Internal): provenance-safe --      -- these symbols were interned from a validated StorePath's own-      -- fields by marshalStringContext, so this is a round-trip, not a-      -- parse boundary.-      let sp = StorePath (symbolText (Symbol hashSym)) (symbolText (Symbol nameSym))-      case tag of-        0 -> pure (SCPlain sp)-        1 -> do-          outSym <- cctxstrElemOutput cptr idx-          pure (SCDrvOutput sp (symbolText (Symbol outSym)))-        _ -> pure (SCAllOutputs sp)---- | Wrap a CAttrSet in a pre-computed C thunk (pointer, no StablePtr).-{-# NOINLINE newComputedAttrsPtr #-}-newComputedAttrsPtr :: CAttrSet -> CThunkPtr-newComputedAttrsPtr cset =-  unsafePerformIO-    $ cset-    `seq` cthunkNewComputedAttrs (castPtr cset)---- | Build a C-allocated slot array from a list of t'Thunk' values.--- Each thunk is converted to 'CThunkPtr' via 'thunkToCPtr'.--- Returns the C array pointer and the slot count.--- Uses 'unsafePerformIO' - safe because allocation is idempotent.-{-# NOINLINE buildCSlots #-}-buildCSlots :: [Thunk] -> (Ptr CThunkPtr, Int)-buildCSlots thunks = unsafePerformIO $ do-  let n = length thunks-  if n == 0-    then pure (nullPtr, 0)-    else do-      arr <- checkedCPtr "nn_env_alloc_slots" =<< cenvAllocSlots (fromIntegral n)-      pokeSlots arr 0 thunks-      pure (arr, n)-  where-    pokeSlots _ _ [] = pure ()-    pokeSlots arr i (t : ts) = do-      pokeElemOff arr i (thunkToCPtr t)-      pokeSlots arr (i + 1) ts---- | Allocate a C slot array of the given size WITHOUT filling it.--- Returns 'nullPtr' for size 0.  Used by knot-tying sites (rec {},--- let) where the Env must reference the slot pointer before the--- thunks are materialized.  Caller MUST fill all slots via 'fillCSlots'--- before any slot is read (e.g. before forcing any thunk).-{-# NOINLINE allocCSlots #-}-allocCSlots :: Int -> Ptr CThunkPtr-allocCSlots 0 = nullPtr-allocCSlots n = unsafePerformIO (checkedCPtr "nn_env_alloc_slots" =<< cenvAllocSlots (fromIntegral n))---- | Fill a pre-allocated C slot array with thunks.  Each thunk is--- converted to 'CThunkPtr' via 'thunkToCPtr' and poked at its index.--- The list length MUST equal the allocated array size.--- Used after 'allocCSlots' in knot-tying contexts.-{-# NOINLINE fillCSlots #-}-fillCSlots :: Ptr CThunkPtr -> [Thunk] -> ()-fillCSlots arr thunks = unsafePerformIO (go 0 thunks)-  where-    go _ [] = pure ()-    go !i (t : ts) = do-      pokeElemOff arr i (thunkToCPtr t)-      go (i + 1) ts---- | A value's type as an error message names it: upstream's @showType@ on--- a value (eval.cc at 2.24.9, the same in 2.33.2), which every type error--- there uses.  It names a primop and the string context the type alone--- does not show.  Upstream's other cases (a thunk, a black hole, a--- function application, an external value) have no 'NixValue': a value--- here is always forced, and there are no plugins.-typeName :: NixValue -> Text-typeName val = case val of-  VInt _ -> "an integer"-  VFloat _ -> "a float"-  VBool _ -> "a Boolean"-  VNull -> "null"-  VStr _ ctx-    | ctx == emptyContext -> "a string"-    | otherwise -> "a string with context"-  VPath _ -> "a path"-  VList _ -> "a list"-  VAttrs _ -> "a set"-  VLambda {} -> "a function"-  VBuiltin name [] -> "the built-in function '" <> name <> "'"-  VBuiltin name _ -> "the partially applied built-in function '" <> name <> "'"-  -- Only ever an argument inside a 'VBuiltin', and carrying no primop-  -- name, so it takes the name upstream gives the function type itself.-  VCompiledRegex _ -> "a function"---- | @builtins.typeOf@: the name of upstream's @ValueType@, the--- classification its type checks compare (a lambda and a primop are both--- @nFunction@).-typeOfValue :: NixValue -> Text-typeOfValue val = case val of-  VInt _ -> "int"-  VFloat _ -> "float"-  VBool _ -> "bool"-  VNull -> "null"-  VStr _ _ -> "string"-  VPath _ -> "path"-  VList _ -> "list"-  VAttrs _ -> "set"-  VLambda {} -> "lambda"-  VBuiltin _ _ -> "lambda"-  VCompiledRegex _ -> "lambda"---- ------------------------------------------------------------------------------ Evaluation monad--- ------------------------------------------------------------------------------- | What @builtins.pathExists@ asks of a path, decided from the--- argument's spelling as upstream's @prim_pathExists@ decides it--- (primops.cc at 2.24.9).-data PathExistence-  = -- | Whether an entry is there: the ancestors are resolved and the-    -- final component is checked in place, so a symlink exists whatever-    -- it points at (upstream's @SymlinkResolution::Ancestors@).-    ExistsAsEntry-  | -- | Whether a directory is there, asked by a string ending in @/@ or-    -- @/.@: every symlink is followed, the final one included-    -- (@SymlinkResolution::Full@), and a file answers false.-    ExistsAsDirectory-  deriving (Eq, Show)---- | Effect class for Nix evaluation.  Core logic is polymorphic in @m@--- so the same evaluator composes into t'PureEval' for tests or @IO@ for--- real file-system access (e.g. @import@, @readFile@).-class (Monad m) => MonadEval m where-  -- | Raise an evaluation error (type error, missing attribute, IO-  -- failure).  NOT caught by @builtins.tryEval@: upstream Nix catches only-  -- ThrownError\/AssertionError there, and every other EvalError escapes.-  throwEvalError :: Text -> m a--  -- | Raise a catchable error - @builtins.throw@ and a failed @assert@.-  -- These are the only errors 'catchEvalError' (tryEval) recovers from.-  throwCatchableError :: Text -> m a--  -- | Abort evaluation (uncatchable by tryEval, matching real Nix).-  abortEvaluation :: Text -> m a--  -- | tryEval semantics: recover from a 'throwCatchableError'-  -- (throw\/assert); eval errors and aborts propagate.-  catchEvalError :: m a -> m (Either Text a)--  -- | Run the action; when it fails with ANY evaluation failure-  -- (catchable throw, eval error, or abort), run the cleanup and let-  -- the failure propagate unchanged.  The error half of a bracket --  -- success runs no cleanup - for builtins that hold external state-  -- (a scratch directory) across throwing calls.  'catchEvalError'-  -- cannot express this: it recovers only catchable throws, and a-  -- failed fetch is an eval error.-  onEvalError :: m a -> m () -> m a--  -- | Run the action; a failure escaping it (a throw, an eval error or an-  -- abort) gains the given line of context outside the lines it already-  -- carries, as upstream's @Error::addTrace@ adds one where a @catch@-  -- rethrows.  Nothing else about the failure changes: its message stays-  -- the same, and a throw stays catchable by @builtins.tryEval@.-  addErrorTrace :: Text -> m a -> m a--  -- | Run an application one call frame deeper, or refuse it with-  -- upstream's "stack overflow; max-call-depth exceeded" when the frames-  -- already active exceed the ceiling ('Nix.Eval.CallDepth.enterCallFrame'-  -- is the rule).  An eval error, not a throw: upstream raises an-  -- EvalError, which its tryEval does not catch.  The frame ends with the-  -- action, on failure too, so an error unwinding through a tryEval-  -- leaves the count that tryEval was entered at.-  withCallFrame :: m a -> m a--  -- | Whether something is at the path, as @builtins.pathExists@ asks-  -- it; the query says how the final component is read.  A path the-  -- policy refuses is absent.-  doesPathExist :: PathExistence -> Text -> m Bool--  -- | List a directory, returning @(name, fileType)@ pairs.-  -- @fileType@ is one of @"regular"@, @"directory"@, or @"symlink"@-  -- (matching Nix's @builtins.readDir@ semantics).-  listDirectory :: Text -> m [(Text, Text)]--  importFile :: Text -> m NixValue--  -- | Look up an environment variable by the bytes of its name, answering-  -- the bytes of its value, or @""@ if unset.-  getEnvVar :: ByteString -> m ByteString--  -- | Get the current epoch time (seconds since 1970-01-01).-  getCurrentTime :: m Int64--  -- | Write a named file to the store at upstream's text-path-  -- (@text:\<refs\>@ scheme, flat sha256 of the contents), returning the-  -- canonical store path.  The contents are raw bytes (a Nix string's-  -- payload) - hashed and stored exactly as given.  The refs are the-  -- contents' plain store-path references; they participate in the path-  -- computation exactly as upstream's addTextToStore.-  writeToStore :: Text -> ByteString -> [StorePath] -> m Text--  -- | Import a file with a custom scope overlaid on builtins.-  scopedImportFile :: [(Text, Thunk)] -> Text -> m NixValue--  -- | Read raw bytes from a file.  Used by @builtins.hashFile@.-  readFileBytes :: Text -> m ByteString--  -- | Classify a single filesystem path as @"regular"@, @"directory"@,-  -- @"symlink"@, or @"unknown"@: an lstat of the path itself, refused-  -- when a symlink sits anywhere above it, as upstream's accessor-  -- refuses one.  Used by @builtins.readFileType@ and, on a resolved-  -- root, by the source tree walk.-  getFileType :: Text -> m Text--  -- | Follow every symlink in a path, as upstream's-  -- @SourcePath::resolveSymlinks@ does before a tree is read-  -- (@addPath@, @prim_filterSource@): no component of the result is a-  -- symlink, so the lstats of the walk that follows never meet one-  -- above the entry they classify.-  resolveSymlinks :: Text -> m Text--  -- | Run an external process: @(command, args, stdin) -> (exitCode, stdout, stderr)@.-  runProcess :: Text -> [Text] -> Text -> m (Int, Text, Text)--  -- | Create a fetcher scratch directory under the system temp dir: the-  -- given name prefix plus an unpredictable suffix, exclusively created.-  -- A fixed scratch name in the shared temp dir gives any other local-  -- process a pre-place\/swap window between creation and the store-  -- copy, so the name must be unguessable and creation must fail rather-  -- than adopt an existing directory.-  createScratchDir :: Text -> m Text--  -- | Recursively remove a directory 'createScratchDir' created.-  removeScratchDir :: Text -> m ()--  -- | Resolve a path literal to a canonical path.-  -- In IO evaluation, @~/@ resolves against the home directory and other-  -- relative paths resolve against the current file's directory-  -- (@esBaseDir@); this ensures that path values captured in closures-  -- remain valid after the import scope ends.  In pure evaluation the-  -- text is not absolutized.  Every implementation ends with lexical-  -- canonicalization ('Nix.Eval.CanonPath.canonPath'), as upstream: no-  -- dot segment or repeated separator survives into a path value.-  resolvePathLiteral :: Text -> m Text--  -- | Copy a path (file or directory) to the store, returning the store-  -- path.  Content-addressed like upstream addToStore: recursive NAR-  -- sha256 under the given name.  Arguments: source path, store name,-  -- and an optional sha256 pin as (error subject, expected digest): a-  -- digest mismatch fails the copy with the subject heading the message.-  -- @builtins.path@ and @builtins.fetchTarball@ share this pin.-  copyPathToStore :: Text -> Text -> Maybe (Text, ByteString) -> m Text--  -- | Recursive NAR sha256 digest of a path, without copying it anywhere.-  -- Used by @builtins.fetchGit@ to report @narHash@.-  narHashOfPath :: Text -> m ByteString--  -- | Whether a regular file carries the executable bit (NAR encodes it).-  isExecutableFile :: Text -> m Bool--  -- | Mark a regular file executable (mode bit on Unix, an alternate data-  -- stream on Windows). Run before the tree is copied to the store.-  setExecutableFile :: Text -> m ()--  -- | Look up a previously recorded fetch by a key naming exactly what was-  -- fetched. 'Nothing' when nothing was recorded, or the record no longer-  -- describes anything on disk.-  lookupFetchCache :: Text -> m (Maybe Text)--  -- | Take over a store path an earlier evaluation wrote: 'True' when it is-  -- still on disk, and recorded as this evaluation's own store write in-  -- that case. Reusing a path instead of rewriting it must still leave the-  -- registration behind, or the build driver never registers it and a-  -- derivation naming it fails with \"path \'...\' is not valid\".-  adoptStorePath :: Text -> m Bool--  -- | Record a fetch under that key. Failing to record is not an error --  -- the cache is an optimisation.-  writeFetchCache :: Text -> Text -> m ()--  -- | Read a symlink's target WITHOUT following it.-  readSymlinkTarget :: Text -> m Text--  -- | Unpack a serialized NAR into the store under the given name at its-  -- canonical recursive fixed-output path (sha256 of the bytes),-  -- returning the store path text.  Used by @builtins.path@ and-  -- @builtins.filterSource@ with a filter, whose filtered tree exists-  -- only as a NAR value and never on the source filesystem.-  addSourceNar :: Text -> ByteString -> m Text--  -- | Write raw bytes to the store at a canonical flat fixed-output path-  -- (@makeFixedOutputPath name "sha256" "flat"@), so a hash-pinned fetch lands-  -- at the same store path C++ Nix computes - reproducible and cacheable.-  addFixedOutputFile :: Text -> ByteString -> m Text--  -- | Print a trace/warning message.-  -- IO evaluators write to stderr; pure evaluators silently discard.-  traceMessage :: Text -> m ()--  -- | Force a thunk to a value, with memoization.-  -- IO evaluators should cache results (via per-thunk @IORef@).-  -- Pure evaluators re-evaluate each time.-  -- The first argument is the bytecode evaluation function (to break-  -- the Eval.Types to Eval circular dependency).-  forceThunk :: (Env -> Word32 -> m NixValue) -> Thunk -> m NixValue--  -- | Look up a cached derivation modulo-hash (hex) by its @.drv@ store-  -- path.  Populated bottom-up as each derivation is computed; used by the-  -- derivation-hash algorithm to substitute input derivations.  Pure-  -- evaluators have no cache and always return 'Nothing'.-  lookupDrvHash :: Text -> m (Maybe Text)--  -- | Cache a derivation's modulo hash (hex) under its @.drv@ store path.-  -- A no-op in pure evaluators (no memoization).-  cacheDrvHash :: Text -> Text -> m ()--  -- | Record a derivation's serialized @.drv@ ATerm (the exact bytes whose-  -- hash is its store path) under its @.drv@ store path, as each derivation-  -- is computed (bottom-up).  Unlike 'cacheDrvHash' (which stores only the-  -- modulo hash), this retains the full ATerm so the build driver can-  -- materialize the entire input-@.drv@ closure to the store before a-  -- dependency-aware build.  A no-op in pure evaluators.-  recordDrvAterm :: Text -> ByteString -> m ()--  -- | Read and parse a derivation from its @.drv@ in the store, or 'Nothing'-  -- if it is absent or unreadable.  Used to resolve an input derivation's-  -- modulo hash on a cache miss - a cross-session reference, or a path-  -- fabricated by @builtins.appendContext@ - where the referenced derivation-  -- was not evaluated this session.  Reading the store is an effect, so this-  -- is an IO-evaluator capability: pure evaluators return 'Nothing', which-  -- makes hashing a dependent derivation something only the IO evaluator can do.-  readStoreDerivation :: StorePath -> m (Maybe Derivation)--  -- | Look up a derivation evaluated earlier THIS session by its @.drv@ store-  -- path, or 'Nothing' if it was not.  The IO evaluator reads the ATerm it-  -- recorded bottom-up ('recordDrvAterm'); pure evaluators return 'Nothing'.-  -- Used to recover a referenced derivation's output names for an all-outputs-  -- (DrvDeep) context reference without a disk read - the in-session @.drv@ is-  -- not on disk during evaluation.-  lookupSessionDrv :: Text -> m (Maybe Derivation)--  -- | The references recorded when this session wrote a store path (a-  -- @builtins.toFile@'s text with context, a copied source's none), or-  -- 'Nothing' if this session did not write it.  The walk of a-  -- @drvPath@'s closure follows them as upstream's @computeFSClosure@-  -- follows its database's.  Pure evaluators write nothing.-  lookupSessionReferences :: StorePath -> m (Maybe [StorePath])--  -- | Compute the store path a source file/directory gets when copied into-  -- the store (recursive NAR sha256 to a @source@ fixed-output path), WITHOUT-  -- performing the copy.  Used when a path literal is coerced in a derivation-  -- argument or environment value.  Unavailable in pure evaluation.-  storeSourcePath :: Text -> m Text--  -- | The policy this evaluation runs under.  The builtins whose behaviour-  -- upstream changes by setting consult it: @storePath@ is refused and the-  -- fetchers demand a hash or revision under @pure-eval@, a search path-  -- miss is worded for the mode, and @traceVerbose@ traces only under-  -- @trace-verbose@.  The filesystem and URI gates are not decided here;-  -- they live in the instance, where the allowed set is.-  evalPolicy :: m EvalPolicy--  -- | Upstream @checkURI@: refuse a fetch of this URI under @restrict-eval@-  -- unless @allowed-uris@ admits it (a path or @file://@ URI is checked-  -- against the allowed paths instead).  A no-op under any other policy.-  -- Every fetcher calls it before anything is spawned or downloaded.-  checkUri :: Text -> m ()--  -- | A path named on the drive this evaluation reads it on-  -- ('Nix.Store.Path.qualifyPathText' against its store directory): on-  -- Windows a rooted path with no drive gains the store's.  For a-  -- fetcher handing a local path to another program, which would-  -- otherwise read it on whatever drive that program has current.-  qualifyPath :: Text -> m Text---- | Unwrap a store-path construction result (the @makeStorePath@ family--- in "Nix.Hash"), raising a refused name as upstream's @BadStorePath@--- text.  The message names the path and not the builtin, as upstream's--- does: upstream names the builtin in its trace.  Every eval-side path--- construction goes through this, so a refused name is an eval error--- before anything is written.-storePathOrThrow :: (MonadEval m) => Either BadStorePath StorePath -> m StorePath-storePathOrThrow = either (throwEvalError . badStorePathText) pure---- | Error raised during pure evaluation.  'PThrow' (@builtins.throw@, a--- failed @assert@) is the only kind @tryEval@ catches; 'PError' (type--- errors, missing attributes) and 'PAbort' (@abort@, infinite recursion)--- escape it, exactly as in C++ Nix.-data PureError = PThrow !Text | PError !Text | PAbort !Text---- | Pure evaluation monad - @Either PureError@ under a reader carrying--- the call depth.  IO builtins ('readFile', 'import') are unavailable;--- everything else evaluates identically to the IO version, the--- @max-call-depth@ ceiling included, at its upstream default.  It carries--- no filesystem policy: there is no filesystem, environment or network--- behind it to gate, so it reports 'unrestrictedPolicy' and every URI--- check passes.-newtype PureEval a = PureEval (ReaderT CallDepth (Either PureError) a)-  deriving (Functor, Applicative, Monad)---- | Fail a pure evaluation.-pureFailure :: PureError -> PureEval a-pureFailure = PureEval . lift . Left---- | Run a pure evaluation, flattening the internal error into 'Text'.  An abort--- is prefixed @\"evaluation aborted: \"@, matching t'Nix.Eval.IO.EvalIO'.-runPureEval :: PureEval a -> Either Text a-runPureEval (PureEval action) =-  case runReaderT action (topLevelCallDepth defaultMaxCallDepth) of-    Right a -> Right a-    Left (PThrow t) -> Left t-    Left (PError t) -> Left t-    Left (PAbort t) -> Left ("evaluation aborted: " <> t)--instance MonadEval PureEval where-  throwEvalError = pureFailure . PError-  throwCatchableError = pureFailure . PThrow-  abortEvaluation = pureFailure . PAbort--  -- Catch only a throw/assert (tryEval sees the error); eval errors,-  -- aborts, and infinite recursion propagate, matching EvalIO and C++ Nix.-  catchEvalError (PureEval action) =-    PureEval $ ReaderT $ \depth -> case runReaderT action depth of-      Left (PThrow t) -> Right (Left t)-      Left other -> Left other-      Right a -> Right (Right a)--  -- Pure evaluation has no external state, so there is nothing to-  -- clean up; the failure passes through unchanged.-  onEvalError (PureEval action) _ = PureEval action--  -- 'runPureEval' reports a failure's message alone, so a line of context-  -- has nowhere to go.-  addErrorTrace _ action = action--  -- The reader scopes the frame: the action runs one deeper, and whatever-  -- follows it sees the depth it started from, failure or not.-  withCallFrame (PureEval action) =-    PureEval $ ReaderT $ \depth -> either (Left . PError) (runReaderT action) (enterCallFrame depth)-  doesPathExist _ _ = pure False-  listDirectory _ = throwEvalError "builtins.readDir: not available in pure evaluation"-  importFile _ = throwEvalError "import: not available in pure evaluation"-  getEnvVar _ = pure ""-  getCurrentTime = pure 0-  writeToStore _ _ _ = throwEvalError "toFile: not available in pure evaluation"-  scopedImportFile _ _ = throwEvalError "scopedImport: not available in pure evaluation"-  readFileBytes _ = throwEvalError "readFile: not available in pure evaluation"-  getFileType _ = throwEvalError "readFileType: not available in pure evaluation"--  -- No filesystem, so no symlinks: a path resolves to itself.-  resolveSymlinks = pure-  runProcess _ _ _ = throwEvalError "runProcess: not available in pure evaluation"-  createScratchDir _ = throwEvalError "createScratchDir: not available in pure evaluation"-  removeScratchDir _ = pure ()-  copyPathToStore _ _ _ = throwEvalError "builtins.path: not available in pure evaluation"-  narHashOfPath _ = throwEvalError "builtins.fetchGit: not available in pure evaluation"-  isExecutableFile _ = throwEvalError "builtins.path: not available in pure evaluation"-  setExecutableFile _ = throwEvalError "builtins.fetchGit: not available in pure evaluation"-  lookupFetchCache _ = pure Nothing-  adoptStorePath _ = pure False-  writeFetchCache _ _ = pure ()-  readSymlinkTarget _ = throwEvalError "builtins.path: not available in pure evaluation"-  addSourceNar _ _ = throwEvalError "builtins.path: not available in pure evaluation"-  addFixedOutputFile _ _ = throwEvalError "builtins.fetchurl: not available in pure evaluation"-  traceMessage _ = pure ()-  lookupDrvHash _ = pure Nothing-  cacheDrvHash _ _ = pure ()-  recordDrvAterm _ _ = pure ()--  -- Pure eval cannot read the store, so a dependent derivation's input hash-  -- is never recoverable here; the caller turns this into a loud error rather-  -- than a guessed hash.-  readStoreDerivation _ = pure Nothing--  -- Pure eval keeps no session drv closure, so an all-outputs reference's-  -- output names are never recoverable here either.-  lookupSessionDrv _ = pure Nothing-  lookupSessionReferences _ = pure Nothing--  -- Pure eval cannot read files: a path coerces to itself (no store copy);-  -- the real copy-to-store happens only under 'EvalIO'.-  storeSourcePath = pure-  evalPolicy = pure unrestrictedPolicy-  checkUri _ = pure ()--  -- No filesystem, so no drive to read on: a path names itself.-  qualifyPath = pure-  resolvePathLiteral = pure . canonPathValue-  forceThunk evalFn (Thunk ptr) =-    -- Read the C thunk via unsafePerformIO - safe because reads are-    -- idempotent and PureEval never writes back (no memoization).-    -- Does NOT mark blackholes - PureEval may re-force the same thunk.-    -- Dispatches on val_tag for computed scalars (no StablePtr deref).-    case unsafePerformIO (cthunkState ptr) of-      ThunkComputed ->-        let tag = unsafePerformIO (cthunkValueTag ptr)-         in case tag of-              ValueInt -> pure (VInt (unsafePerformIO (cthunkGetInt ptr)))-              ValueFloat -> pure (VFloat (unsafePerformIO (cthunkGetFloat ptr)))-              ValueBool -> pure (VBool (unsafePerformIO (cthunkGetBool ptr) /= 0))-              ValueNull -> pure VNull-              ValueStr ->-                let sym = unsafePerformIO (cthunkGetStr ptr)-                 in pure (VStr (symbolBytes (Symbol sym)) emptyContext)-              ValuePath ->-                let sym = unsafePerformIO (cthunkGetPath ptr)-                 in pure (VPath (symbolText (Symbol sym)))-              ValueList ->-                let listPtr = unsafePerformIO (cthunkGetList ptr)-                 in pure (VList (CList (castPtr listPtr)))-              ValueAttrs ->-                let p = unsafePerformIO (cthunkGetAttrs ptr)-                 in pure (VAttrs (AttrSet (castPtr p)))-              ValueCtxStr ->-                let csptr = unsafePerformIO (cthunkGetCtxStr ptr)-                    (t, ctx) = unsafePerformIO (unmarshalStringContext (castPtr csptr))-                 in pure (VStr t ctx)-              ValueLambda ->-                let lamRaw = unsafePerformIO (cthunkPayload ptr)-                    val = unsafePerformIO (unmarshalLambdaValue lamRaw)-                 in pure val-              _ {- PTR -} ->-                let payload = unsafePerformIO (cthunkPayload ptr)-                    val = unsafePerformIO (deRefStablePtr (castPtrToStablePtr payload))-                 in pure val-      ThunkBlackhole ->-        -- Non-catchable: must escape tryEval like in C++ Nix-        abortEvaluation "infinite recursion encountered"-      _ {- PENDING -} ->-        let bcIdx = unsafePerformIO (cthunkGetBcIdx ptr)-            envSp = unsafePerformIO (cthunkPayload ptr)-            env = unsafePerformIO (deRefStablePtr (castPtrToStablePtr envSp))-         in evalFn env bcIdx+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE PatternSynonyms #-}++-- | Shared types for the Nix evaluator, in a module of their own so that+-- "Nix.Eval.Operator", "Nix.Eval.StringInterp", and "Nix.Builtins" can+-- reference 'NixValue', t'Thunk', and t'Env' without an import cycle.+module Nix.Eval.Types+  ( -- * Values+    NixValue (.., VStr, VPath),+    HeldBytes (..),+    BuiltinArg (..),+    Thunk (..),+    readThunkValue,+    readComputed,+    thunkUnderEvaluation,++    -- * Attribute sets (C-backed sorted arrays)+    AttrSet (..),+    CAttrSet,+    AttrEntry (..),+    attrSetLookup,+    attrSetLookupSymbol,+    attrSetLookupEntry,+    attrSetLookupSymbolEntry,+    attrSetKeys,+    attrSetFoldM,+    attrSetFindName,+    attrSetAllPairs,+    attrSetToMap,+    emptyAttrSet,+    attrSetFromMap,+    attrSetFromEntries,+    attrSetFromSymbols,+    attrSetFromSymbolEntries,+    attrSetFromSymbolEntriesSizedFor,+    attrSetMember,+    attrSetMemberSymbol,+    attrSetNull,+    attrSetSize,+    attrSetElems,+    attrSetToAscList,+    attrSetMapWithKey,+    attrSetRemoveKeys,+    FlatCAttrSet,+    flatCAttrSet,+    buildCAttrSetKeys,+    fillCAttrSetValues,++    -- * Lists (C-backed)+    CList (..),+    emptyCList,+    clistFromThunks,+    clistThunks,+    clistLen,++    -- * String context+    StringContextElement (..),+    StringContext (..),+    emptyContext,+    mkStr,+    mkStrBytes,+    bytesToTextLossy,++    -- * Environment+    Env (..),+    NnEnv,+    emptyEnv,+    envLookup,+    envLookupResolved,+    newEnv,+    newScopeEnv,+    pushLazyWithScope,+    buildCaptureEnv,+    buildBcCaptureEnv,+    withScopeAt,+    resolveWithScopeAt,+    envWithScopesRaw,++    -- * Eval-time formals (re-exported from EvalFormals)+    EvalFormals (..),+    EvalFormal (..),++    -- * Thunk operations+    compile,+    compileSource,+    cheapThunk,+    cheapThunkBc,+    mkThunkBc,+    mkApplyThunk,+    mkApply2Thunk,+    Pending (..),+    readPending,+    evaluated,+    tieFrame,+    frameThunkBc,+    shareSlot,+    envSlotCells,++    -- * Lambda marshalling+    marshalLambda,++    -- * Display+    typeName,+    typeOfValue,++    -- * C thunk-state and value tags (mirror cbits/nn_thunk.h)+    pattern ThunkPending,+    pattern ThunkComputed,+    pattern ThunkBlackhole,+    pattern ValueInt,+    pattern ValueFloat,+    pattern ValueBool,+    pattern ValueNull,+    pattern ValueStr,+    pattern ValuePath,+    pattern ValueList,+    pattern ValueAttrs,+    pattern ValueCtxStr,+    pattern ValueLambda,++    -- * Cells holding strings+    heldString,+    StringCell (..),+    stringCell,+    pathCell,+    PrimopCell (..),+    primopCell,++    -- * Evaluation monad+    MonadEval (..),+    addErrorTrace,+    warnMessage,+    PathExistence (..),+    EvalPolicy (..),+    unrestrictedPolicy,+    PureEval,+    runPureEval,+    storePathOrThrow,+  )+where++import Control.Monad (forM_, void, zipWithM_)+import Data.Bits (bit, complement, shiftL, testBit, (.&.), (.|.))+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import Data.Int (Int64)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Text.Encoding.Error (lenientDecode)+import Data.Word (Word32, Word64, Word8)+import Foreign.Marshal.Array (peekArray)+import Foreign.Ptr (Ptr, WordPtr, castPtr, nullPtr, ptrToWordPtr, wordPtrToPtr)+import Foreign.Storable (peekElemOff, pokeElemOff)+import GHC.Float (castWord64ToDouble)+import Nix.Derivation (Derivation)+import Nix.Eval.AllocSite (EnvSite (..), SetSite (..))+import Nix.Eval.Builtin (Builtin, builtinAtIndex, builtinIndex, builtinName)+import Nix.Eval.CAttrSet (CAttrSet, CAttrSetStep (..), FlatCAttrSet, cattrsetEmpty, cattrsetFind, cattrsetFreeze, cattrsetFromNames, cattrsetIndex, cattrsetInsert, cattrsetLookup, cattrsetMember, cattrsetNew, cattrsetRemoveKeys, cattrsetSetValue, cattrsetSize, cattrsetWalk, cattrsetWalkNext, flatCAttrSet)+import Nix.Eval.CBytecode (cbcArg1, cbcArg2, cbcCountedPayload, cbcData, cbcOpcode, cbcShortArg, cbcString, cbcStringBytes, strpartLit, pattern OpList, pattern OpLitBool, pattern OpLitFloat, pattern OpLitInt, pattern OpLitNull, pattern OpLitPath, pattern OpLitUri, pattern OpResolvedVar, pattern OpStr, pattern OpVar)+import Nix.Eval.CCtxStr (CCtxStrPtr, cctxstrCtxCount, cctxstrElemHash, cctxstrElemName, cctxstrElemOutput, cctxstrElemTag, cctxstrNew, cctxstrSetAllOutputs, cctxstrSetDrvOutput, cctxstrSetPlain, cctxstrText, pattern SceAllOutputs, pattern SceDrvOutput, pattern ScePlain)+import Nix.Eval.CData (CData, MonadCData (..), cdataIO, runCDataPure)+import Nix.Eval.CEnv (NnEnv, cenvEmpty, cenvLookupResolved, cenvNameTable, cenvNew, cenvNewScoped, cenvParent, cenvPushWith, cenvResolveWith, cenvSlotCount, cenvSlots, cenvWithCount, cenvWithOwner, cenvWithScopes)+import Nix.Eval.CLambda (clambdaAllowExtra, clambdaBody, clambdaEntryDefault, clambdaEntryHasDefault, clambdaEntryName, clambdaEnv, clambdaFormalCount, clambdaFormalsType, clambdaLambdaNameSym, clambdaNameSym, clambdaNew, clambdaSetEntry, pattern FormalsName, pattern FormalsNamedSet, pattern FormalsSet)+import Nix.Eval.CList (CList (..), clistFromThunks, clistLen, clistThunks, emptyCList)+import Nix.Eval.CPrimop (CPrimopAppPtr, cprimopAppArg, cprimopAppForced, cprimopAppNew, cprimopAppPrimop, cprimopAppTaken)+import Nix.Eval.CStatus (cInvariantViolated)+import Nix.Eval.CStr (CStrPtr, cstrBytes, cstrFromText, cstrNew, cstrText)+import Nix.Eval.CThunk (CThunkPtr, cthunkApplyCell, cthunkBool, cthunkEmptyList, cthunkGetBcIdx, cthunkGetBool, cthunkGetFloat, cthunkGetInt, cthunkGetPrimop, cthunkNewApply1, cthunkNewApply2, cthunkNewBc, cthunkNewComputedAttrs, cthunkNewComputedCtxStr, cthunkNewComputedFloat, cthunkNewComputedInt, cthunkNewComputedLambda, cthunkNewComputedList, cthunkNewComputedPath, cthunkNewComputedPrimop, cthunkNewComputedPrimopApp, cthunkNewComputedStr, cthunkNull, cthunkPayload, cthunkPendingForm, cthunkState, cthunkValueTag, noCode)+import Nix.Eval.CallDepth (CallDepth, defaultMaxCallDepth, enterCallFrame, topLevelCallDepth)+import Nix.Eval.CanonPath (canonPathValue)+import Nix.Eval.Compile (BcCaptureInfo (..), BcCapturedSlots (..), compileExpr, compileFormalsToEval, compileParsed, foldBcCapturedSlots, formalDefaultFromWords, formalDefaultWords)+import Nix.Eval.EvalFormals (EvalFormal (..), EvalFormals (..), lambdaNameFromSymbol, lambdaNameSymbol)+import Nix.Eval.Policy (EvalPolicy (..), unrestrictedPolicy)+import Nix.Eval.RealiseContext (ContextRefusal, PendingOrigin)+import Nix.Eval.SourcePos (PosIdx, noPos)+import Nix.Eval.Symbol (Symbol (..), invalidSymbolId, symbolIntern, symbolText)+import Nix.Expr.Types (CaptureInfo (..), Expr (..), NixAtom (..))+import Nix.Fetch.Archive (FetchFailure)+import Nix.Parser (ParsedSource)+import Nix.Store.Path (BadStorePath, StorePath, badStorePathText)+import Nix.Store.Path.Internal (StorePath (StorePath))++-- ---------------------------------------------------------------------------+-- String context+-- ---------------------------------------------------------------------------++-- | A single element of string context, tracking where a string+-- references store paths.+data StringContextElement+  = -- | Plain store path reference (inputSrcs).+    SCPlain !StorePath+  | -- | Derivation output reference (inputDrvs): .drv path + output name.+    SCDrvOutput !StorePath !Text+  | -- | All outputs of a derivation (for drvPath itself).+    SCAllOutputs !StorePath+  deriving (Eq, Ord, Show)++-- | Context carried by Nix strings, tracking store path dependencies.+newtype StringContext = StringContext {unStringContext :: Set StringContextElement}+  deriving (Eq, Ord, Show, Semigroup, Monoid)++-- | Empty string context (alias for 'mempty').+emptyContext :: StringContext+emptyContext = mempty++-- | Smart constructor for context-free strings from 'Text'.+-- Encodes to the UTF-8 bytes that ARE the string's value: a Nix string+-- is a byte string, and Text-producing sites go through here.+mkStr :: Text -> NixValue+mkStr t = VStr (TE.encodeUtf8 t) emptyContext++-- | Smart constructor for context-free strings from raw bytes+-- (@builtins.readFile@, substring slices - anything already byte-shaped).+mkStrBytes :: ByteString -> NixValue+mkStrBytes b = VStr b emptyContext++-- | Decode string-value bytes for DISPLAY ONLY (trace output, error+-- messages, value pretty-printing): invalid UTF-8 becomes U+FFFD.+-- Never feed the result back into a value, a hash, or an attr name -+-- identity-bearing boundaries decode strictly and error instead.+bytesToTextLossy :: ByteString -> Text+bytesToTextLossy = TE.decodeUtf8With lenientDecode++-- ---------------------------------------------------------------------------+-- Thunks+-- ---------------------------------------------------------------------------++-- | A thunk: a C arena-allocated memoization cell.+--+-- Each thunk points to an @nn_thunk_t@ in the C arena.+-- On first force, the cell transitions PENDING to BLACKHOLE to COMPUTED,+-- which detects infinite recursion (BLACKHOLE) and overwrites the+-- pending work ('Pending') with the value, as upstream mutates a thunk in+-- place.+--+-- A pending cell holds its env as the C pointer, so the env exists before+-- the cell does: 'mkThunkBc' takes a built t'Env', and 'tieFrame' builds a+-- frame whose bindings point back at it before filling its slots.  A+-- deferred application's cell ('mkApplyThunk') holds the cells it applies+-- and no env.  A cell lives until the outermost evaluation session ends+-- ('Nix.Eval.IO.withEvalSession') unless, under+-- 'Nix.Eval.CRegion.RegionsCollect', the close of the force that allocated+-- it finds nothing reaching it and frees its line; the static cells+-- ('Nix.Eval.CThunk.cthunkNull' and its kin) live for the life of the+-- process.+--+-- Two thunks are equal when they are one cell, and 'show' gives the+-- cell's address.  Neither reads the cell, whose state changes as it is+-- forced; 'readThunkValue' reads it, in order with the evaluation.+newtype Thunk = Thunk {unThunk :: CThunkPtr}+  deriving (Eq, Show)++-- | Named constants for the C thunk-state byte and value-tag byte, mirroring+-- the @NN_THUNK_*@ / @NN_VALUE_*@ macros in @cbits\/nn_thunk.h@.  Bidirectional+-- pattern synonyms over literals, so a @case@ on a tag keeps the jump-table+-- compilation a bare-literal @case@ gets, while the state dispatches (the+-- 'forceThunk' of each evaluator) and the value dispatch ('readComputed')+-- share one source of truth instead of repeating literals.  These MUST stay+-- in lockstep with @cbits\/nn_thunk.h@.+pattern ThunkPending, ThunkComputed, ThunkBlackhole :: Word8+pattern ThunkPending = 0+pattern ThunkComputed = 1+pattern ThunkBlackhole = 2++-- | The forms of a pending application, mirroring the+-- @NN_PENDING_APPLY*@ macros in @cbits\/nn_thunk.h@: a function applied+-- to one argument or to two in turn.  A code thunk is told apart by its+-- instruction ('noCode').+pattern PendingApply1Form, PendingApply2Form :: Word8+pattern PendingApply1Form = 1+pattern PendingApply2Form = 2++-- | Value-kind tags for the C value layout, mirroring @cbits\/nn_thunk.h@.+-- The tag selects which payload a COMPUTED thunk carries.+pattern ValueInt, ValueFloat, ValueBool, ValueNull, ValueStr, ValuePath, ValueList, ValueAttrs, ValueCtxStr, ValueLambda, ValuePrimop, ValuePrimopApp :: Word8+pattern ValueInt = 0+pattern ValueFloat = 1+pattern ValueBool = 2+pattern ValueNull = 3+pattern ValueStr = 4+pattern ValuePath = 5+pattern ValueList = 6+pattern ValueAttrs = 7+pattern ValueCtxStr = 8+pattern ValueLambda = 9+pattern ValuePrimop = 10+pattern ValuePrimopApp = 11++-- | Whether a thunk is being forced right now, so it holds no value yet:+-- the cell's BLACKHOLE state.  An answer about this moment: the state+-- changes when the force finishes or is unwound.+thunkUnderEvaluation :: (MonadCData m) => Thunk -> m Bool+thunkUnderEvaluation (Thunk ptr) = (== ThunkBlackhole) <$> cthunkState ptr++-- | Read a COMPUTED thunk's value without forcing.+-- Returns 'Nothing' for PENDING or BLACKHOLE thunks.+readThunkValue :: (MonadCData m) => Thunk -> m (Maybe NixValue)+readThunkValue (Thunk ptr) = do+  state <- cthunkState ptr+  if state == ThunkComputed+    then Just <$> readComputed ptr+    else pure Nothing++-- | The value a COMPUTED cell holds, by its value tag: a scalar or a+-- builtin's index read in place, any other value from the C object the+-- cell points to.  Every value lives in C, so a tag outside the+-- @NN_VALUE_*@ constants is corrupt memory.+readComputed :: (MonadCData m) => CThunkPtr -> m NixValue+readComputed ptr = do+  tag <- cthunkValueTag ptr+  case tag of+    ValueInt -> VInt <$> cthunkGetInt ptr+    ValueFloat -> VFloat <$> cthunkGetFloat ptr+    ValueBool -> (\b -> VBool (b /= 0)) <$> cthunkGetBool ptr+    ValueNull -> pure VNull+    ValueStr -> cthunkPayload ptr >>= heldString . castPtr+    ValuePath -> do+      str <- castPtr <$> cthunkPayload ptr+      (`VPathHeld` HeldStr str) <$> cstrText str+    ValueList -> VList . CList . castPtr <$> cthunkPayload ptr+    ValueAttrs -> VAttrs . AttrSet . castPtr <$> cthunkPayload ptr+    ValueCtxStr -> do+      csptr <- castPtr <$> cthunkPayload ptr+      (\(bytes, ctx) -> VStrHeld bytes ctx (HeldCtxStr csptr)) <$> unmarshalStringContext csptr+    ValueLambda -> cthunkPayload ptr >>= unmarshalLambdaValue+    ValuePrimop -> (`VBuiltin` []) <$> (cthunkGetPrimop ptr >>= knownBuiltin)+    ValuePrimopApp -> cthunkPayload ptr >>= readPrimopApp . castPtr+    other -> cdataIO (cInvariantViolated "nn_thunk_value_tag" ("no value has tag " ++ show other))++-- | The builtin at an index a cell holds.+knownBuiltin :: (MonadCData m) => Word32 -> m Builtin+knownBuiltin index = maybe unknown pure (builtinAtIndex index)+  where+    unknown = cdataIO (cInvariantViolated "nn_thunk_get_primop" ("no builtin has index " ++ show index))++-- | A builtin's partial application, read from its C object: an argument+-- taken forced as the value its cell holds, any other as the cell.+readPrimopApp :: (MonadCData m) => CPrimopAppPtr -> m NixValue+readPrimopApp app = do+  builtin <- cprimopAppPrimop app >>= knownBuiltin+  taken <- cprimopAppTaken app+  forced <- cprimopAppForced app+  VBuiltin builtin <$> traverse (argumentAt forced) (take (fromIntegral taken) [0 ..])+  where+    argumentAt forced i = do+      cell <- cprimopAppArg app i+      if testBit forced (fromIntegral i)+        then ArgForced <$> (readThunkValue (Thunk cell) >>= maybe notComputed pure)+        else pure (ArgDeferred (Thunk cell))+    notComputed = cdataIO (cInvariantViolated "nn_primop_app_arg" "an argument taken forced is not COMPUTED")++-- | A Nix value - the result of evaluating an expression.+data NixValue+  = -- | 64-bit signed integer (matching Nix semantics).+    VInt !Int64+  | -- | Floating-point.+    VFloat !Double+  | -- | Boolean.+    VBool !Bool+  | -- | The null value.+    VNull+  | -- | String with dependency context, and where its bytes already are+    -- in C ('VStr' builds and matches one without).  The payload is a+    -- BYTE string, as upstream: @stringLength@/@substring@ index bytes,+    -- regexes match bytes, and @readFile@ carries raw file bytes (so+    -- invalid UTF-8 is representable).  Text enters via 'mkStr' (UTF-8+    -- encode) and leaves through explicit decode at boundaries (attr+    -- names strictly, display lossily via 'bytesToTextLossy').+    VStrHeld !ByteString !StringContext !HeldBytes+  | -- | Path, and where its bytes already are in C ('VPath' builds and+    -- matches one without).+    VPathHeld !Text !HeldBytes+  | -- | List of thunks (lazy elements), backed by C array.+    VList !CList+  | -- | Attribute set: unified lazy/eager representation.+    VAttrs !AttrSet+  | -- | Lambda closure: captures environment, formals, body bytecode index.+    VLambda !Env !EvalFormals !Word32+  | -- | Built-in function, with the arguments a partial application has+    -- taken so far, first to last.+    VBuiltin !Builtin ![BuiltinArg]+  deriving (Eq, Show)++-- | A string with dependency context: its bytes and their context.  Built+-- with it, a value's bytes are held in Haskell only, and a cell that+-- stores it takes a copy.+pattern VStr :: ByteString -> StringContext -> NixValue+pattern VStr bytes ctx <- VStrHeld bytes ctx _+  where+    VStr bytes ctx = VStrHeld bytes ctx NotHeld++-- | A path.  Built with it, a path's bytes are held in Haskell only, and+-- a cell that stores it takes a copy.+pattern VPath :: Text -> NixValue+pattern VPath path <- VPathHeld path _+  where+    VPath path = VPathHeld path NotHeld++{-# COMPLETE VInt, VFloat, VBool, VNull, VStr, VPath, VList, VAttrs, VLambda, VBuiltin #-}++-- | Where a string or path value's bytes already are in the C data+-- layer.  A value read from a cell, and a literal's value, carry the C+-- object their bytes are in, and a cell that stores the value points at+-- that object rather than at a copy, as upstream copies a @Value@ with+-- the pointer to its bytes (value.hh at 2.24.9): a string passed from+-- cell to cell takes its bytes once.  A value is built held only where+-- its bytes are read from the object it holds, and the objects never+-- change once made, so a value's bytes stay its object's.+data HeldBytes+  = -- | In Haskell only.+    NotHeld+  | -- | A context-free string's or a path's bytes.+    HeldStr !CStrPtr+  | -- | A string with context, whole.+    HeldCtxStr !CCtxStrPtr++-- | Every two are equal.  The held object is where a value's bytes live,+-- not part of the value, so two values with equal bytes and context are+-- equal wherever their bytes are.+instance Eq HeldBytes where+  _ == _ = True++instance Show HeldBytes where+  showsPrec _ held = showString $ case held of+    NotHeld -> "NotHeld"+    HeldStr _ -> "HeldStr"+    HeldCtxStr _ -> "HeldCtxStr"++-- | The value of a context-free string whose bytes are a C string: a+-- cell's, or a literal's in the code.+heldString :: (MonadCData m) => CStrPtr -> m NixValue+heldString str = (\bytes -> VStrHeld bytes emptyContext (HeldStr str)) <$> cstrBytes str++-- | An argument a builtin has taken.  A primop that forces an argument+-- before anything it does can be observed has it forced as it is+-- applied.  One that forces it later, after another argument or only on+-- some paths, has it held as the thunk it arrived as, and forces it where+-- upstream does.  An argument that arrives already forced is held forced+-- either way.+data BuiltinArg+  = ArgForced !NixValue+  | ArgDeferred !Thunk+  deriving (Eq, Show)++-- ---------------------------------------------------------------------------+-- Attribute sets (C-backed sorted arrays)+-- ---------------------------------------------------------------------------++-- | An attribute set: a C set (@cbits/nn_attrset.h@) whose entries are+-- sorted by symbol id, each an interned name, the position it was+-- defined at and its value's cell, so a lookup is a binary search of+-- each of its layers, top first.+--+-- Two sets are equal when they are one C set, and 'show' gives its+-- address.  Neither reads the set; 'attrSetToMap' reads its entries.+newtype AttrSet = AttrSet {unAttrSet :: CAttrSet}+  deriving (Eq, Show)++-- | An attribute's value and the position it was defined at, as a set+-- holds them.+data AttrEntry = AttrEntry+  { entryPos :: {-# UNPACK #-} !PosIdx,+    entryThunk :: {-# UNPACK #-} !Thunk+  }++-- | The value a set binds to an interned name, found by a binary search+-- of each of its layers, top first, each sorted by symbol.+attrSetLookupSymbol :: (MonadCData m) => Symbol -> AttrSet -> m (Maybe Thunk)+attrSetLookupSymbol sym (AttrSet cset) = fmap Thunk <$> cattrsetLookup cset sym++-- | Whether a set binds an interned name, a name table whose entry is not+-- filled yet among them.+attrSetMemberSymbol :: (MonadCData m) => Symbol -> AttrSet -> m Bool+attrSetMemberSymbol sym (AttrSet cset) = cattrsetMember cset sym++-- | 'attrSetLookupSymbol' for a name given as text, which is interned+-- first, so a name no symbol holds yet takes its place in symbol order.+attrSetLookup :: (MonadCData m) => Text -> AttrSet -> m (Maybe Thunk)+attrSetLookup key attrs = do+  sym <- symbolIntern key+  attrSetLookupSymbol sym attrs++-- | 'attrSetLookupSymbol' with the attribute's position.+attrSetLookupSymbolEntry :: (MonadCData m) => Symbol -> AttrSet -> m (Maybe AttrEntry)+attrSetLookupSymbolEntry sym (AttrSet cset) = fmap (\(pos, ptr) -> AttrEntry pos (Thunk ptr)) <$> cattrsetFind cset sym++-- | 'attrSetLookup' with the attribute's position.+attrSetLookupEntry :: (MonadCData m) => Text -> AttrSet -> m (Maybe AttrEntry)+attrSetLookupEntry key attrs = do+  sym <- symbolIntern key+  attrSetLookupSymbolEntry sym attrs++-- | All keys, as symbol text from C, in the set's order: by interned+-- symbol, not by name ('attrSetFoldM').+attrSetKeys :: (MonadCData m) => AttrSet -> m [Text]+attrSetKeys attrs = reverse <$> attrSetFoldM (\names name _ -> pure (symbolText name : names)) [] attrs++-- | Fold an action over a set's attributes, each its name and its entry,+-- first to last by interned symbol, as upstream walks the @Attr@s of a+-- set's @Bindings@, which are sorted by @Symbol@ (@Attr@'s comparison and+-- the @Bindings@ iterators in attr-set.hh), merging its layers' at 2.34.9.+-- It reads a flat set one entry at a time, and a layered one from the+-- entries 'cattrsetWalk' copies out of its layers first, and forces the+-- accumulator at each.+{-# INLINE attrSetFoldM #-}+attrSetFoldM :: (MonadCData m) => (a -> Symbol -> AttrEntry -> m a) -> a -> AttrSet -> m a+attrSetFoldM step initial (AttrSet cset) = cattrsetWalk cset >>= go initial+  where+    go !acc walk =+      cattrsetWalkNext walk >>= \case+        CAttrSetDone -> pure acc+        CAttrSetEntry name pos ptr rest -> step acc name (AttrEntry pos (Thunk ptr)) >>= \next -> go next rest++-- | The first name of a set, in the order 'attrSetFoldM' walks it, that a+-- test holds for, or 'Nothing' if it holds for none.  The walk stops at+-- that name and forces no value.+attrSetFindName :: (MonadCData m) => (Symbol -> Bool) -> AttrSet -> m (Maybe Symbol)+attrSetFindName holds (AttrSet cset) = cattrsetWalk cset >>= go+  where+    go walk =+      cattrsetWalkNext walk >>= \case+        CAttrSetDone -> pure Nothing+        CAttrSetEntry name _ _ rest+          | holds name -> pure (Just name)+          | otherwise -> go rest++-- | Whether an action answers 'True' for every pair of attributes, each a+-- name and its value, that two sets hold at one place in the order+-- 'attrSetFoldM' walks them, asked first to last.  The walk stops at the+-- first pair the action answers 'False' for, so it asks of no pair past+-- it, and answers 'False' where one set ends before the other.+attrSetAllPairs :: (MonadCData m) => ((Symbol, Thunk) -> (Symbol, Thunk) -> m Bool) -> AttrSet -> AttrSet -> m Bool+attrSetAllPairs holds (AttrSet left) (AttrSet right) = do+  leftWalk <- cattrsetWalk left+  rightWalk <- cattrsetWalk right+  go leftWalk rightWalk+  where+    go leftWalk rightWalk = do+      leftStep <- cattrsetWalkNext leftWalk+      rightStep <- cattrsetWalkNext rightWalk+      case (leftStep, rightStep) of+        (CAttrSetEntry leftName _ leftPtr leftRest, CAttrSetEntry rightName _ rightPtr rightRest) -> do+          held <- holds (leftName, Thunk leftPtr) (rightName, Thunk rightPtr)+          if held then go leftRest rightRest else pure False+        (CAttrSetDone, CAttrSetDone) -> pure True+        _ -> pure False++-- | Check key membership without materializing thunks.+attrSetMember :: (MonadCData m) => Text -> AttrSet -> m Bool+attrSetMember key attrs = do+  sym <- symbolIntern key+  attrSetMemberSymbol sym attrs++-- | Check if the attribute set is empty.+attrSetNull :: (MonadCData m) => AttrSet -> m Bool+attrSetNull (AttrSet cset) = (== 0) <$> cattrsetSize cset++-- | Number of attributes.+attrSetSize :: (MonadCData m) => AttrSet -> m Int+attrSetSize (AttrSet cset) = fromIntegral <$> cattrsetSize cset++-- | Full materialization: build a 'Map Text Thunk' from all entries.+-- Walks the set ('attrSetFoldM') and builds a Haskell Map.  Expensive+-- on large sets - avoid on the hot path.+attrSetToMap :: (MonadCData m) => AttrSet -> m (Map Text Thunk)+attrSetToMap = attrSetFoldM (\acc name entry -> pure (Map.insert (symbolText name) (entryThunk entry) acc)) Map.empty++-- | All thunk values (materialized).+attrSetElems :: (MonadCData m) => AttrSet -> m [Thunk]+attrSetElems attrs = Map.elems <$> attrSetToMap attrs++-- | Sorted key-value pairs (materialized).+attrSetToAscList :: (MonadCData m) => AttrSet -> m [(Text, Thunk)]+attrSetToAscList attrs = Map.toAscList <$> attrSetToMap attrs++-- | A set at a site binding each name of a set to what an action makes+-- of the name and its value, as upstream's @mapAttrs@ builds its result+-- (@prim_mapAttrs@ in primops.cc): the action runs on each attribute in+-- the order the set holds them ('attrSetFoldM'), and the result is sized+-- for the set and binds its names, each defined nowhere in source.  An+-- empty set gives 'emptyAttrSet', as upstream's @allocBindings@ answers+-- a size of 0 with its shared bindings (attr-set.cc).+attrSetMapWithKey :: (MonadCData m) => SetSite -> (Symbol -> Thunk -> m Thunk) -> AttrSet -> m AttrSet+attrSetMapWithKey site f attrs =+  attrSetSize attrs >>= \case+    0 -> pure emptyAttrSet+    size -> do+      mapped <- cattrsetNew site size+      attrSetFoldM (\() name entry -> f name (entryThunk entry) >>= cattrsetInsert mapped name noPos . unThunk) () attrs+      cattrsetFreeze mapped+      pure (AttrSet mapped)++-- | Remove a list of keys, returning a new CAttrSet made at a site.+-- Uses the C-side @nn_attrset_remove_keys@, which scans the keys for+-- each attribute.  Upstream+-- sizes the result for the set it removes from (@prim_removeAttrs@ in+-- primops.cc), so removing from an empty set gives 'emptyAttrSet' and+-- removing every attribute of another gives an empty set of its own.+-- Every key is interned either way, as upstream interns each name+-- whatever the set holds.+attrSetRemoveKeys :: (MonadCData m) => SetSite -> [Text] -> AttrSet -> m AttrSet+attrSetRemoveKeys site keys (AttrSet cset) = do+  syms <- mapM symbolIntern keys+  size <- cattrsetSize cset+  case size of+    0 -> pure emptyAttrSet+    _ -> AttrSet <$> cattrsetRemoveKeys site cset syms++-- | The set with no attributes: a C static ('cattrsetEmpty'), one address+-- for the life of the process, as upstream's @emptyBindings@ is one for+-- its evaluator (@EvalState@'s member in eval.hh at 2.24.9, a static of+-- @Bindings@ in attr-set.hh at 2.36.0).  Every set built with no attributes+-- is this one and is allocated nowhere, as upstream's @allocBindings@+-- answers a size of 0 with @emptyBindings@ (attr-set.cc), except a set+-- upstream sizes before it knows it holds nothing+-- ('attrSetFromSymbolEntriesSizedFor', 'attrSetRemoveKeys').  Upstream's+-- printers enter a set by its bindings, so which empty sets are this one+-- shows where a value is printed.+emptyAttrSet :: AttrSet+emptyAttrSet = AttrSet cattrsetEmpty++-- | Build a CAttrSet at a site from a Haskell 'Map' of attributes defined+-- nowhere in source, as those of a set a builtin makes from scratch are;+-- a builtin that copies attributes keeps their positions with+-- 'attrSetFromEntries'.  The keys are interned in name order, so a name+-- no symbol holds yet takes its place in every set by name; a builtin+-- that meets new names in an order of its own interns each where+-- upstream's does and builds with 'attrSetFromSymbols'.  An empty map+-- gives 'emptyAttrSet'.+attrSetFromMap :: (MonadCData m) => SetSite -> Map Text Thunk -> m AttrSet+attrSetFromMap site m = AttrSet <$> newFrozenAttrSet site symbolIntern (const noPos) id m++-- | 'attrSetFromMap' for attributes that keep the positions they were+-- defined at, as an attribute set literal's and a copied attribute's do.+attrSetFromEntries :: (MonadCData m) => SetSite -> Map Text AttrEntry -> m AttrSet+attrSetFromEntries site m = AttrSet <$> newFrozenAttrSet site symbolIntern entryPos entryThunk m++-- | 'attrSetFromMap' over names already interned.+attrSetFromSymbols :: (MonadCData m) => SetSite -> Map Symbol Thunk -> m AttrSet+attrSetFromSymbols site m = AttrSet <$> newFrozenAttrSet site pure (const noPos) id m++-- | 'attrSetFromEntries' over names already interned.+attrSetFromSymbolEntries :: (MonadCData m) => SetSite -> Map Symbol AttrEntry -> m AttrSet+attrSetFromSymbolEntries site m = AttrSet <$> newFrozenAttrSet site pure entryPos entryThunk m++-- | 'attrSetFromSymbolEntries' for a set upstream sizes, before it knows+-- what the set holds, for the given number of attributes, as it sizes a+-- literal for its names (@ExprAttrs::eval@ in eval.cc) and+-- @intersectAttrs@'s result for the smaller of its arguments+-- (@prim_intersectAttrs@ in primops.cc).  Upstream's @allocBindings@ shares+-- its empty set only for a size of 0 (attr-set.cc), so such a set holding+-- nothing is 'emptyAttrSet' when sized for none and an empty set of its own+-- otherwise.  A set holding attributes is made with room for those alone,+-- whatever the size.+attrSetFromSymbolEntriesSizedFor :: (MonadCData m) => SetSite -> Int -> Map Symbol AttrEntry -> m AttrSet+attrSetFromSymbolEntriesSizedFor site size m+  | Map.null m && size > 0 = ownEmptyAttrSet site+  | otherwise = attrSetFromSymbolEntries site m++-- | An empty set at a site that is not 'emptyAttrSet', made with room for+-- one entry: room for none asks @nn_attrset_new@ for its default room,+-- and is what the census counts as a set upstream would share.+ownEmptyAttrSet :: (MonadCData m) => SetSite -> m AttrSet+ownEmptyAttrSet site = do+  cset <- cattrsetNew site 1+  cattrsetFreeze cset+  pure (AttrSet cset)++-- | Insert every entry of a map into a new set at a site, under the+-- symbol, at the position and with the thunk the projections give it,+-- and freeze it; the shared empty set for an empty map.+{-# INLINE newFrozenAttrSet #-}+newFrozenAttrSet :: (MonadCData m) => SetSite -> (k -> m Symbol) -> (a -> PosIdx) -> (a -> Thunk) -> Map k a -> m CAttrSet+newFrozenAttrSet site symbolOf posOf thunkOf m+  | Map.null m = pure cattrsetEmpty+  | otherwise = do+      cset <- cattrsetNew site (Map.size m)+      forM_ (Map.toList m) $ \(key, entry) -> do+        sym <- symbolOf key+        cattrsetInsert cset sym (posOf entry) (unThunk (thunkOf entry))+      cattrsetFreeze cset+      pure cset++-- | Allocate a CAttrSet skeleton with keys only (NULL values), for an+-- environment's name table ('cattrsetFromNames').+-- Used for two-phase construction in @rec {}@ and @let@ (knot-tying):+-- keys are known before thunks, so the CAttrSet is built first, then+-- values are filled via 'fillCAttrSetValues'.  The table is never a+-- value, so its entries carry no position.  A table of no keys is the+-- shared empty set, which 'fillCAttrSetValues' finds no key in.+buildCAttrSetKeys :: (MonadCData m) => [Symbol] -> m FlatCAttrSet+buildCAttrSetKeys = cattrsetFromNames SetScope++-- | Fill values into a pre-allocated CAttrSet (two-phase construction).+-- Looks up each key's index and writes the CThunkPtr at that position.+-- A key the set does not hold has no entry to fill and is skipped.+fillCAttrSetValues :: (MonadCData m) => FlatCAttrSet -> Map Symbol Thunk -> m ()+fillCAttrSetValues cset thunkMap =+  forM_ (Map.toList thunkMap) $ \(sym, Thunk ptr) -> do+    midx <- cattrsetIndex cset sym+    case midx of+      Just idx -> cattrsetSetValue cset idx ptr+      Nothing -> pure ()++-- | Evaluation environment - C-backed scope chain.+--+-- An arena-allocated @nn_env_t@: a word holding its parent and slot+-- count or a header, its slots inline, then, after a header, its parent+-- when it has one and its name table and with-scopes when it has them+-- (@cbits/nn_env.h@).  Haskell holds only the pointer.  Each kind of+-- variable the resolver makes has one lookup:+--+-- * 'envLookupResolved': a single C call, for 'EResolvedVar'+-- * 'envLookup': a walk of the name tables on the parent chain, for 'EVar'+-- * 'envWithScopesRaw': the with-scopes an 'EWithVar' is looked up in,+--   innermost first+--+-- Two envs are equal when they are one C env, and 'show' gives its+-- address.  Neither reads the env.+newtype Env = Env (Ptr NnEnv)+  deriving (Eq, Show)++-- | Empty environment (no variables in scope): a C static, one address+-- for the life of the process.+emptyEnv :: Env+emptyEnv = Env cenvEmpty++-- | An env at a site holding the thunks in its slots, in order, under a+-- parent or none.  It sees its parent's with-scopes.+newEnv :: (MonadCData m) => EnvSite -> Maybe Env -> [Thunk] -> m Env+newEnv site parent thunks = do+  env <- newBlankEnv site parent (length thunks)+  fillSlots env thunks+  pure env++-- | An env at a site of empty slots under a parent or none, for+-- 'tieFrame' to fill.+newBlankEnv :: (MonadCData m) => EnvSite -> Maybe Env -> Int -> m Env+newBlankEnv site parent slotCount =+  Env <$> cenvNew site (fromIntegral slotCount) (parentPtr parent)++-- | An env at a site with no slots whose name table is a set, binding its+-- names, under a parent or none: the root env's builtins, scopedImport's+-- names over them, or the static names of a frame that also has dynamic+-- ones.+newScopeEnv :: (MonadCData m) => EnvSite -> Maybe Env -> AttrSet -> m Env+newScopeEnv site parent (AttrSet cset) =+  Env <$> cenvNewScoped site 0 (parentPtr parent) (castPtr cset) nullPtr 0++-- | The C pointer of a parent, NULL for none.+parentPtr :: Maybe Env -> Ptr NnEnv+parentPtr = maybe nullPtr (\(Env p) -> p)++-- | Look up a resolved variable by level and index: O(level) parent hops+-- in C, then a slot read, in one call.  A level or index outside the env,+-- or a slot a frame has not filled yet, raises+-- 'Nix.Eval.CStatus.CInvariantViolated' ('cenvLookupResolved').+envLookupResolved :: (MonadCData m) => Word32 -> Word32 -> Env -> m Thunk+envLookupResolved level idx (Env envPtr) = Thunk <$> cenvLookupResolved envPtr level idx++-- | Name-based variable lookup for 'EVar': the name's thunk in the first+-- name table on the parent chain, the env's own included, that binds it+-- to a filled entry; an entry not filled yet is passed over as if the+-- table did not bind the name.+-- Positional slots are not searched.  The resolver makes an 'EVar' only+-- of a name a frame's name table or the root env binds, and closure+-- trimming keeps the parent chain of every env an 'EVar' is evaluated in,+-- so the name is found unless the expression was built without the+-- resolver.+envLookup :: (MonadCData m) => Symbol -> Env -> m (Maybe Thunk)+envLookup name (Env envPtr) = walk envPtr+  where+    walk ep = do+      table <- cenvNameTable ep+      found <-+        if table == nullPtr+          then pure Nothing+          else attrSetLookupSymbol name (AttrSet (castPtr table))+      case found of+        Just thunk -> pure (Just thunk)+        Nothing -> cenvParent ep >>= up+    up parent+      | parent == nullPtr = pure Nothing+      | otherwise = walk parent++-- | Push a with-scope whose set is not evaluated yet onto the scope chain+-- (innermost position): the thunk that evaluates to it, tagged lazy+-- (bit 0 set) so that a lookup forces it on first use+-- ('resolveWithScopeAt').  Allocates a copy of the env, with a with-scopes+-- array one longer than the one it sees.+pushLazyWithScope :: (MonadCData m) => Thunk -> Env -> m Env+pushLazyWithScope (Thunk thunkPtr) (Env envPtr) =+  Env <$> cenvPushWith EnvWith envPtr (wordPtrToPtr (ptrToWordPtr (castPtr thunkPtr) .|. lazyWithScopeTag))++-- | @NN_ENV_LAZY_WITH@ of @cbits/nn_env.h@, and must stay in lockstep+-- with it: the bit that marks a with-scope entry as the thunk of a set+-- not yet evaluated, rather than the set.  A thunk cell is word-aligned,+-- so the bit is otherwise zero.+lazyWithScopeTag :: WordPtr+lazyWithScopeTag = 1++-- | The entry at an index of a with-scopes array ('envWithScopesRaw'):+-- 'Left' the thunk of a set not yet evaluated ('pushLazyWithScope'), or+-- 'Right' the set.+withScopeAt :: (MonadCData m) => Ptr (Ptr ()) -> Int -> m (Either Thunk AttrSet)+withScopeAt withArr idx = classify . ptrToWordPtr <$> cdataIO (peekElemOff withArr idx)+  where+    classify word+      | word .&. lazyWithScopeTag /= 0 = Left (Thunk (wordPtrToPtr (word .&. complement lazyWithScopeTag)))+      | otherwise = Right (AttrSet (wordPtrToPtr word))++-- | Replace a lazy with-scope entry with the set its thunk evaluated to,+-- so later lookups read the set directly.  Every env sharing the array+-- would evaluate the thunk to the same set.+resolveWithScopeAt :: (MonadCData m) => Ptr (Ptr ()) -> Int -> AttrSet -> m ()+resolveWithScopeAt withArr idx (AttrSet cset) = cenvResolveWith withArr (fromIntegral idx) (castPtr cset)++-- | The with-scopes an env sees, innermost first, and their count: those+-- of the first env on its parent chain, itself included, that has+-- with-scopes of its own (a with's env, or a trimmed closure's), or none.+envWithScopesRaw :: (MonadCData m) => Env -> m (Ptr (Ptr ()), Word32)+envWithScopesRaw (Env envPtr) = do+  owner <- cenvWithOwner envPtr+  if owner == nullPtr+    then pure (nullPtr, 0)+    else (,) <$> cenvWithScopes owner <*> cenvWithCount owner++-- | Compile an expression to bytecode, answering the index of its code.+-- Appends to the bytecode store; the same expression compiled twice+-- answers two indices running the same code.+compile :: (MonadCData m) => Expr -> m Word32+compile expr = cdataIO (compileExpr expr)++-- | 'compile' for parsed source, whose names are interned first, in the+-- order upstream's parser interns them ('compileParsed').+compileSource :: (MonadCData m) => ParsedSource -> m Word32+compileSource parsed = cdataIO (compileParsed parsed)++-- | Create an unevaluated thunk with a fresh C arena-allocated cell,+-- compiling the Expr to bytecode first.+mkThunk :: (MonadCData m) => Env -> Expr -> m Thunk+mkThunk env thunkExpr = compile thunkExpr >>= mkThunkBc env++-- | Like 'mkThunk' but makes no pending thunk for trivial expressions.+-- Resolved variables reuse the existing thunk from the env (no wrapper).+-- Literals use inline C scalars.+-- Lambdas compile formals+body to bytecode and produce VLambda directly.+-- Everything else falls back to 'mkThunk'.+cheapThunk :: (MonadCData m) => Env -> Expr -> m Thunk+cheapThunk env (EResolvedVar level idx) = envLookupResolved (fromIntegral level) (fromIntegral idx) env+cheapThunk _ (ELit (NixInt n)) = Thunk <$> cthunkNewComputedInt n+cheapThunk _ (ELit (NixFloat n)) = Thunk <$> cthunkNewComputedFloat n+cheapThunk _ (ELit (NixBool b)) = pure (Thunk (cthunkBool b))+cheapThunk _ (ELit NixNull) = pure (Thunk cthunkNull)+cheapThunk env (ELambda formals body captureInfo) = do+  closureEnv <- buildCaptureEnv EnvClosure env captureInfo+  bodyBcIdx <- compile body+  evalFormals <- cdataIO (compileFormalsToEval formals)+  evaluated (VLambda closureEnv evalFormals bodyBcIdx)+cheapThunk env expr = mkThunk env expr++-- | The env, at a site, that a closure made in an env runs in, by its+-- capture info: 'NoCaptureInfo' keeps the env as it is, 'Captures' makes+-- an env of the captured slots with no parent, and 'CapturesWithScopes'+-- gives that env the with-scopes the env it is made in sees as its own,+-- the same array ('cenvNewScoped').  When that env sees none, the+-- closure's with-variables are all under withs inside it, and its env is+-- the one 'Captures' makes.+buildCaptureEnv :: (MonadCData m) => EnvSite -> Env -> CaptureInfo -> m Env+buildCaptureEnv _ env NoCaptureInfo = pure env+buildCaptureEnv site env (Captures captureList) = captureListEnv site env NoWithScopes captureList+buildCaptureEnv site env (CapturesWithScopes captureList) = captureListEnv site env EnclosingWithScopes captureList++-- | 'buildCaptureEnv' for capture info the bytecode holds: each captured+-- slot is filled as its pair is read from the data buffer.+buildBcCaptureEnv :: (MonadCData m) => EnvSite -> Env -> BcCaptureInfo -> m Env+buildBcCaptureEnv _ env BcNoCaptureInfo = pure env+buildBcCaptureEnv site env (BcCaptures slots) = capturedSlotsEnv site env NoWithScopes slots+buildBcCaptureEnv site env (BcCapturesWithScopes slots) = capturedSlotsEnv site env EnclosingWithScopes slots++-- | The with-scopes the env of a closure's captured slots sees.+data CapturedScopes+  = -- | None ('Captures').+    NoWithScopes+  | -- | Those the env the closure is made in sees ('CapturesWithScopes').+    EnclosingWithScopes++-- | The env of a closure's captured slots, from a list of their pairs.+captureListEnv :: (MonadCData m) => EnvSite -> Env -> CapturedScopes -> [(Int, Int)] -> m Env+captureListEnv site env scopes captureList = do+  thunks <- capturedThunks env captureList+  captured <- newCaptureEnv site env scopes (length thunks)+  fillSlots captured thunks+  pure captured++-- | The env of a closure's captured slots, from their pairs in the data+-- buffer.+capturedSlotsEnv :: (MonadCData m) => EnvSite -> Env -> CapturedScopes -> BcCapturedSlots -> m Env+capturedSlotsEnv site env scopes slots@(BcCapturedSlots count _) = do+  captured@(Env capturedPtr) <- newCaptureEnv site env scopes count+  dest <- cenvSlots capturedPtr+  let fillSlot i level idx = do+        Thunk cell <- envLookupResolved level idx env+        cdataIO (pokeElemOff dest i cell)+        pure (i + 1)+  void (foldBcCapturedSlots fillSlot 0 slots)+  pure captured++-- | An env at a site of empty slots and no parent, for the slots a+-- closure made in an env captures from it, seeing the with-scopes+-- 'buildCaptureEnv' describes.+newCaptureEnv :: (MonadCData m) => EnvSite -> Env -> CapturedScopes -> Int -> m Env+newCaptureEnv site _ NoWithScopes slotCount = newBlankEnv site Nothing slotCount+newCaptureEnv site env EnclosingWithScopes slotCount = do+  (withArr, withCount) <- envWithScopesRaw env+  if withCount == 0+    then newBlankEnv site Nothing slotCount+    else Env <$> cenvNewScoped site (fromIntegral slotCount) nullPtr nullPtr withArr withCount++-- | The thunks a closure captures, read from the env it is made in by+-- their resolved level and index.+capturedThunks :: (MonadCData m) => Env -> [(Int, Int)] -> m [Thunk]+capturedThunks env = mapM (\(lvl, idx) -> envLookupResolved (fromIntegral lvl) (fromIntegral idx) env)++-- | A pending thunk running the code at a bytecode index in an env: a+-- fresh PENDING cell holding the index and the env's C pointer, neither+-- of them on the GHC heap.  Forcing the t'Thunk' runs the code in that+-- env.  The env's slots need not be filled yet: 'tieFrame' builds a+-- recursive frame's env before the thunks that point at it and fills its+-- slots after.+mkThunkBc :: (MonadCData m) => Env -> Word32 -> m Thunk+mkThunkBc (Env envPtr) bcIdx = Thunk <$> cthunkNewBc bcIdx (castPtr envPtr)++-- | A pending thunk applying the function in one cell to the argument in+-- another when it is forced, as upstream's app value does (@mkApp@,+-- value.hh at 2.24.9): a fresh PENDING cell holding the two cells, which+-- live in the env pages, and no env.  Unlike an app value, which upstream+-- never blackholes, the cell is blackholed while it is forced, as every+-- pending cell is.+mkApplyThunk :: (MonadCData m) => Thunk -> Thunk -> m Thunk+mkApplyThunk (Thunk fn) (Thunk arg) = Thunk <$> cthunkNewApply1 fn arg++-- | 'mkApplyThunk' applying the function to a first argument and the+-- result to a second, as upstream's @mapAttrs@ and @zipAttrsWith@ nest+-- two app values.  The inner application's result is not kept, where+-- upstream's inner app value holds it once forced, so a force retried+-- after a failure applies the function to the first argument again.+mkApply2Thunk :: (MonadCData m) => Thunk -> Thunk -> Thunk -> m Thunk+mkApply2Thunk (Thunk fn) (Thunk first) (Thunk second) = Thunk <$> cthunkNewApply2 fn first second++-- | What a pending thunk does when it is forced.+data Pending+  = -- | Run the code at a bytecode index in an env ('mkThunkBc').+    PendingCode !Env !Word32+  | -- | Apply the function in a cell to the argument in another+    -- ('mkApplyThunk').+    PendingApply !Thunk !Thunk+  | -- | Apply the function to the first argument and the result to the+    -- second ('mkApply2Thunk').+    PendingApply2 !Thunk !Thunk !Thunk++-- | What a PENDING or BLACKHOLE thunk does, as 'mkThunkBc' or+-- 'mkApplyThunk' and 'mkApply2Thunk' stored it.  Its instruction is read+-- first, so a code thunk, nearly every thunk forced, takes two reads:+-- its instruction and its env.+readPending :: (MonadCData m) => CThunkPtr -> m Pending+readPending ptr =+  cthunkGetBcIdx ptr >>= \case+    bcIdx+      | bcIdx /= noCode -> (\env -> PendingCode (Env (castPtr env)) bcIdx) <$> cthunkPayload ptr+      | otherwise ->+          cthunkPendingForm ptr >>= \case+            PendingApply1Form -> PendingApply <$> cell 0 <*> cell 1+            PendingApply2Form -> PendingApply2 <$> cell 0 <*> cell 1 <*> cell 2+            other -> cdataIO (cInvariantViolated "nn_thunk_pending_form" ("no pending application has form " ++ show other))+  where+    cell i = Thunk <$> cthunkApplyCell ptr i++-- | The cell a binding, a list element, a call's argument or a with's+-- scope holds for the code at a bytecode index in an env, as upstream's+-- @maybeThunk@ makes it (eval.cc).  A variable is its own cell, found by its+-- slot or, when the resolver left it to a name table, by its name+-- ('envLookup'), so the binding and the variable are one value, as @==@+-- shows of a function.  A constant is a cell of its value.  Anything else is+-- a pending thunk ('mkThunkBc'): a variable only a with supplies among them,+-- since upstream looks in no with until the variable is forced+-- (@EvalState::lookupVar@ in eval.cc), and a name no table binds, which+-- fails when the thunk is forced.+--+-- Every slot and name table the variable is read from must be filled: a+-- frame that is being tied makes its values with 'frameThunkBc'.+cheapThunkBc :: (MonadCData m) => Env -> Word32 -> m Thunk+cheapThunkBc = maybeThunkBc OwnSlotsFilled++-- | 'cheapThunkBc' for a value made in a frame that is being tied+-- ('tieFrame'), whose own slots are not filled yet: a variable naming one+-- of them is a thunk of its own, as upstream's @maybeThunk@ makes it for+-- a slot it has not filled (@ExprVar::maybeThunk@ in eval.cc).  The frame's+-- shares then give it the slot's cell where upstream's would have it+-- ('Nix.Eval.Compile.siblingShares').+frameThunkBc :: (MonadCData m) => Env -> Word32 -> m Thunk+frameThunkBc = maybeThunkBc OwnSlotsEmpty++-- | Whether the env a value is made in has filled its own slots: every+-- env has once it is built, but a frame that is being tied has not.+data OwnSlots = OwnSlotsFilled | OwnSlotsEmpty++-- | 'cheapThunkBc' and 'frameThunkBc', by whether the env's own slots+-- are filled.+maybeThunkBc :: (MonadCData m) => OwnSlots -> Env -> Word32 -> m Thunk+maybeThunkBc ownSlots env bcIdx =+  cbcOpcode bcIdx >>= \case+    OpResolvedVar ->+      cbcArg1 bcIdx >>= \case+        0 | OwnSlotsEmpty <- ownSlots -> mkThunkBc env bcIdx+        level -> cbcArg2 bcIdx >>= \idx -> envLookupResolved level idx env+    OpVar -> cbcArg1 bcIdx >>= \sym -> envLookup (Symbol sym) env >>= maybe (mkThunkBc env bcIdx) pure+    OpLitInt -> do+      w64 <- literalWord64 bcIdx+      Thunk <$> cthunkNewComputedInt (fromIntegral w64)+    OpLitFloat -> do+      w64 <- literalWord64 bcIdx+      Thunk <$> cthunkNewComputedFloat (castWord64ToDouble w64)+    OpLitBool -> do+      flag <- cbcShortArg bcIdx+      pure (Thunk (cthunkBool (flag /= 0)))+    OpLitNull -> pure (Thunk cthunkNull)+    OpLitUri -> Thunk <$> (cbcArg1 bcIdx >>= cbcString >>= cthunkNewComputedStr)+    OpStr ->+      literalStr bcIdx >>= \case+        Just str -> Thunk <$> cthunkNewComputedStr str+        Nothing -> mkThunkBc env bcIdx+    OpLitPath ->+      constantPathValue bcIdx >>= \case+        Just resolved -> Thunk <$> cthunkNewComputedPath resolved+        Nothing -> mkThunkBc env bcIdx+    OpList -> do+      empty <- emptyBcList bcIdx+      if empty+        then pure emptyListThunk+        else mkThunkBc env bcIdx+    _ -> mkThunkBc env bcIdx++-- | The one cell every empty list literal evaluates to, as upstream's+-- @vEmptyList@ is one value: a C static, like the @null@ cell, so it is+-- the same in every arena window.+emptyListThunk :: Thunk+emptyListThunk = Thunk cthunkEmptyList++-- | The 64 bits of an integer or float literal, split across the+-- instruction's two 32-bit arguments, low word first.+literalWord64 :: (MonadCData m) => Word32 -> m Word64+literalWord64 bcIdx = do+  lo <- cbcArg1 bcIdx+  hi <- cbcArg2 bcIdx+  pure (fromIntegral lo .|. (fromIntegral hi `shiftL` 32))++-- | The bytes of a path literal's value, when producing it is not work:+-- the literal's own in the code when they are already canonical, as they+-- are for any path written canonically, and a copy of the canonical form+-- otherwise.+--+-- Parsing resolves every relative path literal against the file's directory+-- ('Nix.Expr.Resolve.resolveRelativePaths'), so what reaches here is already+-- absolute and only wants the lexical canonicalisation every path value+-- carries.  The exception is a home-relative literal, which parsing leaves+-- alone: expanding it reads @HOME@, and that is an effect this cannot run.+constantPathValue :: (MonadCData m) => Word32 -> m (Maybe CStrPtr)+constantPathValue bcIdx = do+  code <- cbcArg1 bcIdx >>= cbcString+  text <- cstrText code+  let canonical = canonPathValue text+      held = if canonical == text then HeldStr code else NotHeld+  if T.isPrefixOf "~/" text+    then pure Nothing+    else Just <$> pathCell canonical held++-- | Whether a list expression has no elements, and so is the same empty list+-- however many times it is written.  Upstream hands back one shared+-- @vEmptyList@ for this rather than a thunk; here it is 'emptyListThunk'.+emptyBcList :: (MonadCData m) => Word32 -> m Bool+emptyBcList bcIdx = do+  (count, _) <- cbcCountedPayload bcIdx =<< cbcArg1 bcIdx+  pure (count == 0)++-- | The string a string expression makes when every part of it is+-- literal, or 'Nothing' when one is an interpolation and producing the+-- value is work.  A string with no interpolation is one literal part,+-- since the lexer joins a run of characters and escapes into one chunk,+-- and its value is that part's own string in the code, which the cell+-- points at rather than a copy, as upstream's @ExprString@ hands out the+-- value it holds (@ExprString::maybeThunk@ in eval.cc).+--+-- Upstream draws this line in the parser: a fully literal string folds into+-- an @ExprString@ carrying a ready-made value, and only a string with+-- interpolation survives as @ExprConcatStrings@.  The split is made here+-- instead by reading the parts back, because this compiler emits one opcode+-- for both shapes.+--+-- Deliberately not extended to @OpIndStr@, whose common indentation is+-- stripped during evaluation rather than in the parser, so its value is not+-- yet a constant at this point.  Upstream can treat one as a constant+-- because its parser has already done that stripping.+literalStr :: (MonadCData m) => Word32 -> m (Maybe CStrPtr)+literalStr bcIdx = do+  (count, dataOff) <- cbcCountedPayload bcIdx =<< cbcArg1 bcIdx+  partsLiteral count dataOff >>= \case+    False -> pure Nothing+    True+      | count == 1 -> Just <$> (cbcData (dataOff + 1) >>= cbcString)+      | otherwise -> Just <$> (partsBytes count dataOff >>= cstrNew . BS.concat)+  where+    -- Whether each of the parts, the count given from a data offset on,+    -- is a literal, read before any part is collected.  Each helper takes+    -- the offset as a strict argument rather than closing over it, so the+    -- offset is never boxed for a string that is not all literal.+    partsLiteral 0 !_ = pure True+    partsLiteral n !off =+      cbcData off >>= \case+        tag+          | tag == strpartLit -> partsLiteral (n - 1 :: Int) (off + 2)+          | otherwise -> pure False+    -- The bytes of each literal part, the count given from a data offset+    -- on.+    partsBytes 0 !_ = pure []+    partsBytes n !off = (:) <$> (cbcData (off + 1) >>= cbcStringBytes) <*> partsBytes (n - 1 :: Int) (off + 2)++-- | Wrap an already-computed value as a thunk.+-- Ints, floats and a builtin with no argument taken are inline in a new+-- cell; booleans and null are the shared static cells, as upstream hands+-- out one @vTrue@, @vFalse@ and @vNull@ (eval.cc at 2.24.9,+-- @EvalState::getBool@).  Every other value is a new cell pointing at its+-- C object, a string or a path over the bytes it holds or a copy of+-- them, and a partial application over a new object holding the cells+-- of its arguments.+evaluated :: (MonadCData m) => NixValue -> m Thunk+evaluated val =+  Thunk <$> case val of+    VInt n -> cthunkNewComputedInt n+    VFloat d -> cthunkNewComputedFloat d+    VBool b -> pure (cthunkBool b)+    VNull -> pure cthunkNull+    VAttrs (AttrSet cset) -> cthunkNewComputedAttrs (castPtr cset)+    VPathHeld p held -> pathCell p held >>= cthunkNewComputedPath+    VStrHeld t ctx held ->+      stringCell t ctx held >>= \case+        StrCell str -> cthunkNewComputedStr str+        CtxStrCell csptr -> cthunkNewComputedCtxStr (castPtr csptr)+    VList (CList clistPtr) -> cthunkNewComputedList (castPtr clistPtr)+    VLambda (Env envPtr) formals bodyBcIdx -> marshalLambda envPtr formals bodyBcIdx >>= cthunkNewComputedLambda+    VBuiltin builtin args ->+      primopCell builtin args >>= \case+        PrimopCell primop -> cthunkNewComputedPrimop primop+        PrimopAppCell app -> cthunkNewComputedPrimopApp (castPtr app)++-- | What a cell holding a builtin value holds.+data PrimopCell+  = -- | A builtin with no argument taken: its index, inline.+    PrimopCell !Word32+  | -- | A partial application.+    PrimopAppCell !CPrimopAppPtr++-- | The C form of a builtin value: its index, or a partial application+-- holding the cells of the arguments it has taken, an argument taken+-- forced in a new cell for its value and any other as the cell it is.+primopCell :: (MonadCData m) => Builtin -> [BuiltinArg] -> m PrimopCell+primopCell builtin [] = pure (PrimopCell (builtinIndex builtin))+primopCell builtin args = do+  cells <- traverse argumentCell args+  PrimopAppCell <$> cprimopAppNew (builtinIndex builtin) forced cells+  where+    argumentCell (ArgForced val) = unThunk <$> evaluated val+    argumentCell (ArgDeferred (Thunk cell)) = pure cell+    forced = foldl' (.|.) 0 [bit i | (i, ArgForced _) <- zip [0 ..] args]++-- | The C object a cell holding a string value points at.+data StringCell+  = -- | A context-free string's bytes.+    StrCell !CStrPtr+  | -- | A string with context.+    CtxStrCell !CCtxStrPtr++-- | The C object for a cell holding a string: the one its bytes are held+-- in, or a new one made from them.  A string with context held whole is+-- reused only while it still has context, and a context-free one only+-- while it is context-free, which is how a cell read gives them.+stringCell :: (MonadCData m) => ByteString -> StringContext -> HeldBytes -> m StringCell+stringCell bytes ctx held+  | ctx == emptyContext = StrCell <$> heldOr (cstrNew bytes) held+  | otherwise = case held of+      HeldCtxStr csptr -> pure (CtxStrCell csptr)+      _ -> CtxStrCell <$> marshalStringContext bytes ctx+  where+    heldOr _ (HeldStr str) = pure str+    heldOr make _ = make++-- | The C string for a cell holding a path: the one its bytes are held+-- in, or a copy of its text's bytes.+pathCell :: (MonadCData m) => Text -> HeldBytes -> m CStrPtr+pathCell _ (HeldStr str) = pure str+pathCell path _ = cstrFromText path++-- | Marshal Env + EvalFormals + body bc_idx to a C nn_lambda_t, which+-- holds each name as the symbol the formals hold.+marshalLambda :: (MonadCData m) => Ptr NnEnv -> EvalFormals -> Word32 -> m (Ptr ())+marshalLambda envPtr formals bodyBcIdx = case formals of+  EFName (Symbol nameSym) -> do+    lam <- clambdaNew envPtr bodyBcIdx FormalsName nameSym invalidSymbolId 0 0+    pure (castPtr lam)+  EFSet lambdaName entries allowExtra -> do+    let count = fromIntegral (length entries) :: Word32+        extraFlag = if allowExtra then 1 else 0 :: Word8+    lam <- clambdaNew envPtr bodyBcIdx FormalsSet invalidSymbolId (lambdaNameSymbol lambdaName) extraFlag count+    fillEntries lam 0 entries+    pure (castPtr lam)+  EFNamedSet lambdaName (Symbol nameSym) entries allowExtra -> do+    let count = fromIntegral (length entries) :: Word32+        extraFlag = if allowExtra then 1 else 0 :: Word8+    lam <- clambdaNew envPtr bodyBcIdx FormalsNamedSet nameSym (lambdaNameSymbol lambdaName) extraFlag count+    fillEntries lam 0 entries+    pure (castPtr lam)+  where+    fillEntries _ _ [] = pure ()+    fillEntries lam !idx (EvalFormal (Symbol nameSym) def : rest) = do+      let (kind, code) = formalDefaultWords def+      clambdaSetEntry lam idx nameSym kind code+      fillEntries lam (idx + 1) rest++-- | Read a C nn_lambda_t back into VLambda.+-- Reconstructs Env (newtype wrap), EvalFormals (each name the symbol the+-- closure holds), body bc_idx.+unmarshalLambdaValue :: (MonadCData m) => Ptr () -> m NixValue+unmarshalLambdaValue rawPtr = do+  let lamPtr = castPtr rawPtr+  envPtr <- clambdaEnv lamPtr+  bodyIdx <- clambdaBody lamPtr+  formalsType <- clambdaFormalsType lamPtr+  formals <- case formalsType of+    FormalsName -> EFName . Symbol <$> clambdaNameSym lamPtr+    FormalsSet -> do+      lambdaSym <- clambdaLambdaNameSym lamPtr+      count <- clambdaFormalCount lamPtr+      extra <- clambdaAllowExtra lamPtr+      entries <- readLambdaEntries lamPtr count+      pure (EFSet (lambdaNameFromSymbol lambdaSym) entries (extra /= 0))+    FormalsNamedSet -> do+      lambdaSym <- clambdaLambdaNameSym lamPtr+      nameSym <- clambdaNameSym lamPtr+      count <- clambdaFormalCount lamPtr+      extra <- clambdaAllowExtra lamPtr+      entries <- readLambdaEntries lamPtr count+      pure (EFNamedSet (lambdaNameFromSymbol lambdaSym) (Symbol nameSym) entries (extra /= 0))+    other -> cdataIO (cInvariantViolated "nn_lambda_formals_type" ("no lambda has formals type " ++ show other))+  pure (VLambda (Env envPtr) formals bodyIdx)+  where+    -- Zero-formal set patterns ({}:, { ... }:) store count 0 and a NULL+    -- entries array; count - 1 would underflow Word32.+    readLambdaEntries lamPtr count+      | count == 0 = pure []+      | otherwise = mapM (readOneEntry lamPtr) [0 .. count - 1]+    readOneEntry lamPtr idx = do+      nameSym <- clambdaEntryName lamPtr idx+      kind <- clambdaEntryHasDefault lamPtr idx+      code <- clambdaEntryDefault lamPtr idx+      case formalDefaultFromWords kind code of+        Just def -> pure (EvalFormal (Symbol nameSym) def)+        Nothing -> cdataIO (cInvariantViolated "nn_lambda_entry_kind" ("no formal has default kind " ++ show kind))++-- | Marshal payload bytes + StringContext to a C nn_ctxstr_t, each a+-- string's bytes: the payload as it is, and the StorePath and output-name+-- fields as their text's UTF-8.+marshalStringContext :: (MonadCData m) => ByteString -> StringContext -> m CCtxStrPtr+marshalStringContext textVal (StringContext ctxSet) = do+  text <- cstrNew textVal+  let elems = Set.toAscList ctxSet+      count = fromIntegral (length elems) :: Word32+  ptr <- cctxstrNew text count+  fillElems ptr 0 elems+  pure ptr+  where+    fillElems _ _ [] = pure ()+    fillElems ptr !idx (e : es) = do+      marshalElem ptr idx e+      fillElems ptr (idx + 1) es+    marshalElem eptr eidx (SCPlain (StorePath h n)) = do+      hash <- cstrFromText h+      name <- cstrFromText n+      cctxstrSetPlain eptr eidx hash name+    marshalElem eptr eidx (SCDrvOutput (StorePath h n) out) = do+      hash <- cstrFromText h+      name <- cstrFromText n+      output <- cstrFromText out+      cctxstrSetDrvOutput eptr eidx hash name output+    marshalElem eptr eidx (SCAllOutputs (StorePath h n)) = do+      hash <- cstrFromText h+      name <- cstrFromText n+      cctxstrSetAllOutputs eptr eidx hash name++-- | Unmarshal a C nn_ctxstr_t back to (payload bytes, StringContext).+unmarshalStringContext :: (MonadCData m) => CCtxStrPtr -> m (ByteString, StringContext)+unmarshalStringContext ptr = do+  textVal <- cctxstrText ptr >>= cstrBytes+  count <- cctxstrCtxCount ptr+  -- count - 1 underflows Word32 at 0 (defensive: marshal sites store+  -- only non-empty contexts).+  elems <-+    if count == 0+      then pure []+      else mapM (readElem ptr) [0 .. count - 1]+  pure (textVal, StringContext (Set.fromList elems))+  where+    readElem cptr idx =+      cctxstrElemTag cptr idx >>= \case+        ScePlain -> SCPlain <$> storePathAt cptr idx+        SceDrvOutput -> SCDrvOutput <$> storePathAt cptr idx <*> (cctxstrElemOutput cptr idx >>= cstrText)+        SceAllOutputs -> SCAllOutputs <$> storePathAt cptr idx+        other -> cdataIO (cInvariantViolated "nn_ctxstr_elem_tag" ("no string context element has tag " ++ show other))+    -- Raw construction (Nix.Store.Path.Internal): provenance-safe -+    -- these strings were made from a validated StorePath's own fields+    -- by marshalStringContext, so this is a round-trip, not a parse+    -- boundary.+    storePathAt cptr idx =+      StorePath+        <$> (cctxstrElemHash cptr idx >>= cstrText)+        <*> (cctxstrElemName cptr idx >>= cstrText)++-- | Tie a frame whose slots hold thunks that may point back at it: the+-- env of @slotCount@ empty slots under the parent, at the site given, is+-- allocated first, the thunks are made against it, and the slots are+-- filled last, as upstream allocates @env2@ before it fills the values+-- (@ExprLet::eval@, @ExprAttrs::eval@ and @EvalState::callFunction@,+-- eval.cc at 2.24.9).+-- @mkThunks@ answers one thunk per slot, in slot order, and must not+-- read the frame's own slots, which are not all filled until this+-- returns ('mkThunkBc' does not; 'envLookupResolved' refuses an unfilled+-- one).  Nothing is evaluated in the frame before then, which a with's+-- env relies on when it copies the slots of the env it is made in+-- ('pushLazyWithScope').  Answers the env and those thunks.+tieFrame :: (MonadCData m) => EnvSite -> Maybe Env -> Int -> (Env -> m [Thunk]) -> m (Env, [Thunk])+tieFrame site parent slotCount mkThunks = do+  env <- newBlankEnv site parent slotCount+  thunks <- mkThunks env+  fillSlots env (take slotCount thunks)+  pure (env, thunks)++-- | Give a slot of a frame 'tieFrame' has filled, and nothing has been+-- evaluated in, the cell another slot holds: the first slot's binding is+-- a variable naming the second, whose cell it shares.  Both slots are read+-- from bytecode, so one past the frame's slots, which only corrupt+-- bytecode holds, is handed to @pastFrame@ and nothing is written.+shareSlot :: (MonadCData m) => (Word32 -> m ()) -> Env -> Word32 -> Word32 -> m ()+shareSlot pastFrame (Env envPtr) slot target = cenvSlotCount envPtr >>= share+  where+    share slotCount+      | slot >= slotCount = pastFrame slot+      | target >= slotCount = pastFrame target+      | otherwise = do+          slots <- cenvSlots envPtr+          cdataIO (peekElemOff slots (fromIntegral target) >>= pokeElemOff slots (fromIntegral slot))++-- | The cells in an env's slots, the count given from slot 0.+envSlotCells :: (MonadCData m) => Env -> Int -> m [Thunk]+envSlotCells (Env envPtr) count = do+  slots <- cenvSlots envPtr+  cdataIO (map Thunk <$> peekArray count slots)++-- | Write thunks into an env's slots, first to last from slot 0.  There+-- are no more thunks than slots.+fillSlots :: (MonadCData m) => Env -> [Thunk] -> m ()+fillSlots (Env envPtr) thunks = do+  slots <- cenvSlots envPtr+  cdataIO (zipWithM_ (\i thunk -> pokeElemOff slots i (unThunk thunk)) [0 ..] thunks)++-- | A value's type as an error message names it: upstream's @showType@ on+-- a value (eval.cc at 2.24.9, the same in 2.33.2), which every type error+-- there uses.  It names a primop and the string context the type alone+-- does not show.  Upstream's other cases (a thunk, a black hole, a+-- function application, an external value) have no 'NixValue': a value+-- here is always forced, and there are no plugins.+typeName :: NixValue -> Text+typeName val = case val of+  VInt _ -> "an integer"+  VFloat _ -> "a float"+  VBool _ -> "a Boolean"+  VNull -> "null"+  VStr _ ctx+    | ctx == emptyContext -> "a string"+    | otherwise -> "a string with context"+  VPath _ -> "a path"+  VList _ -> "a list"+  VAttrs _ -> "a set"+  VLambda {} -> "a function"+  VBuiltin builtin [] -> "the built-in function '" <> builtinName builtin <> "'"+  VBuiltin builtin _ -> "the partially applied built-in function '" <> builtinName builtin <> "'"++-- | @builtins.typeOf@: the name of upstream's @ValueType@, the+-- classification its type checks compare (a lambda and a primop are both+-- @nFunction@).+typeOfValue :: NixValue -> Text+typeOfValue val = case val of+  VInt _ -> "int"+  VFloat _ -> "float"+  VBool _ -> "bool"+  VNull -> "null"+  VStr _ _ -> "string"+  VPath _ -> "path"+  VList _ -> "list"+  VAttrs _ -> "set"+  VLambda {} -> "lambda"+  VBuiltin _ _ -> "lambda"++-- ---------------------------------------------------------------------------+-- Evaluation monad+-- ---------------------------------------------------------------------------++-- | Upstream's @warn@ from its own code rather than an expression, which+-- its logger prefixes @warning:@ (@Logger::warn@ in logging.cc).+warnMessage :: (MonadEval m) => Text -> m ()+warnMessage = traceMessage . ("warning: " <>)++-- | What @builtins.pathExists@ asks of a path, decided from the+-- argument's spelling as upstream's @prim_pathExists@ decides it+-- (primops.cc at 2.24.9).+data PathExistence+  = -- | Whether an entry is there: the ancestors are resolved and the+    -- final component is checked in place, so a symlink exists whatever+    -- it points at (upstream's @SymlinkResolution::Ancestors@).+    ExistsAsEntry+  | -- | Whether a directory is there, asked by a string ending in @/@ or+    -- @/.@: every symlink is followed, the final one included+    -- (@SymlinkResolution::Full@), and a file answers false.+    ExistsAsDirectory+  deriving (Eq, Show)++-- | Effect class for Nix evaluation.  Core logic is polymorphic in @m@+-- so the same evaluator composes into t'PureEval' for tests or @IO@ for+-- real file-system access (e.g. @import@, @readFile@).  Every evaluator+-- runs the C data layer's actions in sequence with its own+-- ('MonadCData').+class (MonadCData m) => MonadEval m where+  -- | Raise an evaluation error (type error, missing attribute, IO+  -- failure).  NOT caught by @builtins.tryEval@: upstream Nix catches only+  -- ThrownError\/AssertionError there, and every other EvalError escapes.+  throwEvalError :: Text -> m a++  -- | Raise a catchable error - @builtins.throw@, a failed @assert@, and a+  -- search path lookup that matches no entry.  These are the only errors+  -- 'catchEvalError' (tryEval) recovers from.+  throwCatchableError :: Text -> m a++  -- | Abort evaluation (uncatchable by tryEval, matching real Nix).+  abortEvaluation :: Text -> m a++  -- | tryEval semantics: recover from a 'throwCatchableError'+  -- (throw, assert, a search path miss); eval errors and aborts propagate.+  catchEvalError :: m a -> m (Either Text a)++  -- | Run the action; when it fails with ANY evaluation failure+  -- (catchable throw, eval error, or abort), run the cleanup and let+  -- the failure propagate unchanged.  The error half of a bracket -+  -- success runs no cleanup - for builtins that hold external state+  -- (a scratch directory) across throwing calls.  'catchEvalError'+  -- cannot express this: it recovers only catchable throws, and a+  -- failed fetch is an eval error.+  onEvalError :: m a -> m () -> m a++  -- | @addEvaluatedTrace onFailedLine line action@ runs the action; a+  -- failure escaping it (a throw, an eval error or an abort) runs @line@+  -- for a line of context and gains that line outside the lines it+  -- already carries, as upstream's @Error::addTrace@ adds one where a+  -- @catch@ rethrows.  Nothing else about the failure changes: its message+  -- stays the same, and a throw stays catchable by @builtins.tryEval@.  The+  -- line is made only on failure.  When making it fails, the action's+  -- failure still escapes, and gains @onFailedLine@ of that failure's+  -- message as its line instead, as upstream rethrows the error it caught+  -- whatever evaluating its context does (@prim_addErrorContext@ in+  -- primops.cc at 2.36.0).+  addEvaluatedTrace :: (Text -> Text) -> m Text -> m a -> m a++  -- | Run an application one call frame deeper, or refuse it with+  -- upstream's "stack overflow; max-call-depth exceeded" when the frames+  -- already active exceed the ceiling ('Nix.Eval.CallDepth.enterCallFrame'+  -- is the rule).  An eval error, not a throw: upstream raises an+  -- EvalError, which its tryEval does not catch.  The frame ends with the+  -- action, on failure too, so an error unwinding through a tryEval+  -- leaves the count that tryEval was entered at.+  withCallFrame :: m a -> m a++  -- | Whether something is at the path, as @builtins.pathExists@ asks+  -- it; the query says how the final component is read.  A path the+  -- policy refuses is absent.+  doesPathExist :: PathExistence -> Text -> m Bool++  -- | List a directory, returning @(name, fileType)@ pairs.+  -- @fileType@ is one of @"regular"@, @"directory"@, @"symlink"@ or+  -- @"unknown"@ (matching Nix's @builtins.readDir@ semantics), and+  -- 'Nothing' for an entry whose lstat is refused with @EACCES@ or+  -- @EPERM@, which upstream's @readDirectory@ gives no type+  -- (posix-source-accessor.cc at 2.24.9).+  listDirectory :: Text -> m [(Text, Maybe Text)]++  importFile :: Text -> m NixValue++  -- | Look up an environment variable by the bytes of its name, answering+  -- the bytes of its value, or @""@ if unset.+  getEnvVar :: ByteString -> m ByteString++  -- | Get the current epoch time (seconds since 1970-01-01).+  getCurrentTime :: m Int64++  -- | Write a named file to the store at upstream's text-path+  -- (@text:\<refs\>@ scheme, flat sha256 of the contents), returning the+  -- canonical store path.  The contents are raw bytes (a Nix string's+  -- payload) - hashed and stored exactly as given.  The refs are the+  -- contents' plain store-path references; they participate in the path+  -- computation exactly as upstream's addTextToStore.+  writeToStore :: Text -> ByteString -> [StorePath] -> m Text++  -- | Import a file with a set's names bound over the builtins, each to+  -- its value in the set.+  scopedImportFile :: AttrSet -> Text -> m NixValue++  -- | Read raw bytes from a file.  Used by @builtins.hashFile@.+  readFileBytes :: Text -> m ByteString++  -- | Classify a single filesystem path as @"regular"@, @"directory"@,+  -- @"symlink"@, or @"unknown"@: an lstat of the path itself, refused+  -- when a symlink sits above it beneath the accessor's root (for a path+  -- in the store, beneath the store directory), as upstream's accessor+  -- refuses one.  Used by @builtins.readFileType@ and, on a resolved+  -- root, by the source tree walk.+  getFileType :: Text -> m Text++  -- | Follow every symlink in a path, as upstream's+  -- @SourcePath::resolveSymlinks@ does before a tree is read+  -- (@addPath@, @prim_filterSource@): no component of the result is a+  -- symlink, so the lstats of the walk that follows never meet one+  -- above the entry they classify.+  resolveSymlinks :: Text -> m Text++  -- | Run an external process: @(command, args, stdin) -> (exitCode, stdout, stderr)@.+  runProcess :: Text -> [Text] -> Text -> m (Int, Text, Text)++  -- | Create a fetcher scratch directory under the system temp dir: the+  -- given name prefix plus an unpredictable suffix, exclusively created.+  -- A fixed scratch name in the shared temp dir gives any other local+  -- process a pre-place\/swap window between creation and the store+  -- copy, so the name must be unguessable and creation must fail rather+  -- than adopt an existing directory.+  createScratchDir :: Text -> m Text++  -- | Recursively remove a directory 'createScratchDir' created.+  removeScratchDir :: Text -> m ()++  -- | Resolve a path literal to a canonical path.+  -- In IO evaluation, @~/@ resolves against the home directory and other+  -- relative paths resolve against the current file's directory+  -- (@esBaseDir@); this ensures that path values captured in closures+  -- remain valid after the import scope ends.  In pure evaluation the+  -- text is not absolutized.  Every implementation ends with lexical+  -- canonicalization ('Nix.Eval.CanonPath.canonPath'), as upstream: no+  -- dot segment or repeated separator survives into a path value.+  resolvePathLiteral :: Text -> m Text++  -- | Copy a path (file or directory) to the store, returning the store+  -- path.  Content-addressed like upstream addToStore: recursive NAR+  -- sha256 under the given name.  Arguments: how the copy came to be (a+  -- fetcher's, or @builtins.path@'s), source path, store name, and an+  -- optional sha256 pin as (expected digest, refusal): a copy whose+  -- digest is another fails before anything is written, with the refusal+  -- of the digest it has.  @builtins.path@ and @builtins.fetchTarball@+  -- share this pin.+  copyPathToStore :: PendingOrigin -> Text -> Text -> Maybe (ByteString, ByteString -> Text) -> m Text++  -- | Recursive NAR sha256 digest of a path, without copying it anywhere.+  -- Used by @builtins.fetchGit@ to report @narHash@.+  narHashOfPath :: Text -> m ByteString++  -- | Whether a regular file carries the executable bit (NAR encodes it).+  isExecutableFile :: Text -> m Bool++  -- | Mark a regular file executable (mode bit on Unix, an alternate data+  -- stream on Windows). Run before the tree is copied to the store.+  setExecutableFile :: Text -> m ()++  -- | Look up a previously recorded fetch by a key naming exactly what was+  -- fetched. 'Nothing' when nothing readable was recorded.  A record is+  -- answered whether or not what it names is still on disk, which the+  -- caller asks with 'adoptStorePath'.+  lookupFetchCache :: Text -> m (Maybe Text)++  -- | Take over a store path an earlier evaluation wrote: 'True' when it is+  -- still there, on disk or in a store that takes writes as they are made,+  -- and recorded as this evaluation's own store write in that case.+  -- Reusing a path instead of rewriting it must still leave the+  -- registration behind, or the build driver never registers it and a+  -- derivation naming it fails with \"path \'...\' is not valid\".+  adoptStorePath :: Text -> m Bool++  -- | Whether the session's store already holds the path a pinned fetch+  -- names, admitting it as a fetch result is admitted when it does:+  -- upstream's early exit, which then neither downloads nor writes+  -- (@fetch@ in fetchTree.cc at 2.24.9).+  pinnedFetchHeld :: StorePath -> m Bool++  -- | Record a fetch under that key. Failing to record is not an error -+  -- the cache is an optimisation.+  writeFetchCache :: Text -> Text -> m ()++  -- | Read a symlink's target WITHOUT following it.+  readSymlinkTarget :: Text -> m Text++  -- | Unpack a serialized NAR into the store under the given name at its+  -- canonical recursive fixed-output path (sha256 of the bytes),+  -- returning the store path text.  Used by @builtins.path@ and+  -- @builtins.filterSource@ with a filter, whose filtered tree exists+  -- only as a NAR value and never on the source filesystem.+  addSourceNar :: Text -> ByteString -> m Text++  -- | Write raw bytes to the store at a canonical flat fixed-output path+  -- (@makeFixedOutputPath name "sha256" FlatIngestion@), so a hash-pinned+  -- fetch lands at the same store path C++ Nix computes - reproducible and+  -- cacheable.  The origin says whether a fetcher or @builtins.path@+  -- wrote them.+  addFixedOutputFile :: PendingOrigin -> Text -> ByteString -> m Text++  -- | A URL's body, whole: a @file:\/\/@ URL's file as it is on disk+  -- ('Nix.Eval.Policy.fileUrlPath'), any other URL through the transfer+  -- layer every download goes through ("Nix.Http"), a transient failure+  -- retried as the session's policy says, or why it could not be read.+  fetchUrlBytes :: Text -> m (Either Text ByteString)++  -- | The archive a URL serves, unpacked as upstream's tarball fetcher+  -- unpacks one and added to the store under the name, as its store+  -- path.  The tree's NAR is held to the pin, when there is one, before+  -- anything is written; one that differs fails with the message the+  -- given function makes of the digest it has.+  fetchArchiveToStore :: Text -> Text -> Maybe (ByteString, ByteString -> Text) -> m (Either FetchFailure Text)++  -- | Report a trace/warning message.+  -- IO evaluators tell their session's logger; pure evaluators silently+  -- discard.+  traceMessage :: Text -> m ()++  -- | Force a thunk to a value, with memoization.+  -- IO evaluators store the value in the thunk's C cell; pure+  -- evaluators re-evaluate each time.+  -- The first argument runs what a pending thunk holds ('readPending'),+  -- passed in to break the Eval.Types to Eval circular dependency.+  forceThunk :: (Pending -> m NixValue) -> Thunk -> m NixValue++  -- | Look up a cached derivation modulo-hash (hex) by its @.drv@ store+  -- path.  Populated bottom-up as each derivation is computed; used by the+  -- derivation-hash algorithm to substitute input derivations.  Pure+  -- evaluators have no cache and always return 'Nothing'.+  lookupDrvHash :: Text -> m (Maybe Text)++  -- | Cache a derivation's modulo hash (hex) under its @.drv@ store path.+  -- A no-op in pure evaluators (no memoization).+  cacheDrvHash :: Text -> Text -> m ()++  -- | Record a derivation's serialized @.drv@ ATerm (the exact bytes whose+  -- hash is its store path) under its @.drv@ store path, as each derivation+  -- is computed (bottom-up).  Unlike 'cacheDrvHash' (which stores only the+  -- modulo hash), this retains the full ATerm so the build driver can+  -- materialize the entire input-@.drv@ closure to the store before a+  -- dependency-aware build.  A no-op in pure evaluators.+  recordDrvAterm :: Text -> ByteString -> m ()++  -- | Read and parse a derivation from its @.drv@ in the store, or 'Nothing'+  -- if it is absent or unreadable.  Used to resolve an input derivation's+  -- modulo hash on a cache miss - a cross-session reference, or a path+  -- fabricated by @builtins.appendContext@ - where the referenced derivation+  -- was not evaluated this session.  Reading the store is an effect, so this+  -- is an IO-evaluator capability: pure evaluators return 'Nothing', which+  -- makes hashing a dependent derivation something only the IO evaluator can do.+  readStoreDerivation :: StorePath -> m (Maybe Derivation)++  -- | Look up a derivation evaluated earlier THIS session by its @.drv@ store+  -- path, or 'Nothing' if it was not.  The IO evaluator reads the ATerm it+  -- recorded bottom-up ('recordDrvAterm'); pure evaluators return 'Nothing'.+  -- Used to recover a referenced derivation's output names for an all-outputs+  -- (DrvDeep) context reference without a disk read - the in-session @.drv@ is+  -- not on disk during evaluation.+  lookupSessionDrv :: Text -> m (Maybe Derivation)++  -- | The references recorded when this session wrote a store path (a+  -- @builtins.toFile@'s text with context, a copied source's none), or+  -- 'Nothing' if this session did not write it.  The walk of a+  -- @drvPath@'s closure follows them as upstream's @computeFSClosure@+  -- follows its database's.  Pure evaluators write nothing.+  lookupSessionReferences :: StorePath -> m (Maybe [StorePath])++  -- | Realise a string's context before a path reader reads the path it+  -- spells, as upstream's @EvalState::realiseContext@ does: every path it+  -- names found valid or made so, and every output it names built or+  -- substituted, or why that cannot be ("Nix.Eval.RealiseContext").  Pure+  -- evaluators have no store and realise nothing.+  realiseContext :: StringContext -> m (Either ContextRefusal ())++  -- | Compute the store path a source file/directory gets when copied into+  -- the store (recursive NAR sha256 to a fixed-output path named by the+  -- path's base name), WITHOUT performing the copy.  Used when a path+  -- literal is coerced in a derivation argument or environment value.  Pure+  -- evaluation has no store, so a path there answers itself.+  storeSourcePath :: Text -> m Text++  -- | The policy this evaluation runs under.  The builtins whose behaviour+  -- upstream changes by setting consult it: @storePath@ is refused and the+  -- fetchers demand a hash or revision under @pure-eval@, a search path+  -- miss is worded for the mode, and @traceVerbose@ traces only under+  -- @trace-verbose@.  The filesystem and URI gates are not decided here;+  -- they live in the instance, where the allowed set is.+  evalPolicy :: m EvalPolicy++  -- | Upstream @checkURI@: refuse a fetch of this URI under @restrict-eval@+  -- unless @allowed-uris@ admits it (a path or @file://@ URI is checked+  -- against the allowed paths instead).  A no-op under any other policy.+  -- Every fetcher calls it before anything is spawned or downloaded.+  checkUri :: Text -> m ()++  -- | A path named on the drive this evaluation reads it on+  -- ('Nix.Store.Path.qualifyPathText' against its store directory): on+  -- Windows a rooted path with no drive gains the store's.  For a+  -- fetcher handing a local path to another program, which would+  -- otherwise read it on whatever drive that program has current.+  qualifyPath :: Text -> m Text++-- | Unwrap the result of a construction that makes a store path (the+-- @makeStorePath@ family in "Nix.Hash", and the @.drv@ files of+-- "Nix.Derivation"), raising a refused name as upstream's @BadStorePath@+-- text.  The message names the path and not the builtin, as upstream's+-- does: upstream names the builtin in its trace.  Every eval-side path+-- construction goes through this, so a refused name is an eval error+-- before anything is written.+storePathOrThrow :: (MonadEval m) => Either BadStorePath a -> m a+storePathOrThrow = either (throwEvalError . badStorePathText) pure++-- | 'addEvaluatedTrace' with a line that is already made, which cannot+-- fail.+addErrorTrace :: (MonadEval m) => Text -> m a -> m a+addErrorTrace line = addEvaluatedTrace (const line) (pure line)++-- | Error raised during pure evaluation.  'PThrow' (@builtins.throw@, a+-- failed @assert@) is the only kind @tryEval@ catches; 'PError' (type+-- errors, missing attributes) and 'PAbort' (@abort@, infinite recursion)+-- escape it, exactly as in C++ Nix.+data PureError = PThrow !Text | PError !Text | PAbort !Text++-- | Pure evaluation monad: given the call depth, a t'CData' action+-- answering @Either PureError@, so its only effect is the C data layer.+-- IO builtins (@builtins.readFile@, @import@) are unavailable, and+-- everything else evaluates identically to the IO version, the+-- @max-call-depth@ ceiling included, at its upstream default.  It carries+-- no filesystem policy: there is no filesystem, environment or network+-- behind it to gate, so it reports 'unrestrictedPolicy' and every URI+-- check passes.  It writes no cell it did not allocate but a builtin's+-- static cell, which it fills with the one value that cell ever holds+-- ('Nix.Eval.CThunk.cthunkPrimop'): a force reads a thunk and evaluates+-- it without memoizing, so it marks no blackhole either.+newtype PureEval a = PureEval (CallDepth -> CData (Either PureError a))++instance Functor PureEval where+  fmap f (PureEval run) = PureEval (fmap (fmap f) . run)++instance Applicative PureEval where+  pure a = PureEval (\_ -> pure (Right a))+  PureEval runF <*> PureEval runA = PureEval $ \depth ->+    runF depth >>= either (pure . Left) (\f -> fmap f <$> runA depth)++instance Monad PureEval where+  PureEval run >>= k = PureEval $ \depth ->+    run depth >>= either (pure . Left) (\a -> runPure (k a) depth)++instance MonadCData PureEval where+  liftCData act = PureEval (\_ -> Right <$> act)++-- | A pure evaluation run at a call depth.+runPure :: PureEval a -> CallDepth -> CData (Either PureError a)+runPure (PureEval run) = run++-- | Fail a pure evaluation.+pureFailure :: PureError -> PureEval a+pureFailure failure = PureEval (\_ -> pure (Left failure))++-- | Run a pure evaluation, flattening the internal error into 'Text': a+-- failure's message, as t'Nix.Eval.IO.EvalIO' reports it.  The run is a+-- value ('runCDataPure'): the evaluation writes only cells it allocates,+-- the with-scope entries it resolves ("Nix.Eval.CData" says what two+-- runs resolving one entry can show) and the builtins' static cells it+-- binds.+runPureEval :: PureEval a -> Either Text a+runPureEval action =+  case runCDataPure (runPure action (topLevelCallDepth defaultMaxCallDepth)) of+    Right a -> Right a+    Left (PThrow t) -> Left t+    Left (PError t) -> Left t+    Left (PAbort t) -> Left t++instance MonadEval PureEval where+  throwEvalError = pureFailure . PError+  throwCatchableError = pureFailure . PThrow+  abortEvaluation = pureFailure . PAbort++  -- Catch only a throw/assert (tryEval sees the error); eval errors,+  -- aborts, and infinite recursion propagate, matching EvalIO and C++ Nix.+  catchEvalError (PureEval action) = PureEval (fmap caught . action)+    where+      caught (Left (PThrow t)) = Right (Left t)+      caught (Left other) = Left other+      caught (Right a) = Right (Right a)++  -- Pure evaluation has no external state, so there is nothing to+  -- clean up; the failure passes through unchanged.+  onEvalError (PureEval action) _ = PureEval action++  -- 'runPureEval' reports a failure's message alone, so a line of context+  -- has nowhere to go.  The line is still made, since a failure making it+  -- replaces the action's.+  -- A pure failure carries no trace: the line is made, as upstream makes+  -- it, and the action's failure escapes whatever making it does.+  addEvaluatedTrace _ (PureEval line) (PureEval action) =+    PureEval $ \depth ->+      action depth >>= \case+        Left failure -> Left failure <$ line depth+        Right a -> pure (Right a)++  -- The reader scopes the frame: the action runs one deeper, and whatever+  -- follows it sees the depth it started from, failure or not.+  withCallFrame (PureEval action) =+    PureEval $ \depth -> either (pure . Left . PError) action (enterCallFrame depth)+  doesPathExist _ _ = pure False+  listDirectory _ = throwEvalError "builtins.readDir: not available in pure evaluation"+  importFile _ = throwEvalError "import: not available in pure evaluation"+  getEnvVar _ = pure ""+  getCurrentTime = pure 0+  writeToStore _ _ _ = throwEvalError "toFile: not available in pure evaluation"+  scopedImportFile _ _ = throwEvalError "scopedImport: not available in pure evaluation"+  readFileBytes _ = throwEvalError "readFile: not available in pure evaluation"+  getFileType _ = throwEvalError "readFileType: not available in pure evaluation"++  -- No filesystem, so no symlinks: a path resolves to itself.+  resolveSymlinks = pure+  runProcess _ _ _ = throwEvalError "runProcess: not available in pure evaluation"+  createScratchDir _ = throwEvalError "createScratchDir: not available in pure evaluation"+  removeScratchDir _ = pure ()+  copyPathToStore _ _ _ _ = throwEvalError "builtins.path: not available in pure evaluation"+  narHashOfPath _ = throwEvalError "builtins.fetchGit: not available in pure evaluation"+  isExecutableFile _ = throwEvalError "builtins.path: not available in pure evaluation"+  setExecutableFile _ = throwEvalError "builtins.fetchGit: not available in pure evaluation"+  lookupFetchCache _ = pure Nothing+  adoptStorePath _ = pure False+  pinnedFetchHeld _ = pure False+  writeFetchCache _ _ = pure ()+  readSymlinkTarget _ = throwEvalError "builtins.path: not available in pure evaluation"+  addSourceNar _ _ = throwEvalError "builtins.path: not available in pure evaluation"+  addFixedOutputFile _ _ _ = throwEvalError "builtins.fetchurl: not available in pure evaluation"+  fetchUrlBytes _ = throwEvalError "builtins.fetchurl: not available in pure evaluation"+  fetchArchiveToStore _ _ _ = throwEvalError "builtins.fetchTarball: not available in pure evaluation"+  traceMessage _ = pure ()+  lookupDrvHash _ = pure Nothing+  cacheDrvHash _ _ = pure ()+  recordDrvAterm _ _ = pure ()++  -- Pure eval cannot read the store, so a dependent derivation's input hash+  -- is never recoverable here; the caller turns this into a loud error rather+  -- than a guessed hash.+  readStoreDerivation _ = pure Nothing++  -- Pure eval keeps no session drv closure, so an all-outputs reference's+  -- output names are never recoverable here either.+  lookupSessionDrv _ = pure Nothing+  lookupSessionReferences _ = pure Nothing+  realiseContext _ = pure (Right ())++  -- Pure eval cannot read files: a path coerces to itself (no store copy);+  -- the real copy-to-store happens only under 'EvalIO'.+  storeSourcePath = pure+  evalPolicy = pure unrestrictedPolicy+  checkUri _ = pure ()++  -- No filesystem, so no drive to read on: a path names itself.+  qualifyPath = pure+  resolvePathLiteral = pure . canonPathValue++  -- Reads the cell and never writes it: no memoization, and no+  -- blackhole, so PureEval may force the same thunk again.+  forceThunk evalFn (Thunk ptr) =+    cthunkState ptr >>= \case+      ThunkComputed -> readComputed ptr+      -- Non-catchable: must escape tryEval like in C++ Nix+      ThunkBlackhole -> abortEvaluation "infinite recursion encountered"+      _ {- PENDING -} -> readPending ptr >>= evalFn
+ src/Nix/ExperimentalFeature.hs view
@@ -0,0 +1,146 @@+-- | Upstream's experimental features: the names its+-- @experimental-features@ setting takes (experimental-features.cc at+-- 2.36.0), the set a configuration enables, and the refusal of what needs+-- a feature that is off.+--+-- A feature is one upstream knows by name; a name it does not know is+-- dropped from the set with a warning, as upstream's setting parses it+-- (configuration.cc).  nova-nix implements few of them: a feature turned+-- on is held whatever nova-nix does with it, so a check reads the set as+-- upstream's would.+module Nix.ExperimentalFeature+  ( -- * Features+    ExperimentalFeature,+    featureName,+    flakesFeature,+    verifiedFetchesFeature,++    -- * Sets+    FeatureSet,+    noFeatures,+    featureEnabled,+    parseFeatures,+    replaceFeatures,+    addFeatures,+    featureSetWarnings,++    -- * Refusals+    requireFeature,+    missingFeatureMessage,+  )+where++import Data.ByteString (ByteString)+import qualified Data.ByteString.Char8 as BC+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text.Encoding as TE+import Data.Text.Encoding.Error (lenientDecode)++-- | A feature upstream knows, by its name.  The constructor is not+-- exported: a feature is one of 'knownFeatureNames'.+newtype ExperimentalFeature = ExperimentalFeature Text+  deriving (Eq, Ord, Show)++-- | A feature's name, as the setting spells it.+featureName :: ExperimentalFeature -> Text+featureName (ExperimentalFeature name) = name++-- | The names of upstream's features (@xpFeatureDetails@ in+-- experimental-features.cc at 2.36.0).+knownFeatureNames :: Set Text+knownFeatureNames =+  Set.fromList+    [ "ca-derivations",+      "impure-derivations",+      "flakes",+      "fetch-tree",+      "nix-command",+      "git-hashing",+      "recursive-nix",+      "fetch-closure",+      "auto-allocate-uids",+      "cgroups",+      "dynamic-derivations",+      "parse-toml-timestamps",+      "read-only-local-store",+      "local-overlay-store",+      "configurable-impure-env",+      "mounted-ssh-store",+      "verified-fetches",+      "pipe-operators",+      "external-builders",+      "blake3-hashes"+    ]++-- | @flakes@: flake references and the fetchers only flakes use.+flakesFeature :: ExperimentalFeature+flakesFeature = ExperimentalFeature "flakes"++-- | @verified-fetches@: a Git input's commit signature attributes.+verifiedFetchesFeature :: ExperimentalFeature+verifiedFetchesFeature = ExperimentalFeature "verified-fetches"++-- | The name a feature had before upstream stabilized it as a setting,+-- which the setting refuses with a warning naming the setting.+stabilizedUrlLiterals :: Text+stabilizedUrlLiterals = "no-url-literals"++-- | The features a configuration enables, and the warnings parsing its+-- values gave, in the order given, which the caller reports once the+-- configuration is read.+data FeatureSet = FeatureSet+  { fsFeatures :: !(Set ExperimentalFeature),+    fsWarnings :: ![Text]+  }+  deriving (Eq, Show)++-- | No feature, upstream's default.+noFeatures :: FeatureSet+noFeatures = FeatureSet Set.empty []++-- | Whether a feature is on.+featureEnabled :: ExperimentalFeature -> FeatureSet -> Bool+featureEnabled feature = Set.member feature . fsFeatures++-- | The warnings parsing the set's values gave.+featureSetWarnings :: FeatureSet -> [Text]+featureSetWarnings = fsWarnings++-- | Parse a value as upstream's setting parses one: its whitespace+-- separated names as a set, so a repeated name counts once and the names+-- are read in byte order, each it does not know dropped with a warning.+parseFeatures :: ByteString -> FeatureSet+parseFeatures value = foldr add noFeatures (Set.toAscList names)+  where+    names = Set.fromList (filter (not . BC.null) (BC.splitWith (`elem` separators) value))+    separators = " \t\n\r" :: String+    add raw (FeatureSet features warnings)+      | name `Set.member` knownFeatureNames = FeatureSet (Set.insert (ExperimentalFeature name) features) warnings+      | name == stabilizedUrlLiterals =+          FeatureSet features (("experimental feature '" <> name <> "' has been stabilized and renamed; use 'lint-url-literals = fatal' setting instead") : warnings)+      | otherwise = FeatureSet features (("unknown experimental feature '" <> name <> "'") : warnings)+      where+        name = TE.decodeUtf8With lenientDecode raw++-- | An assignment of the setting: its features replace the set's, and+-- its warnings follow the set's.+replaceFeatures :: FeatureSet -> FeatureSet -> FeatureSet+replaceFeatures (FeatureSet _ earlier) (FeatureSet features warnings) = FeatureSet features (earlier ++ warnings)++-- | An @extra-@ assignment: its features join the set's.+addFeatures :: FeatureSet -> FeatureSet -> FeatureSet+addFeatures (FeatureSet held earlier) (FeatureSet features warnings) = FeatureSet (Set.union held features) (earlier ++ warnings)++-- | Refuse what needs a feature that is off, in upstream's words.+requireFeature :: ExperimentalFeature -> FeatureSet -> Either Text ()+requireFeature feature set+  | featureEnabled feature set = Right ()+  | otherwise = Left (missingFeatureMessage feature)++-- | Upstream's refusal of what needs a feature that is off+-- (@MissingExperimentalFeature@ in experimental-features.cc).+missingFeatureMessage :: ExperimentalFeature -> Text+missingFeatureMessage feature =+  "experimental Nix feature '" <> featureName feature <> "' is disabled; add '--extra-experimental-features " <> featureName feature <> "' to enable it"
src/Nix/Expr/ClosureTrim.hs view
@@ -9,11 +9,13 @@ -- build a flat env with @envParent = Nothing@, breaking the retention -- chain. ----- A scope is trimmable when its body contains only 'EResolvedVar'--- references to outer scopes (no 'EVar' that resolves through the--- parent chain).  Scopes with outer 'EVar' references (with-scope--- lookups, non-positional bindings) cannot be trimmed because those--- require walking the full parent chain at runtime.+-- A scope is trimmed when it holds no 'EVar' and makes at least one+-- reference to an outer scope, each an 'EResolvedVar' or an 'EWithVar'.+-- An 'EVar' (a name a frame's name table or the root environment binds)+-- is found by walking the parent chain at runtime, so a scope holding one,+-- even one a frame inside the scope binds, keeps its chain and is not+-- trimmed; so does a scope with no outer reference.  An 'EWithVar' needs+-- only the with-scopes, which a trimmed scope keeps ('CapturesWithScopes'). module Nix.Expr.ClosureTrim   ( trimClosures,   )@@ -109,7 +111,7 @@     EAssert (trimExpr cond) (trimExpr body)   EUnary op operand -> EUnary op (trimExpr operand)   EBinary op l r -> EBinary op (trimExpr l) (trimExpr r)-  ESearchPath {} -> expr+  EPos {} -> expr  trimPart :: StringPart -> StringPart trimPart p@(StrLit _) = p@@ -169,12 +171,11 @@ -- Returns @(freeVars, hasOuterEVar, hasOuterWithVar)@ where: -- * @freeVars@ is the set of @(level, index)@ pairs for 'EResolvedVar' --   references that point outside the lambda (level > current depth)--- * @hasOuterEVar@ is 'True' if there's any 'EVar' that could reference---   the outer scope (not shadowed by inner let/rec/lambda scopes)+-- * @hasOuterEVar@ is 'True' if there's any 'EVar' in the body, whatever+--   binds it -- * @hasOuterWithVar@ is 'True' if there's any 'EWithVar' that needs --   with-scope access (doesn't block trimming, but env must preserve---   its with-scopes ('Nix.Eval.Types.envWithScopesRaw') with builtins---   appended)+--   its with-scopes ('Nix.Eval.Types.envWithScopesRaw')) -- -- @depth@ tracks how many scope-creating constructs we've entered -- inside the lambda body (nested lambdas, let, rec attrs).@@ -264,7 +265,7 @@     let (vs1, h1, w1) = collectFreeVars depth l         (vs2, h2, w2) = collectFreeVars depth r      in (Set.union vs1 vs2, h1 || h2, w1 || w2)-  ESearchPath {} -> (Set.empty, False, False)+  EPos {} -> (Set.empty, False, False)  foldExprs :: Int -> [Expr] -> (Set (Int, Int), Bool, Bool) foldExprs depth = foldl' combine (Set.empty, False, False)@@ -385,7 +386,7 @@   EUnary op operand -> EUnary op (rewriteBody depth captureMap operand)   EBinary op l r ->     EBinary op (rewriteBody depth captureMap l) (rewriteBody depth captureMap r)-  ESearchPath {} -> expr+  EPos {} -> expr  rewritePart :: Int -> Map (Int, Int) Int -> StringPart -> StringPart rewritePart _ _ p@(StrLit _) = p
src/Nix/Expr/Resolve.hs view
@@ -35,7 +35,6 @@ import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T-import qualified Data.Text.Encoding as TE import Nix.Expr.Types import System.FilePath (isRelative, (</>)) @@ -80,6 +79,7 @@   EPathStr headPiece parts -> EPathStr headPiece <$> traverse (resolvePart stack) parts   EVar name -> resolveVar stack name   EResolvedVar _ _ -> Right expr+  EPos _ -> Right expr   EAttrs True bindings _captureInfo     | allStaticSingleKey bindings ->         -- Positional: all bindings are single static keys or inherits.@@ -134,18 +134,6 @@     EAssert <$> resolve stack cond <*> resolve stack body   EUnary op operand -> EUnary op <$> resolve stack operand   EBinary op l r -> EBinary op <$> resolve stack l <*> resolve stack r-  -- Desugar: <name> becomes __findFile __nixPath "name"-  -- Matches C++ Nix's parser desugaring.  __findFile and __nixPath are-  -- in the root scope (Builtins.hs), so they resolve via name-based-  -- lookup at runtime.  This ensures closure trimming captures the-  -- implicit builtins dependency.-  ESearchPath name ->-    resolve-      stack-      ( EApp-          (EApp (EVar "__findFile") (EVar "__nixPath"))-          (EStr [StrLit (TE.encodeUtf8 name)])-      )   where     recAttrs resolved = EAttrs True resolved NoCaptureInfo     letIn resolved body = ELet resolved body NoCaptureInfo@@ -170,7 +158,6 @@   where     go [] _ crossedWith       | crossedWith = Right (EWithVar name)-      | name == curPosName = Right (EVar name)       | otherwise = Left name     go (LexicalScope scope : rest) level crossedWith =       case Map.lookup name scope of@@ -183,18 +170,6 @@     -- level at runtime); it only records that an enclosing with exists.     go (WithBarrier : rest) level _ = go rest level True --- | A temporary accommodation.  Upstream's parser reads @__curPos@ as a--- position expression, never a variable (parser.y at 2.24.9, expr_simple),--- so binding never sees it.  Here it still parses as a variable: 'Nix.Parser.parseNix'--- takes the source's origin, which decides between upstream's position set--- (a file) and its null (a string), but no expression builds a position--- from it.  Until one does, the name is exempt from the check and fails--- when forced, as before binding checked anything; nixpkgs uses it in files--- every NixOS evaluation imports.  Delete the exemption when the parser--- builds the position.-curPosName :: Text-curPosName = "__curPos"- -- | The names upstream binds in its base environment by default, which is -- every name the root environment ('Nix.Builtins.builtinEnv') binds and -- every name binding accepts with nothing else in scope.  Upstream installs@@ -203,9 +178,12 @@ -- in @builtins@, so @__typeOf@ and @builtins.typeOf@ are one value.  The -- set is @createBaseEnv@'s (primops.cc) with every @RegisterPrimOp@ not -- gated on an experimental feature, which leaves out @__fetchClosure@,--- @__outputOf@, @fetchTree@ and the flake builtins, and with--- @__importNative@ and @__exec@, which need--- @allow-unsafe-native-code-during-evaluation@, left out too.+-- @__outputOf@ and @fetchTree@, and with @__importNative@ and @__exec@,+-- which need @allow-unsafe-native-code-during-evaluation@, left out too.+-- It holds the three flake builtins, which upstream's @nix@ adds to every+-- evaluator it makes whatever the features (@configureEvalSettings@ in+-- libflake's settings.cc, the @extraPrimOps@ in @createBaseEnv@, at+-- 2.36.0). -- 'impureOnlyGlobalNames' are dropped from it under @pure-eval@. -- -- A name here is never a with-variable: the global binds at parse time and@@ -273,6 +251,7 @@         "filter",         "filterSource",         "findFile",+        "flakeRefToString",         "floor",         "foldl'",         "fromJSON",@@ -282,6 +261,7 @@         "getAttr",         "getContext",         "getEnv",+        "getFlake",         "groupBy",         "hasAttr",         "hasContext",@@ -307,6 +287,7 @@         "nixPath",         "nixVersion",         "parseDrvName",+        "parseFlakeRef",         "partition",         "path",         "pathExists",@@ -500,6 +481,7 @@       EVar _ -> expr       EWithVar _ -> expr       EResolvedVar _ _ -> expr+      EPos _ -> expr       EAttrs isRec bindings captureInfo -> EAttrs isRec (map goBinding bindings) captureInfo       EList elems -> EList (map goExpr elems)       ESelect target path mDef ->@@ -513,7 +495,6 @@       EAssert cond body -> EAssert (goExpr cond) (goExpr body)       EUnary op e -> EUnary op (goExpr e)       EBinary op l r -> EBinary op (goExpr l) (goExpr r)-      ESearchPath _ -> expr      goPart part = case part of       StrLit _ -> part
src/Nix/Expr/Types.hs view
@@ -1,7 +1,10 @@ -- | Core AST types for the Nix expression language. ----- Every Nix source file parses into an 'Expr'. The AST is a direct--- representation of the language grammar - no desugaring at parse time.+-- Every Nix source file parses into an 'Expr'. The AST follows the+-- language grammar, with the desugarings upstream's parser makes: a dotted+-- binding is nested into sets and the sets of one attribute merged+-- ('NamedBinding'), and a search path @\<name\>@ becomes a call of+-- @__findFile@. -- The evaluator ("Nix.Eval") reduces expressions to values. module Nix.Expr.Types   ( -- * Expressions@@ -55,7 +58,8 @@  -- | A part of an interpolated string (@"hello ${name}"@). data StringPart-  = -- | Literal bytes, the source's with escapes resolved, which are the+  = -- | Literal bytes, the source's with escapes resolved (and, in a+    -- double-quoted string, each line ending read as LF), which are the     -- bytes the value holds whether or not they are UTF-8.     StrLit !ByteString   | -- | Resolved escape bytes inside an indented string (@'''@, @''$@,@@ -97,7 +101,7 @@ sourceName (SourceText name) = name  -- | A point in parsed source: where the source came from, and the 1-based--- line and column (in characters) the lexer gives the token there.+-- line and column (in bytes) the lexer gives the token there. data SrcPos   = SrcPos       -- | Where the source came from.@@ -152,8 +156,8 @@  -- | Closure capture information for lambda trimming. ----- After 'Nix.Expr.ClosureTrim.trimClosures', lambdas that only reference--- a subset of their outer scope carry a 'Captures' list.  At eval time+-- After 'Nix.Expr.ClosureTrim.trimClosures', lambdas that hold no 'EVar'+-- and reference their outer scope carry a 'Captures' list.  At eval time -- this drives extraction of exactly those thunks into a flat t'Nix.Eval.Types.Env', -- breaking the retention chain to the full parent scope. data CaptureInfo@@ -161,8 +165,8 @@     NoCaptureInfo   | -- | Sorted list of @(level, index)@ pairs to extract from the parent env.     Captures ![(Int, Int)]-  | -- | Like 'Captures', but the trimmed env must preserve its with-scopes-    -- ('Nix.Eval.Types.envWithScopesRaw'), with builtins appended, so that+  | -- | Like 'Captures', but the trimmed env keeps the with-scopes of the+    -- env it is made in ('Nix.Eval.Types.envWithScopesRaw'), so that     -- 'EWithVar' references can still be resolved.     CapturesWithScopes ![(Int, Int)]   deriving (Eq, Show)@@ -171,7 +175,7 @@ data UnaryOp   = OpNot   | OpNegate-  deriving (Eq, Show)+  deriving (Bounded, Enum, Eq, Show)  -- | Binary operators. data BinaryOp@@ -190,7 +194,7 @@   | OpGte   | OpConcat   | OpUpdate-  deriving (Eq, Show)+  deriving (Bounded, Enum, Eq, Show)  -- | The Nix expression AST. --@@ -240,8 +244,8 @@   | -- | Let binding: @let bindings in body@.     --     -- The 'CaptureInfo' field is populated by 'Nix.Expr.ClosureTrim.trimClosures'-    -- after variable resolution.  Positional let blocks that only reference-    -- a subset of their parent scope carry a 'Captures' list; at eval time+    -- after variable resolution.  Positional let blocks that hold no 'EVar'+    -- and reference their parent scope carry a 'Captures' list; at eval time     -- this drives construction of a trimmed parent env.     ELet ![Binding] !Expr !CaptureInfo   | -- | If-then-else: @if cond then t else f@.@@ -254,17 +258,23 @@     EUnary !UnaryOp !Expr   | -- | Binary operator application.     EBinary !BinaryOp !Expr !Expr-  | -- | Search path lookup: @\<nixpkgs\>@ is @ESearchPath "nixpkgs"@.-    ESearchPath !Text+  | -- | @__curPos@, at the position it is written.  Upstream's parser reads+    -- that identifier as a position wherever it is an expression, never as+    -- a variable (@expr_simple@, parser.y at 2.24.9), so no binding of the+    -- name reaches it.  It evaluates to the set @EvalState::mkPos@ makes of+    -- the position (@ExprPos::eval@, eval.cc).+    EPos !SrcPos   | -- | De Bruijn-style resolved variable: @(level, index)@.     -- Produced by 'Nix.Expr.Resolve.resolveVars' for variables-    -- bound by lambda formals.  @level@ counts parent-chain hops;+    -- bound by lambda formals and by let and rec blocks whose keys are all+    -- static, and renumbered to capture slots by+    -- 'Nix.Expr.ClosureTrim.trimClosures'.  @level@ counts parent-chain hops;     -- @index@ is the positional slot within that env's slot array.     EResolvedVar !Int !Int   | -- | Variable resolved via with-scopes (not lexical).     -- Produced by 'Nix.Expr.Resolve.resolveVars' for names inside     -- a @with@ body that are not found in any lexical scope.     -- At runtime, looked up in the env's with-scopes-    -- ('Nix.Eval.Types.envWithScopesRaw'), with builtins as the fallback.+    -- ('Nix.Eval.Types.envWithScopesRaw'), and undefined when none has it.     EWithVar !Text   deriving (Eq, Show)
+ src/Nix/Fetch/Archive.hs view
@@ -0,0 +1,426 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE TupleSections #-}++-- | A downloaded archive unpacked into a tree, as upstream's tarball+-- fetcher unpacks one: decompressed by what its first bytes announce,+-- read as libarchive reads tar ("Nix.Fetch.Tar"), and its entries placed+-- by the rules of upstream's tar sink.+--+-- The rules are pure: an entry's path is read as upstream reads a path,+-- the last entry at a path wins, a non-empty directory cannot be+-- replaced, a hard link names what its target is at that point in the+-- archive, and a tree holding a name that Git's tree builder refuses is+-- refused.  The edge decompresses, drives the reader, and writes each+-- file's bytes to a blob in a scratch directory as they arrive, so no+-- file is held whole.+--+-- It reads the compressions gzip, bzip2, xz and zstd, and tar.  Upstream's+-- libarchive also reads lzip, lzma, lz4, lzop, compress, uuencode, RPM,+-- lrzip and grzip streams, which this reads as an archive it does not+-- recognize.+module Nix.Fetch.Archive+  ( -- * Failures+    FetchFailure (..),++    -- * The tar sink+    ArchiveEntry (..),+    ArchiveNode (..),+    ArchiveSink,+    emptySink,+    sinkEntry,+    finishSink,++    -- * Unpacking+    readArchive,+    drainFile,+    unpackArchive,+  )+where++import Control.Applicative ((<|>))+import Control.Monad.Except (ExceptT, runExceptT, throwError, withExceptT)+import Control.Monad.Writer.Strict (Writer, runWriter, tell)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import Data.IORef (newIORef, readIORef, writeIORef)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import Data.Word (Word64, Word8)+import Nix.Compression.Stream (compressionMagicBytes, compressionOf, decodingFailure, withDecompressed)+import Nix.Fetch.Tar (FileStep (..), TarEntry (..), TarFailure (..), TarNode (..), TarStep (..), tarReader)+import Nix.Fetch.Tree (Blob (..), Tree (..), blobFile, dereferenceSingleton)+import Nix.Fetch.Url (bytesToTextLossy)+import System.IO (IOMode (WriteMode), withBinaryFile)++-- ---------------------------------------------------------------------------+-- Failures+-- ---------------------------------------------------------------------------++-- | Why a fetch failed: upstream's message, and the lines of context+-- upstream gives it, outermost first.+data FetchFailure = FetchFailure+  { fetchTraces :: ![Text],+    fetchMessage :: !Text+  }+  deriving (Eq, Show)++-- | Placing entries, with the warnings it gives in order.+type Sinking = ExceptT FetchFailure (Writer [Text])++refuseWith :: Text -> Sinking a+refuseWith = throwError . FetchFailure []++-- ---------------------------------------------------------------------------+-- Paths+-- ---------------------------------------------------------------------------++-- | A path in an archive as upstream holds one: its components, with+-- empty ones and @.@ dropped and @..@ taking the one before it away.  Paths+-- order component by component, which sorts a separator before every+-- byte.+newtype ArchivePath = ArchivePath [ByteString]+  deriving (Eq, Ord, Show)++-- | An entry's path, read as upstream reads one under the root.+archivePath :: ByteString -> ArchivePath+archivePath raw = ArchivePath (reverse (foldl' step [] (BS.split slash raw)))+  where+    step kept component+      | BS.null component || component == "." = kept+      | component == ".." = drop 1 kept+      | otherwise = component : kept++-- | A path as upstream prints one: absolute, the root as @\/@.+renderArchivePath :: ArchivePath -> Text+renderArchivePath (ArchivePath components) = "/" <> T.intercalate "/" (map bytesToTextLossy components)++slash, backslash, colon, space, dot, upperA, upperZ, asciiCaseOffset :: Word8+slash = 0x2f+backslash = 0x5c+colon = 0x3a+space = 0x20+dot = 0x2e+upperA = 0x41+upperZ = 0x5a+asciiCaseOffset = 0x20++-- ---------------------------------------------------------------------------+-- The tar sink+-- ---------------------------------------------------------------------------++-- | An entry as the sink takes it: its path as the archive names it and+-- what it is.+data ArchiveEntry blob = ArchiveEntry+  { entryPath :: !ByteString,+    entryNode :: !(ArchiveNode blob)+  }+  deriving (Eq, Show)++-- | What an entry is.+data ArchiveNode blob+  = ArchiveFile !Bool !blob+  | ArchiveDirectory+  | ArchiveSymlink !ByteString+  | ArchiveHardLink !ByteString+  | -- | A device or a FIFO, by its file type.+    ArchiveSpecial !Int+  deriving (Eq, Show)++-- | The tree so far and the paths hard links have made one file.+data ArchiveSink blob = ArchiveSink+  { sinkRoot :: !(Tree blob),+    -- | The group each linked path is in.+    sinkGroupOf :: !(Map ArchivePath Int),+    -- | The paths of each group.+    sinkGroups :: !(Map Int (Set ArchivePath)),+    sinkNextGroup :: !Int+  }++-- | Nothing placed yet: an empty root directory.+emptySink :: ArchiveSink blob+emptySink = ArchiveSink (TreeDirectory Map.empty) Map.empty Map.empty 0++-- | Place an entry, as upstream's tar sink places one.+sinkEntry :: ArchiveSink blob -> ArchiveEntry blob -> (Either FetchFailure (ArchiveSink blob), [Text])+sinkEntry sink entry = runWriter (runExceptT (place sink))+  where+    path = archivePath (entryPath entry)+    place current = case entryNode entry of+      ArchiveFile executable blob -> addNode path (TreeFile executable blob) current+      ArchiveDirectory -> addNode path (TreeDirectory Map.empty) current+      ArchiveSymlink target -> addNode path (TreeSymlink target) current+      ArchiveHardLink target -> hardLink path (archivePath target) current+      ArchiveSpecial fileType ->+        refuseWith ("file '" <> bytesToTextLossy (entryPath entry) <> "' in tarball has unsupported file type " <> T.pack (show fileType))++-- | What placing a node did to what was at its path.+data Placed = Added | Replaced | Unchanged++-- | Put a node at a path, making its parents directories as needed: the+-- last entry wins, a directory onto a directory changes nothing, and a+-- non-empty directory cannot be replaced.  Replacing a path a hard link+-- made one file with others unlinks it from them, with upstream's+-- warning.+addNode :: ArchivePath -> Tree blob -> ArchiveSink blob -> Sinking (ArchiveSink blob)+addNode path@(ArchivePath components) child sink = do+  (root, placed) <- either refuseWith pure (placeAt components (sinkRoot sink))+  let updated = sink {sinkRoot = root}+  case placed of+    Replaced -> unlinked path updated+    Added -> pure updated+    Unchanged -> pure updated+  where+    shown = renderArchivePath path+    notDirectory = "parent of '" <> shown <> "' is not a directory"+    placeAt remaining current = case (remaining, current) of+      ([], _) -> overwrite current+      ([name], TreeDirectory entries) -> case Map.lookup name entries of+        Nothing -> Right (TreeDirectory (Map.insert name child entries), Added)+        Just existing -> (\(node, placed) -> (TreeDirectory (Map.insert name node entries), placed)) <$> overwrite existing+      (name : deeper, TreeDirectory entries) ->+        (\(node, placed) -> (TreeDirectory (Map.insert name node entries), placed))+          <$> placeAt deeper (Map.findWithDefault (TreeDirectory Map.empty) name entries)+      (_, _) -> Left notDirectory+    overwrite existing = case (existing, child) of+      (TreeDirectory _, TreeDirectory _) -> Right (existing, Unchanged)+      (TreeDirectory entries, _)+        | not (Map.null entries) -> Left ("cannot create '" <> shown <> "', conflicting non-empty directory")+      _ -> Right (child, Replaced)++-- | Unlink a replaced path from the paths a hard link made the same file,+-- warning as upstream does; a path left alone in its group is linked to+-- nothing any more.+unlinked :: ArchivePath -> ArchiveSink blob -> Sinking (ArchiveSink blob)+unlinked path sink = case Map.lookup path (sinkGroupOf sink) of+  Nothing -> pure sink+  Just group -> do+    let others = Set.delete path (Map.findWithDefault Set.empty group (sinkGroups sink))+        groupOf = Map.delete path (sinkGroupOf sink)+    tell+      [ renderQuoted path+          <> " is replaced, though a hard link makes it the same file as "+          <> T.intercalate ", " (map renderQuoted (Set.toAscList others))+          <> ". Older versions of Nix resolved hard links differently, so this archive unpacks to a different store path than it used to."+      ]+    pure $+      if Set.size others < 2+        then sink {sinkGroupOf = foldr Map.delete groupOf (Set.toList others), sinkGroups = Map.delete group (sinkGroups sink)}+        else sink {sinkGroupOf = groupOf, sinkGroups = Map.insert group others (sinkGroups sink)}+  where+    renderQuoted p = "'" <> renderArchivePath p <> "'"++-- | Make a path a hard link to what its target is now, a file or a+-- symlink, and the two one file from then on.+hardLink :: ArchivePath -> ArchivePath -> ArchiveSink blob -> Sinking (ArchiveSink blob)+hardLink path target sink =+  withExceptT traced $ do+    node <- case lookupPath target (sinkRoot sink) of+      Nothing -> refuseWith "target does not exist"+      Just (TreeDirectory _) -> refuseWith "target is a directory"+      Just found -> pure found+    placed <- addNode path node sink+    let (group, withTarget) = case Map.lookup target (sinkGroupOf placed) of+          Just existing -> (existing, placed)+          Nothing ->+            ( sinkNextGroup placed,+              placed+                { sinkGroupOf = Map.insert target (sinkNextGroup placed) (sinkGroupOf placed),+                  sinkGroups = Map.insert (sinkNextGroup placed) (Set.singleton target) (sinkGroups placed),+                  sinkNextGroup = sinkNextGroup placed + 1+                }+            )+    pure+      withTarget+        { sinkGroupOf = Map.insert path group (sinkGroupOf withTarget),+          sinkGroups = Map.adjust (Set.insert path) group (sinkGroups withTarget)+        }+  where+    traced (FetchFailure traces message) =+      FetchFailure (("while creating a hard link from '" <> renderArchivePath path <> "' to '" <> renderArchivePath target <> "'") : traces) message++-- | The node at a path, if there is one: none when something on the way+-- is not a directory.+lookupPath :: ArchivePath -> Tree blob -> Maybe (Tree blob)+lookupPath (ArchivePath components) = go components+  where+    go remaining current = case (remaining, current) of+      ([], _) -> Just current+      (name : deeper, TreeDirectory entries) -> Map.lookup name entries >>= go deeper+      (_, _) -> Nothing++-- | The tree the sink holds, the lone top-level directory taken as the+-- root when there is one.  A root an entry replaced with something other+-- than a directory is refused: upstream's tarball cache reads the root as+-- a Git tree, and fails on any other object.  So is a tree holding a name+-- that its tree builder refuses, at any depth, before anything is written.+finishSink :: ArchiveSink blob -> Either FetchFailure (Tree blob)+finishSink sink = case sinkRoot sink of+  root@(TreeDirectory _) -> maybe (Right (dereferenceSingleton root)) (Left . FetchFailure []) (treeNameRefusal root)+  _ -> Left (FetchFailure [] "the archive's root is not a directory")++-- | Why the tree's first name that Git's tree builder refuses is+-- refused, if it holds one.  Upstream writes the tree's directories+-- depth first in name order, the names inside a directory before the+-- directory's own name, so the first refusal it meets is the one given.+treeNameRefusal :: Tree blob -> Maybe Text+treeNameRefusal tree = case tree of+  TreeDirectory entries -> firstJust (map entryRefusal (Map.toAscList entries))+  _ -> Nothing+  where+    entryRefusal (name, sub) = treeNameRefusal sub <|> nameRefusal name+    firstJust = foldr (<|>) Nothing+    nameRefusal name+      | refusedTreeName name = Just (treeBuilderRefusal name)+      | otherwise = Nothing++-- | Whether Git's tree builder refuses a name for an entry: any spelling+-- of @.git@ that NTFS reads as the same name, which it refuses on every+-- platform, so the name's case is not read, a short name @git~1@ stands+-- for it, trailing dots and spaces and a stream or separator after it+-- are ignored.  A build of its Git library for macOS also refuses spellings+-- with the code points HFS+ ignores, which is not checked here.+refusedTreeName :: ByteString -> Bool+refusedTreeName name = any reserved reservedNames+  where+    reserved candidate = case BS.splitAt (BS.length candidate) name of+      (lead, rest)+        | foldedAscii lead == candidate -> ignoredEnding rest+      _ -> False+    ignoredEnding rest = case BS.uncons rest of+      Just (c, _) | c == backslash || c == colon -> True+      _ -> BS.all (\c -> c == space || c == dot) rest+    foldedAscii = BS.map (\c -> if c >= upperA && c <= upperZ then c + asciiCaseOffset else c)+    reservedNames = [".git", "git~1"]++-- | Upstream's failure for a name its tree builder refuses.+treeBuilderRefusal :: ByteString -> Text+treeBuilderRefusal name =+  "adding '"+    <> shown+    <> "' to a tree builder: failed to insert entry: invalid name for a tree entry - "+    <> shown+    <> " (libgit2 error code = "+    <> T.pack (show treeErrorClass)+    <> ")"+  where+    shown = bytesToTextLossy name++-- | The class libgit2 gives an error in a tree.+treeErrorClass :: Int+treeErrorClass = 14++-- ---------------------------------------------------------------------------+-- Unpacking+-- ---------------------------------------------------------------------------++-- | The first bytes of a zip archive's local file header, which+-- libarchive reads and this does not yet.+zipMagic :: ByteString+zipMagic = "PK\x03\x04"++-- | Unpack the archive a source gives, writing each file's bytes to a+-- blob under the scratch directory, numbered in archive order, as they+-- arrive, and give its tree with the warnings unpacking gave, in order.+-- A corrupt compressed stream, an archive libarchive would not read and+-- an entry the sink refuses are failures; anything else the source+-- throws, a failed download among them, is left to the caller.+unpackArchive :: FilePath -> IO ByteString -> IO ([Text], Either FetchFailure (Tree Blob))+unpackArchive scratch source = do+  (lead, replayed) <- peek compressionMagicBytes source+  if zipMagic `BS.isPrefixOf` lead+    then pure ([], Left (FetchFailure [] "zip archives are not supported"))+    else withDecompressed (compressionOf lead) replayed $ \decompressed ->+      let pull = decodingFailure decompressed+          store count size contents = do+            let blob = Blob count size+            fmap (blob,) <$> withBinaryFile (blobFile scratch blob) WriteMode (\handle -> drainFile pull (BS.hPut handle) contents)+       in readArchive pull store++-- | Read an archive's entries into the sink, as upstream's tarball+-- fetcher hands them to its own: chunks come from the pull, which gives a+-- decoder's refusal as a value, and each regular file's contents go to+-- the blob the store makes of them, given the file's number in archive+-- order and its size.  The warnings come in the order the archive gives+-- them, a member's own before what the sink says of it.+readArchive ::+  (Monad m) =>+  m (Either Text ByteString) ->+  (Int -> Word64 -> FileStep -> m (Either FetchFailure (blob, TarStep))) ->+  m ([Text], Either FetchFailure (Tree blob))+readArchive pull store = drive [] emptySink 0 tarReader+  where+    -- Warnings are held newest first.+    drive !warnings !sink !count step = case step of+      TarAwait continue -> pull >>= either (stopped warnings . unreadable) (drive warnings sink count . continue)+      TarDone -> pure (reverse warnings, finishSink sink)+      TarFail failure -> stopped warnings (tarFailure failure)+      TarOther entry node next -> placing warnings sink count entry (otherNode node) next+      TarFile entry size contents ->+        store count size contents+          >>= either (stopped warnings) (\(blob, next) -> placing warnings sink (count + 1) entry (ArchiveFile (tarExecutable entry) blob) next)+    placing warnings sink count entry node next =+      let (placed, sinkWarnings) = sinkEntry sink (ArchiveEntry (tarPath entry) node)+          given = foldl' held warnings (maybe [] (pure . memberWarning entry) (tarWarning entry) ++ sinkWarnings)+       in either (stopped given) (\updated -> drive given updated count next) placed+    -- Each warning is forced as it is held, so what is held is text and+    -- not a thunk that keeps its entry alive.+    held warnings warning = warning `seq` (warning : warnings)+    stopped warnings failure = pure (reverse warnings, Left failure)+    memberWarning entry reason = "getting archive member '" <> bytesToTextLossy (tarPath entry) <> "': " <> reason+    otherNode node = case node of+      TarDirectory -> ArchiveDirectory+      TarSymlink target -> ArchiveSymlink target+      TarHardLink target -> ArchiveHardLink target+      TarSpecial fileType -> ArchiveSpecial fileType++-- | Hand a file's contents to the sink as they arrive, and give the+-- archive after them.+drainFile :: (Monad m) => m (Either Text ByteString) -> (ByteString -> m ()) -> FileStep -> m (Either FetchFailure TarStep)+drainFile pull sink step = case step of+  FileAwait continue -> pull >>= either (pure . Left . unreadable) (drainFile pull sink . continue)+  FileChunk bytes rest -> sink bytes >> drainFile pull sink rest+  FileEnd next -> pure (Right next)+  FileFail failure -> pure (Left (tarFailure failure))++-- | A compressed stream the decoder refused, as a fetch failure.+unreadable :: Text -> FetchFailure+unreadable reason = FetchFailure [] ("cannot read the archive: " <> reason)++-- | A reader's failure as a fetch failure.+tarFailure :: TarFailure -> FetchFailure+tarFailure = FetchFailure [] . tarFailureMessage++-- | A reader's failure as upstream reports it: an input no format reader+-- takes as an archive it failed to open, a header that failed before the+-- entry had a name as a member it cannot name, one after as an archive it+-- failed to extract, and a body as a file it cannot read.+tarFailureMessage :: TarFailure -> Text+tarFailureMessage failure = case failure of+  TarUnrecognized -> "Failed to open archive (Unrecognized archive format)"+  TarHeaderFailure Nothing reason -> "cannot get archive member name: " <> reason+  TarHeaderFailure (Just _) reason -> "failed to extract archive (" <> reason <> ")"+  TarDataFailure reason -> "cannot read file from tarball: " <> reason++-- | Read at least @n@ bytes from a source, or all it has when it has+-- fewer, and give them with a source that gives them again first.+peek :: Int -> IO ByteString -> IO (ByteString, IO ByteString)+peek n source = do+  lead <- gather []+  pending <- newIORef (Just lead)+  let replayed =+        readIORef pending >>= \case+          Just bytes -> writeIORef pending Nothing >> if BS.null bytes then source else pure bytes+          Nothing -> source+  pure (lead, replayed)+  where+    gather held = do+      let have = BS.concat (reverse held)+      if BS.length have >= n+        then pure have+        else do+          chunk <- source+          if BS.null chunk then pure have else gather (chunk : held)
+ src/Nix/Fetch/Attrs.hs view
@@ -0,0 +1,93 @@+-- | A fetcher input's attributes, as upstream's fetchers hold them+-- (attrs.cc at 2.36.0): each a string, an unsigned integer or a Boolean,+-- by name in name order, and read back by accessors that refuse a missing+-- or mistyped attribute in upstream's words.+module Nix.Fetch.Attrs+  ( -- * Attributes+    AttrValue (..),+    Attrs,++    -- * Reading+    maybeStrAttr,+    strAttr,+    maybeIntAttr,+    maybeBoolAttr,++    -- * Rendering+    attrsJson,+    attrsJsonText,+    attrsToQuery,+  )+where++import Data.ByteString (ByteString)+import qualified Data.ByteString.Char8 as BC+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Text (Text)+import qualified Data.Text.Encoding as TE+import Data.Word (Word64)+import Nix.Fetch.Url (Checked, bytesToTextLossy, refuse)+import Nix.Json (Json (..), renderJson)++-- | One attribute's value.  A string is bytes, as a Nix string is.+data AttrValue+  = AttrString !ByteString+  | AttrInt !Word64+  | AttrBool !Bool+  deriving (Eq, Ord, Show)++-- | An input's attributes by name.+type Attrs = Map Text AttrValue++-- | A string attribute, if there is one.+maybeStrAttr :: Text -> Attrs -> Checked (Maybe ByteString)+maybeStrAttr name attrs = case Map.lookup name attrs of+  Nothing -> pure Nothing+  Just (AttrString value) -> pure (Just value)+  Just _ -> refuse ("input attribute '" <> name <> "' is not a string " <> attrsJsonText attrs)++-- | A string attribute the input must have.+strAttr :: Text -> Attrs -> Checked ByteString+strAttr name attrs = maybeStrAttr name attrs >>= maybe (refuse ("input attribute '" <> name <> "' is missing")) pure++-- | An integer attribute, if there is one.+maybeIntAttr :: Text -> Attrs -> Checked (Maybe Word64)+maybeIntAttr name attrs = case Map.lookup name attrs of+  Nothing -> pure Nothing+  Just (AttrInt value) -> pure (Just value)+  Just _ -> refuse ("input attribute '" <> name <> "' is not an integer")++-- | A Boolean attribute, if there is one.+maybeBoolAttr :: Text -> Attrs -> Checked (Maybe Bool)+maybeBoolAttr name attrs = case Map.lookup name attrs of+  Nothing -> pure Nothing+  Just (AttrBool value) -> pure (Just value)+  Just _ -> refuse ("input attribute '" <> name <> "' is not a Boolean")++-- | The attributes as a JSON object, as upstream's @attrsToJSON@ makes+-- it.  A string with no UTF-8 reading, which nlohmann refuses to write,+-- has its bytes read leniently: the object is only ever shown in a+-- message.+attrsJson :: Attrs -> Json+attrsJson = JsonObject . Map.map valueJson+  where+    valueJson value = case value of+      AttrString s -> JsonString (bytesToTextLossy s)+      AttrInt n -> JsonInt (toInteger n)+      AttrBool b -> JsonBool b++-- | 'attrsJson' as nlohmann's @dump@ writes it.+attrsJsonText :: Attrs -> Text+attrsJsonText = bytesToTextLossy . renderJson . attrsJson++-- | The attributes as a URL query, as upstream's @attrsToQuery@ makes it:+-- an integer in decimal and a Boolean as @1@ or @0@.+attrsToQuery :: Attrs -> Map ByteString ByteString+attrsToQuery = Map.fromList . map query . Map.toList+  where+    query (name, value) = (TE.encodeUtf8 name, rendered value)+    rendered value = case value of+      AttrString s -> s+      AttrInt n -> BC.pack (show n)+      AttrBool b -> if b then "1" else "0"
+ src/Nix/Fetch/Download.hs view
@@ -0,0 +1,58 @@+{-# LANGUAGE ScopedTypeVariables #-}++-- | The evaluator's downloads: a URL's body read as a pull source, from+-- a local file or through nova-nix's HTTP client ("Nix.Http"), each+-- attempt under upstream's retry policy.+module Nix.Fetch.Download+  ( DownloadSource (..),+    withUrlBody,+    downloadBytes,+  )+where++import Control.Exception (IOException, catch)+import Data.Bifunctor (first)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import Data.Text (Text)+import qualified Network.HTTP.Client as HTTP+import Nix.Http (FetchRetryPolicy, attemptFailureMessage, downloadUrlWith, fetchWriteFailure, ioRetryEffects, retryTransient)+import Nix.Logger (Logger)+import System.IO (IOMode (ReadMode), withBinaryFile)++-- | Where a download reads a URL's body from.+data DownloadSource+  = -- | The file a @file:\/\/@ URL names, by its path.+    LocalFile !FilePath+  | -- | A URL the HTTP client requests.+    RemoteUrl !Text+  deriving (Eq, Show)++-- | The bytes read from a local file at a time.+localChunkBytes :: Int+localChunkBytes = 65536++-- | Read a URL's body as a pull source whose empty chunk ends it, handing+-- the source to the consumer, and give what the consumer gives.  An+-- attempt whose transfer fails in a way a retry could outlive is made+-- again from the start, so a consumer starts from nothing each time; a+-- failure no retry changes, a local file that cannot be read among them,+-- is the message "Nix.Http" words it in.  The URL names the source in+-- messages.+withUrlBody :: Logger -> FetchRetryPolicy -> Text -> DownloadSource -> (IO ByteString -> IO a) -> IO (Either Text a)+withUrlBody logger policy url source consume =+  first attemptFailureMessage <$> retryTransient policy (ioRetryEffects logger) attempt+  where+    attempt = case source of+      LocalFile path ->+        (Right <$> withBinaryFile path ReadMode (\handle -> consume (BS.hGetSome handle localChunkBytes)))+          `catch` \(err :: IOException) -> pure (Left (fetchWriteFailure url err))+      RemoteUrl remote -> downloadUrlWith remote (fmap Right . consume . HTTP.brRead)++-- | A URL's body, whole, as upstream reads a downloaded file.+downloadBytes :: Logger -> FetchRetryPolicy -> Text -> DownloadSource -> IO (Either Text ByteString)+downloadBytes logger policy url source = withUrlBody logger policy url source (drain [])+  where+    drain held pull = do+      chunk <- pull+      if BS.null chunk then pure (BS.concat (reverse held)) else drain (chunk : held) pull
+ src/Nix/Fetch/Input.hs view
@@ -0,0 +1,661 @@+{-# LANGUAGE LambdaCase #-}++-- | Fetcher inputs as upstream's input schemes read and write them: from+-- a URL, from attributes, and back to a URL (fetchers.cc, git.cc,+-- github.cc, mercurial.cc, indirect.cc, path.cc and tarball.cc at+-- 2.36.0).  Nothing here fetches.+--+-- Upstream keeps its schemes in a map by name and asks each in turn+-- whether a URL is its own, so the first scheme in name order to claim+-- one parses it.  A scheme behind an experimental feature refuses a URL+-- it has claimed, or attributes naming it, while the feature is off.+module Nix.Fetch.Input+  ( -- * Inputs+    Scheme (..),+    schemeName,+    Input (..),+    InputContext (..),+    TreeRequirement (..),++    -- * Reading and writing+    inputFromUrl,+    inputFromAttrs,+    inputToUrl,+    inputToUrlString,++    -- * Git names+    isLegalRefName,+  )+where++import Control.Monad (forM_, unless, void, when)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BC+import Data.Char (isAsciiLower, isAsciiUpper, isDigit, isHexDigit)+import Data.Foldable (foldlM)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import qualified Data.Text.Encoding as TE+import Data.Word (Word64)+import Nix.Eval.Policy (PathRules)+import Nix.ExperimentalFeature (ExperimentalFeature, FeatureSet, flakesFeature, requireFeature, verifiedFetchesFeature)+import Nix.Fetch.Attrs (AttrValue (..), Attrs, attrsJsonText, attrsToQuery, maybeBoolAttr, maybeIntAttr, maybeStrAttr, strAttr)+import Nix.Fetch.Url (Checked, Leniency (..), ParsedUrl (..), UrlScheme (..), authHost, bytesToTextLossy, fixGitUrl, parseUrl, parseUrlScheme, pathToUrlPath, refuse, renderAuthority, renderUrl, urlPathSegments, urlPathToPath)+import Nix.Hash (bytesToHexText, parseAnyHash, parseNarHash)+import Nix.Json (Json (..), parseJson, renderJson)+import qualified NovaCache.Base64 as B64++-- ---------------------------------------------------------------------------+-- Inputs+-- ---------------------------------------------------------------------------++-- | An input scheme, in the order of upstream's map of them: by name.+data Scheme+  = SchemeFile+  | SchemeGit+  | SchemeGitHub+  | SchemeGitLab+  | SchemeMercurial+  | SchemeIndirect+  | SchemePath+  | SchemeSourceHut+  | SchemeTarball+  deriving (Eq, Ord, Show, Enum, Bounded)++-- | A scheme's name, the @type@ attribute of its inputs.+schemeName :: Scheme -> Text+schemeName scheme = case scheme of+  SchemeFile -> "file"+  SchemeGit -> "git"+  SchemeGitHub -> "github"+  SchemeGitLab -> "gitlab"+  SchemeMercurial -> "hg"+  SchemeIndirect -> "indirect"+  SchemePath -> "path"+  SchemeSourceHut -> "sourcehut"+  SchemeTarball -> "tarball"++-- | An input: its scheme, when its @type@ names one upstream has, and its+-- attributes, the @type@ among them.+data Input = Input+  { inputScheme :: !(Maybe Scheme),+    inputAttrs :: !Attrs+  }+  deriving (Eq, Show)++-- | What reading an input depends on: the features that are on, and the+-- host's path rules, which a @path:@ input's path and a Git URL's+-- absolute path are read under.+data InputContext = InputContext+  { icFeatures :: !FeatureSet,+    icPathRules :: !PathRules+  }++-- | Whether a URL must name a tree, as a flake reference must, or may+-- name a plain file.+data TreeRequirement = RequireTree | AllowFile+  deriving (Eq, Show)++-- | The feature a scheme needs.+schemeFeature :: Scheme -> Maybe ExperimentalFeature+schemeFeature scheme = case scheme of+  SchemeGitHub -> Just flakesFeature+  SchemeGitLab -> Just flakesFeature+  SchemeSourceHut -> Just flakesFeature+  SchemeIndirect -> Just flakesFeature+  SchemePath -> Just flakesFeature+  SchemeFile -> Nothing+  SchemeGit -> Nothing+  SchemeMercurial -> Nothing+  SchemeTarball -> Nothing++requireSchemeFeature :: InputContext -> Scheme -> Checked ()+requireSchemeFeature ctx scheme = forM_ (schemeFeature scheme) (\feature -> either refuse pure (requireFeature feature (icFeatures ctx)))++-- ---------------------------------------------------------------------------+-- From a URL+-- ---------------------------------------------------------------------------++-- | An input from a URL, as upstream's @Input::fromURL@ reads one: the+-- first scheme in name order that claims the URL parses it, needing its+-- feature only once it has, and the attributes every input has are then+-- checked.  A URL no scheme claims is refused.+inputFromUrl :: InputContext -> TreeRequirement -> ParsedUrl -> Checked Input+inputFromUrl ctx tree url = go [minBound .. maxBound]+  where+    go schemes = case schemes of+      scheme : rest ->+        schemeFromUrl ctx tree scheme url >>= \case+          Nothing -> go rest+          Just attrs -> do+            requireSchemeFeature ctx scheme+            let input = Input (Just scheme) attrs+            input <$ fixupInput input+      []+        | UrlScheme (Just "file") "git" <- parseUrlScheme (urlScheme url) ->+            refuse ("input " <> quotedUrl url <> " is unsupported; did you mean 'git+file' instead of 'file+git'?")+        | otherwise -> refuse ("input " <> quotedUrl url <> " is unsupported")++-- | A URL quoted for a message.+quotedUrl :: ParsedUrl -> Text+quotedUrl url = "'" <> bytesToTextLossy (renderUrl url) <> "'"++-- | A scheme's reading of a URL, or 'Nothing' when it is not the+-- scheme's.+schemeFromUrl :: InputContext -> TreeRequirement -> Scheme -> ParsedUrl -> Checked (Maybe Attrs)+schemeFromUrl ctx tree scheme url = case scheme of+  SchemeFile -> pure (curlFromUrl scheme tree url)+  SchemeTarball -> pure (curlFromUrl scheme tree url)+  SchemeGit -> traverse (gitFromAttrs ctx) (gitUrlAttrs url)+  SchemeGitHub -> forgeFromUrl scheme url+  SchemeGitLab -> forgeFromUrl scheme url+  SchemeSourceHut -> forgeFromUrl scheme url+  SchemeMercurial -> traverse mercurialFromAttrs (mercurialUrlAttrs url)+  SchemeIndirect -> indirectFromUrl url+  SchemePath -> pathFromUrl ctx url++-- | A string attribute.+str :: ByteString -> AttrValue+str = AttrString++-- | The @type@ attribute of a scheme's inputs.+typeAttr :: Scheme -> (Text, AttrValue)+typeAttr scheme = ("type", str (TE.encodeUtf8 (schemeName scheme)))++-- | Upstream's @string2Int@ for an unsigned 64-bit number: decimal digits+-- with an optional leading @+@, in range.+unsignedValue :: ByteString -> Maybe Word64+unsignedValue raw = case BC.readInteger digits of+  Just (n, rest)+    | BS.null rest,+      not (BS.null digits),+      BC.all isDigit digits,+      n <= toInteger (maxBound :: Word64) ->+        Just (fromInteger n)+  _ -> Nothing+  where+    digits = fromMaybe raw (BC.stripPrefix "+" raw)++-- | The file and tarball schemes' reading of a URL: one fetched over+-- @file@, @http@ or @https@, with the scheme named as its application or,+-- with none named, a tarball by its extension or because a tree is+-- required, a file otherwise.  The query's @narHash@, @rev@, @revCount@+-- and @lastModified@ become attributes, and every name the scheme allows+-- is dropped from the URL.+curlFromUrl :: Scheme -> TreeRequirement -> ParsedUrl -> Maybe Attrs+curlFromUrl scheme tree url+  | not valid = Nothing+  | otherwise =+      Just+        $ Map.fromList+        $ [typeAttr scheme, ("url", str (renderUrl fetchedUrl))]+          ++ [("narHash", str v) | Just v <- [Map.lookup "narHash" query]]+          ++ [("rev", str v) | Just v <- [Map.lookup "rev" query]]+          ++ [("revCount", AttrInt n) | Just n <- [Map.lookup "revCount" query >>= unsignedValue]]+          ++ [("lastModified", AttrInt n) | Just n <- [Map.lookup "lastModified" query >>= unsignedValue]]+  where+    UrlScheme application transport = parseUrlScheme (urlScheme url)+    query = urlQuery url+    valid =+      transport `elem` ["file", "http", "https"] && case application of+        Just named -> named == TE.encodeUtf8 (schemeName scheme)+        Nothing -> case scheme of+          SchemeFile -> tree == AllowFile && not hasTarballExtension+          _ -> tree == RequireTree || hasTarballExtension+    hasTarballExtension = case reverse (urlPath url) of+      final : _ -> any (`BS.isSuffixOf` final) [".zip", ".tar", ".tgz", ".tar.gz", ".tar.xz", ".tar.bz2", ".tar.zst"]+      [] -> False+    fetchedUrl = url {urlScheme = transport, urlQuery = foldr (Map.delete . TE.encodeUtf8) query curlAttrNames}++-- | The attributes the file and tarball schemes allow.+curlAttrNames :: [Text]+curlAttrNames = ["url", "narHash", "name", "unpack", "rev", "revCount", "lastModified"]++-- | The git scheme's attributes from a URL whose scheme is @git@ or has+-- @git@ as its application: @rev@, @ref@ and the key attributes as+-- strings, the flags as true when their value is @1@, and every other+-- parameter left in the URL.+gitUrlAttrs :: ParsedUrl -> Maybe Attrs+gitUrlAttrs url+  | urlScheme url /= "git" && utApplication (parseUrlScheme (urlScheme url)) /= Just "git" = Nothing+  | otherwise =+      Just . Map.fromList $+        [typeAttr SchemeGit, ("url", str (renderUrl url {urlQuery = kept}))]+          ++ [(name, str value) | name <- gitStringNames, Just value <- [lookupParam name]]+          ++ [(name, AttrBool (value == "1")) | name <- gitFlagNames, Just value <- [lookupParam name]]+  where+    lookupParam name = Map.lookup (TE.encodeUtf8 name) (urlQuery url)+    kept = foldr (Map.delete . TE.encodeUtf8) (urlQuery url) (gitStringNames ++ gitFlagNames)++-- | The git scheme's string parameters.+gitStringNames :: [Text]+gitStringNames = ["rev", "ref", "keytype", "publicKey", "publicKeys"]++-- | The git scheme's flags.+gitFlagNames :: [Text]+gitFlagNames = ["shallow", "submodules", "lfs", "exportIgnore", "allRefs", "verifyCommit"]++-- | The git scheme's check of its attributes, as its @inputFromAttrs@+-- makes it: the key attributes need @verified-fetches@, a @ref@ must be a+-- legal name, the flags must be Booleans, and the URL is made a Git URL+-- ('fixGitUrl').+gitFromAttrs :: InputContext -> Attrs -> Checked Attrs+gitFromAttrs ctx attrs = do+  when (any (`Map.member` attrs) ["verifyCommit", "keytype", "publicKey", "publicKeys"]) $+    either refuse pure (requireFeature verifiedFetchesFeature (icFeatures ctx))+  _ <- maybeBoolAttr "verifyCommit" attrs+  maybeStrAttr "ref" attrs >>= mapM_ (\ref -> unless (isLegalRefName ref) (refuse ("invalid Git branch/tag name '" <> bytesToTextLossy ref <> "'")))+  url <- strAttr "url" attrs >>= fixGitUrl (icPathRules ctx)+  let fixed = Map.insert "url" (str (renderUrl url)) attrs+  mapM_ (`maybeBoolAttr` fixed) ["shallow", "submodules", "allRefs"]+  pure fixed++-- | The forge schemes' reading of a URL: @OWNER\/REPO@ and an optional+-- revision or ref, the empty path segments skipped; then the @rev@,+-- @ref@, @host@ and @narHash@ parameters, any other refused.+forgeFromUrl :: Scheme -> ParsedUrl -> Checked (Maybe Attrs)+forgeFromUrl scheme url+  | urlScheme url /= TE.encodeUtf8 (schemeName scheme) = pure Nothing+  | otherwise = case urlPathSegments url of+      owner : repo : rest -> do+        let fromPath = case rest of+              [] -> Map.empty+              [single] | isRev single -> Map.singleton "rev" (str single)+              _ -> Map.singleton "ref" (str (BS.intercalate "/" rest))+        withQuery <- foldlM addParam fromPath (Map.toList (urlQuery url))+        Just <$> forgeFromAttrs (Map.union (Map.fromList [typeAttr scheme, ("owner", str owner), ("repo", str repo)]) withQuery)+      _ -> refuse ("URL " <> quotedUrl url <> " is invalid")+  where+    addParam acc (name, value)+      | name == "rev" = once "rev" "contains multiple commit hashes"+      | name == "ref" = once "ref" "contains multiple branch/tag names"+      | name == "host" = pure (Map.insert "host" (str value) acc)+      | name == "narHash" = pure (Map.insert "narHash" (str value) acc)+      | otherwise = refuse ("URL " <> quotedUrl url <> " contains unknown parameter '" <> bytesToTextLossy name <> "'")+      where+        once key problem+          | Map.member key acc = refuse ("URL " <> quotedUrl url <> " " <> problem)+          | otherwise = pure (Map.insert key (str value) acc)++-- | The forge schemes' check of their attributes: an owner and a repo, a+-- revision or a ref and not both, a revision that is a SHA-1, a legal+-- ref, and a host of letters, digits, dots and dashes.+forgeFromAttrs :: Attrs -> Checked Attrs+forgeFromAttrs attrs = do+  _ <- strAttr "owner" attrs+  _ <- strAttr "repo" attrs+  ref <- maybeStrAttr "ref" attrs+  rev <- maybeStrAttr "rev" attrs+  case (ref, rev) of+    (Just r, Just v) ->+      refuse ("input " <> attrsJsonText attrs <> " contains both a commit hash ('" <> bytesToTextLossy v <> "') and a branch/tag name ('" <> bytesToTextLossy r <> "')")+    _ -> pure ()+  mapM_ (parseHashAs (Just sha1Algo)) rev+  forM_ ref $ \r -> unless (isLegalRefName r) (refuse ("input " <> attrsJsonText attrs <> " contains an invalid branch/tag name"))+  maybeStrAttr "host" attrs >>= mapM_ (\host -> unless (BC.all isHostChar host) (refuse ("input " <> attrsJsonText attrs <> " contains an invalid instance host")))+  pure attrs+  where+    isHostChar c = isAsciiLower c || isAsciiUpper c || isDigit c || c == '.' || c == '-'++-- | The Mercurial scheme's attributes from a @hg+http@, @hg+https@,+-- @hg+ssh@ or @hg+file@ URL: @rev@ and @ref@, every other parameter left+-- in the URL, whose scheme loses its @hg+@.+mercurialUrlAttrs :: ParsedUrl -> Maybe Attrs+mercurialUrlAttrs url+  | urlScheme url `notElem` ["hg+http", "hg+https", "hg+ssh", "hg+file"] = Nothing+  | otherwise =+      Just+        $ Map.fromList+        $ [typeAttr SchemeMercurial, ("url", str (renderUrl url {urlScheme = BS.drop 3 (urlScheme url), urlQuery = kept}))]+          ++ [(name, str value) | name <- ["rev", "ref"], Just value <- [Map.lookup (TE.encodeUtf8 name) (urlQuery url)]]+  where+    kept = Map.filterWithKey (\name _ -> name `notElem` ["rev", "ref"]) (urlQuery url)++-- | The Mercurial scheme's check of its attributes: a URL that parses,+-- and a ref of the characters a Git ref may start and go on with.+mercurialFromAttrs :: Attrs -> Checked Attrs+mercurialFromAttrs attrs = do+  _ <- strAttr "url" attrs >>= parseUrl Strict+  maybeStrAttr "ref" attrs >>= mapM_ (\ref -> unless (matchesRefRegex ref) (refuse ("invalid Mercurial branch/tag name '" <> bytesToTextLossy ref <> "'")))+  pure attrs++-- | The indirect scheme's reading of a @flake:@ URL: an id, then a+-- revision or a ref, or a ref and a revision, the empty path segments+-- skipped.  Its query is not read.+indirectFromUrl :: ParsedUrl -> Checked (Maybe Attrs)+indirectFromUrl url+  | urlScheme url /= "flake" = pure Nothing+  | otherwise = do+      (flakeId, ref, rev) <- case urlPathSegments url of+        [flakeId] -> pure (flakeId, Nothing, Nothing)+        [flakeId, second]+          | isRev second -> (\digest -> (flakeId, Nothing, Just digest)) <$> parseHashAs (Just sha1Algo) second+          | isLegalRefName second -> pure (flakeId, Just second, Nothing)+          | otherwise -> refuse ("in flake URL " <> quotedUrl url <> ", '" <> bytesToTextLossy second <> "' is not a commit hash or branch/tag name")+        [flakeId, second, third] -> do+          unless (isLegalRefName second) $ refuse ("in flake URL " <> quotedUrl url <> ", '" <> bytesToTextLossy second <> "' is not a branch/tag name")+          unless (isRev third) $ refuse ("in flake URL " <> quotedUrl url <> ", '" <> bytesToTextLossy third <> "' is not a commit hash")+          (\digest -> (flakeId, Just second, Just digest)) <$> parseHashAs (Just sha1Algo) third+        _ -> refuse ("GitHub URL " <> quotedUrl url <> " is invalid")+      unless (isFlakeId flakeId) $ refuse ("'" <> bytesToTextLossy flakeId <> "' is not a valid flake ID")+      pure . Just . Map.fromList $+        [typeAttr SchemeIndirect, ("id", str flakeId)]+          ++ [("rev", str (TE.encodeUtf8 (bytesToHexText digest))) | Just digest <- [rev]]+          ++ [("ref", str r) | Just r <- [ref]]++-- | The path scheme's reading of a @path:@ URL: one with no host, its path+-- the URL's, and its query's @rev@, @narHash@, @revCount@ and+-- @lastModified@ as attributes, the counts unsigned; any other parameter+-- is refused.+pathFromUrl :: InputContext -> ParsedUrl -> Checked (Maybe Attrs)+pathFromUrl ctx url+  | urlScheme url /= "path" = pure Nothing+  | otherwise = do+      case urlAuthority url of+        Just authority+          | not (BS.null (authHost authority)) ->+              refuse ("path URL " <> quotedUrl url <> " should not have an authority ('" <> bytesToTextLossy (renderAuthority authority) <> "')")+        _ -> pure ()+      path <- urlPathToPath (icPathRules ctx) (urlPath url)+      params <- traverse param (Map.toList (urlQuery url))+      pure (Just (Map.fromList ([typeAttr SchemePath, ("path", str path)] ++ params)))+  where+    param (name, value)+      | name == "rev" = pure ("rev", str value)+      | name == "narHash" = pure ("narHash", str value)+      | name == "revCount" = count "revCount"+      | name == "lastModified" = count "lastModified"+      | otherwise = refuse ("path URL " <> quotedUrl url <> " has unsupported parameter '" <> bytesToTextLossy name <> "'")+      where+        count key = case unsignedValue value of+          Just n -> pure (key, AttrInt n)+          Nothing -> refuse ("path URL " <> quotedUrl url <> " has invalid parameter '" <> bytesToTextLossy name <> "'")++-- ---------------------------------------------------------------------------+-- From attributes+-- ---------------------------------------------------------------------------++-- | An input from attributes, as upstream's @Input::fromAttrs@ reads+-- them: a @type@ is required; one naming no scheme gives an input no+-- scheme reads, which shows as unsupported; one naming a scheme needs its+-- feature, admits only the attributes the scheme allows, and is checked+-- as the scheme checks its own.  The attributes every input has are+-- checked last.+inputFromAttrs :: InputContext -> Attrs -> Checked Input+inputFromAttrs ctx attrs = do+  typeName <- case Map.lookup "type" attrs of+    Just (AttrString name) -> pure name+    Just _ -> refuse ("input attribute 'type' is not a string " <> attrsJsonText attrs)+    Nothing -> refuse "'type' attribute to specify input scheme is required but not provided"+  input <- case [scheme | scheme <- [minBound .. maxBound], TE.encodeUtf8 (schemeName scheme) == typeName] of+    scheme : _ -> do+      requireSchemeFeature ctx scheme+      forM_ (Map.keys attrs) $ \name ->+        unless (name `elem` ["type", "__final"] || name `elem` allowedAttrs scheme) $+          refuse ("input attribute '" <> name <> "' not supported by scheme '" <> schemeName scheme <> "'")+      Input (Just scheme) <$> schemeFromAttrs ctx scheme attrs+    [] -> pure (Input Nothing attrs)+  input <$ fixupInput input++-- | The attributes a scheme allows beyond @type@.+allowedAttrs :: Scheme -> [Text]+allowedAttrs scheme = case scheme of+  SchemeFile -> curlAllowed+  SchemeTarball -> curlAllowed+  SchemeGit ->+    [ "url",+      "ref",+      "rev",+      "shallow",+      "submodules",+      "lfs",+      "exportIgnore",+      "lastModified",+      "revCount",+      "narHash",+      "allRefs",+      "name",+      "dirtyRev",+      "dirtyShortRev",+      "verifyCommit",+      "keytype",+      "publicKey",+      "publicKeys"+    ]+  SchemeGitHub -> forgeAllowed+  SchemeGitLab -> forgeAllowed+  SchemeSourceHut -> forgeAllowed+  SchemeMercurial -> ["url", "ref", "rev", "revCount", "narHash", "name"]+  SchemeIndirect -> ["id", "ref", "rev", "narHash"]+  SchemePath -> ["path", "rev", "revCount", "lastModified", "narHash"]+  where+    curlAllowed = curlAttrNames+    forgeAllowed = ["owner", "repo", "ref", "rev", "narHash", "lastModified", "host", "treeHash"]++-- | A scheme's own check of its attributes.+schemeFromAttrs :: InputContext -> Scheme -> Attrs -> Checked Attrs+schemeFromAttrs ctx scheme attrs = case scheme of+  SchemeFile -> pure attrs+  SchemeTarball -> pure attrs+  SchemeGit -> gitFromAttrs ctx attrs+  SchemeGitHub -> forgeFromAttrs attrs+  SchemeGitLab -> forgeFromAttrs attrs+  SchemeSourceHut -> forgeFromAttrs attrs+  SchemeMercurial -> mercurialFromAttrs attrs+  SchemeIndirect -> do+    flakeId <- strAttr "id" attrs+    unless (isFlakeId flakeId) $ refuse ("'" <> bytesToTextLossy flakeId <> "' is not a valid flake ID")+    pure attrs+  SchemePath -> attrs <$ strAttr "path" attrs++-- | The checks every input gets once read (@fixupInput@ in fetchers.cc):+-- a string @type@ and @ref@, and integer @revCount@ and @lastModified@.+fixupInput :: Input -> Checked ()+fixupInput (Input _ attrs) = do+  _ <- strAttr "type" attrs+  _ <- maybeStrAttr "ref" attrs+  _ <- maybeIntAttr "revCount" attrs+  void (maybeIntAttr "lastModified" attrs)++-- ---------------------------------------------------------------------------+-- To a URL+-- ---------------------------------------------------------------------------++-- | An input's URL, as its scheme's @toURL@ writes it.  An input no scheme+-- reads has none.+inputToUrl :: PathRules -> Input -> Checked ParsedUrl+inputToUrl rules (Input scheme attrs) = case scheme of+  Nothing -> refuse ("cannot show unsupported input '" <> attrsJsonText attrs <> "'")+  Just SchemeFile -> curlToUrl+  Just SchemeTarball -> curlToUrl+  Just SchemeGit -> do+    url <- strAttr "url" attrs >>= parseUrl Strict+    rev <- inputRev attrs+    ref <- maybeStrAttr "ref" attrs+    flags <- traverse (\name -> (,) name <$> maybeBoolAttr name attrs) ["shallow", "lfs", "submodules", "exportIgnore", "verifyCommit"]+    keys <- publicKeys attrs+    let keyParams = case keys of+          [PublicKey keyType key] -> [("keytype", keyType), ("publicKey", key)]+          [] -> []+          _ -> [("publicKeys", renderJson (JsonArray (map publicKeyJson keys)))]+        params =+          [("rev", gitRev digest) | Just digest <- [rev]]+            ++ [("ref", r) | Just r <- [ref]]+            ++ [(TE.encodeUtf8 name, "1") | (name, Just True) <- flags]+            ++ keyParams+    pure+      url+        { urlScheme = if urlScheme url == "git" then urlScheme url else "git+" <> urlScheme url,+          urlQuery = Map.union (Map.fromList params) (urlQuery url)+        }+  Just SchemeGitHub -> forgeToUrl SchemeGitHub+  Just SchemeGitLab -> forgeToUrl SchemeGitLab+  Just SchemeSourceHut -> forgeToUrl SchemeSourceHut+  Just SchemeMercurial -> do+    url <- strAttr "url" attrs >>= parseUrl Strict+    rev <- inputRev attrs+    ref <- maybeStrAttr "ref" attrs+    let params = [("rev", gitRev digest) | Just digest <- [rev]] ++ [("ref", r) | Just r <- [ref]]+    pure url {urlScheme = "hg+" <> urlScheme url, urlQuery = Map.union (Map.fromList params) (urlQuery url)}+  Just SchemeIndirect -> do+    flakeId <- strAttr "id" attrs+    ref <- maybeStrAttr "ref" attrs+    rev <- inputRev attrs+    pure (ParsedUrl "flake" Nothing ([flakeId] ++ maybe [] pure ref ++ [gitRev digest | Just digest <- [rev]]) Map.empty BS.empty)+  Just SchemePath -> do+    path <- strAttr "path" attrs+    let query = foldr Map.delete (attrsToQuery attrs) ["path", "type", "__final"]+    pure (ParsedUrl "path" Nothing (pathToUrlPath rules path) query BS.empty)+  where+    curlToUrl = do+      url <- strAttr "url" attrs >>= parseUrl Strict+      narHash <- inputNarHash attrs+      pure url {urlQuery = maybe id (Map.insert "narHash") narHash (urlQuery url)}+    forgeToUrl forge = do+      owner <- strAttr "owner" attrs+      repo <- strAttr "repo" attrs+      ref <- maybeStrAttr "ref" attrs+      rev <- inputRev attrs+      narHash <- inputNarHash attrs+      host <- maybeStrAttr "host" attrs+      let query = Map.fromList ([("narHash", h) | Just h <- [narHash]] ++ [("host", h) | Just h <- [host]])+      pure (ParsedUrl (TE.encodeUtf8 (schemeName forge)) Nothing ([owner, repo] ++ maybe [] pure ref ++ [gitRev digest | Just digest <- [rev]]) query BS.empty)++-- | An input's URL with extra parameters, a name the URL has already+-- keeping its own value, as upstream's @Input::toURLString@ adds them.+inputToUrlString :: PathRules -> [(ByteString, ByteString)] -> Input -> Checked ByteString+inputToUrlString rules extra input = do+  url <- inputToUrl rules input+  pure (renderUrl url {urlQuery = Map.union (urlQuery url) (Map.fromList extra)})++-- | The input's revision, as upstream's @Input::getRev@ reads it: a hash+-- with its algorithm named, else a SHA-1.+inputRev :: Attrs -> Checked (Maybe ByteString)+inputRev attrs =+  maybeStrAttr "rev" attrs >>= traverse (\rev -> either (const (parseHashAs (Just sha1Algo) rev)) (pure . snd) (parseAnyHash Nothing (bytesToTextLossy rev)))++-- | The input's NAR hash in SRI, as upstream's @Input::getNarHash@ reads+-- it and writes it back: an SRI SHA-256, or the empty string for a+-- digest of zeros.+inputNarHash :: Attrs -> Checked (Maybe ByteString)+inputNarHash attrs =+  maybeStrAttr "narHash" attrs+    >>= traverse (either refuse (pure . sri) . parseNarHash . bytesToTextLossy)+  where+    sri digest = "sha256-" <> TE.encodeUtf8 (B64.encode digest)++-- | A digest in lower-case hex, as a Git revision is written.+gitRev :: ByteString -> ByteString+gitRev = TE.encodeUtf8 . bytesToHexText++-- | SHA-1, the algorithm of a Git revision.+sha1Algo :: Text+sha1Algo = "sha1"++-- | A hash read as upstream's @Hash::parseAny@ reads one, its digest.+parseHashAs :: Maybe Text -> ByteString -> Checked ByteString+parseHashAs algo hash = either refuse (pure . snd) (parseAnyHash algo (bytesToTextLossy hash))++-- | A Git input's signing key: its type and the key.+data PublicKey = PublicKey !ByteString !ByteString++-- | The type of a key that names none.+defaultKeyType :: ByteString+defaultKeyType = "ssh-ed25519"++publicKeyJson :: PublicKey -> Json+publicKeyJson (PublicKey keyType key) = JsonObject (Map.fromList [("key", JsonString (bytesToTextLossy key)), ("type", JsonString (bytesToTextLossy keyType))])++-- | A Git input's keys, as upstream's @getPublicKeys@ reads them: those+-- @publicKeys@ lists as JSON, then the one @publicKey@ names, of the type+-- @keytype@ names or @ssh-ed25519@.+publicKeys :: Attrs -> Checked [PublicKey]+publicKeys attrs = do+  listed <-+    maybeStrAttr "publicKeys" attrs >>= \case+      Nothing -> pure []+      Just text -> case parseJson (bytesToTextLossy text) of+        Left err -> refuse err+        Right (JsonArray items) -> traverse keyOf items+        Right other -> refuse (expectedType "array" other)+  single <-+    maybeStrAttr "publicKey" attrs >>= \case+      Nothing -> pure []+      Just key -> (\keyType -> [PublicKey (fromMaybe defaultKeyType keyType) key]) <$> maybeStrAttr "keytype" attrs+  pure (listed ++ single)+  where+    keyOf item = case item of+      JsonObject fields -> do+        keyType <- case Map.lookup "type" fields of+          Nothing -> pure defaultKeyType+          Just (JsonString t) -> pure (TE.encodeUtf8 t)+          Just other -> refuse (expectedType "string" other)+        key <- case Map.lookup "key" fields of+          Just (JsonString k) -> pure (TE.encodeUtf8 k)+          Just other -> refuse (expectedType "string" other)+          Nothing -> refuse ("Expected JSON object to contain key 'key' but it doesn't: " <> bytesToTextLossy (renderJson item))+        pure (PublicKey keyType key)+      other -> refuse (expectedType "object" other)+    expectedType want value = "Expected JSON value to be of type '" <> want <> "' but it is of type '" <> jsonTypeName value <> "': " <> bytesToTextLossy (renderJson value)+    jsonTypeName value = case value of+      JsonNull -> "null"+      JsonBool _ -> "boolean"+      JsonInt _ -> "number"+      JsonFloat _ -> "number"+      JsonString _ -> "string"+      JsonArray _ -> "array"+      JsonObject _ -> "object"++-- ---------------------------------------------------------------------------+-- Names+-- ---------------------------------------------------------------------------++-- | Whether a string is a full Git revision: 40 hex digits.+isRev :: ByteString -> Bool+isRev s = BS.length s == revLength && BC.all isHexDigit s++-- | Hex digits in a SHA-1.+revLength :: Int+revLength = 40++-- | Whether a string is a flake ID: a letter, then letters, digits, @_@+-- and @-@.+isFlakeId :: ByteString -> Bool+isFlakeId s = case BC.uncons s of+  Just (first, rest) -> (isAsciiLower first || isAsciiUpper first) && BC.all (\c -> isAlphaNum c || c == '_' || c == '-') rest+  Nothing -> False++isAlphaNum :: Char -> Bool+isAlphaNum c = isAsciiLower c || isAsciiUpper c || isDigit c++-- | Whether a string matches upstream's @refRegexS@: a letter, a digit+-- or @\@@, then letters, digits and @_.\/\@+-@.+matchesRefRegex :: ByteString -> Bool+matchesRefRegex s = case BC.uncons s of+  Just (first, rest) -> (isAlphaNum first || first == '@') && BC.all (\c -> isAlphaNum c || c `elem` ("_./@+-" :: String)) rest+  Nothing -> False++-- | Whether a name is one Git accepts for a ref, a branch or a tag, as+-- upstream's @isLegalRefName@ asks libgit2: not @\@@ alone and holding no+-- DEL, then valid as a ref name of one or more levels (git-check-ref-format):+-- no empty level, no level starting with a dot or ending in @.lock@, no+-- @..@ or @\@{@, no control character, space or any of @~^:?*[\\@, and+-- not ending in a dot.+isLegalRefName :: ByteString -> Bool+isLegalRefName name =+  name /= "@"+    && not (BC.elem '\DEL' name)+    && not (BS.null name)+    && not (".." `BS.isInfixOf` name)+    && not ("@{" `BS.isInfixOf` name)+    && not ("." `BS.isSuffixOf` name)+    && BC.all allowedChar name+    && all validLevel (BC.split '/' name)+  where+    allowedChar c = c > ' ' && c /= '\DEL' && c `notElem` ("~^:?*[\\" :: String)+    validLevel level =+      not (BS.null level)+        && not ("." `BS.isPrefixOf` level)+        && not (".lock" `BS.isSuffixOf` level)
+ src/Nix/Fetch/Tar.hs view
@@ -0,0 +1,827 @@+-- | The entries of a tar archive, read as libarchive's tar reader reads+-- them, the reader upstream's tarball fetcher unpacks with.+--+-- The reader is a pure machine fed chunks, so an archive is read as it+-- arrives: only a header, or the body of a header that names the next+-- entry, is ever held whole, a pax body is read a record at a time, and a+-- file's contents pass through as slices of the chunks fed.  It reads the+-- formats libarchive reads for source archives: v7, ustar with its prefix,+-- GNU with its long names, and pax extended headers.  A pax global header+-- is read for the attributes libarchive refuses in one and applies to+-- nothing, a GNU volume label is passed over, and a Solaris ACL header's+-- body is skipped unparsed.  A sparse member is refused, since nothing+-- here rebuilds its holes.+--+-- Names and link targets are bytes, as the archive carries them, and are+-- copies, so an entry does not keep alive the chunk it was read from.+module Nix.Fetch.Tar+  ( TarEntry (..),+    TarNode (..),+    TarFailure (..),+    TarStep (..),+    FileStep (..),+    tarReader,+  )+where++import Control.Applicative ((<|>))+import Data.Bits (complement, shiftL, testBit, xor, (.&.), (.|.))+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import Data.Int (Int64, Int8)+import Data.Maybe (fromMaybe, isNothing)+import Data.Text (Text)+import qualified Data.Text as T+import Data.Word (Word64, Word8)+import Nix.Fetch.Url (bytesToTextLossy)++-- ---------------------------------------------------------------------------+-- Entries and events+-- ---------------------------------------------------------------------------++-- | One entry, once every header naming it is read.+data TarEntry = TarEntry+  { -- | The path, as the archive names it.+    tarPath :: !ByteString,+    -- | The owner's execute bit of the entry's mode.+    tarExecutable :: !Bool,+    -- | What libarchive warns of while reading the entry's headers: the+    -- last warning, as its error string holds only the last.+    tarWarning :: !(Maybe Text)+  }+  deriving (Eq, Show)++-- | An entry that is not a regular file.+data TarNode+  = TarDirectory+  | TarSymlink !ByteString+  | -- | A hard link to the entry the path names.+    TarHardLink !ByteString+  | -- | A device or a FIFO, by the file type libarchive gives it.+    TarSpecial !Int+  deriving (Eq, Show)++-- | Why an archive stopped reading, in libarchive's words.+data TarFailure+  = -- | No format reader takes the input, so libarchive refuses to open it.+    TarUnrecognized+  | -- | A header, with the name the entry has so far, if it has one.+    TarHeaderFailure !(Maybe ByteString) !Text+  | -- | A regular file's contents.+    TarDataFailure !Text+  deriving (Eq, Show)++-- | The reader between entries.  Hand 'TarAwait' the next chunk, the+-- empty chunk meaning the end of input.  After 'TarDone' the rest of the+-- input is not read, as libarchive reads nothing past the end-of-archive+-- mark.  The continuations of 'TarFile' and 'TarOther' are lazy, so an+-- entry is handed over before the next is worked out.+data TarStep+  = TarAwait !(ByteString -> TarStep)+  | -- | A regular file of the given size, whose contents follow.+    TarFile !TarEntry !Word64 FileStep+  | TarOther !TarEntry !TarNode TarStep+  | TarDone+  | TarFail !TarFailure++-- | The reader inside a regular file's contents, which pass through as+-- slices of the chunks fed.+data FileStep+  = FileAwait !(ByteString -> FileStep)+  | FileChunk !ByteString FileStep+  | -- | The contents are complete, and the archive goes on.+    FileEnd TarStep+  | FileFail !TarFailure++-- | The reader at the start of an archive.+tarReader :: TarStep+tarReader = headers FirstHeader FormatOld noPending BS.empty++-- ---------------------------------------------------------------------------+-- Layout+-- ---------------------------------------------------------------------------++-- | Every header is one block, and every body is padded to whole blocks.+blockBytes :: Int+blockBytes = 512++-- | The bytes that pad a body of the given size to whole blocks.+paddingOf :: Int64 -> Int64+paddingOf size = negate size .&. fromIntegral (blockBytes - 1)++-- | A header field, by its offset and width in the ustar layout.+data Field = Field !Int !Int++nameField, modeField, uidField, gidField, sizeField, mtimeField, checksumField, linkNameField, magicField, versionField, devMajorField, devMinorField, prefixField :: Field+nameField = Field 0 100+modeField = Field 100 8+uidField = Field 108 8+gidField = Field 116 8+sizeField = Field 124 12+mtimeField = Field 136 12+checksumField = Field 148 8+linkNameField = Field 157 100+magicField = Field 257 6+versionField = Field 263 2+devMajorField = Field 329 8+devMinorField = Field 337 8+prefixField = Field 345 155++-- | Where the type flag is.+typeFlagOffset :: Int+typeFlagOffset = 156++-- | The bytes of a field.+fieldBytes :: Field -> ByteString -> ByteString+fieldBytes (Field offset width) = BS.take width . BS.drop offset++-- | A string field, to its first NUL.+fieldString :: Field -> ByteString -> ByteString+fieldString field = BS.takeWhile (/= 0) . fieldBytes field++-- | A numeric field, as libarchive reads one.+fieldNumber :: Field -> ByteString -> Int64+fieldNumber field = tarNumber . fieldBytes field++-- | The type flag of a header.+typeFlag :: ByteString -> Word8+typeFlag block = fromMaybe 0 (BS.indexMaybe block typeFlagOffset)++-- | The magic and version a POSIX ustar header carries.+ustarMagic, ustarVersion :: ByteString+ustarMagic = "ustar\0"+ustarVersion = "00"++-- | The magic and version GNU tar writes, eight bytes together.+gnuMagic, gnuVersion :: ByteString+gnuMagic = "ustar "+gnuVersion = " \0"++-- | Which writer a header's magic names, as libarchive tells them apart:+-- GNU's whole eight bytes, then the five that POSIX's begins with.+data Variant = VariantGnu | VariantUstar | VariantOld++variantOf :: ByteString -> Variant+variantOf block+  | hasGnuMagic block = VariantGnu+  | BS.take ustarStemBytes (fieldBytes magicField block) == BS.take ustarStemBytes ustarMagic = VariantUstar+  | otherwise = VariantOld+  where+    ustarStemBytes = 5++hasGnuMagic, hasUstarMagic :: ByteString -> Bool+hasGnuMagic block = fieldBytes magicField block == gnuMagic && fieldBytes versionField block == gnuVersion+hasUstarMagic block = fieldBytes magicField block == ustarMagic && fieldBytes versionField block == ustarVersion++-- | The path a header names: a ustar header's prefix and name joined by a+-- slash unless the prefix ends in one, and otherwise the name.  A GNU+-- header holds times where ustar's prefix is, so it has none.+headerPath :: ByteString -> ByteString+headerPath block = case (variantOf block, BS.unsnoc prefix) of+  (VariantUstar, Just (_, lastByte))+    | lastByte == slash -> prefix <> name+    | otherwise -> BS.snoc prefix slash <> name+  _ -> name+  where+    prefix = fieldString prefixField block+    name = fieldString nameField block++-- ---------------------------------------------------------------------------+-- Numbers+-- ---------------------------------------------------------------------------++-- | A numeric field as libarchive reads it: base 256 when its first byte+-- has the high bit set, as GNU tar writes a value octal cannot hold, and+-- otherwise octal.+tarNumber :: ByteString -> Int64+tarNumber bytes = case BS.uncons bytes of+  Just (lead, _) | testBit lead 7 -> base256 bytes+  _ -> baseN 8 bytes++-- | A number in a base: leading spaces and tabs, an optional minus sign,+-- then digits to the first byte that is not one, saturating on overflow.+baseN :: Integer -> ByteString -> Int64+baseN base bytes = go 0 digits+  where+    trimmed = BS.dropWhile (\b -> b == space || b == tab) bytes+    (sign, digits) = case BS.uncons trimmed of+      Just (b, rest) | b == minus -> (-1, rest)+      _ -> (1, trimmed)+    go :: Integer -> ByteString -> Int64+    go !acc rest = case BS.uncons rest of+      Just (b, more) | b >= zero && toInteger (b - zero) < base -> step (acc * base + sign * toInteger (b - zero)) more+      _ -> fromInteger acc+    step next more+      | next > toInteger (maxBound :: Int64) = maxBound+      | next < toInteger (minBound :: Int64) = minBound+      | otherwise = go next more++-- | A base-256 number: a big-endian two's complement value whose first byte's+-- high bit is the base-256 marker, saturating where it overflows 64 bits.+base256 :: ByteString -> Int64+base256 bytes = case BS.uncons bytes of+  Nothing -> 0+  Just (lead, rest)+    | testBit lead 6 -> fit 0xff (complement 0) (lead .|. 0x80) rest (BS.length bytes)+    | otherwise -> fit 0 0 (lead .&. 0x7f) rest (BS.length bytes)+  where+    fit :: Word8 -> Word64 -> Word8 -> ByteString -> Int -> Int64+    fit signByte start c rest count+      | count > int64Bytes = case BS.uncons rest of+          Just (next, more) | c == signByte -> fit signByte start next more (count - 1)+          _ -> saturated signByte+      | (c `xor` signByte) .&. 0x80 /= 0 = saturated signByte+      | otherwise = fromIntegral (BS.foldl' shiftIn (shiftIn start c) rest)+    saturated signByte = if signByte == 0 then maxBound else minBound+    shiftIn acc b = shiftL acc 8 .|. fromIntegral b+    int64Bytes = 8++-- ---------------------------------------------------------------------------+-- Header checks+-- ---------------------------------------------------------------------------++-- | Whether a block is the end-of-archive mark, all zeros.+nullBlock :: ByteString -> Bool+nullBlock = BS.all (== 0)++-- | libarchive's checksum test: the field holds octal, and equals the sum+-- of the header's bytes with the field read as spaces, the bytes unsigned+-- as POSIX says or signed as some old writers summed them.+checksumValid :: ByteString -> Bool+checksumValid block = BS.all octalOrPadding stored && (expected == unsignedSum || expected == signedSum)+  where+    stored = fieldBytes checksumField block+    octalOrPadding c = c == space || c == 0 || (c >= zero && c <= seven)+    expected = toInteger (baseN 8 stored)+    Field offset width = checksumField+    outside = BS.take offset block <> BS.drop (offset + width) block+    fieldAsSpaces = toInteger width * toInteger space+    unsignedSum = fieldAsSpaces + BS.foldl' (\acc b -> acc + toInteger b) 0 outside+    signedSum = fieldAsSpaces + BS.foldl' (\acc b -> acc + toInteger (fromIntegral b :: Int8)) 0 outside++-- | Whether libarchive's tar bidder takes a header: a valid checksum, a+-- type flag that is NUL or alphanumeric, and number fields that are base+-- 256 or octal with only padding after.+bidsAsTar :: ByteString -> Bool+bidsAsTar block =+  checksumValid block+    && (flag == 0 || isAlphaNumeric flag)+    && all (validNumber . (`fieldBytes` block)) [modeField, uidField, gidField, mtimeField, sizeField, devMajorField, devMinorField]+  where+    flag = typeFlag block+    isAlphaNumeric c = (c >= zero && c <= nine) || (c >= upperA && c <= upperZ) || (c >= lowerA && c <= lowerZ)+    validNumber bytes = case BS.uncons bytes of+      Just (marker, _) | marker == 0x80 || marker == 0xff || marker == 0 -> True+      _ -> BS.all (\c -> c == space || c == 0) (BS.dropWhile (\c -> c >= zero && c <= seven) (BS.dropWhile (== space) bytes))++-- | Whether the bidder scores a header past 50, the threshold above which+-- it takes a ustar header as the start of a tar archive and a hard link+-- keeps no body: the header is taken, and carries POSIX's or GNU's magic.+bidsAsHeader :: ByteString -> Bool+bidsAsHeader block = bidsAsTar block && (hasUstarMagic block || hasGnuMagic block)++-- ---------------------------------------------------------------------------+-- The header sequence+-- ---------------------------------------------------------------------------++-- | Whether a header is the archive's first, where libarchive decides the+-- input is a tar archive at all.+data Position = FirstHeader | LaterHeader++-- | The format libarchive records the archive as, as the last header+-- sets it: it decides whether a hard link's size counts.+data Format = FormatOld | FormatUstar | FormatGnu | FormatPax++-- | What the headers before an entry's own have said about it.+data Pending = Pending+  { pendingPath :: !(Maybe ByteString),+    pendingLink :: !(Maybe ByteString),+    pendingSize :: !(Maybe Int64),+    pendingSparse :: !Bool,+    pendingWarning :: !(Maybe Text),+    -- | The type flags of the headers seen.+    pendingSeen :: ![Word8],+    -- | Whether a header was seen after which the end of input is a+    -- damaged archive rather than its end: any but a volume label or a+    -- global header.+    pendingStarted :: !Bool+  }++noPending :: Pending+noPending = Pending Nothing Nothing Nothing False Nothing [] False++-- | Fail while reading an entry's headers, naming the entry as far as+-- they have.+failFor :: Pending -> Text -> TarStep+failFor pending = TarFail . TarHeaderFailure (pendingPath pending)++-- | Read the headers of the next entry, from what is left of the last+-- chunk.+headers :: Position -> Format -> Pending -> ByteString -> TarStep+headers position format pending leftover = collect blockBytes leftover header short+  where+    short partial+      | BS.null partial && pendingStarted pending = failHeader "Damaged tar archive (end-of-archive within a sequence of headers)"+      | BS.null partial = TarDone+      | FirstHeader <- position = TarFail TarUnrecognized+      | otherwise = failHeader "Truncated tar archive detected while reading next header"+    header block rest+      | nullBlock block = TarDone+      | FirstHeader <- position, not (bidsAsTar block) = TarFail TarUnrecognized+      | not (checksumValid block) = failHeader "Damaged tar archive (bad header checksum)"+      | otherwise = special block rest+    failHeader = failFor pending+    later = headers LaterHeader+    seen flag = flag `elem` pendingSeen pending+    marked flag =+      pending+        { pendingSeen = flag : pendingSeen pending,+          pendingStarted = pendingStarted pending || (flag /= volumeFlag && flag /= globalFlag)+        }+    warned flag message+      | seen flag = (marked flag) {pendingWarning = Just message}+      | otherwise = marked flag+    metadataShort = failHeader "Truncated archive detected while reading metadata"+    special block rest = case typeFlag block of+      flag+        | flag == aclFlag, seen flag -> failHeader "Redundant 'A' header"+        | flag == aclFlag -> specialBody block rest (marked flag) (const id) (later FormatPax)+        | flag == globalFlag, seen flag -> failHeader "Redundant 'g' header"+        | flag == globalFlag -> paxHeader PaxGlobal block rest (marked flag)+        | flag == longLinkFlag ->+            specialBody block rest (warned flag "Damaged archive: Redundant 'K' headers may cause linknames to be incorrect") (\body updated -> updated {pendingLink = Just (cString body)}) (later FormatGnu)+        | flag == longNameFlag ->+            specialBody block rest (warned flag "Damaged archive: Redundant 'L' headers may cause filenames to be incorrect") (\body updated -> updated {pendingPath = Just (cString body)}) (later FormatGnu)+        | flag == volumeFlag, bodySize block < 0 || bodySize block > pathnameLimit -> failHeader "Damaged tar archive (invalid GNU volume header)"+        | flag == volumeFlag ->+            -- The label's block is consumed with its body, so a short input+            -- is reported against both.+            skipping (fromIntegral blockBytes + padded (bodySize block)) (fromIntegral blockBytes) rest (later FormatGnu (warned flag "Redundant 'V' header")) failHeader+        | flag == sunPaxFlag || flag == paxFlag,+          seen sunPaxFlag || seen paxFlag ->+            failHeader (if flag == paxFlag then "Redundant 'x' header" else "Redundant 'X'/'x' header")+        | flag == sunPaxFlag || flag == paxFlag -> paxHeader PaxExtended block rest (marked flag)+        | otherwise -> entryHeader format pending block rest+    -- The body of a long name, a long link or an ACL, held whole, with+    -- the headers' state once the flag is marked and how the body+    -- changes it.  The body's padding is consumed with it, so a short+    -- input is reported against both.+    specialBody block rest marking update next+      | size < 0 || size > entryLimit = failHeader ("Special header has invalid size: " <> T.pack (show size))+      | size > pathnameLimit =+          skipping (padded size) 0 rest (next marking {pendingWarning = Just ("Special header too large: " <> T.pack (show size) <> " > 1MiB")}) failHeader+      | otherwise =+          collect+            (fromIntegral size)+            rest+            (\body afterBody -> let updated = update body marking in skipping (size + paddingOf size) size afterBody (next updated) (failFor updated))+            (const metadataShort)+      where+        size = bodySize block+    paxHeader scope block rest marking+      | size < 0 = failHeader ("pax extension header has invalid size: " <> T.pack (show size))+      | size == 0 = failHeader (case scope of PaxGlobal -> "Invalid empty pax global extended header"; PaxExtended -> "Invalid empty pax extended header")+      | size > paxBodyLimit =+          skipping (padded size) 0 rest (later FormatPax marking {pendingWarning = Just ("Ignoring oversized pax extensions: " <> T.pack (show size) <> " > " <> T.pack (show paxBodyLimit))}) failHeader+      | otherwise = paxBody scope (later FormatPax) marking size rest+      where+        size = bodySize block++-- | The size a special header's body declares.+bodySize :: ByteString -> Int64+bodySize = fieldNumber sizeField++-- | A body's size with its padding.+padded :: Int64 -> Int64+padded size = size + paddingOf size++-- | A string to its first NUL, as libarchive copies a header's body.+cString :: ByteString -> ByteString+cString = BS.takeWhile (/= 0)++-- | The longest body libarchive reads for a long name, a long link or a+-- volume label: 1 MiB.+pathnameLimit :: Int64+pathnameLimit = 1048576++-- | The largest pax body libarchive reads, 1 GiB, past which it passes+-- over the body with a warning.+paxBodyLimit :: Int64+paxBodyLimit = 1073741824++-- | The largest entry size libarchive accepts, 2^60 bytes.+entryLimit :: Int64+entryLimit = 0xfffffffffffffff++-- ---------------------------------------------------------------------------+-- pax records+-- ---------------------------------------------------------------------------++-- | What a pax header applies to: the entry after it, or, as a global+-- header says, every entry after it, which libarchive does not do and so+-- refuses the attributes that would need it.+data PaxScope = PaxExtended | PaxGlobal++-- | The names a pax body gives, which libarchive sets on the entry only+-- once it has read the whole body.+data PaxNames = PaxNames+  { paxPath :: !(Maybe ByteString),+    paxLink :: !(Maybe ByteString)+  }++-- | The names set on the entry the body is for, a path or a link target+-- of no bytes at all given having been ignored.+applyNames :: PaxNames -> Pending -> Pending+applyNames names pending =+  pending+    { pendingPath = (cString <$> paxPath names) <|> pendingPath pending,+      pendingLink = (cString <$> paxLink names) <|> pendingLink pending+    }++-- | What a pax key is for.+data PaxKey = PathKey | LinkKey | SizeKey | SparseKey | OtherKey++paxKeyOf :: ByteString -> PaxKey+paxKeyOf key+  | key == "path" = PathKey+  | key == "linkpath" = LinkKey+  | key == "size" = SizeKey+  | "GNU.sparse." `BS.isPrefixOf` key = SparseKey+  | otherwise = OtherKey++-- | One record of a pax body, read up to its value.+data PaxRecord = PaxRecord+  { recordKey :: !ByteString,+    -- | The bytes of the record's length, key and equals sign.+    recordPrologue :: !Int,+    -- | The bytes of the record's value, its newline not counted.+    recordValue :: !Int64+  }++-- | Read a pax body a record at a time, as libarchive does, and keep only+-- what it applies: the size, a sparse marker and the names, which are set+-- once the body is read through.  A malformed record warns and ends the+-- reading, the rest of the body passed over, and the names before it are+-- not set; a value is applied before its record's newline is checked.  A+-- global body applies nothing and refuses the attributes that libarchive+-- would have to apply to every entry.+--+-- @finish@ goes on from the headers once the body, with its padding, is+-- read.+paxBody :: PaxScope -> (Pending -> ByteString -> TarStep) -> Pending -> Int64 -> ByteString -> TarStep+paxBody scope finish marking size = records marking (PaxNames Nothing Nothing) size+  where+    padding = paddingOf size+    records pending names remaining bytes+      | remaining == 0 =+          let applied = applyNames names pending+           in skipping padding 0 bytes (finish applied) (failFor applied)+      | otherwise =+          peeking+            (fromIntegral (windowOf remaining))+            bytes+            (record pending names remaining)+            (failFor pending "Truncated tar archive detected while reading pax attribute name")+    record pending names remaining ahead = case paxRecord (BS.take (fromIntegral (windowOf remaining)) ahead) remaining of+      Left message -> abandon pending message remaining ahead+      Right found+        | PaxGlobal <- scope,+          refusedGlobally (recordKey found) ->+            failFor pending ("Unsupported pax global extended header attribute '" <> bytesToTextLossy (recordKey found) <> "'")+        | otherwise -> value pending names (remaining - fromIntegral (recordPrologue found)) found (BS.drop (recordPrologue found) ahead)+    -- A record's value, from the bytes after its equals sign.+    value pending names remaining found bytes = case scope of+      PaxGlobal -> ignored pending+      PaxExtended -> case paxKeyOf (recordKey found) of+        PathKey -> keepName (\v -> names {paxPath = nonEmpty v})+        LinkKey -> keepName (\v -> names {paxLink = nonEmpty v})+        SizeKey+          -- A size too long to be a number fails without a message.+          | len > paxNumberLimit -> failFor pending ""+          | otherwise ->+              collect+                (fromIntegral len)+                bytes+                (sized . baseN 10)+                (const metadataShort)+        SparseKey -> ignored pending {pendingSparse = True}+        OtherKey -> ignored pending+      where+        len = recordValue found+        left = remaining - len+        nonEmpty v = if BS.null v then Nothing else Just v+        metadataShort = failFor pending "Truncated archive detected while reading metadata"+        ignored kept =+          skipping len 0 bytes (terminated kept names left) (const (failFor pending "Truncated tar archive detected while completing pax attribute"))+        -- A name too long to keep is passed over with a warning, and one+        -- of no bytes is not a name.+        keepName store+          | len > pathnameLimit =+              skipping len 0 bytes (terminated pending {pendingWarning = Just ""} names left) (failFor pending)+          | otherwise =+              collect (fromIntegral len) bytes (\v after -> terminated pending (store v) left after) (const metadataShort)+        sized number after+          | number < 0 || number == maxBound = failFor pending "Tar size attribute overflow"+          | otherwise = terminated pending {pendingSize = Just number} names left after+    -- A record ends in a newline, checked once its value is applied.+    terminated pending names remaining bytes =+      peeking 1 bytes check (failFor pending "Truncated tar archive detected while completing pax attribute")+      where+        check available = case BS.uncons available of+          Just (c, after) | c == lineFeed -> records pending names (remaining - 1) after+          _ -> abandon pending "Malformed pax attributes" remaining available+    -- A body that cannot be read on is passed over, with a warning.+    abandon pending message remaining bytes =+      skipping (remaining + padding) 0 bytes (finish pending {pendingWarning = Just message}) (failFor pending)++-- | The most of a record libarchive looks at to find its length and key.+paxPrologueBytes :: Int64+paxPrologueBytes = 512++-- | The bytes of what is left of a body that libarchive looks at to find+-- the next record's length and key.+windowOf :: Int64 -> Int64+windowOf = min paxPrologueBytes++-- | The longest record libarchive reads, as its length says.+paxLineLimit :: Int64+paxLineLimit = 99999999++-- | The longest number a pax record may hold, as libarchive reads one.+paxNumberLimit :: Int64+paxNumberLimit = 64++-- | The first record of what is left of a pax body, from the window+-- libarchive looks at, or why it is malformed.+paxRecord :: ByteString -> Int64 -> Either Text PaxRecord+paxRecord window remaining = do+  (lineLength, lengthBytes) <- paxLength window+  if lineLength > remaining+    then Left ("Ignoring malformed pax attribute:  " <> T.pack (show lineLength) <> " > " <> T.pack (show remaining))+    else Right ()+  let keyArea = BS.take (fromIntegral lineLength - lengthBytes) (BS.drop lengthBytes window)+  case BS.uncons keyArea of+    Just (c, _) | c /= equals -> Right ()+    _ -> Left "Ignoring malformed pax attributes: empty name found"+  keyLength <- maybe (Left "Ignoring malformed pax attributes: overlarge attribute name") Right (BS.elemIndex equals keyArea)+  let prologue = lengthBytes + keyLength + 1+      valueBytes = fromIntegral lineLength - prologue+  if valueBytes == 0+    then Left "Malformed pax attributes"+    else Right (PaxRecord (BS.take keyLength keyArea) prologue (fromIntegral valueBytes - 1))++-- | The length a record opens with, and the bytes it and the space after+-- it take.+paxLength :: ByteString -> Either Text (Int64, Int)+paxLength = go 0 0+  where+    go :: Int64 -> Int -> ByteString -> Either Text (Int64, Int)+    go !acc !used bytes = case BS.uncons bytes of+      Nothing -> Left "Ignoring malformed pax attributes: overlarge attribute size field"+      Just (c, rest)+        | c == space -> Right (acc, used + 1)+        | c < zero || c > nine -> Left "Ignoring malformed pax attributes: malformed attribute size field"+        | next > paxLineLimit -> Left ("Ignoring malformed pax attribute: size > " <> T.pack (show paxLineLimit))+        | otherwise -> go next (used + 1) rest+        where+          next = acc * 10 + fromIntegral (c - zero)++-- | Whether libarchive refuses an attribute in a pax global header, whose+-- attributes it would have to apply to every entry after it and does not:+-- the ones it acts on in an extended header, exactly or by prefix.+refusedGlobally :: ByteString -> Bool+refusedGlobally key = key `elem` exact || any prefixed prefixes+  where+    exact =+      [ "atime",+        "ctime",+        "gid",+        "gname",+        "hdrcharset",+        "linkpath",+        "mtime",+        "path",+        "size",+        "uid",+        "uname",+        "GNU.sparse",+        "LIBARCHIVE.creationtime",+        "LIBARCHIVE.symlinktype",+        "RHT.security.selinux",+        "SCHILY.acl.access",+        "SCHILY.acl.ace",+        "SCHILY.acl.default",+        "SCHILY.dev",+        "SCHILY.devmajor",+        "SCHILY.devminor",+        "SCHILY.fflags",+        "SCHILY.ino",+        "SCHILY.nlink",+        "SCHILY.realsize",+        "SUN.holesdata"+      ]+    prefixes = ["GNU.sparse.", "LIBARCHIVE.xattr.", "SCHILY.xattr."]+    prefixed prefix = BS.length key > BS.length prefix && prefix `BS.isPrefixOf` key++-- ---------------------------------------------------------------------------+-- An entry's own header+-- ---------------------------------------------------------------------------++-- | Read an entry's own header, with what the headers before it said, and+-- go on past its body.+entryHeader :: Format -> Pending -> ByteString -> ByteString -> TarStep+entryHeader format pending block rest+  | pendingSparse pending || flag == sparseFlag = failWith "sparse archive members are not supported"+  | size < 0 = failWith "Tar entry has negative file size"+  | size > entryLimit = failWith "Tar entry size overflow"+  | otherwise = case node of+      Nothing -> TarFile entry (fromIntegral size) (fileContents size rest (\after -> skipping (paddingOf size) 0 after next (TarFail . TarDataFailure)))+      Just other -> TarOther entry other (bodyAfter other)+  where+    flag = typeFlag block+    headerFormat = case (variantOf block, format) of+      (VariantGnu, _) -> FormatGnu+      (VariantUstar, FormatPax) -> FormatPax+      (VariantUstar, _) -> FormatUstar+      (VariantOld, _) -> FormatOld+    -- Names are copied, so no entry holds the chunk its header came in.+    path = BS.copy $ case pendingPath pending of+      Just named | not (BS.null named) -> named+      _ -> headerPath block+    link = BS.copy $ case pendingLink pending of+      Just named | not (BS.null named) -> named+      _ -> fieldString linkNameField block+    size = fromMaybe (fieldNumber sizeField block) (pendingSize pending)+    -- A link a GNU long-link header or a pax linkpath gave is set as a hard+    -- link on any entry that is not a symlink, a regular file or a+    -- directory among them.+    givenLink = case pendingLink pending of+      Just target | flag /= symlinkFlag && flag /= hardLinkFlag -> Just (BS.copy target)+      _ -> Nothing+    -- libarchive reads a regular entry whose name ends in a slash as a+    -- directory, with no body, when its headers gave no warning.+    endsInSlash = maybe False ((== slash) . snd) (BS.unsnoc path)+    asDirectory = regular && endsInSlash && isNothing (pendingWarning pending)+    -- Whether the type flag is one libarchive reads as a regular file.+    regular = flag `notElem` [hardLinkFlag, symlinkFlag, charDeviceFlag, blockDeviceFlag, directoryFlag, fifoFlag, dumpDirFlag]+    -- What the entry is, when it is not a regular file.+    node+      | Just target <- givenLink = Just (TarHardLink target)+      | flag == hardLinkFlag = Just (TarHardLink link)+      | flag == symlinkFlag = Just (TarSymlink link)+      | flag == charDeviceFlag = Just (TarSpecial characterDeviceType)+      | flag == blockDeviceFlag = Just (TarSpecial blockDeviceType)+      | flag == directoryFlag || flag == dumpDirFlag = Just TarDirectory+      | flag == fifoFlag = Just (TarSpecial fifoType)+      | asDirectory = Just TarDirectory+      | otherwise = Nothing+    entry =+      TarEntry+        { tarPath = path,+          tarExecutable = testBit (fieldNumber modeField block) ownerExecuteBit,+          tarWarning = pendingWarning pending+        }+    next = headers LaterHeader headerFormat noPending+    -- What follows an entry that is not a regular file.  A hard link keeps+    -- its size by the rules below; the body a regular entry or a dump+    -- directory has is passed over when the entry is a hard link only+    -- through a given link.+    bodyAfter other = case other of+      TarHardLink _+        | flag == hardLinkFlag -> hardLinkBody+        | hasBody -> skipBody rest+      TarDirectory | flag == dumpDirFlag -> skipBody rest+      _ -> next rest+    hasBody = flag == dumpDirFlag || (regular && not asDirectory)+    -- A hard link's size counts in a pax archive and not in a GNU or old+    -- one.  In a ustar archive it counts unless libarchive's bidder takes+    -- the link's own header, which a standard ustar header always is.+    hardLinkBody+      | size == 0 = next rest+      | otherwise = case headerFormat of+          FormatPax -> skipBody rest+          FormatGnu -> next rest+          FormatOld -> next rest+          FormatUstar+            | bidsAsHeader block -> next rest+            | otherwise -> skipBody rest+    -- A body no reader asks for is passed over when the next header is+    -- read, which a short input fails without naming an entry.+    skipBody bytes = skipping (padded size) 0 bytes next (TarFail . TarHeaderFailure Nothing)+    failWith = TarFail . TarHeaderFailure (Just path)++-- | The owner's execute bit of a mode.+ownerExecuteBit :: Int+ownerExecuteBit = 6++-- | libarchive's file types for the entries upstream refuses, as its+-- refusal prints them.+characterDeviceType, blockDeviceType, fifoType :: Int+characterDeviceType = 0o020000+blockDeviceType = 0o060000+fifoType = 0o010000++-- ---------------------------------------------------------------------------+-- Reading bytes+-- ---------------------------------------------------------------------------++-- | Collect exactly @n@ bytes from what is left of the last chunk and then+-- from chunks fed, handing them on with what follows them, or handing on+-- what was collected when the input ends first.+collect :: Int -> ByteString -> (ByteString -> ByteString -> TarStep) -> (ByteString -> TarStep) -> TarStep+collect n leftover got short+  | BS.length leftover >= n = uncurry got (BS.splitAt n leftover)+  | otherwise = go [leftover] (BS.length leftover)+  where+    go held have = TarAwait (fed held have)+    fed held have chunk+      | BS.null chunk = short (BS.concat (reverse held))+      | have + BS.length chunk >= n = uncurry got (BS.splitAt n (BS.concat (reverse (chunk : held))))+      | otherwise = go (chunk : held) (have + BS.length chunk)++-- | Hand on at least @n@ bytes of what is left of the last chunk and then+-- of chunks fed, none of them passed over, or go on with @short@ when the+-- input ends first.  What is left of the chunk is handed on as it is, not+-- copied, when it holds @n@ bytes already.+peeking :: Int -> ByteString -> (ByteString -> TarStep) -> TarStep -> TarStep+peeking n leftover got short+  | BS.length leftover >= n = got leftover+  | otherwise = TarAwait $ \chunk ->+      if BS.null chunk then short else peeking n (leftover <> chunk) got short++-- | Pass over the rest of a request for @needed@ bytes, @held@ of which+-- are already in hand, then go on with what follows them.  When the input+-- ends first the request fails in libarchive's words, which count the+-- bytes the request asked for and the bytes there were.+skipping :: Int64 -> Int64 -> ByteString -> (ByteString -> TarStep) -> (Text -> TarStep) -> TarStep+skipping needed held leftover next failed = go (needed - held) leftover+  where+    go owed bytes+      | owed <= fromIntegral (BS.length bytes) = next (BS.drop (fromIntegral owed) bytes)+      | otherwise = TarAwait $ \chunk ->+          let remaining = owed - fromIntegral (BS.length bytes)+           in if BS.null chunk then failed (truncatedInput needed (needed - remaining)) else go remaining chunk++-- | libarchive's words for a request to pass over bytes that the input+-- ends before.+truncatedInput :: Int64 -> Int64 -> Text+truncatedInput needed available =+  "Truncated input file (needed " <> T.pack (show needed) <> " bytes, only " <> T.pack (show available) <> " available)"++-- | A file's @n@ bytes of contents as they arrive, then the archive+-- after them, or a failure when the input ends first.+fileContents :: Int64 -> ByteString -> (ByteString -> TarStep) -> FileStep+fileContents n leftover next = go n leftover+  where+    go owed bytes+      | owed <= fromIntegral (BS.length bytes) =+          let (slice, rest) = BS.splitAt (fromIntegral owed) bytes+           in chunk slice (FileEnd (next rest))+      | otherwise = chunk bytes (FileAwait (fed (owed - fromIntegral (BS.length bytes))))+    fed owed bytes+      | BS.null bytes = FileFail (TarDataFailure truncatedDataMessage)+      | otherwise = go owed bytes+    chunk slice after+      | BS.null slice = after+      | otherwise = FileChunk slice after++-- | libarchive's words for an archive that ends inside an entry's body.+truncatedDataMessage :: Text+truncatedDataMessage = "Truncated tar archive detected while reading data"++-- ---------------------------------------------------------------------------+-- Bytes+-- ---------------------------------------------------------------------------++space, tab, minus, zero, seven, nine, equals, lineFeed, slash, upperA, upperZ, lowerA, lowerZ :: Word8+space = 0x20+tab = 0x09+minus = 0x2d+zero = 0x30+seven = 0x37+nine = 0x39+equals = 0x3d+lineFeed = 0x0a+slash = 0x2f+upperA = 0x41+upperZ = 0x5a+lowerA = 0x61+lowerZ = 0x7a++-- | The type flags the reader acts on.+hardLinkFlag, symlinkFlag, charDeviceFlag, blockDeviceFlag, directoryFlag, fifoFlag, dumpDirFlag, sparseFlag, aclFlag, globalFlag, longLinkFlag, longNameFlag, volumeFlag, sunPaxFlag, paxFlag :: Word8+hardLinkFlag = 0x31+symlinkFlag = 0x32+charDeviceFlag = 0x33+blockDeviceFlag = 0x34+directoryFlag = 0x35+fifoFlag = 0x36+dumpDirFlag = 0x44+sparseFlag = 0x53+aclFlag = 0x41+globalFlag = 0x67+longLinkFlag = 0x4b+longNameFlag = 0x4c+volumeFlag = 0x56+sunPaxFlag = 0x58+paxFlag = 0x78
+ src/Nix/Fetch/Tree.hs view
@@ -0,0 +1,207 @@+{-# LANGUAGE LambdaCase #-}++-- | A fetched tree, as a fetcher builds it before anything is written to+-- the store: every name in it, what each names, and where a file's bytes+-- are.  The tree is never extracted to a directory and copied, since a+-- volume that folds case would merge two names that differ only in case;+-- its NAR is streamed instead, once to give its hash and once into the+-- store, whose restore spells each name for its volume.+module Nix.Fetch.Tree+  ( -- * Trees+    Tree (..),+    dereferenceSingleton,++    -- * NARs+    NarPiece (..),+    narPieces,+    Blob (..),+    blobFile,+    withTreeNarSource,+    treeNarHash,+    treeNarBytes,+  )+where++import Control.Exception (bracketOnError, finally, throwIO)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Builder as B+import qualified Data.ByteString.Lazy as BL+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Word (Word64)+import qualified NovaCache.Hash as Hash+import qualified NovaCache.NAR.Stream as Stream+import System.FilePath ((</>))+import System.IO (Handle, IOMode (ReadMode), hClose, openBinaryFile)++-- ---------------------------------------------------------------------------+-- Trees+-- ---------------------------------------------------------------------------++-- | A tree whose files' bytes are where @blob@ says.  A directory's+-- entries are keyed by their names' bytes, which is the order a NAR+-- lists them in.+data Tree blob+  = -- | A regular file: whether it is executable, and its bytes.+    TreeFile !Bool !blob+  | TreeSymlink !ByteString+  | TreeDirectory !(Map ByteString (Tree blob))+  deriving (Eq, Show)++-- | The tree a fetched archive gives: the one directory at its top, when+-- it holds a directory and nothing else, as upstream's tarball cache+-- dereferences a singleton directory, and otherwise the archive's own+-- top.+dereferenceSingleton :: Tree blob -> Tree blob+dereferenceSingleton tree = case tree of+  TreeDirectory entries+    | [(_, inner@(TreeDirectory _))] <- Map.toList entries -> inner+  _ -> tree++-- ---------------------------------------------------------------------------+-- NARs+-- ---------------------------------------------------------------------------++-- | A piece of a tree's NAR: structural bytes, or a file's contents of a+-- size, framed by the pieces around them.+data NarPiece blob+  = NarBytes !ByteString+  | NarContents !Word64 !blob+  deriving (Eq, Show)++-- | A tree's NAR, as the pieces it is made of, with each file's size+-- read off its blob.  Consecutive structural bytes are one piece, joined+-- once however long the run.+narPieces :: (blob -> Word64) -> Tree blob -> [NarPiece blob]+narPieces sizeOf tree = coalesce (bytesOf (narString Stream.tokMagic) : node tree [])+  where+    node current rest = case current of+      TreeFile executable blob ->+        let size = sizeOf blob+         in bytesOf+              ( open+                  <> narString Stream.tokRegular+                  <> (if executable then narString Stream.tokExecutable <> narString BS.empty else mempty)+                  <> narString Stream.tokContents+                  <> B.word64LE size+              )+              : NarContents size blob+              : bytesOf (padding size <> close)+              : rest+      TreeSymlink target ->+        bytesOf (open <> narString Stream.tokSymlink <> narString Stream.tokTarget <> narString target <> close) : rest+      TreeDirectory entries ->+        bytesOf (open <> narString Stream.tokDirectory)+          : Map.foldrWithKey entry (bytesOf close : rest) entries+    entry name sub rest =+      bytesOf (narString Stream.tokEntry <> narString Stream.tokLParen <> narString Stream.tokName <> narString name <> narString Stream.tokNode)+        : node sub (bytesOf close : rest)+    open = narString Stream.tokLParen <> narString Stream.tokType+    close = narString Stream.tokRParen+    padding size = B.byteString (BS.replicate (Stream.narPadOf size) 0)+    bytesOf = NarBytes . BL.toStrict . B.toLazyByteString+    coalesce pieces = case pieces of+      NarBytes first : rest ->+        let (run, after) = bytesRun rest+         in NarBytes (BS.concat (first : run)) : coalesce after+      piece : rest -> piece : coalesce rest+      [] -> []+    -- The structural bytes at the head of the pieces, and the pieces after them.+    bytesRun pieces = case pieces of+      NarBytes bytes : rest -> let (run, after) = bytesRun rest in (bytes : run, after)+      _ -> ([], pieces)++-- | A NAR wire string: its length, its bytes and its padding.+narString :: ByteString -> B.Builder+narString bytes =+  B.word64LE (fromIntegral (BS.length bytes))+    <> B.byteString bytes+    <> B.byteString (BS.replicate (Stream.narPad (BS.length bytes)) 0)++-- | A file a fetcher wrote, holding a fetched file's bytes: its number+-- among the fetch's files and its size.  The file is named by number+-- under the directory the fetch wrote its files to ('blobFile'), so a+-- tree of many files holds no path for each.+data Blob = Blob+  { blobNumber :: !Int,+    blobSize :: !Word64+  }+  deriving (Eq, Show)++-- | The file holding a blob's bytes, under the directory the fetch wrote+-- its files to.+blobFile :: FilePath -> Blob -> FilePath+blobFile scratch blob = scratch </> show (blobNumber blob)++-- | How far a NAR source has got: the pieces still to give, or a blob+-- open part way with the bytes it still owes.+data SourceState+  = SourcePieces ![NarPiece Blob]+  | SourceBlob !Handle !FilePath !Word64 ![NarPiece Blob]++-- | The bytes read from a blob at a time.+blobChunkBytes :: Int+blobChunkBytes = 131072++-- | A tree's NAR as a pull source of chunks, the empty chunk ending it,+-- with no blob's bytes held whole.  A blob holding fewer bytes than its+-- size fails the pull.  A blob still open when the continuation returns+-- is closed.  This source and its state are one deliberate boundary of+-- mutable state, as the store's own NAR sources are.  The blobs are read+-- from the directory the fetch wrote them to.+withTreeNarSource :: FilePath -> Tree Blob -> (IO ByteString -> IO a) -> IO a+withTreeNarSource scratch tree consume = do+  stateRef <- newIORef (SourcePieces (narPieces blobSize tree))+  consume (pull scratch stateRef) `finally` (closeHeld =<< readIORef stateRef)+  where+    closeHeld state = case state of+      SourceBlob handle _ _ _ -> hClose handle+      SourcePieces _ -> pure ()++-- | The next chunk of a NAR source.+pull :: FilePath -> IORef SourceState -> IO ByteString+pull scratch stateRef =+  readIORef stateRef >>= \case+    SourcePieces [] -> pure BS.empty+    SourcePieces (NarBytes bytes : rest) -> bytes <$ writeIORef stateRef (SourcePieces rest)+    SourcePieces (NarContents 0 _ : rest) -> writeIORef stateRef (SourcePieces rest) >> pull scratch stateRef+    -- The handle is the state's as soon as it is open, so the+    -- continuation's exit closes it whatever interrupts the pull.+    SourcePieces (NarContents size blob : rest) -> do+      let file = blobFile scratch blob+      bracketOnError (openBinaryFile file ReadMode) hClose $ \handle ->+        writeIORef stateRef (SourceBlob handle file size rest)+      pull scratch stateRef+    SourceBlob handle file owed rest -> do+      chunk <- BS.hGet handle (fromIntegral (min owed (fromIntegral blobChunkBytes)))+      if BS.null chunk+        then throwIO (userError ("the fetched file " <> file <> " ends before its size"))+        else do+          let remaining = owed - fromIntegral (BS.length chunk)+          if remaining == 0+            then hClose handle >> writeIORef stateRef (SourcePieces rest)+            else writeIORef stateRef (SourceBlob handle file remaining rest)+          pure chunk++-- | A tree's NAR hash, its NAR streamed once, from the blobs under the+-- directory the fetch wrote them to.+treeNarHash :: FilePath -> Tree Blob -> IO Hash.NixHash+treeNarHash scratch tree = withTreeNarSource scratch tree (go Hash.hashInit)+  where+    go !ctx source = do+      chunk <- source+      if BS.null chunk+        then pure (Hash.hashFinalize ctx)+        else go (Hash.hashUpdate ctx chunk) source++-- | A tree's NAR, held whole, for a store that takes a tree as bytes.  A+-- restore into a store directory streams the NAR instead+-- ('withTreeNarSource'), so the tree is never held whole there.+treeNarBytes :: FilePath -> Tree Blob -> IO ByteString+treeNarBytes scratch tree = withTreeNarSource scratch tree (go [])+  where+    go held source = do+      chunk <- source+      if BS.null chunk then pure (BS.concat (reverse held)) else go (chunk : held) source
+ src/Nix/Fetch/Url.hs view
@@ -0,0 +1,765 @@+{-# LANGUAGE LambdaCase #-}++-- | URLs as upstream's fetchers read and write them: parsed into a+-- scheme, an authority, a path of decoded segments, a query and a+-- fragment, and rendered back with the percent-encoding upstream applies+-- (url.cc at 2.36.0).+--+-- Upstream parses with Boost.URL's grammar for a URI reference (RFC+-- 3986), so a string with a character the grammar has no place for is not+-- a URL, and a flake reference falls back to being a path.  Its lenient+-- mode, the one flake references use, first percent-encodes the spaces+-- and double quotes in a query and the spaces, double quotes and carets+-- in a fragment, which older releases let through unencoded.+--+-- A URL is bytes: a path segment may decode to any byte, so every part is+-- held as a 'ByteString', and a message spells one through+-- 'bytesToTextLossy'.  Every function here is pure; a warning a parse+-- gives is returned with its result ('Checked').+module Nix.Fetch.Url+  ( -- * Checked results+    Checked,+    runChecked,+    refuse,+    warn,++    -- * URLs+    ParsedUrl (..),+    Authority (..),+    HostType (..),+    Leniency (..),+    parseUrl,+    renderUrl,+    renderAuthority,+    urlPathSegments,+    emptyAuthority,++    -- * Schemes+    UrlScheme (..),+    parseUrlScheme,++    -- * Encoding+    percentEncode,+    encodeUrlPath,+    percentDecode,+    decodeQuery,+    encodeQuery,++    -- * Git URLs+    fixGitUrl,++    -- * Paths+    pathToUrlPath,+    urlPathToPath,+    isAbsoluteHostPath,++    -- * Messages+    bytesToTextLossy,+  )+where++import Control.Monad (forM, unless, when)+import Control.Monad.Except (ExceptT, runExceptT, throwError)+import Control.Monad.Writer.Strict (Writer, runWriter, tell)+import Data.Bits (shiftR, (.&.))+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BC+import Data.Char (isAsciiLower, isAsciiUpper, isDigit, isHexDigit, toLower)+import Data.List (intercalate)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing)+import Data.Text (Text)+import qualified Data.Text.Encoding as TE+import Data.Text.Encoding.Error (lenientDecode)+import Data.Word (Word16, Word8)+import Nix.Eval.Policy (PathRules (..))+import Numeric (showHex)++-- ---------------------------------------------------------------------------+-- Checked results+-- ---------------------------------------------------------------------------++-- | A step that may refuse its input, with the warnings it gave in the+-- order it gave them.  The warnings outlive a refusal, as upstream prints+-- each one when it is given, before any later error.+type Checked = ExceptT Text (Writer [Text])++-- | The outcome of a checked step and the warnings it gave.+runChecked :: Checked a -> (Either Text a, [Text])+runChecked = runWriter . runExceptT++-- | Refuse, with upstream's message.+refuse :: Text -> Checked a+refuse = throwError++-- | Give a warning, upstream's text without its @warning:@ prefix.+warn :: Text -> Checked ()+warn message = tell [message]++-- | Bytes as text for a message, a byte with no UTF-8 reading replaced.+bytesToTextLossy :: ByteString -> Text+bytesToTextLossy = TE.decodeUtf8With lenientDecode++-- | A message's quoting of bytes.+quoted :: ByteString -> Text+quoted bytes = "'" <> bytesToTextLossy bytes <> "'"++-- ---------------------------------------------------------------------------+-- URLs+-- ---------------------------------------------------------------------------++-- | A URL as upstream's @ParsedURL@ holds it: the path as its segments,+-- each decoded, a leading empty one standing for a leading @\/@; the+-- query's parameters, each decoded, by name; and the fragment, decoded,+-- empty when there is none.+data ParsedUrl = ParsedUrl+  { urlScheme :: !ByteString,+    urlAuthority :: !(Maybe Authority),+    urlPath :: ![ByteString],+    urlQuery :: !(Map ByteString ByteString),+    urlFragment :: !ByteString+  }+  deriving (Eq, Show)++-- | A URL's authority, its parts decoded.+data Authority = Authority+  { authHostType :: !HostType,+    authHost :: !ByteString,+    authUser :: !(Maybe ByteString),+    authPassword :: !(Maybe ByteString),+    authPort :: !(Maybe Word16)+  }+  deriving (Eq, Show)++-- | What kind of host an authority names, which decides how it renders.+data HostType = HostName | HostIPv4 | HostIPv6 | HostIPvFuture+  deriving (Eq, Show)++-- | An authority with an empty host, as @file:\/\/\/@ has.+emptyAuthority :: Authority+emptyAuthority = Authority HostName BS.empty Nothing Nothing Nothing++-- | Whether a parse first encodes the characters older releases left+-- unencoded in a query and a fragment.+data Leniency = Lenient | Strict+  deriving (Eq, Show)++-- | The path's segments less the empty ones (@ParsedURL::pathSegments@+-- with @skipEmpty@).+urlPathSegments :: ParsedUrl -> [ByteString]+urlPathSegments = filter (not . BS.null) . urlPath++-- | Parse a URL as upstream's @parseURL@ does: a URI reference that+-- must have a scheme, its authority, path, query and fragment decoded.+-- A file URL whose authority names a host is refused, and one with no+-- path has the path @\/@.+parseUrl :: Leniency -> ByteString -> Checked ParsedUrl+parseUrl leniency url = case splitReference buffer of+  Nothing -> refuse (quoted url <> " is not a valid URL: " <> grammarRefusal)+  Just reference -> case refScheme reference of+    Nothing -> refuse (quoted buffer <> " doesn't have a scheme")+    Just scheme -> do+      authority <- traverse parseAuthority (refAuthority reference)+      let transportIsFile = utTransport (parseUrlScheme scheme) == fileScheme+      case authority of+        Just parsed+          | not (BS.null (authHost parsed)) && transportIsFile ->+              refuse ("file:// URL " <> quoted buffer <> " has unexpected authority " <> quoted (renderAuthority parsed))+        _ -> pure ()+      let encodedPath+            | transportIsFile && BS.null (refPath reference) = BC.singleton '/'+            | otherwise = refPath reference+      -- Upstream's splitString keeps an empty string as one empty+      -- segment, where 'BC.split' gives none.+      path <- traverse percentDecode (if BS.null encodedPath then [BS.empty] else BC.split '/' encodedPath)+      query <- decodeQuery leniency (fromMaybe BS.empty (refQuery reference))+      fragment <- percentDecode (fromMaybe BS.empty (refFragment reference))+      pure (ParsedUrl scheme authority path query fragment)+  where+    buffer = case leniency of+      Lenient -> lenientFixup url+      Strict -> url++-- | How upstream words a URL its grammar refuses: Boost.URL's own reason,+-- which for a character the grammar has no place for is input left over.+grammarRefusal :: Text+grammarRefusal = "leftover"++-- | Upstream's lenient fixup: the query's spaces and double quotes, and+-- the fragment's spaces, double quotes and carets, percent-encoded.  The+-- query is what follows the first @?@ up to the next @#@, and the+-- fragment what follows the first @#@ after the query, or the first @#@+-- when there is no query.+lenientFixup :: ByteString -> ByteString+lenientFixup url = case BC.break (== '?') url of+  (beforeQuery, rest)+    | Just afterMark <- BC.stripPrefix "?" rest ->+        let (queryPart, fromFragment) = BC.break (== '#') afterMark+         in beforeQuery <> "?" <> encodeChars queryExtras queryPart <> fixFragment fromFragment+  _ -> fixFragment url+  where+    fixFragment view = case BC.break (== '#') view of+      (beforeFragment, rest)+        | Just fragment <- BC.stripPrefix "#" rest -> beforeFragment <> "#" <> encodeChars fragmentExtras fragment+      _ -> view+    encodeChars extras = BC.concatMap (\c -> if c `elem` extras then encodedByte (charByte c) else BC.singleton c)++-- | The characters older releases accepted unencoded in a query.+queryExtras :: String+queryExtras = " \""++-- | The characters older releases accepted unencoded in a fragment.+fragmentExtras :: String+fragmentExtras = " \"^"++-- | A file URL's transport.+fileScheme :: ByteString+fileScheme = "file"++-- | Render a URL as upstream's @ParsedURL::to_string@ does: each path+-- segment encoded keeping @:@ and @\@@, the query's names and values+-- keeping @:@, @\@@, @\/@ and @?@, and the fragment keeping only the+-- unreserved characters.+renderUrl :: ParsedUrl -> ByteString+renderUrl url =+  BS.concat+    [ urlScheme url,+      ":",+      maybe BS.empty (("//" <>) . renderAuthority) (urlAuthority url),+      encodeUrlPath (urlPath url),+      if Map.null (urlQuery url) then BS.empty else "?" <> encodeQuery (urlQuery url),+      if BS.null (urlFragment url) then BS.empty else "#" <> percentEncode BS.empty (urlFragment url)+    ]++-- | Render an authority as upstream's does: the user and password+-- encoded, a host name encoded, an IPv4 address as it is, and an IPv6+-- address in brackets.+renderAuthority :: Authority -> ByteString+renderAuthority authority =+  BS.concat+    [ case authUser authority of+        Just user -> percentEncode BS.empty user <> maybe BS.empty ((":" <>) . percentEncode BS.empty) (authPassword authority) <> "@"+        Nothing -> BS.empty,+      case authHostType authority of+        HostName -> percentEncode BS.empty (authHost authority)+        HostIPv4 -> authHost authority+        HostIPv6 -> "[" <> percentEncode ":" (authHost authority) <> "]"+        HostIPvFuture -> "[" <> percentEncode ":" (authHost authority) <> "]",+      maybe BS.empty ((":" <>) . BC.pack . show) (authPort authority)+    ]++-- | A path's segments encoded and joined with @\/@.+encodeUrlPath :: [ByteString] -> ByteString+encodeUrlPath = BS.intercalate "/" . map (percentEncode pathKeeps)++-- | What a path segment keeps unencoded beyond the unreserved characters.+pathKeeps :: ByteString+pathKeeps = ":@"++-- | What a query keeps unencoded beyond the unreserved characters.+queryKeeps :: ByteString+queryKeeps = ":@/?"++-- | A query's parameters encoded, in name order, as upstream's+-- @encodeQuery@ writes them.+encodeQuery :: Map ByteString ByteString -> ByteString+encodeQuery query =+  BS.intercalate "&" [percentEncode queryKeeps name <> "=" <> percentEncode queryKeeps value | (name, value) <- Map.toAscList query]++-- ---------------------------------------------------------------------------+-- Schemes+-- ---------------------------------------------------------------------------++-- | A scheme split as upstream's @parseUrlScheme@ splits it: an+-- application before the first @+@, and the transport after it.+data UrlScheme = UrlScheme+  { utApplication :: !(Maybe ByteString),+    utTransport :: !ByteString+  }+  deriving (Eq, Show)++-- | Split a scheme into its application and transport.+parseUrlScheme :: ByteString -> UrlScheme+parseUrlScheme scheme = case BC.break (== '+') scheme of+  (application, rest) | Just transport <- BC.stripPrefix "+" rest -> UrlScheme (Just application) transport+  _ -> UrlScheme Nothing scheme++-- ---------------------------------------------------------------------------+-- Encoding+-- ---------------------------------------------------------------------------++-- | Encode every byte but the unreserved characters and those kept as+-- @%XX@, upper-case, as Boost.URL's @encode@ does.+percentEncode :: ByteString -> ByteString -> ByteString+percentEncode keep = BC.concatMap encodeOne+  where+    encodeOne c+      | isUnreserved c || BC.elem c keep = BC.singleton c+      | otherwise = encodedByte (charByte c)++-- | A byte as @%XX@.+encodedByte :: Word8 -> ByteString+encodedByte byte = BC.pack ['%', hexDigit (byte `shiftR` 4), hexDigit (byte .&. 0xf)]+  where+    hexDigit nibble+      | nibble < 10 = toEnum (fromEnum '0' + fromIntegral nibble)+      | otherwise = toEnum (fromEnum 'A' + fromIntegral nibble - 10)++-- | A character's byte.+charByte :: Char -> Word8+charByte = fromIntegral . fromEnum++-- | Decode every @%XX@, refusing a @%@ not followed by two hex digits as+-- upstream's @percentDecode@ does.+percentDecode :: ByteString -> Checked ByteString+percentDecode encoded = maybe (refuse ("invalid URI parameter " <> quoted encoded <> ": " <> pctRefusal)) pure (decodeEncoded encoded)++-- | How Boost.URL words a @%@ without two hex digits.+pctRefusal :: Text+pctRefusal = "bad hexdig"++-- | Decode every @%XX@, or 'Nothing' for a @%@ without two hex digits.+decodeEncoded :: ByteString -> Maybe ByteString+decodeEncoded = fmap BS.pack . go . BS.unpack+  where+    go bytes = case bytes of+      [] -> Just []+      percent : hi : lo : rest+        | percent == percentByte,+          Just high <- hexValue hi,+          Just low <- hexValue lo ->+            ((high * 16 + low) :) <$> go rest+      percent : _ | percent == percentByte -> Nothing+      byte : rest -> (byte :) <$> go rest+    percentByte = charByte '%'++-- | A hex digit's value.+hexValue :: Word8 -> Maybe Word8+hexValue byte+  | isHexDigit c = Just (fromIntegral (hexDigitValue c))+  | otherwise = Nothing+  where+    c = toEnum (fromIntegral byte)+    hexDigitValue d+      | isDigit d = fromEnum d - fromEnum '0'+      | otherwise = fromEnum (toLower d) - fromEnum 'a' + 10++-- | Decode a query as upstream's @decodeQuery@ does: leniently, its+-- spaces and double quotes encoded first; then each @&@-separated+-- parameter split at its first @=@ and decoded, the first of two with one+-- name kept, and one with no @=@ dropped with a warning.  A query the+-- grammar refuses is refused.+decodeQuery :: Leniency -> ByteString -> Checked (Map ByteString ByteString)+decodeQuery leniency query+  | not (validEncoded isQueryChar fixed) = refuse ("invalid URI query " <> quoted query <> ": " <> grammarRefusal)+  | BS.null fixed = pure Map.empty+  | otherwise = do+      params <- forM (BC.split '&' fixed) $ \param -> case BC.break (== '=') param of+        (name, rest)+          | Just value <- BC.stripPrefix "=" rest -> Just <$> ((,) <$> percentDecode name <*> percentDecode value)+          | otherwise -> Nothing <$ warn ("dubious URI query " <> quoted name <> " is missing equal sign '=', ignoring")+      pure (Map.fromListWith (\_ earlier -> earlier) (catMaybes params))+  where+    fixed = case leniency of+      Lenient -> BC.concatMap (\c -> if c `elem` queryExtras then encodedByte (charByte c) else BC.singleton c) query+      Strict -> query++-- ---------------------------------------------------------------------------+-- The grammar+-- ---------------------------------------------------------------------------++-- | A URI reference split into its parts, each still encoded.+data Reference = Reference+  { refScheme :: !(Maybe ByteString),+    refAuthority :: !(Maybe ByteString),+    refPath :: !ByteString,+    refQuery :: !(Maybe ByteString),+    refFragment :: !(Maybe ByteString)+  }++-- | Split a string as RFC 3986's URI reference, or 'Nothing' when the+-- grammar refuses it: a URI when it starts with a scheme and a colon, a+-- relative reference otherwise, whose first segment then holds no colon.+splitReference :: ByteString -> Maybe Reference+splitReference input = do+  let (scheme, afterScheme) = case BC.uncons input of+        Just (first, _)+          | isAlpha first,+            (name, rest) <- BC.span isSchemeChar input,+            Just hier <- BC.stripPrefix ":" rest ->+              (Just name, hier)+        _ -> (Nothing, input)+      (beforeFragment, fragment) = splitAtMark '#' afterScheme+      (hierPart, query) = splitAtMark '?' beforeFragment+      (authority, path) = case BC.stripPrefix "//" hierPart of+        Just afterSlashes -> let (auth, rest) = BC.break (== '/') afterSlashes in (Just auth, rest)+        Nothing -> (Nothing, hierPart)+  unless (all (validEncoded isFragmentChar) fragment && all (validEncoded isQueryChar) query) Nothing+  unless (validEncoded (\c -> isPathChar c || c == '/') path) Nothing+  when (isJust authority && not (BS.null path || BC.isPrefixOf "/" path)) Nothing+  -- A relative reference's first segment cannot hold a colon, which would+  -- read as a scheme.+  when (isNothing scheme && isNothing authority && BC.elem ':' (BC.takeWhile (/= '/') path)) Nothing+  mapM_ splitAuthority authority+  pure (Reference scheme authority path query fragment)+  where+    splitAtMark mark s = case BC.break (== mark) s of+      (before, rest) | Just after <- BC.stripPrefix (BC.singleton mark) rest -> (before, Just after)+      _ -> (s, Nothing)++-- | An authority split into its encoded user information, its host and+-- the host's kind, and its port's digits, or 'Nothing' when the grammar+-- refuses it.+data AuthorityParts = AuthorityParts+  { apUserInfo :: !(Maybe ByteString),+    apHostType :: !HostType,+    apHost :: !ByteString,+    apPort :: !(Maybe ByteString)+  }++splitAuthority :: ByteString -> Maybe AuthorityParts+splitAuthority authority = do+  let (userInfo, hostPort) = case BC.break (== '@') authority of+        (user, rest) | Just after <- BC.stripPrefix "@" rest -> (Just user, after)+        _ -> (Nothing, authority)+  unless (all (validEncoded (\c -> isUnreserved c || isSubDelim c || c == ':')) userInfo) Nothing+  (hostType, host, portPart) <- case BC.stripPrefix "[" hostPort of+    Just inner -> do+      let (literal, rest) = BC.break (== ']') inner+      afterBracket <- BC.stripPrefix "]" rest+      kind <- literalKind literal+      pure (kind, literal, afterBracket)+    Nothing -> do+      let (name, rest) = BC.break (== ':') hostPort+      unless (validEncoded (\c -> isUnreserved c || isSubDelim c) name) Nothing+      pure (if isJust (parseIPv4 name) then HostIPv4 else HostName, name, rest)+  port <- case BC.uncons portPart of+    Nothing -> Just Nothing+    Just (':', digits) | BC.all isDigit digits -> Just (Just digits)+    _ -> Nothing+  pure (AuthorityParts userInfo hostType host port)+  where+    literalKind literal+      | isJust (parseIPv6 literal) = Just HostIPv6+      | isIPvFuture literal = Just HostIPvFuture+      | otherwise = Nothing++-- | An authority as upstream's @Authority::parse@ reads one: its parts+-- decoded, a user and a password when the user information holds them,+-- and a port only when it is a number from 1 to 65535.+parseAuthority :: ByteString -> Checked Authority+parseAuthority encoded = case splitAuthority encoded of+  Nothing -> refuse ("invalid URL authority: " <> quoted encoded <> ": " <> grammarRefusal)+  Just parts -> do+    host <- case apHostType parts of+      HostName -> percentDecode (apHost parts)+      _ -> pure (apHost parts)+    (user, password) <- case apUserInfo parts of+      Nothing -> pure (Nothing, Nothing)+      Just info -> case BC.break (== ':') info of+        (name, rest)+          | Just secret <- BC.stripPrefix ":" rest -> (\decoded decodedSecret -> (Just decoded, Just decodedSecret)) <$> percentDecode name <*> percentDecode secret+          | otherwise -> (\decoded -> (Just decoded, Nothing)) <$> percentDecode name+    port <- case apPort parts of+      Nothing -> pure Nothing+      Just digits+        | BS.null digits -> pure Nothing+        | Just number <- portNumber digits -> pure (Just number)+        | otherwise -> refuse ("port " <> quoted digits <> " is invalid")+    pure (Authority (apHostType parts) host user password port)+  where+    portNumber digits = case BC.readInteger digits of+      Just (n, rest) | BS.null rest, n >= 1, n <= toInteger (maxBound :: Word16) -> Just (fromInteger n)+      _ -> Nothing++-- | Whether every character is one the class allows, or part of a+-- @%XX@.+validEncoded :: (Char -> Bool) -> ByteString -> Bool+validEncoded allowed = go+  where+    go s = case BC.uncons s of+      Nothing -> True+      Just ('%', rest) -> case BC.unpack (BC.take 2 rest) of+        [hi, lo] | isHexDigit hi && isHexDigit lo -> go (BS.drop 2 rest)+        _ -> False+      Just (c, rest) -> allowed c && go rest++isAlpha :: Char -> Bool+isAlpha c = isAsciiLower c || isAsciiUpper c++isSchemeChar :: Char -> Bool+isSchemeChar c = isAlpha c || isDigit c || c `elem` ("+-." :: String)++isUnreserved :: Char -> Bool+isUnreserved c = isAlpha c || isDigit c || c `elem` ("-._~" :: String)++isSubDelim :: Char -> Bool+isSubDelim c = c `elem` ("!$&'()*+,;=" :: String)++isPathChar :: Char -> Bool+isPathChar c = isUnreserved c || isSubDelim c || c == ':' || c == '@'++isQueryChar :: Char -> Bool+isQueryChar c = isPathChar c || c == '/' || c == '?'++isFragmentChar :: Char -> Bool+isFragmentChar = isQueryChar++-- | An IPv4 address's four octets, each 0 to 255 with no leading zero.+parseIPv4 :: ByteString -> Maybe [Int]+parseIPv4 s = case BC.split '.' s of+  octets@[_, _, _, _] -> traverse decOctet octets+  _ -> Nothing+  where+    decOctet o+      | BS.null o || BS.length o > 3 || not (BC.all isDigit o) = Nothing+      | BS.length o > 1 && BC.isPrefixOf "0" o = Nothing+      | otherwise = case BC.readInt o of+          Just (n, _) | n <= 255 -> Just n+          _ -> Nothing++-- | An IPv6 address's eight 16-bit groups, read as RFC 3986's+-- @IPv6address@: groups of one to four hex digits, at most one @::@+-- standing for one or more zero groups, and an IPv4 address in place of+-- the last two.+parseIPv6 :: ByteString -> Maybe [Int]+parseIPv6 s = case breakDouble s of+  Just (before, after) -> do+    left <- groupsOf False before+    right <- groupsOf True after+    let missing = 8 - length left - length right+    if missing >= 1 then Just (left ++ replicate missing 0 ++ right) else Nothing+  Nothing -> do+    groups <- groupsOf True s+    if length groups == 8 then Just groups else Nothing+  where+    breakDouble text = case BS.breakSubstring "::" text of+      (before, rest)+        | not (BS.null rest),+          after <- BS.drop 2 rest,+          not ("::" `BS.isInfixOf` after) ->+            Just (before, after)+      _ -> Nothing+    groupsOf ipv4Last text+      | BS.null text = Just []+      | otherwise = do+          let parts = BC.split ':' text+          lastGroups <- case reverse parts of+            final : _+              | ipv4Last,+                BC.elem '.' final -> do+                  octets <- parseIPv4 final+                  case octets of+                    [a, b, c, d] -> Just [a * 256 + b, c * 256 + d]+                    _ -> Nothing+            final : _ -> pure <$> h16 final+            [] -> Nothing+          initial <- traverse h16 (dropEnd1 parts)+          Just (initial ++ lastGroups)+    h16 g+      | BS.null g || BS.length g > 4 || not (BC.all isHexDigit g) = Nothing+      | otherwise = Just (BC.foldl' (\acc c -> acc * 16 + hexDigitInt c) 0 g)+    dropEnd1 xs = take (length xs - 1) xs+    hexDigitInt c+      | isDigit c = fromEnum c - fromEnum '0'+      | otherwise = fromEnum (toLower c) - fromEnum 'a' + 10++-- | Whether a literal is RFC 3986's @IPvFuture@: @v@, hex digits, a dot,+-- then unreserved characters, sub-delimiters and colons.+isIPvFuture :: ByteString -> Bool+isIPvFuture literal = case BC.uncons literal of+  Just (v, rest) | toLower v == 'v' -> case BC.break (== '.') rest of+    (version, dotted)+      | not (BS.null version),+        BC.all isHexDigit version,+        Just afterDot <- BC.stripPrefix "." dotted ->+          not (BS.null afterDot) && BC.all (\c -> isUnreserved c || isSubDelim c || c == ':') afterDot+    _ -> False+  _ -> False++-- | An IPv6 address as Boost.URL renders one (RFC 5952): each group in+-- lower-case hex without leading zeros, the longest run of two or more+-- zero groups, the first of equals, written as @::@.+renderIPv6 :: [Int] -> ByteString+renderIPv6 groups = BC.pack $ case longestZeroRun of+  Just (start, len) ->+    intercalate ":" (map hexGroup (take start groups)) ++ "::" ++ intercalate ":" (map hexGroup (drop (start + len) groups))+  Nothing -> intercalate ":" (map hexGroup groups)+  where+    hexGroup g = showHex g ""+    indexed = zip [0 :: Int ..] groups+    -- Each run of zero groups, as its first index and its length.+    runs = zeroRuns indexed+    zeroRuns entries = case dropWhile ((/= 0) . snd) entries of+      [] -> []+      zeros@((start, _) : _) ->+        let (run, rest) = span ((== 0) . snd) zeros+         in (start, length run) : zeroRuns rest+    longestZeroRun = foldl' pickLonger Nothing (filter ((>= 2) . snd) runs)+    pickLonger best run = case best of+      Just (_, bestLen) | bestLen >= snd run -> best+      _ -> Just run++-- ---------------------------------------------------------------------------+-- Git URLs+-- ---------------------------------------------------------------------------++-- | A Git URL as upstream's @fixGitURL@ makes one: an absolute path+-- becomes a @file:\/\/\/@ URL, its bytes taken as they are; an SCP-style+-- @host:path@ becomes an @ssh:\/\/@ URL; anything else is parsed strictly,+-- and a @git+@ prefix dropped from its scheme.+fixGitUrl :: PathRules -> ByteString -> Checked ParsedUrl+fixGitUrl rules url+  | isAbsoluteHostPath rules url = pure (ParsedUrl fileScheme (Just emptyAuthority) (pathToUrlPath rules url) Map.empty BS.empty)+  | otherwise =+      scpStyle url >>= \case+        Just parsed -> pure parsed+        Nothing -> do+          parsed <- parseUrl Strict url+          pure $ case parseUrlScheme (urlScheme parsed) of+            UrlScheme (Just "git") transport -> parsed {urlScheme = transport}+            _ -> parsed++-- | The schemes Git reads as such, with and without @git+@: a URL with+-- one of them before its first colon is no SCP-style URL.+schemesSupportedByGit :: [ByteString]+schemesSupportedByGit = concat [[scheme, "git+" <> scheme] | scheme <- ["ssh", "http", "https", "file", "ftp", "ftps", "git"]]++-- | An SCP-style Git URL as upstream's @tryParseScpStyle@ reads one, or+-- 'Nothing' when the URL is not one: it holds no @:\/\/@, has a colon with+-- no @\/@ before it, does not start with a scheme Git knows, and a+-- bracketed host closes with @]@ right before the colon.  A relative path+-- is made absolute with a warning.+scpStyle :: ByteString -> Checked (Maybe ParsedUrl)+scpStyle url+  | "://" `BS.isInfixOf` url = pure Nothing+  | otherwise = case BC.elemIndex ':' url of+      Nothing -> pure Nothing+      Just firstColon+        | BC.elem '/' (BS.take firstColon url) -> pure Nothing+        | BS.take firstColon url `elem` schemesSupportedByGit -> pure Nothing+        | otherwise -> case bracketedHostEnd of+            BracketNotScp -> pure Nothing+            BracketHostEnds hostEnd -> Just <$> scpParts (BS.take hostEnd url) (BS.drop (hostEnd + 1) url)+            NoBracket -> Just <$> scpParts (BS.take firstColon url) (BS.drop (firstColon + 1) url)+  where+    bracketStart = case BS.breakSubstring "@[" url of+      (before, rest) | not (BS.null rest) -> Just (BS.length before + 1)+      _ -> if BC.isPrefixOf "[" url then Just 0 else Nothing+    bracketedHostEnd = case bracketStart of+      Nothing -> NoBracket+      Just start -> case BC.elemIndex ']' (BS.drop (start + 1) url) of+        Nothing -> NoBracket+        Just offset ->+          let close = start + 1 + offset+           in case BS.indexMaybe url (close + 1) of+                Just next | next == charByte ':' -> BracketHostEnds (close + 1)+                _ -> BracketNotScp+    scpParts hostWithUser pathView = do+      let (user, host) = case BC.break (== '@') hostWithUser of+            (name, rest) | Just after <- BC.stripPrefix "@" rest -> (Just name, after)+            _ -> (Nothing, hostWithUser)+      authority <- case () of+        _+          | Just octets <- parseIPv4 host -> pure (Authority HostIPv4 (BC.pack (intercalate "." (map show octets))) user Nothing Nothing)+          | Just inner <- BC.stripPrefix "[" host >>= BC.stripSuffix "]" -> case parseIPv6 inner of+              Just groups -> pure (Authority HostIPv6 (renderIPv6 groups) user Nothing Nothing)+              Nothing -> refuse ("Git SCP bracketed URL is not valid: " <> quoted inner <> " is not a valid IPv6 address")+          | otherwise -> pure (Authority HostName host user Nothing Nothing)+      when (BS.null pathView) $ refuse ("SCP-style Git URL " <> quoted url <> " has an empty path")+      let segments = BC.split '/' pathView+          parsed = ParsedUrl "ssh" (Just authority) segments Map.empty BS.empty+      case segments of+        first : _ | not (BS.null first) -> do+          let absolute = parsed {urlPath = BS.empty : segments}+              tilde = absolute {urlPath = BS.empty : "~" : segments}+          unless ("~" `BS.isPrefixOf` first) $+            warn+              ( "SCP-style URL "+                  <> quoted url+                  <> " has a relative path which cannot be faithfully converted to an SSH URL: we will convert it to an absolute path when making an SSH URL.\n\nUse an explicit absolute path:\n\n    "+                  <> bytesToTextLossy (host <> ":/" <> pathView)+                  <> "\n\nor with an explicit SSH URL:\n\n    "+                  <> bytesToTextLossy (renderUrl absolute)+                  <> "\n\ninstead, to explicitly use an absolute path (and silence this warning). Or, to be relative to the remote user's home directory:\n\n    "+                  <> bytesToTextLossy (host <> ":~/" <> pathView)+                  <> "\n\nor with an explicit SSH URL:\n\n    "+                  <> bytesToTextLossy (renderUrl tilde)+              )+          pure absolute+        _ -> pure parsed++-- | Where an SCP-style URL's bracketed host ends, when it has one.+data BracketedHost = NoBracket | BracketHostEnds !Int | BracketNotScp++-- ---------------------------------------------------------------------------+-- Paths+-- ---------------------------------------------------------------------------++-- | Whether a path is absolute as @std::filesystem::path@ reads one on+-- the host: rooted at @\/@ on POSIX, and with a drive and a separator+-- after it on Windows.+isAbsoluteHostPath :: PathRules -> ByteString -> Bool+isAbsoluteHostPath rules path = case rules of+  PosixPaths -> BC.isPrefixOf "/" path+  WindowsPaths -> case BC.unpack (BS.take 3 path) of+    [drive, ':', sep] -> isAlpha drive && isSeparator WindowsPaths sep+    _ -> False++isSeparator :: PathRules -> Char -> Bool+isSeparator rules c = c == '/' || (rules == WindowsPaths && c == '\\')++-- | A path's URL segments as upstream's @pathToUrlPath@ makes them: an+-- empty segment for a root directory, a drive as its own segment, then+-- the path's elements as @std::filesystem::path@ iterates them, separators+-- collapsed and a trailing one an empty element, and one more empty+-- segment when the path has no file name, as one ending in a separator+-- has not.+pathToUrlPath :: PathRules -> ByteString -> [ByteString]+pathToUrlPath rules path = root ++ drive ++ elements ++ [BS.empty | BS.null path || endsWithSeparator]+  where+    (driveName, afterDrive) = case (rules, BC.unpack (BS.take 2 path)) of+      (WindowsPaths, [letter, ':']) | isAlpha letter -> (Just (BS.take 2 path), BS.drop 2 path)+      _ -> (Nothing, path)+    rooted = maybe False (isSeparator rules . fst) (BC.uncons afterDrive)+    root = [BS.empty | rooted]+    drive = maybe [] pure driveName+    relative = BC.dropWhile (isSeparator rules) afterDrive+    pieces = filter (not . BS.null) (BC.splitWith (isSeparator rules) relative)+    endsWithSeparator = maybe False (isSeparator rules . snd) (BC.unsnoc path)+    elements = pieces ++ [BS.empty | not (BS.null relative) && endsWithSeparator]++-- | A path from URL segments as upstream's @urlPathToPath@ makes it: a+-- segment holding a @\/@ or a NUL is refused; a leading empty segment+-- roots it (at the drive the next segment names, on Windows); and each+-- further segment is appended as @std::filesystem::path@'s @\/=@ appends+-- it, an empty one adding a separator only after a file name.+urlPathToPath :: PathRules -> [ByteString] -> Checked ByteString+urlPathToPath rules segments = do+  mapM_ checkSegment segments+  pure $ case segments of+    [] -> BS.empty+    first : rest+      | BS.null first -> case (rules, rest) of+          (WindowsPaths, driveSegment : more) | isDrive driveSegment -> foldl' append (driveSegment <> "/") more+          _ -> foldl' append "/" rest+      | otherwise -> foldl' append BS.empty segments+  where+    checkSegment segment+      | BC.elem '/' segment = refuse ("URL path component " <> quoted segment <> " contains '/', which is not allowed in file names")+      | BC.elem '\0' segment = refuse ("URL path component " <> quoted (BC.concatMap (\c -> if c == '\0' then nulSymbol else BC.singleton c) segment) <> " contains NUL byte which is not allowed")+      | otherwise = pure ()+    isDrive segment = case BC.unpack segment of+      [letter, ':'] -> isAlpha letter+      _ -> False+    append acc segment+      | BS.null segment = if hasFileName acc then acc <> "/" else acc+      | BS.null acc = segment+      | hasFileName acc = acc <> "/" <> segment+      | otherwise = acc <> segment+    hasFileName acc = maybe False (not . isSeparator rules . snd) (BC.unsnoc acc)+    -- U+2400, SYMBOL FOR NULL, in UTF-8, as upstream spells a NUL in this+    -- message.+    nulSymbol = BS.pack [0xe2, 0x90, 0x80]
+ src/Nix/Flake/Ref.hs view
@@ -0,0 +1,157 @@+-- | Flake references as upstream reads and writes them (flakeref.cc at+-- 2.36.0): an input and the subdirectory of its tree that holds the+-- flake, read from a URL-like string with an optional @#fragment@, from+-- attributes, and back to a string.+--+-- A string is read in upstream's order: first as a flake ID+-- (@nixpkgs\/branch#attr@), then as a URL, then as a path.  The path form+-- here is the one with no base directory, as @builtins.parseFlakeRef@+-- reads it, where a path must be absolute.+module Nix.Flake.Ref+  ( -- * References+    FlakeRef (..),++    -- * Reading and writing+    parseFlakeRefWithFragment,+    parseFlakeRef,+    flakeRefFromAttrs,+    flakeRefAttrs,+    flakeRefToString,+  )+where++import Control.Monad (guard)+import Control.Monad.Writer.Strict (tell)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BC+import Data.Char (isAsciiLower, isAsciiUpper, isDigit, isHexDigit)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import Nix.Fetch.Attrs (AttrValue (..), Attrs, maybeStrAttr)+import Nix.Fetch.Input (Input (..), InputContext (..), TreeRequirement (..), inputFromAttrs, inputFromUrl, inputToUrlString)+import Nix.Fetch.Url (Checked, Leniency (..), ParsedUrl (..), bytesToTextLossy, decodeQuery, emptyAuthority, isAbsoluteHostPath, parseUrl, pathToUrlPath, percentDecode, refuse, runChecked)++-- | A flake reference: the input that fetches the flake's tree, and the+-- directory in it that holds @flake.nix@, empty for its root.+data FlakeRef = FlakeRef+  { flakeInput :: !Input,+    flakeSubdir :: !ByteString+  }+  deriving (Eq, Show)++-- | Read a flake reference and its fragment, as upstream's+-- @parseFlakeRefWithFragment@ reads one given no base directory: as a+-- flake ID, else as a URL, else as an absolute path.  A string that is+-- not a URL by the grammar is read as a path; one that is a URL but no+-- input is refused as the input refuses it.+parseFlakeRefWithFragment :: InputContext -> ByteString -> Checked (FlakeRef, ByteString)+parseFlakeRefWithFragment ctx ref = case flakeIdParts ref of+  Just (idPart, fragment) -> do+    input <- inputFromUrl ctx RequireTree (ParsedUrl "flake" Nothing (BC.split '/' idPart) Map.empty BS.empty)+    (,) (FlakeRef input BS.empty) <$> percentDecode fragment+  Nothing -> do+    let (asUrl, warnings) = runChecked (parseUrl Lenient ref)+    tell warnings+    either (const (pathFlakeRef ctx ref)) (fromParsedUrl ctx) asUrl++-- | Read a flake reference that has no fragment.+parseFlakeRef :: InputContext -> ByteString -> Checked FlakeRef+parseFlakeRef ctx ref = do+  (flakeRef, fragment) <- parseFlakeRefWithFragment ctx ref+  if BS.null fragment+    then pure flakeRef+    else refuse ("unexpected fragment '" <> bytesToTextLossy fragment <> "' in flake reference '" <> bytesToTextLossy ref <> "'")++-- | A flake reference from a URL: its @dir@ parameter the subdirectory,+-- and its fragment returned beside it.+fromParsedUrl :: InputContext -> ParsedUrl -> Checked (FlakeRef, ByteString)+fromParsedUrl ctx url = do+  let subdir = Map.findWithDefault BS.empty dirParam (urlQuery url)+  input <- inputFromUrl ctx RequireTree url {urlQuery = Map.delete dirParam (urlQuery url), urlFragment = BS.empty}+  pure (FlakeRef input subdir, urlFragment url)++-- | A path flake reference, as upstream reads one with no base+-- directory: the path up to the first @?@ or @#@, the query up to the+-- next @#@, read leniently, and the fragment, decoded.  The path must be+-- absolute.+pathFlakeRef :: InputContext -> ByteString -> Checked (FlakeRef, ByteString)+pathFlakeRef ctx ref = do+  let (path, afterPath) = BC.break (`elem` ("?#" :: String)) ref+      (queryPart, fragmentPart) = case BC.stripPrefix "?" afterPath of+        Just afterMark -> BC.break (== '#') afterMark+        Nothing -> (BS.empty, afterPath)+      fragment = BS.drop 1 fragmentPart+  -- The fragment is @.*@ in upstream's pattern, which matches no line+  -- break.+  if BC.any (`elem` ("\n\r" :: String)) fragment+    then refuse ("invalid flakeref '" <> bytesToTextLossy ref <> "'")+    else do+      query <- decodeQuery Lenient queryPart+      decodedFragment <- percentDecode fragment+      if isAbsoluteHostPath (icPathRules ctx) path+        then fromParsedUrl ctx (ParsedUrl "path" (Just emptyAuthority) (pathToUrlPath (icPathRules ctx) path) query decodedFragment)+        else refuse ("flake reference '" <> bytesToTextLossy ref <> "' is not an absolute path")++-- | A flake ID reference's ID and ref or revision, and its fragment+-- still encoded, when the whole string is one: upstream's pattern of a+-- flake ID, then a @\/@ and a ref or revision, then a @#@ and a fragment.+-- A ref's characters include @\/@, so a ref followed by a revision reads+-- as one ref here as in upstream's pattern; the input splits them.+flakeIdParts :: ByteString -> Maybe (ByteString, ByteString)+flakeIdParts ref = do+  let (idPart, fragmentPart) = BC.break (== '#') ref+      (flakeId, afterId) = BC.break (== '/') idPart+  guard (isFlakeIdText flakeId)+  guard (BS.null afterId || maybe False matchesRef (BC.stripPrefix "/" afterId))+  fragment <- case BC.stripPrefix "#" fragmentPart of+    Nothing -> Just BS.empty+    Just encoded | validFragment encoded -> Just encoded+    _ -> Nothing+  pure (idPart, fragment)+  where+    isFlakeIdText s = case BC.uncons s of+      Just (first, rest) -> isLetter first && BC.all (\c -> isLetter c || isDigit c || c == '_' || c == '-') rest+      Nothing -> False+    matchesRef s = case BC.uncons s of+      Just (first, rest) -> (isLetter first || isDigit first || first == '@') && BC.all (\c -> isLetter c || isDigit c || c `elem` ("_./@+-" :: String)) rest+      Nothing -> False+    isLetter c = isAsciiLower c || isAsciiUpper c+    validFragment s = case BC.uncons s of+      Nothing -> True+      Just ('%', rest) -> case BC.unpack (BC.take 2 rest) of+        [hi, lo] | isHexDigit hi && isHexDigit lo -> validFragment (BS.drop 2 rest)+        _ -> False+      Just (c, rest) -> fragmentChar c && validFragment rest+    fragmentChar c =+      isLetter c || isDigit c || c `elem` ("-._~" :: String) || c `elem` ("!$&'\"()*+,;=" :: String) || c `elem` (":@/? ^" :: String)++-- | A flake reference from attributes, as upstream's @FlakeRef::fromAttrs@+-- reads them: @dir@ the subdirectory, the rest the input's.+flakeRefFromAttrs :: InputContext -> Attrs -> Checked FlakeRef+flakeRefFromAttrs ctx attrs = do+  subdir <- maybeStrAttr dirKey attrs+  input <- inputFromAttrs ctx (Map.delete dirKey attrs)+  pure (FlakeRef input (fromMaybe BS.empty subdir))++-- | A flake reference's attributes, the input's with @dir@ beside them+-- for a subdirectory, an attribute the input has already keeping its+-- value.+flakeRefAttrs :: FlakeRef -> Attrs+flakeRefAttrs (FlakeRef input subdir)+  | BS.null subdir = inputAttrs input+  | otherwise = Map.insertWith (\_ held -> held) dirKey (AttrString subdir) (inputAttrs input)++-- | A flake reference as its URL, with @dir@ for a subdirectory.+flakeRefToString :: InputContext -> FlakeRef -> Checked ByteString+flakeRefToString ctx (FlakeRef input subdir) =+  inputToUrlString (icPathRules ctx) [(dirParam, subdir) | not (BS.null subdir)] input++-- | The attribute naming a flake's subdirectory.+dirKey :: Text+dirKey = "dir"++-- | The URL parameter naming a flake's subdirectory.+dirParam :: ByteString+dirParam = "dir"
src/Nix/Hash.hs view
@@ -1,10 +1,12 @@ {-# LANGUAGE ExistentialQuantification #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE TupleSections #-}  -- | Cryptographic hashing for the Nix store. -- -- == How Nix uses hashes ----- Everything in Nix is content-addressed. A store path like:+-- Every store path is named by a hash. A store path like: -- -- @\/nix\/store\/s66mzxpvicwk07gjbjfw9izjfa797vsw-hello-2.12.1@ --@@ -20,7 +22,9 @@ -- == Hash types in Nix -- -- * __Input hash__ (derivation hash): SHA-256 of all build inputs.---   Computed BEFORE building.  This is the hash in the store path.+--   Computed BEFORE building.  This is the hash in an input-addressed+--   output's store path; a fixed output's path hashes its declared+--   content instead ('makeFixedOutputPath'). -- * __Output hash__ (NAR hash): SHA-256 of the built output serialized --   as a NAR archive.  Computed AFTER building.  Stored in the narinfo --   for integrity verification.@@ -28,8 +32,9 @@ --   network transfer integrity. -- -- nova-cache already handles output hashes and file hashes.  This module--- provides the shared hashing utilities and the @makeStorePath@ family that--- constructs content-addressed store paths exactly as C++ Nix does.+-- provides the shared hashing utilities, the @makeStorePath@ family that+-- constructs store paths exactly as C++ Nix does, and+-- the reading of a hash from each spelling upstream accepts. module Nix.Hash   ( -- * Shared hashing utilities     sha256Hex,@@ -37,23 +42,41 @@     hashPlaceholder,     byteToHex,     hexToBytes,+    base64ToBytes,     rawHashWithAlgo,     IncrementalHash,     hashInitWithAlgo,     hashUpdateChunk,     hashFinalizeBytes,+    ModuloHash,+    moduloHashInit,+    moduloHashUpdate,+    moduloHashFinalize,     hashAlgoBytes,     hexHashLen,     nix32HashLen,     base64HashLen, +    -- * Hash spellings+    unknownHashAlgo,+    parseHashAlgo,+    parseAnyHash,+    parseSriHash,+    parseNarHash,+    digestByLength,+    sriDigest,+     -- * Store path construction (Nix @makeStorePath@ family)     makeStorePath,     makeTextPath,+    FileIngestionMethod (..),+    fileIngestionPrefix,     makeFixedOutputPath,+    makeSourcePath,     makeOutputPath,     compressHash,     sha256Digest,+    sha256LazyHex,     bytesToHexText,      -- * Re-exports from nova-cache@@ -64,10 +87,11 @@ where  import qualified Crypto.Hash as CH-import Data.Bits (xor)+import Data.Bits (shiftL, shiftR, xor, (.|.)) import qualified Data.ByteArray as BA import qualified Data.ByteString as BS-import Data.Char (digitToInt, isHexDigit)+import qualified Data.ByteString.Lazy as BL+import Data.Char (digitToInt, isAsciiLower, isAsciiUpper, isDigit, isHexDigit, ord) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T@@ -75,7 +99,7 @@ import Data.Word (Word8) import Nix.Store.Path (BadStorePath (BadStorePath), StoreDir (..), StorePath, checkStorePathName, defaultStoreDir, storePathToText) import Nix.Store.Path.Internal (StorePath (StorePath))-import NovaCache.Base32 (encode)+import qualified NovaCache.Base32 as Nix32 import NovaCache.Hash (formatNixHash, hashBytes, parseNixHash)  -- | SHA-256 hex digest of a ByteString.@@ -92,14 +116,14 @@ truncatedBase32 :: BS.ByteString -> Text truncatedBase32 bs =   let digest = CH.hash bs :: CH.Digest CH.SHA256-   in encode (compressHash 20 (BA.convert digest))+   in Nix32.encode (compressHash 20 (BA.convert digest))  -- | Nix's output placeholder for @builtins.placeholder@: @\/@ followed by the -- full SHA-256 of @"nix-output:" <> name@ in Nix base-32 (no truncation, no -- store-dir prefix).  Matches C++ Nix @hashPlaceholder@. hashPlaceholder :: Text -> Text hashPlaceholder name =-  "/" <> encode (sha256Digest (encodeUtf8 ("nix-output:" <> name)))+  "/" <> Nix32.encode (sha256Digest (encodeUtf8 ("nix-output:" <> name)))  -- | XOR-fold a hash to @targetLen@ bytes, matching C++ Nix @compressHash@ -- (hash.cc): byte @i@ is XOR'd into position @i mod targetLen@, which is@@ -143,6 +167,11 @@ sha256Digest :: BS.ByteString -> BS.ByteString sha256Digest bs = BA.convert (CH.hash bs :: CH.Digest CH.SHA256) +-- | The SHA-256 of lazy bytes in lowercase base-16, hashed a chunk at a+-- time, so no more of them is held than a chunk.+sha256LazyHex :: BL.ByteString -> Text+sha256LazyHex bytes = bytesToHexText (BA.convert (CH.hashlazy bytes :: CH.Digest CH.SHA256))+ -- | Lowercase base-16 of raw bytes (two hex characters per byte). bytesToHexText :: BS.ByteString -> Text bytesToHexText = T.pack . concatMap byteToHex . BS.unpack@@ -162,6 +191,36 @@     pairs (hi : lo : rest) = fromIntegral (digitToInt hi * 16 + digitToInt lo) : pairs rest     pairs [_] = [] -- unreachable: even length checked above +-- | Decode base64 as upstream's @base64Decode@ does (util.cc at 2.24.9,+-- @base64::decode@ in base-n.cc at 2.36.0).  Reading stops at the first @=@,+-- so nothing after it is read; a newline is skipped; any other character+-- outside the standard alphabet, a carriage return among them, refuses the+-- input; and the bits left after the last whole byte are dropped, whatever+-- their value.+base64ToBytes :: Text -> Maybe BS.ByteString+base64ToBytes encoded =+  BS.pack . sextetsToBytes <$> traverse sextet (T.unpack (T.filter (/= '\n') (T.takeWhile (/= '=') encoded)))+  where+    sextet :: Char -> Maybe Word8+    sextet c+      | isAsciiUpper c = Just (fromIntegral (ord c - ord 'A'))+      | isAsciiLower c = Just (fromIntegral (ord c - ord 'a' + 26))+      | isDigit c = Just (fromIntegral (ord c - ord '0' + 52))+      | c == '+' = Just 62+      | c == '/' = Just 63+      | otherwise = Nothing+    -- Four sextets make three bytes, a final three make two and a final+    -- two make one; a final one is six bits, short of a byte.  'shiftL'+    -- on a 'Word8' drops the bits that belong to the previous byte.+    sextetsToBytes (a : b : c : d : rest) = joinFirst a b : joinSecond b c : joinThird c d : sextetsToBytes rest+    sextetsToBytes [a, b, c] = [joinFirst a b, joinSecond b c]+    sextetsToBytes [a, b] = [joinFirst a b]+    sextetsToBytes [_] = []+    sextetsToBytes [] = []+    joinFirst a b = shiftL a 2 .|. shiftR b 4+    joinSecond b c = shiftL b 4 .|. shiftR c 2+    joinThird c d = shiftL c 6 .|. d+ -- | Raw digest of a 'BS.ByteString' under a named algorithm (@sha256@, -- @sha512@, @sha1@, @md5@).  Returns 'Nothing' for an unknown algorithm. -- Used to verify a fixed-output fetch against its declared @outputHashAlgo@.@@ -197,6 +256,67 @@ hashFinalizeBytes :: IncrementalHash -> BS.ByteString hashFinalizeBytes (IncrementalHash ctx) = BA.convert (CH.hashFinalize ctx) +-- | An in-progress digest of a stream modulo a store path's hash part, as+-- upstream hashes a content-addressed path's contents: every occurrence+-- of the hash part, found left to right, is hashed as as many zero+-- bytes, and once the stream ends the offset of each follows as+-- @|OFFSET@, so a stream holding the hash part and one holding zeros there+-- do not collide.  A stream without the hash part hashes as it is.+data ModuloHash = ModuloHash+  { mhHash :: !IncrementalHash,+    -- | The hash part.+    mhModulus :: !BS.ByteString,+    -- | The bytes held back, too few to hold the hash part, so that one+    -- split across chunks is still found.+    mhHeld :: !BS.ByteString,+    -- | How many bytes have been hashed.+    mhHashed :: !Int,+    -- | The offset of each occurrence, the latest first.+    mhOffsets :: ![Int]+  }++-- | Start a digest modulo a hash part under a named algorithm, or+-- 'Nothing' for an unknown algorithm or an empty hash part.+moduloHashInit :: Text -> BS.ByteString -> Maybe ModuloHash+moduloHashInit algo modulus+  | BS.null modulus = Nothing+  | otherwise = (\hash -> ModuloHash hash modulus BS.empty 0 []) <$> hashInitWithAlgo algo++-- | Absorb one chunk.  What it gives the digest is the same however the+-- stream is split into chunks.+moduloHashUpdate :: ModuloHash -> BS.ByteString -> ModuloHash+moduloHashUpdate state chunk =+  state+    { mhHash = hashUpdateChunk (mhHash state) settled,+      mhHeld = held,+      mhHashed = mhHashed state + BS.length settled,+      mhOffsets = foldl' (\offsets offset -> let !absolute = offset + mhHashed state in absolute : offsets) (mhOffsets state) found+    }+  where+    (masked, found) = maskOccurrences (mhModulus state) (mhHeld state <> chunk)+    (settled, held) = BS.splitAt (BS.length masked - min (BS.length masked) (BS.length (mhModulus state) - 1)) masked++-- | Finish: the held bytes, then the offset of each occurrence, first to+-- last.+moduloHashFinalize :: ModuloHash -> BS.ByteString+moduloHashFinalize state =+  hashFinalizeBytes (foldl' hashUpdateChunk (hashUpdateChunk (mhHash state) (mhHeld state)) offsets)+  where+    offsets = [encodeUtf8 ("|" <> T.pack (show offset)) | offset <- reverse (mhOffsets state)]++-- | The bytes with every occurrence of a needle, found left to right,+-- replaced by as many zero bytes, and the offset of each.+maskOccurrences :: BS.ByteString -> BS.ByteString -> (BS.ByteString, [Int])+maskOccurrences needle = go 0 [] []+  where+    width = BS.length needle+    go !at pieces offsets rest = case BS.breakSubstring needle rest of+      (before, after)+        | BS.null after -> (BS.concat (reverse (before : pieces)), reverse offsets)+        | otherwise ->+            let offset = at + BS.length before+             in go (offset + width) (BS.replicate width 0 : before : pieces) (offset : offsets) (BS.drop width after)+ -- | Raw digest size in bytes of a supported hash algorithm.  'Nothing' for -- an unknown algorithm name. hashAlgoBytes :: Text -> Maybe Int@@ -224,9 +344,132 @@ base64HashLen :: Int -> Int base64HashLen n = 4 * ((n + 2) `div` 3) +-- ---------------------------------------------------------------------------+-- Hash spellings+--+-- A hash read from text, in each spelling upstream accepts.+-- ---------------------------------------------------------------------------++-- | Upstream's refusal of an algorithm name it does not know+-- (@parseHashAlgo@ in hash.cc at 2.24.9).+unknownHashAlgo :: Text -> Text+unknownHashAlgo algo = "unknown hash algorithm '" <> algo <> "', expect 'md5', 'sha1', 'sha256', or 'sha512'"++-- | The digest size in bytes of an algorithm upstream knows, or upstream's+-- refusal of the name (@parseHashAlgo@ in hash.cc at 2.24.9).+parseHashAlgo :: Text -> Either Text Int+parseHashAlgo algo = maybe (Left (unknownHashAlgo algo)) Right (hashAlgoBytes algo)++-- | Parse a hash as upstream's @Hash::parseAny@ does (hash.cc at 2.24.9).+-- The algorithm is the one the hash's own tag names, else @expected@; when+-- both are given they must be the same.  @expected@ is a name 'parseHashAlgo'+-- accepts.+parseAnyHash :: Maybe Text -> Text -> Either Text (Text, BS.ByteString)+parseAnyHash expected original =+  hashSpelling original >>= \case+    SriHash algo digest -> agreeing algo (sriDigest algo digest)+    PrefixedHash algo digest -> agreeing algo (digestByLength algo digest)+    UntaggedHash -> case expected of+      Just algo -> (algo,) <$> digestByLength algo original+      Nothing -> Left ("hash '" <> original <> "' does not include a type, nor is the type otherwise known from context")+  where+    agreeing algo decoded = case expected of+      Just want | want /= algo -> Left ("hash '" <> original <> "' should have type '" <> want <> "'")+      _ -> (algo,) <$> decoded++-- | Parse an SRI hash as upstream's @Hash::parseSRI@ does (hash.cc): the+-- algorithm before the first @-@ and a base64 digest after it.  A hash in+-- any other spelling is refused.+parseSriHash :: Text -> Either Text (Text, BS.ByteString)+parseSriHash original = case T.breakOn "-" original of+  (algo, rest) | Just digest <- T.stripPrefix "-" rest -> (algo,) <$> sriDigest algo digest+  _ -> Left ("hash '" <> original <> "' is not SRI")++-- | A declared @narHash@'s SHA-256 digest, read as upstream's+-- @Input::getNarHash@ reads it (fetchers.cc): an SRI hash, which must be+-- SHA-256, or the empty string, which is a digest whose every byte is zero.+parseNarHash :: Text -> Either Text BS.ByteString+parseNarHash declared+  | T.null declared = Right (BS.replicate sha256DigestSize 0)+  | otherwise =+      parseSriHash declared >>= \case+        ("sha256", digest) -> Right digest+        _ -> Left "narHash must use SHA-256"+  where+    sha256DigestSize = 32++-- | Decode a digest that is not SRI, keyed by its length as upstream's+-- @Hash@ constructor keys it (hash.cc at 2.24.9, @baseFromSize@ there at+-- 2.36.0): an algorithm's base16, nix32, and base64 spellings have pairwise+-- distinct lengths, so the input length selects the decoder and every other+-- length is an error.  Trying decoders in sequence instead mis-reads edge+-- inputs - an all-hex-digit string of nix32 length is a nix32 hash, and a+-- truncated hash must be rejected, not decoded by whichever shorter format+-- happens to accept it.  The length is counted in bytes, as upstream counts+-- it, not in characters: base64 decoding ignores what follows the padding,+-- and a character there that UTF-8 spells in more than one byte must still+-- make the length wrong.+digestByLength :: Text -> Text -> Either Text BS.ByteString+digestByLength algo s = parseHashAlgo algo >>= byLength+  where+    len = BS.length (encodeUtf8 s)+    byLength size+      | len == hexHashLen size = sizedDigest "base-16" size s (hexToBytes s)+      | len == nix32HashLen size = sizedDigest "base-32" size s (either (const Nothing) Just (Nix32.decode s))+      | len == base64HashLen size = sizedDigest "base-64" size s (base64ToBytes s)+      | otherwise = Left ("hash '" <> s <> "' has wrong length for hash algorithm '" <> algo <> "'")++-- | Decode an SRI digest, base64 of whatever length, as the @isSRI@ branch+-- of upstream's @Hash@ constructor does (hash.cc at 2.24.9).+sriDigest :: Text -> Text -> Either Text BS.ByteString+sriDigest algo b64 = do+  size <- parseHashAlgo algo+  sizedDigest "SRI" size b64 (base64ToBytes b64)++-- | A decoded digest of the algorithm's size, or upstream's refusal of+-- the spelling it was decoded from: @invalid base-16 hash@ and+-- @invalid base-32 hash@ for a character outside the alphabet or nix32+-- bits past the digest's end (the @Hash@ constructor in hash.cc at 2.24.9),+-- and @invalid SRI hash@ or @invalid base-64 hash@ for base64 that is refused+-- or decodes to the wrong length (its @isSRI@ branch).  A refused base64+-- character is the same error as a wrong length there: the constructor+-- catches @base64Decode@'s exception without rethrowing it, so the length+-- check fails on the empty result.+sizedDigest :: Text -> Int -> Text -> Maybe BS.ByteString -> Either Text BS.ByteString+sizedDigest spelling size encoded decoded = case decoded of+  Just bytes | BS.length bytes == size -> Right bytes+  _ -> Left ("invalid " <> spelling <> " hash '" <> encoded <> "'")++-- | A hash string, its algorithm tag split off.+data HashSpelling+  = -- | @algo:digest@, the digest in base16, nix32 or base64 by its length.+    PrefixedHash !Text !Text+  | -- | @algo-digest@ (SRI), the digest in base64.+    SriHash !Text !Text+  | -- | No tag: the algorithm comes from context.+    UntaggedHash++-- | Split a hash string's algorithm tag off as upstream's+-- @getParsedTypeAndSRI@ does (hash.cc at 2.24.9): at the first+-- @:@, else at the first @-@, which marks SRI.  The tag is everything+-- before the separator, and one that names no known algorithm is an+-- error.  Base64 decoding ignores what follows the padding, so this split+-- is what refuses a separator there: @sha256-...=:x@ names the algorithm+-- @sha256-...=@.+hashSpelling :: Text -> Either Text HashSpelling+hashSpelling s+  | Just (tag, digest) <- splitTag ":" = tagged PrefixedHash tag digest+  | Just (tag, digest) <- splitTag "-" = tagged SriHash tag digest+  | otherwise = Right UntaggedHash+  where+    splitTag sep = case T.breakOn sep s of+      (tag, rest) | not (T.null rest) -> Just (tag, T.drop 1 rest)+      _ -> Nothing+    tagged spelling tag digest = spelling tag digest <$ parseHashAlgo tag+ -- | The core store-path construction primitive.  Given a @type@ string, the -- inner content digest (raw SHA-256 bytes), and a name, produce the store--- path.  Mirrors C++ Nix @makeStorePath@:+-- path, as upstream Nix builds one: -- -- @ -- s = type ":sha256:" hex(innerDigest) ":" storeDir ":" name@@ -242,7 +485,9 @@ -- ('checkStorePathName'), carrying the hash part the path would have had: -- upstream hashes before it checks the name, and its refusal names both. -- Construction validates like the parse boundary does, so every--- t'StorePath' that exists has a clean name: the write sinks downstream+-- t'StorePath' that names a path has a clean name (the masking+-- placeholder of "Nix.Store.Path.Internal" has an empty one and never+-- reaches a sink): the write sinks downstream -- (store copies, the builder's delete-and-move) never see a path that -- resolves outside the store root, and no sink needs its own ad hoc name -- check.@@ -256,7 +501,7 @@           <> T.pack dir           <> ":"           <> name-      hashPart = encode (compressHash storePathHashBytes (sha256Digest (encodeUtf8 preimage)))+      hashPart = Nix32.encode (compressHash storePathHashBytes (sha256Digest (encodeUtf8 preimage)))    in case checkStorePathName name of         Left err -> Left (BadStorePath hashPart err)         Right () -> Right (StorePath hashPart name)@@ -273,23 +518,55 @@       typ = "text" <> T.concat [":" <> storePathToText defaultStoreDir r | r <- sortedRefs]    in makeStorePath defaultStoreDir typ contentsDigest name +-- | How a fixed output's contents are hashed: upstream's+-- @FileIngestionMethod@ (file-content-address.hh) without the git method its+-- @git-hashing@ experimental feature adds.+data FileIngestionMethod+  = -- | The bytes of a single file (upstream's @Flat@).+    FlatIngestion+  | -- | The NAR serialisation of a tree (upstream's @NixArchive@).+    NarIngestion+  deriving (Eq, Show)++-- | What a method puts before the algorithm in a fixed output's hash+-- fields and path (upstream's @makeFileIngestionPrefix@,+-- content-address.cc): @r:@ for a NAR hash, and nothing for a flat one,+-- which predates the prefix.+fileIngestionPrefix :: FileIngestionMethod -> Text+fileIngestionPrefix FlatIngestion = ""+fileIngestionPrefix NarIngestion = "r:"+ -- | Construct a fixed-output store path.  @foHashDigest@ is the raw bytes of--- the EXPECTED output hash (e.g. a tarball's SHA-256).  @mode@ is @\"flat\"@--- or @\"recursive\"@.  Mirrors C++ Nix @makeFixedOutputPath@:+-- the EXPECTED output hash (e.g. a tarball's SHA-256), taken under+-- @method@.  Mirrors C++ Nix @makeFixedOutputPath@ (store-api.cc at+-- 2.24.9, store-dir-config.cc from 2.34.9): ----- * @sha256@ + @recursive@ yields @makeStorePath \"source\" foHash name@+-- * @sha256@ under 'NarIngestion' yields 'makeSourcePath' with no references -- * otherwise, @makeStorePath \"output:out\" sha256(\"fixed:out:\" prefix algo \":\" hex \":\") name@ -- -- 'Left' on an invalid name, as 'makeStorePath'.-makeFixedOutputPath :: Text -> Text -> Text -> BS.ByteString -> Either BadStorePath StorePath-makeFixedOutputPath name algo mode foHashDigest-  | algo == "sha256" && mode == "recursive" =-      makeStorePath defaultStoreDir "source" foHashDigest name+makeFixedOutputPath :: Text -> Text -> FileIngestionMethod -> BS.ByteString -> Either BadStorePath StorePath+makeFixedOutputPath name algo method foHashDigest+  | NarIngestion <- method,+    algo == "sha256" =+      makeSourcePath name foHashDigest Set.empty   | otherwise =-      let prefix = if mode == "recursive" then "r:" else ""-          inner = "fixed:out:" <> prefix <> algo <> ":" <> bytesToHexText foHashDigest <> ":"+      let inner = "fixed:out:" <> fileIngestionPrefix method <> algo <> ":" <> bytesToHexText foHashDigest <> ":"           innerDigest = sha256Digest (encodeUtf8 inner)        in makeStorePath defaultStoreDir "output:out" innerDigest name++-- | The path of a tree added by the SHA-256 of its NAR, @narDigest@, with+-- the store paths it references: upstream's @makeFixedOutputPath@ under+-- @NixArchive@ and SHA-256 (store-dir-config.cc from 2.34.9, store-api.cc at+-- 2.24.9), whose type is @source@ followed by each reference after a colon,+-- in path order, as @makeType@ beside it appends them.  Upstream's @makeType@+-- also marks a self-reference with @:self@, which no caller here makes.+-- 'Left' on an invalid name, as 'makeStorePath'.+makeSourcePath :: Text -> BS.ByteString -> Set.Set StorePath -> Either BadStorePath StorePath+makeSourcePath name narDigest refs =+  makeStorePath defaultStoreDir typ narDigest name+  where+    typ = "source" <> T.concat [":" <> storePathToText defaultStoreDir r | r <- Set.toAscList refs]  -- | Construct an input-addressed output store path.  @moduloDigest@ is the raw -- bytes of @hashDerivationModulo@ (masked).  Mirrors C++ Nix @makeOutputPath@:
src/Nix/HostPath.hs view
@@ -2,9 +2,9 @@  -- | A path as the host's file API takes it ('OsPath'), spelled from the -- bytes nova-nix holds for it, and shown back in a message.  One spelling--- serves every such path: a NAR's entry names and link targets--- ("Nix.Store.EntryName"), and nix.conf's include targets and directories--- ("Nix.Config").+-- serves every such path, among them a NAR's entry names and link+-- targets ("Nix.Store.EntryName"), and nix.conf's include targets and+-- directories ("Nix.Config"). -- -- Upstream keeps such a path as the bytes it read and hands them to the -- file system unchanged (@RestoreSink@ in fs-sink.cc, @parseConfigFiles@@@ -23,14 +23,16 @@ -- name no Windows file. module Nix.HostPath   ( hostPathFromBytes,+    hostPathBytes,     hostPathText,+    absolutePath,   ) where  import Data.ByteString (ByteString) import Data.Text (Text) import qualified Data.Text.Encoding as TE-import System.OsPath (OsPath)+import System.OsPath (OsPath, (</>)) import qualified System.OsPath as OP #if defined(mingw32_HOST_OS) import qualified Data.Text as T@@ -52,6 +54,17 @@ hostPathFromBytes = Just . OP.pack . map OP.unsafeFromChar . BS8.unpack #endif +-- | The bytes nova-nix holds for a host path, the inverse of+-- 'hostPathFromBytes': on POSIX the path's own bytes, on Windows the+-- UTF-8 of its UTF-16, or 'Nothing' for one holding an unpaired+-- surrogate, which has no UTF-8 form.+hostPathBytes :: OsPath -> Maybe ByteString+#if defined(mingw32_HOST_OS)+hostPathBytes path = TE.encodeUtf8 . T.pack <$> OP.decodeUtf path+#else+hostPathBytes = Just . BS8.pack . map OP.toChar . OP.unpack+#endif+ -- | A host path as a message shows it, for display only: its UTF-8 -- (POSIX) or UTF-16 (Windows) reading, with U+FFFD where that reading -- fails.  Never the way back to a path.@@ -62,3 +75,26 @@ #else hostPathText = TE.decodeUtf8Lenient . BS8.pack . map OP.toChar . OP.unpack #endif++-- | A path made absolute against a directory and collapsed, @.@ dropped+-- and @..@ taking off what precedes it, without reading a link, as+-- upstream's @absPath@ makes one.  It works on the path's own units, so+-- a path no text can spell comes back as the same bytes.+absolutePath :: OsPath -> OsPath -> OsPath+absolutePath base path = OP.joinPath (reverse (foldl' step [] (OP.splitDirectories joined)))+  where+    joined+      | OP.isAbsolute path = path+      | otherwise = base </> path+    -- The components kept so far, last first.  A @..@ at the root stays+    -- at the root.+    step kept component+      | component == dot = kept+      | component == dotDot, parent : rest <- kept, not (OP.isAbsolute parent), parent /= component = rest+      | component == dotDot, root : _ <- kept, OP.isAbsolute root = kept+      | otherwise = component : kept++-- | The components naming a directory itself and its parent.+dot, dotDot :: OsPath+dot = OP.pack [OP.unsafeFromChar '.']+dotDot = OP.pack (replicate 2 (OP.unsafeFromChar '.'))
src/Nix/Http.hs view
@@ -1,13 +1,15 @@--- | The HTTP transfer layer every download nova-nix makes goes through:--- the User-Agent each request carries, and upstream's retry policy with--- the classification that decides what a retry can outlive.+-- | The HTTP transfer layer nova-nix's own HTTP client goes through, for+-- every download it makes (@builtin:fetchurl@, the substituter, push, and+-- the evaluator's @builtins.fetchurl@ and @builtins.fetchTarball@): the+-- User-Agent each request carries, one request's download, and upstream's+-- retry policy with the classification that decides what a retry can+-- outlive. ----- Upstream serves every download, a fetcher's and a substituter's alike,--- through one @FileTransfer@ (@libstore/filetransfer.cc@ at 2.24.9), with--- one @download-attempts@ setting, one backoff and one table of the--- failures that are never retried.  @builtin:fetchurl@ ("Nix.Builder")--- and the substituter ("Nix.Substituter") share this module for the same--- reason: a source tarball, a narinfo and a NAR fail and retry alike.+-- Upstream serves every transfer, a fetcher's and a substituter's alike,+-- through one transfer layer, with one attempts setting, one backoff and+-- one table of the failures that are never retried.  Every caller shares+-- this module for the same reason: a source tarball, a narinfo and a NAR+-- fail and retry alike. module Nix.Http   ( -- * Identity     userAgent,@@ -18,8 +20,12 @@     attemptFailureMessage,     catchSync, +    -- * Download+    downloadUrlWith,+     -- * Retry policy     FetchRetryPolicy (..),+    defaultDownloadAttempts,     defaultFetchRetryPolicy,     RetryEffects (..),     ioRetryEffects,@@ -34,22 +40,25 @@     transferFailureHandlers,     fetchStatusFailure,     fetchExceptionFailure,+    exceptionFailure,     fetchWriteFailure,+    fileUrlFailure,   ) where  import Control.Concurrent (threadDelay)-import Control.Exception (Handler (..), IOException, SomeAsyncException (..), SomeException, catch, displayException, fromException, throwIO)+import Control.Exception (Handler (..), IOException, SomeAsyncException (..), SomeException, catch, catches, displayException, fromException, throwIO) import qualified Data.ByteString.Char8 as BS8 import Data.Text (Text) import qualified Data.Text as T-import qualified Data.Text.IO as TIO import Data.Version (showVersion)+import Data.Word (Word32) import qualified Network.HTTP.Client as HTTP+import qualified Network.HTTP.Client.TLS as HTTPS import Network.HTTP.Types.Header (hUserAgent) import qualified Network.HTTP.Types.Status as HTTP+import Nix.Logger (Logger, logWarning) import Paths_nova_nix (version)-import System.IO (stderr) import System.Random (randomRIO)  -- ---------------------------------------------------------------------------@@ -64,9 +73,8 @@ -- front of a server scores lowest: ftp.gnu.org answers one with 403 -- outright, and Cloudflare in front of cache.novavero.ai challenged every -- request a GitHub runner made without one while passing the same requests--- carrying this header.  The fetcher sent one; the substituter and push--- sent none, so the public cache could be read by a person and not by the--- tool built to read it.  The version comes from Cabal, so the header+-- carrying this header.  The fetcher, the substituter and push each send+-- it through 'withUserAgent'.  The version comes from Cabal, so the header -- names the build that made the request rather than a spelling that can -- drift at release time. userAgent :: BS8.ByteString@@ -115,49 +123,71 @@       | otherwise = handler someErr  -- ---------------------------------------------------------------------------+-- Download+-- ---------------------------------------------------------------------------++-- | Request a URL with nova-nix's own linked HTTP client, on the+-- process's one TLS manager so connections are pooled, and hand the body+-- of a success to the consumer.  A status other than 200, or a failure of+-- the transfer or of the consumer's writes, becomes a 'Left' carrying its+-- retry class ('transferFailureHandlers'); an asynchronous exception+-- propagates.  One call is one attempt: 'retryTransient' makes the+-- retries.+downloadUrlWith :: Text -> (HTTP.BodyReader -> IO (Either AttemptFailure a)) -> IO (Either AttemptFailure a)+downloadUrlWith url consume =+  fetch `catches` transferFailureHandlers url+  where+    fetch = do+      manager <- HTTPS.getGlobalManager+      request <- withUserAgent <$> HTTP.parseRequest (T.unpack url)+      withTransfer request manager $ \response -> do+        let status = HTTP.responseStatus response+        if status == HTTP.status200+          then consume (HTTP.responseBody response)+          else pure (Left (fetchStatusFailure url status))++-- --------------------------------------------------------------------------- -- Retry policy -- --------------------------------------------------------------------------- --- | How many times one download is tried before it fails: upstream's--- @download-attempts@ default (@libstore/filetransfer.hh@ at 2.24.9,--- @Setting<unsigned int> tries{this, 5, "download-attempts", ...}@).-downloadAttempts :: Int-downloadAttempts = 5+-- | How many times one download is tried before it fails, unless+-- @download-attempts@ says otherwise: upstream's default.+defaultDownloadAttempts :: Word32+defaultDownloadAttempts = 5  -- | The delay before the first retry, in milliseconds; every later retry--- doubles it (@FileTransferRequest::baseRetryTimeMs = 250@ in the same--- header).+-- doubles it. retryBaseDelayMs :: Int retryBaseDelayMs = 250 --- | The spread upstream adds to the backoff exponent so that clients--- which failed together do not retry together: a uniform draw from--- @[0, 0.5)@ (@filetransfer.cc@ at 2.24.9, line 500).+-- | The spread added to the backoff exponent so that clients which failed+-- together do not retry together: a uniform draw from @[0, 0.5)@. retryJitterCeiling :: Double retryJitterCeiling = 0.5  microsPerMilli :: Int microsPerMilli = 1000 --- | How often one download is tried and how long to wait between tries.--- 'defaultFetchRetryPolicy' is upstream's; tests shrink the delay.+-- | How often one download is tried and how long to wait between tries:+-- 'defaultFetchRetryPolicy', with the attempts @download-attempts@ sets,+-- and in tests a shorter delay. data FetchRetryPolicy = FetchRetryPolicy-  { frpAttempts :: !Int,+  { frpAttempts :: !Word32,     frpBaseDelayMs :: !Int   }   deriving (Eq, Show) --- | Upstream's policy: five attempts, 250 ms before the first retry.+-- | The default policy: 'defaultDownloadAttempts' attempts, 250 ms before+-- the first retry. defaultFetchRetryPolicy :: FetchRetryPolicy-defaultFetchRetryPolicy = FetchRetryPolicy {frpAttempts = downloadAttempts, frpBaseDelayMs = retryBaseDelayMs}+defaultFetchRetryPolicy = FetchRetryPolicy {frpAttempts = defaultDownloadAttempts, frpBaseDelayMs = retryBaseDelayMs}  -- | The delay before retry number @retry@ (counting from one), given the--- jitter drawn for it: upstream's @baseRetryTimeMs * 2 ^ (attempt - 1 +--- jitter)@ (@filetransfer.cc@ at 2.24.9, line 500), truncated to whole--- milliseconds as its assignment to an @int@ truncates.-retryDelayMs :: FetchRetryPolicy -> Int -> Double -> Int+-- jitter drawn for it: the base delay times @2 ^ (retry - 1 + jitter)@,+-- truncated to whole milliseconds.+retryDelayMs :: FetchRetryPolicy -> Word32 -> Double -> Int retryDelayMs policy retry jitter =-  truncate (fromIntegral (frpBaseDelayMs policy) * 2 ** (fromIntegral (retry - 1) + jitter) :: Double)+  truncate (fromIntegral (frpBaseDelayMs policy) * 2 ** (fromIntegral retry - 1 + jitter) :: Double)  -- | What the retry loop needs from the outside world, injected so the -- policy is testable with no clock, no entropy and no network.@@ -167,14 +197,14 @@     reWarn :: !(Text -> m ())   } --- | The real effects: a sleep, a uniform jitter, and a warning on stderr--- in the shape of upstream's @warn("%s; retrying in %d ms", ...)@.-ioRetryEffects :: RetryEffects IO-ioRetryEffects =+-- | The real effects: a sleep, a uniform jitter, and a warning to the+-- logger in the shape of upstream's @warn("%s; retrying in %d ms", ...)@.+ioRetryEffects :: Logger -> RetryEffects IO+ioRetryEffects logger =   RetryEffects     { reSleepMs = threadDelay . (* microsPerMilli),       reJitter = randomRIO (0, retryJitterCeiling),-      reWarn = TIO.hPutStrLn stderr . ("warning: " <>)+      reWarn = logWarning logger     }  -- | Run one download's attempt under the retry policy: a@@ -238,14 +268,11 @@     Handler (pure . Left . fetchWriteFailure url)   ] --- | Upstream's verdict on a response that is not a success--- (@FileTransfer::Error@, @filetransfer.hh@ at 2.24.9, whose--- @Interrupted@ is an asynchronous exception here, never a value).  Only+-- | The verdict on a response that is not a success.  An interrupted+-- transfer is an asynchronous exception here, never a value.  Only -- 'Transient' is retried.  A binary cache store reads 'NotFound' and--- 'Forbidden' alike as the file not being in that cache--- (@http-binary-cache-store.cc@ at 2.24.9, lines 123, 160 and 182),--- since an S3 bucket that cannot be listed answers a missing key with--- 403.+-- 'Forbidden' alike as the file not being in that cache, since an S3+-- bucket that cannot be listed answers a missing key with 403. data TransferError   = -- | 404 or 410: the file is not there.     NotFound@@ -257,13 +284,12 @@     Transient   deriving (Eq, Show) --- | Classify a response status the way upstream's transfer layer does,--- in its order (@filetransfer.cc@ at 2.24.9, lines 423-441): 404 and 410--- are 'NotFound'; 401, 403 and 407 are 'Forbidden'; every other 4xx--- except 408 and 429 (the server timed out waiting for the request, or--- asked for a slower pace) is 'Misc', as are 501, 505 and 511 (the--- server cannot speak this protocol, or a captive portal is in the way).--- Everything else is 'Transient', the remaining 5xx included.+-- | Classify a response status, in this order: 404 and 410 are+-- 'NotFound'; 401, 403 and 407 are 'Forbidden'; every other 4xx except 408+-- and 429 (the server timed out waiting for the request, or asked for a+-- slower pace) is 'Misc', as are 501, 505 and 511 (the server cannot speak+-- this protocol, or a captive portal is in the way).  Everything else is+-- 'Transient', the remaining 5xx included. statusError :: HTTP.Status -> TransferError statusError status   | status `elem` [HTTP.status404, HTTP.status410] = NotFound@@ -283,28 +309,33 @@   where     message = "HTTP " <> T.pack (show (HTTP.statusCode status)) <> " fetching " <> url --- | Classify a failure of the HTTP client, by upstream's list of curl--- results that are not retried (@filetransfer.cc@ at 2.24.9, lines--- 443-465).  A URL the client cannot parse (@CURLE_URL_MALFORMAT@) is an--- 'HTTP.InvalidUrlException' from the parser, except for an empty host,--- which the parser accepts and the connection lookup rejects as--- 'HTTP.InvalidDestinationHost' on every attempt.  A scheme the client--- does not speak (@CURLE_UNSUPPORTED_PROTOCOL@) is an--- 'HTTP.InvalidUrlException' too, or 'HTTP.TlsNotSupported' when the--- manager has no TLS.  A redirect loop (@CURLE_TOO_MANY_REDIRECTS@)--- completes the deterministic set.  Every other transport failure is--- transient, name resolution and TLS included, as upstream has it.  The+-- | Classify a failure of the HTTP client: one no retry can change is+-- fatal, and every other is transient.  A URL the client cannot parse+-- (@CURLE_URL_MALFORMAT@) is an 'HTTP.InvalidUrlException' from the+-- parser, except for an empty host, which the parser accepts and the+-- connection lookup rejects as 'HTTP.InvalidDestinationHost' on every+-- attempt.  A scheme the client does not speak+-- (@CURLE_UNSUPPORTED_PROTOCOL@) is an 'HTTP.InvalidUrlException' too, or+-- 'HTTP.TlsNotSupported' when the manager has no TLS.  A redirect loop+-- (@CURLE_TOO_MANY_REDIRECTS@) completes the set.  Every other transport+-- failure is transient, name resolution, TLS and a timeout included.  The -- message names the URL and the failure only: the client's own rendering -- prints the whole request record over a dozen lines, and a retry would -- repeat it. fetchExceptionFailure :: Text -> HTTP.HttpException -> AttemptFailure-fetchExceptionFailure url err = case err of-  HTTP.InvalidUrlException _ reason -> FatalFailure (describeFailure url reason)+fetchExceptionFailure url = exceptionFailure (describeFailure url)++-- | The classification of 'fetchExceptionFailure', with the message made+-- from the failure's detail by the given function, for a request that is+-- not a download.+exceptionFailure :: (String -> Text) -> HTTP.HttpException -> AttemptFailure+exceptionFailure describe err = case err of+  HTTP.InvalidUrlException _ reason -> FatalFailure (describe reason)   HTTP.HttpExceptionRequest _ content -> case content of-    HTTP.InvalidDestinationHost _ -> FatalFailure (describeFailure url "empty host")-    HTTP.TlsNotSupported -> FatalFailure (describeFailure url "TLS is not supported")-    HTTP.TooManyRedirects _ -> FatalFailure (describeFailure url "too many redirects")-    _ -> TransientFailure (describeFailure url (show content))+    HTTP.InvalidDestinationHost _ -> FatalFailure (describe "empty host")+    HTTP.TlsNotSupported -> FatalFailure (describe "TLS is not supported")+    HTTP.TooManyRedirects _ -> FatalFailure (describe "too many redirects")+    _ -> TransientFailure (describe (show content))  -- | A failure writing what the transfer delivered: upstream's -- @CURLE_WRITE_ERROR@, never retried, since the disk that refused one@@ -313,6 +344,13 @@ -- connection as an 'HTTP.HttpException'. fetchWriteFailure :: Text -> IOException -> AttemptFailure fetchWriteFailure url err = FatalFailure (describeFailure url (displayException err))++-- | A @file://@ URL whose file cannot be read, or that names no file here,+-- with the detail: never retried, since the same URL fails the same way+-- every time, as upstream's transfer reads a file it cannot open as not+-- being there.+fileUrlFailure :: Text -> String -> AttemptFailure+fileUrlFailure url detail = FatalFailure (describeFailure url detail)  describeFailure :: Text -> String -> Text describeFailure url detail = "download error fetching " <> url <> ": " <> T.pack detail
src/Nix/Json.hs view
@@ -7,6 +7,9 @@ -- 'renderJson' is identity, not presentation: every byte of it is -- nlohmann's.  'parseJson' is the way back, for the builder, which reads -- @__json@ out of a @.drv@ the way upstream's @nlohmann::json::parse@ does.+-- 'parseJsonInto' hands each value to a t'JsonBuilder' as it reads it, an+-- object's members in document order, for @builtins.fromJSON@, which+-- upstream reads through nlohmann's SAX interface. module Nix.Json   ( -- * Values     Json (..),@@ -15,11 +18,17 @@     renderJson,     renderJsonWith,     formatJsonFloat,+    jsonText, +    -- * Refusals+    expectJson,+     -- * Parsing     IntegerRange (..),+    JsonBuilder (..),     parseJson,     parseJsonWith,+    parseJsonInto,   ) where @@ -68,6 +77,29 @@ -- Rendering -- --------------------------------------------------------------------------- +-- | A JSON value as nlohmann's @dump@ writes it ('renderJson'), for a+-- message.  'renderJson' writes UTF-8, so the decoding is exact.+jsonText :: Json -> Text+jsonText = TE.decodeUtf8Lenient . renderJson++-- | A JSON value of the type upstream's @ensureType@ expects, or its+-- refusal (json-utils.cc at 2.36.0), given the name nlohmann gives that+-- type and the match that takes the value when it has it.+expectJson :: Text -> (Json -> Maybe a) -> Json -> Either Text a+expectJson expected match value =+  maybe (Left ("Expected JSON value to be of type '" <> expected <> "' but it is of type '" <> jsonTypeName value <> "': " <> jsonText value)) Right (match value)++-- | The name nlohmann gives a JSON value's type.+jsonTypeName :: Json -> Text+jsonTypeName value = case value of+  JsonNull -> "null"+  JsonBool _ -> "boolean"+  JsonInt _ -> "number"+  JsonFloat _ -> "number"+  JsonString _ -> "string"+  JsonArray _ -> "array"+  JsonObject _ -> "object"+ -- | nlohmann's @dump()@: no whitespace, members in name order, strings -- escaped as 'escapeJsonString' describes, floats as 'formatJsonFloat'. renderJson :: Json -> ByteString@@ -197,6 +229,41 @@     NixRange   deriving (Eq, Show) +-- | What a parse makes of each value it reads, as nlohmann's SAX interface+-- hands each to its consumer: an object's members arrive in the order the+-- document gives them, a name given twice each time it appears, each with+-- what its value was made into.+data JsonBuilder a = JsonBuilder+  { -- | @null@.+    buildNull :: !a,+    -- | @true@ or @false@.+    buildBool :: !(Bool -> a),+    -- | A number the parse reads as an integer.+    buildInt :: !(Integer -> a),+    -- | A number the parse reads as a float.+    buildFloat :: !(Double -> a),+    -- | A string, its escapes decoded.+    buildString :: !(Text -> a),+    -- | An array's elements, first to last.+    buildArray :: !([a] -> a),+    -- | An object's members, in document order.+    buildObject :: !([(Text, a)] -> a)+  }++-- | Makes the 'Json' nlohmann's DOM parser makes: a name given twice+-- keeps its last value, as the parser assigns each member in turn.+jsonBuilder :: JsonBuilder Json+jsonBuilder =+  JsonBuilder+    { buildNull = JsonNull,+      buildBool = JsonBool,+      buildInt = JsonInt,+      buildFloat = JsonFloat,+      buildString = JsonString,+      buildArray = JsonArray,+      buildObject = JsonObject . Map.fromList+    }+ -- | Read one JSON document as nlohmann's @parse@ does: a single value with -- optional whitespace around it, a leading byte order mark skipped, and -- nothing after it.  A member name given twice keeps its last value, as@@ -207,8 +274,13 @@  -- | 'parseJson' over a chosen 'IntegerRange'. parseJsonWith :: IntegerRange -> Text -> Either Text Json-parseJsonWith range input = do-  (value, rest) <- parseValue range (skipSpace (dropByteOrderMark input))+parseJsonWith range = parseJsonInto range jsonBuilder++-- | 'parseJsonWith' handing each value it reads to a builder, as+-- nlohmann's SAX interface does, rather than making a 'Json'.+parseJsonInto :: IntegerRange -> JsonBuilder a -> Text -> Either Text a+parseJsonInto range builder input = do+  (value, rest) <- parseValue range builder (skipSpace (dropByteOrderMark input))   let trailing = skipSpace rest   if T.null trailing     then Right value@@ -216,6 +288,11 @@   where     dropByteOrderMark t = fromMaybe t (T.stripPrefix (T.singleton byteOrderMark) t) +-- | A value a parse made and the input after it, the value forced, so a+-- parse leaves no thunk of a builder's behind it.+built :: a -> Text -> Either Text (a, Text)+built !value rest = Right (value, rest)+ -- | U+FEFF, which nlohmann skips at the start of a document. byteOrderMark :: Char byteOrderMark = '\xFEFF'@@ -235,44 +312,45 @@ excerptLength = 20  -- | One value, its leading whitespace already skipped.-parseValue :: IntegerRange -> Text -> Either Text (Json, Text)-parseValue range t = case T.uncons t of+parseValue :: IntegerRange -> JsonBuilder a -> Text -> Either Text (a, Text)+parseValue range builder t = case T.uncons t of   Nothing -> Left "unexpected end of input, expected a JSON value"-  Just ('{', rest) -> parseObject range (skipSpace rest)-  Just ('[', rest) -> parseArray range (skipSpace rest)+  Just ('{', rest) -> parseObject range builder (skipSpace rest)+  Just ('[', rest) -> parseArray range builder (skipSpace rest)   Just ('"', rest) -> do     (s, afterString) <- parseString rest-    pure (JsonString s, afterString)-  Just ('t', _) -> literal "true" (JsonBool True)-  Just ('f', _) -> literal "false" (JsonBool False)-  Just ('n', _) -> literal "null" JsonNull+    built (buildString builder s) afterString+  Just ('t', _) -> literal "true" (buildBool builder True)+  Just ('f', _) -> literal "false" (buildBool builder False)+  Just ('n', _) -> literal "null" (buildNull builder)   Just (c, _)-    | c == '-' || isDigit c -> parseNumber range t+    | c == '-' || isDigit c -> parseNumber range builder t   Just _ -> Left ("unexpected " <> excerpt t <> ", expected a JSON value")   where     literal word value = case T.stripPrefix word t of-      Just rest -> Right (value, rest)+      Just rest -> built value rest       Nothing -> Left ("invalid literal " <> excerpt t)  -- | The elements of an array, after its @[@ and any whitespace.-parseArray :: IntegerRange -> Text -> Either Text (Json, Text)-parseArray range t = case T.uncons t of-  Just (']', rest) -> Right (JsonArray [], rest)+parseArray :: IntegerRange -> JsonBuilder a -> Text -> Either Text (a, Text)+parseArray range builder t = case T.uncons t of+  Just (']', rest) -> built (buildArray builder []) rest   _ -> elements [] t   where     elements !acc s = do-      (value, rest) <- parseValue range s+      (value, rest) <- parseValue range builder s       let after = skipSpace rest       case T.uncons after of         Just (',', more) -> elements (value : acc) (skipSpace more)-        Just (']', more) -> Right (JsonArray (reverse (value : acc)), more)+        Just (']', more) -> built (buildArray builder (reverse (value : acc))) more         _ -> Left ("unexpected " <> excerpt after <> " in an array, expected ',' or ']'") --- | The members of an object, after its @{@ and any whitespace.-parseObject :: IntegerRange -> Text -> Either Text (Json, Text)-parseObject range t = case T.uncons t of-  Just ('}', rest) -> Right (JsonObject Map.empty, rest)-  _ -> members Map.empty t+-- | The members of an object, after its @{@ and any whitespace, in+-- document order, a name given twice each time it appears.+parseObject :: IntegerRange -> JsonBuilder a -> Text -> Either Text (a, Text)+parseObject range builder t = case T.uncons t of+  Just ('}', rest) -> built (buildObject builder []) rest+  _ -> members [] t   where     members !acc s = case T.uncons s of       Just ('"', afterQuote) -> do@@ -280,12 +358,12 @@         let beforeColon = skipSpace afterName         case T.uncons beforeColon of           Just (':', afterColon) -> do-            (value, afterValue) <- parseValue range (skipSpace afterColon)-            let updated = Map.insert name value acc+            (value, afterValue) <- parseValue range builder (skipSpace afterColon)+            let gathered = (name, value) : acc                 after = skipSpace afterValue             case T.uncons after of-              Just (',', more) -> members updated (skipSpace more)-              Just ('}', more) -> Right (JsonObject updated, more)+              Just (',', more) -> members gathered (skipSpace more)+              Just ('}', more) -> built (buildObject builder (reverse gathered)) more               _ -> Left ("unexpected " <> excerpt after <> " in an object, expected ',' or '}'")           _ -> Left ("unexpected " <> excerpt beforeColon <> " after a member name, expected ':'")       _ -> Left ("unexpected " <> excerpt s <> " in an object, expected a member name")@@ -369,8 +447,8 @@ -- back; any other is a float (strtod, which 'readMaybe' matches: correctly -- rounded, infinite past the double range).  An infinite one is an error, -- nlohmann's out_of_range 406.-parseNumber :: IntegerRange -> Text -> Either Text (Json, Text)-parseNumber range t = do+parseNumber :: IntegerRange -> JsonBuilder a -> Text -> Either Text (a, Text)+parseNumber range builder t = do   let (sign, afterSign) = case T.stripPrefix "-" t of         Just rest -> ("-", rest)         Nothing -> ("", t)@@ -381,14 +459,14 @@       asFloat = case readMaybe (T.unpack lexeme) of         Just d           | isInfinite d -> Left ("number overflow parsing '" <> lexeme <> "'")-          | otherwise -> Right (JsonFloat d, afterExponent)+          | otherwise -> built (buildFloat builder d) afterExponent         Nothing -> Left ("invalid number " <> excerpt t)   if T.null fraction && T.null exponentText     then case readMaybe (T.unpack lexeme) of       Just n-        | n >= toInteger (minBound :: Int64) && n <= toInteger (maxBound :: Int64) -> Right (JsonInt n, afterExponent)+        | n >= toInteger (minBound :: Int64) && n <= toInteger (maxBound :: Int64) -> built (buildInt builder n) afterExponent         | n > toInteger (maxBound :: Int64) && n <= toInteger (maxBound :: Word64) -> case range of-            NlohmannRange -> Right (JsonInt n, afterExponent)+            NlohmannRange -> built (buildInt builder n) afterExponent             NixRange -> Left ("unsigned json number " <> T.pack (show n) <> " outside of Nix integer range")       _ -> asFloat     else asFloat
+ src/Nix/Key.hs view
@@ -0,0 +1,275 @@+-- | Signing keys as upstream spells, reads and makes them, for+-- @key generate-secret@ and @key convert-secret-to-public@, and the+-- public keys a store trusts ('trustedKeys').+--+-- A key, like a signature, is spelled as a name, a colon and the base64 of+-- its bytes ('parseColonBase64').  An Ed25519 secret key is 64 bytes: the+-- seed it was made from and then the public key of that seed, as libsodium+-- lays one out, and its public key is read off as those last 32 bytes, as+-- upstream reads it, rather than derived again from the seed.  The two+-- agree for every key 'generateSecretKey' makes; for a key whose halves do+-- not match, the second half is what upstream prints.+--+-- Names and keys are bytes from end to end: a name is whatever the command+-- line or standard input gave, and is printed back unchanged.+module Nix.Key+  ( -- * The spelling of keys and signatures+    ColonBase64Refusal (..),+    parseColonBase64,+    colonBase64Message,+    renderColonBase64,++    -- * Secret keys+    SecretKey,+    KeyRefusal (..),+    keyRefusalReason,+    keyRefusalMessage,+    parseSecretKey,+    parsePublicKey,+    generateSecretKey,+    renderSecretKey,+    renderPublicKey,++    -- * The keys a store trusts+    trustedKeys,+    verifyingKey,+  )+where++import Control.Exception (IOException, try)+import qualified Crypto.PubKey.Ed25519 as Ed25519+import Data.Bifunctor (first)+import qualified Data.ByteArray as BA+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import Data.Char (chr)+import Data.Maybe (mapMaybe)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Word (Word8)+import Nix.Hash (base64ToBytes)+import Nix.HostPath (hostPathFromBytes)+import qualified NovaCache.Base64 as B64+import qualified NovaCache.Signing as Signing+import qualified System.OsPath as OP++-- ---------------------------------------------------------------------------+-- The spelling of keys and signatures+-- ---------------------------------------------------------------------------++-- | Why a spelling is not a name, a colon and base64.+data ColonBase64Refusal+  = -- | It has no colon, nothing before its first colon, or no bytes+    -- after it.+    ColonBase64Corrupt+  | -- | Its base64 holds this byte, which base64 does not.+    ColonBase64BadCharacter !Word8+  deriving (Eq, Show)++-- | A name and the bytes its base64 gives, from a spelling, as upstream+-- reads a key or a signature: the name is what comes before the first+-- colon and must not be empty, and the base64 after it is read as+-- 'base64ToBytes' reads it, up to its first @=@ and skipping line feeds,+-- and must give at least one byte.+parseColonBase64 :: ByteString -> Either ColonBase64Refusal (ByteString, ByteString)+parseColonBase64 spelled = case BS.break (== colonByte) spelled of+  (name, rest)+    | not (BS.null name),+      Just encoded <- BS.stripPrefix (BS.singleton colonByte) rest ->+        -- Latin-1 gives each byte a character of its own, so a byte+        -- outside base64 is a character outside it.+        case base64ToBytes (TE.decodeLatin1 encoded) of+          Just bytes+            | not (BS.null bytes) -> Right (name, bytes)+            | otherwise -> Left ColonBase64Corrupt+          Nothing -> Left (maybe ColonBase64Corrupt ColonBase64BadCharacter (BS.find (not . readAsBase64) (BS.takeWhile (/= paddingByte) encoded)))+  _ -> Left ColonBase64Corrupt++-- | What upstream says of a refused spelling of the named kind (@key@ or+-- @signature@).  A byte that is not ASCII is shown as the character of its+-- value, where upstream writes the byte itself.+colonBase64Message :: Text -> ColonBase64Refusal -> Text+colonBase64Message kind refusal = case refusal of+  ColonBase64Corrupt -> kind <> " is corrupt"+  ColonBase64BadCharacter byte -> "invalid character in Base64 string: '" <> T.singleton (chr (fromIntegral byte)) <> "'"++-- | A name and bytes spelled as upstream spells a key or a signature: the+-- name, a colon and the padded base64 of the bytes.+renderColonBase64 :: ByteString -> ByteString -> ByteString+renderColonBase64 name bytes = name <> BS.singleton colonByte <> TE.encodeUtf8 (B64.encode bytes)++-- | Whether upstream's base64 reader takes a byte before the padding: one+-- of the standard alphabet, or a line feed, which it skips.+readAsBase64 :: Word8 -> Bool+readAsBase64 byte =+  (byte >= 0x41 && byte <= 0x5a)+    || (byte >= 0x61 && byte <= 0x7a)+    || (byte >= 0x30 && byte <= 0x39)+    || byte `elem` [0x2b, 0x2f, 0x0a]++-- | The byte that ends a key's or a signature's name.+colonByte :: Word8+colonByte = 0x3a++-- | The byte at which base64 reading stops.+paddingByte :: Word8+paddingByte = 0x3d++-- ---------------------------------------------------------------------------+-- Secret keys+-- ---------------------------------------------------------------------------++-- | An Ed25519 secret key and its name.  Only 'parseSecretKey' and+-- 'generateSecretKey' make one, so the bytes are always 64.+data SecretKey = SecretKey !ByteString !ByteString++-- | The bytes of an Ed25519 secret key, libsodium's+-- @crypto_sign_SECRETKEYBYTES@.+ed25519SecretKeyBytes :: Int+ed25519SecretKeyBytes = 64++-- | The bytes of an Ed25519 public key, the last of a secret key's,+-- libsodium's @crypto_sign_PUBLICKEYBYTES@.+ed25519PublicKeyBytes :: Int+ed25519PublicKeyBytes = 32++-- | Why a key, secret or public, does not read.+data KeyRefusal+  = -- | It is not a name, a colon and base64.+    KeyUnreadable !ColonBase64Refusal+  | -- | Its bytes are not 64.+    SecretKeyNotValid+  | -- | A public key's bytes are not 32.+    PublicKeyNotValid+  deriving (Eq, Show)++-- | Why upstream refuses a key, in its words, without the trace it adds+-- to a key that is not a name, a colon and base64.+keyRefusalReason :: KeyRefusal -> Text+keyRefusalReason (KeyUnreadable unreadable) = colonBase64Message "key" unreadable+keyRefusalReason SecretKeyNotValid = "secret key is not valid"+keyRefusalReason PublicKeyNotValid = "public key is not valid"++-- | A refused secret key as upstream's command reports it on standard+-- error where that is not a terminal, without the final line feed.  A key+-- that is not a name, a colon and base64 fails with the trace upstream+-- adds as it decodes one, which names the key it has not yet read, so the+-- name is always empty; upstream sets the trace and then the error on+-- lines of their own below an @error:@ line, indented by that prefix's+-- width, the trace after an ellipsis.  A key of the wrong size fails on+-- one line.+keyRefusalMessage :: KeyRefusal -> ByteString+keyRefusalMessage refusal = case refusal of+  KeyUnreadable unreadable ->+    BS.intercalate+      "\n"+      [ "error:",+        indentation <> TE.encodeUtf8 (T.singleton traceEllipsis) <> " while decoding key named ''",+        "",+        indentation <> errorPrefix <> unreadableMessage unreadable+      ]+  SecretKeyNotValid -> errorPrefix <> "secret key is not valid"+  PublicKeyNotValid -> errorPrefix <> "public key is not valid"+  where+    indentation = BS.replicate (BS.length errorPrefix) spaceByte+    unreadableMessage unreadable = case unreadable of+      ColonBase64Corrupt -> "key is corrupt"+      ColonBase64BadCharacter byte -> "invalid character in Base64 string: '" <> BS.singleton byte <> "'"++-- | What starts the line of an error.+errorPrefix :: ByteString+errorPrefix = "error: "++-- | What starts a line of an error's trace.+traceEllipsis :: Char+traceEllipsis = '\x2026'++-- | A space.+spaceByte :: Word8+spaceByte = 0x20++-- | A secret key from its spelling, all of it as given, as upstream reads+-- one: 'parseColonBase64', then 64 bytes.  Nothing around it is trimmed,+-- but the base64 is read up to its first @=@, so what follows a padded+-- key, a line feed or a carriage return, is not read, while a carriage+-- return or a space before the padding is refused and a line feed there+-- skipped.+parseSecretKey :: ByteString -> Either KeyRefusal SecretKey+parseSecretKey spelled = do+  (name, bytes) <- first KeyUnreadable (parseColonBase64 spelled)+  if BS.length bytes == ed25519SecretKeyBytes+    then Right (SecretKey name bytes)+    else Left SecretKeyNotValid++-- | A public key's name and bytes from its spelling, as upstream reads+-- one: 'parseColonBase64', then 32 bytes.+parsePublicKey :: ByteString -> Either KeyRefusal (ByteString, ByteString)+parsePublicKey spelled = do+  (name, bytes) <- first KeyUnreadable (parseColonBase64 spelled)+  if BS.length bytes == ed25519PublicKeyBytes+    then Right (name, bytes)+    else Left PublicKeyNotValid++-- | A new secret key with the given name: a seed from the system's source+-- of randomness and the public key of that seed, as libsodium's+-- @crypto_sign_keypair@ makes the key upstream generates.+generateSecretKey :: ByteString -> IO SecretKey+generateSecretKey name = do+  seed <- Ed25519.generateSecretKey+  pure (SecretKey name (BA.convert seed <> BA.convert (Ed25519.toPublic seed)))++-- | A secret key spelled as upstream spells one.+renderSecretKey :: SecretKey -> ByteString+renderSecretKey (SecretKey name bytes) = renderColonBase64 name bytes++-- | The public key of a secret key, spelled as upstream spells one: the+-- secret key's name and its last 32 bytes.+renderPublicKey :: SecretKey -> ByteString+renderPublicKey (SecretKey name bytes) = renderColonBase64 name (BS.takeEnd ed25519PublicKeyBytes bytes)++-- ---------------------------------------------------------------------------+-- The keys a store trusts+-- ---------------------------------------------------------------------------++-- | The keys a store trusts a path's signatures to be made with, as+-- upstream gathers them: the trusted public keys given, then the public+-- key of the secret key in each file named (upstream's+-- @secret-key-files@).  A file that cannot be read is passed over, as+-- upstream passes one over, since in a multi-user installation only the+-- store's owner can read its key files; one that does not hold a secret+-- key refuses them all.  Of keys that share a name only+-- the first is kept, as upstream keeps one key a name and checks a+-- signature with the key its name names.  A secret key whose name is not+-- UTF-8 is left out ('verifyingKey').+trustedKeys :: [Signing.PublicKey] -> [ByteString] -> IO (Either KeyRefusal [Signing.PublicKey])+trustedKeys given files = fmap (firstOfEachName . (given ++) . mapMaybe (>>= verifyingKey)) . sequence <$> traverse secretKeyFileHalf files++-- | The public key of the secret key in a file named by the bytes given,+-- or nothing for a file that cannot be read.+secretKeyFileHalf :: ByteString -> IO (Either KeyRefusal (Maybe (ByteString, ByteString)))+secretKeyFileHalf spelled = case hostPathFromBytes spelled of+  Nothing -> pure (Right Nothing)+  Just path -> do+    contents <- try (OP.decodeFS path >>= BS.readFile) :: IO (Either IOException ByteString)+    pure $ case contents of+      Left _ -> Right Nothing+      Right bytes -> Just . publicHalf <$> parseSecretKey bytes+  where+    publicHalf (SecretKey name bytes) = (name, BS.takeEnd ed25519PublicKeyBytes bytes)++-- | A key a signature is checked with, from its name and bytes: none for+-- a name that is not UTF-8, since no signature is read as one by a key so+-- named, so such a key verifies nothing.+verifyingKey :: (ByteString, ByteString) -> Maybe Signing.PublicKey+verifyingKey (name, bytes) = either (const Nothing) (Just . (`Signing.PublicKey` bytes)) (TE.decodeUtf8' name)++-- | The first key of each name, in the order given.+firstOfEachName :: [Signing.PublicKey] -> [Signing.PublicKey]+firstOfEachName = go Set.empty+  where+    go _ [] = []+    go seen (key : rest)+      | Signing.pkName key `Set.member` seen = go seen rest+      | otherwise = key : go (Set.insert (Signing.pkName key) seen) rest
+ src/Nix/Logger.hs view
@@ -0,0 +1,273 @@+-- | Where the library reports what it is doing while it does it.+--+-- An operation with something to say as it runs (a wait on a lock, a+-- step of a collection, a warning, a line its builder wrote) says it to+-- the t'Logger' it was given and never writes to standard error itself,+-- so the program running it decides where each report goes.  A message+-- has a level, and a build or a substitution is an activity+-- ('withActivity'), so a daemon can pass each on to its client as+-- upstream's daemon passes on its logger's calls.  'handleLogger'+-- writes them to a handle, a build line filtered for the terminal as+-- upstream's default logger filters one ('filterLogLine').+module Nix.Logger+  ( -- * Loggers+    Logger (..),+    Level (..),+    logMessage,+    logWarning,+    plainLogger,+    handleLogger,++    -- * Activities+    ActivityStart (..),+    withActivity,++    -- * Terminal filter+    EscapeFilter (..),+    filterLogLine,+    escapeFilterFor,+  )+where++import Control.Exception (IOException, bracket, catch)+import Data.Bits ((.&.))+import qualified Data.ByteString as BS+import qualified Data.ByteString.Builder as BB+import qualified Data.ByteString.Char8 as BS8+import qualified Data.ByteString.Lazy as BL+import Data.Text (Text)+import qualified Data.Text.IO as TIO+import Data.Word (Word8)+import Nix.Environment (EnvLookup (..), lookupEnvBytes)+import Nix.Store.Path (StorePath)+import System.IO (Handle, hIsTerminalDevice)++-- ---------------------------------------------------------------------------+-- Loggers+-- ---------------------------------------------------------------------------++-- | What an operation reports through.+data Logger = Logger+  { -- | A message for the user at a level, one line without its line+    -- feed: a wait on a lock, a step of a collection, a warning+    -- ('logMessage', 'logWarning').+    logAt :: !(Level -> Text -> IO ()),+    -- | A line a builder wrote, as the line completed: its bytes,+    -- unfiltered, without the line feed ("Nix.Builder.Log"), for the+    -- activity this logger reports for.  A logger drops a line it cannot+    -- deliver rather than throw, since a build is not to fail over its+    -- log.+    logBuildLine :: !(BS.ByteString -> IO ()),+    -- | Start an activity: where its builder's lines go, and how to stop+    -- it ('withActivity').+    logActivity :: !(ActivityStart -> IO (BS.ByteString -> IO (), IO ()))+  }++-- | How much a message matters, as upstream's levels rank it.+data Level+  = -- | Upstream's @lvlError@, which every reader is shown.+    LevelError+  | -- | Upstream's @lvlWarn@.+    LevelWarn+  | -- | Upstream's @lvlInfo@, which its command line shows by default.+    LevelInfo+  deriving (Eq, Show)++-- | Report a message at upstream's info level, which its command line+-- shows by default.+logMessage :: Logger -> Text -> IO ()+logMessage logger = logAt logger LevelInfo++-- | Report a warning: the message after upstream's @warning: @ prefix.+logWarning :: Logger -> Text -> IO ()+logWarning logger = logAt logger LevelWarn . ("warning: " <>)++-- | A logger over a message sink and a build-line sink, whose activities+-- send their builders' lines to that sink and start and stop with+-- nothing to say.+plainLogger :: (Level -> Text -> IO ()) -> (BS.ByteString -> IO ()) -> Logger+plainLogger message line = Logger {logAt = message, logBuildLine = line, logActivity = const (pure (line, pure ()))}++-- | A logger writing each message and each build line to a handle, on a+-- line of its own.  A+-- build line is filtered ('filterLogLine') and goes out in one write, as+-- upstream's default logger writes one to standard error, and one the+-- handle fails to take is dropped, as upstream's logger ignores a+-- failing write, so a reader that went away does not fail the build.  A+-- message is written as it is, and an activity's start and stop write+-- nothing.  The command line passes standard error, with the filter+-- 'escapeFilterFor' finds for it.+handleLogger :: EscapeFilter -> Handle -> Logger+handleLogger escapes handle = plainLogger (const (TIO.hPutStrLn handle)) line+  where+    line bytes = BS.hPut handle (BS8.snoc (filterLogLine escapes bytes) '\n') `catch` dropLine+    dropLine :: IOException -> IO ()+    dropLine _ = pure ()++-- ---------------------------------------------------------------------------+-- Activities+-- ---------------------------------------------------------------------------++-- | What an activity is.+data ActivityStart+  = -- | A derivation's build.+    Building !StorePath+  | -- | A derivation built again, its outputs compared with those the+    -- store holds.+    Checking !StorePath+  | -- | A path substituted from the cache at a URL.+    Substituting !StorePath !Text+  deriving (Eq, Show)++-- | Run an action as an activity: it reports through the logger it is+-- given, which takes its builder's lines as the activity's, and the+-- activity stops as the action ends, however it ends.+withActivity :: Logger -> ActivityStart -> (Logger -> IO a) -> IO a+withActivity logger start action = bracket (logActivity logger start) snd (\(line, _) -> action logger {logBuildLine = line})++-- ---------------------------------------------------------------------------+-- Terminal filter+-- ---------------------------------------------------------------------------++-- | Which escape sequences a build-log line keeps on its way to the user.+data EscapeFilter+  = -- | Keep colour (an SGR sequence, CSI ending in @m@) and drop the rest,+    -- for a terminal that renders it.+    KeepColour+  | -- | Drop every escape sequence.+    DropEscapes+  deriving (Eq, Show)++-- | A build-log line as upstream's default logger writes it to standard+-- error, at no width limit: an escape sequence is dropped unless the+-- filter keeps it, a tab becomes spaces up to the next multiple of+-- eight columns, a bell or carriage return is dropped, and every other+-- byte is kept.  A column is one character as upstream groups one: a+-- UTF-8 lead byte with as many continuation bytes as it announces and+-- as follow it, or any other byte alone.+filterLogLine :: EscapeFilter -> BS.ByteString -> BS.ByteString+filterLogLine escapes = BL.toStrict . BB.toLazyByteString . go 0+  where+    go :: Int -> BS.ByteString -> BB.Builder+    go !column bytes =+      let (plain, rest) = BS.span isPlainAscii bytes+       in BB.byteString plain <> special (column + BS.length plain) rest+    special column bytes = case BS.uncons bytes of+      Nothing -> mempty+      Just (byte, rest)+        | byte == escapeByte ->+            let (escape, after) = escapeSequence rest+                escapeBytes = BS.cons byte (BS.take (BS.length rest - BS.length after) rest)+             in kept escape escapeBytes <> go column after+        | byte == tabByte ->+            let width = tabStop - column `mod` tabStop+             in BB.byteString (BS.replicate width spaceByte) <> go (column + width) rest+        | byte == bellByte || byte == carriageReturnByte -> go column rest+        | otherwise ->+            let continued = BS.takeWhile isContinuation (BS.take (continuationCount byte) rest)+             in BB.word8 byte <> BB.byteString continued <> go (column + 1) (BS.drop (BS.length continued) rest)+    kept escape escapeBytes+      | escapes == KeepColour && escape == ColourEscape = BB.byteString escapeBytes+      | otherwise = mempty+    isPlainAscii byte =+      byte < asciiLimit+        && byte /= escapeByte+        && byte /= tabByte+        && byte /= bellByte+        && byte /= carriageReturnByte++-- | What an escape sequence does, as far as the filter cares.+data EscapeKind = ColourEscape | OtherEscape+  deriving (Eq)++-- | The kind of escape the bytes after an ESC begin, and the bytes after+-- its sequence, which upstream's filter reads as a CSI's parameter,+-- intermediate and final bytes, or the one byte a two-byte escape takes,+-- or nothing.+escapeSequence :: BS.ByteString -> (EscapeKind, BS.ByteString)+escapeSequence bytes = case BS.uncons bytes of+  Just (byte, afterBracket)+    | byte == csiByte ->+        let afterParameters = BS.dropWhile (within csiParameterBytes) afterBracket+            afterIntermediates = BS.dropWhile (within csiIntermediateBytes) afterParameters+         in case BS.uncons afterIntermediates of+              Just (final, after)+                | within csiFinalBytes final -> (if final == sgrFinalByte then ColourEscape else OtherEscape, after)+              _ -> (OtherEscape, afterIntermediates)+    | within escapeFinalBytes byte -> (OtherEscape, afterBracket)+  _ -> (OtherEscape, bytes)++-- | How many continuation bytes a UTF-8 lead byte announces.+continuationCount :: Word8 -> Int+continuationCount lead+  | lead .&. 0xE0 == 0xC0 = 1+  | lead .&. 0xF0 == 0xE0 = 2+  | lead .&. 0xF8 == 0xF0 = 3+  | otherwise = 0++-- | Whether a byte continues a UTF-8 character.+isContinuation :: Word8 -> Bool+isContinuation byte = byte .&. 0xC0 == 0x80++-- | Whether a byte lies in an inclusive range.+within :: (Word8, Word8) -> Word8 -> Bool+within (low, high) byte = low <= byte && byte <= high++-- | The control bytes the filter treats specially, and the space a tab+-- expands to.+escapeByte, tabByte, bellByte, carriageReturnByte, spaceByte :: Word8+escapeByte = 0x1B+tabByte = 0x09+bellByte = 0x07+carriageReturnByte = 0x0D+spaceByte = 0x20++-- | The byte opening a control sequence after an ESC (@[@), and the+-- final byte of a colour one (@m@).+csiByte, sgrFinalByte :: Word8+csiByte = 0x5B+sgrFinalByte = 0x6D++-- | The ECMA-48 byte ranges upstream's filter reads a sequence by.+csiParameterBytes, csiIntermediateBytes, csiFinalBytes, escapeFinalBytes :: (Word8, Word8)+csiParameterBytes = (0x30, 0x3F)+csiIntermediateBytes = (0x20, 0x2F)+csiFinalBytes = (0x40, 0x7E)+escapeFinalBytes = (0x40, 0x5F)++-- | The first byte that is not ASCII.+asciiLimit :: Word8+asciiLimit = 0x80++-- | The columns between tab stops.+tabStop :: Int+tabStop = 8++-- | The filter upstream's default logger applies: colour survives only+-- on a terminal, with @TERM@ set to something other than @dumb@, and+-- neither @NO_COLOR@ nor @NOCOLOR@ set.  Upstream asks about its+-- standard error; this asks about the handle given.+escapeFilterFor :: Handle -> IO EscapeFilter+escapeFilterFor handle = do+  terminal <- hIsTerminalDevice handle+  term <- lookupEnvBytes termVar+  noColour <- traverse lookupEnvBytes noColourVars+  pure $+    if terminal && rendersColour term && all (== EnvUnset) noColour+      then KeepColour+      else DropEscapes+  where+    rendersColour term = case term of+      EnvUnset -> False+      EnvValue value -> value /= dumbTerm+      EnvUnpairedSurrogate -> True++-- | The variable naming the terminal type, and the type upstream reads+-- as rendering no colour.+termVar, dumbTerm :: BS.ByteString+termVar = "TERM"+dumbTerm = "dumb"++-- | The variables whose presence, whatever their value, turns colour off.+noColourVars :: [BS.ByteString]+noColourVars = ["NO_COLOR", "NOCOLOR"]
src/Nix/Parser.hs view
@@ -41,15 +41,19 @@ -- -- == Lifecycle ----- Parsing is pure and touches none of the C data layer, so it runs with--- or without 'Nix.Eval.Arena.arenaInit'.  Evaluating the resulting--- 'Expr' does need the arena; see "Nix.Eval.Arena".+-- Parsing is pure and touches none of the C data layer, so it runs in an+-- evaluation session or outside one.  Evaluating the resulting 'Expr'+-- runs in a session ('Nix.Eval.IO.withEvalSession'). module Nix.Parser   ( -- * Parsing     parseNix,     parseNixWithScope,-    parseNixFile, +    -- * Parsed source+    ParsedSource,+    parsedExpr,+    parsedNames,+     -- * Origins     SourceOrigin (..), @@ -67,7 +71,6 @@ import qualified Data.ByteString.Lazy as BL import Data.Set (Set) import Data.Text (Text)-import qualified Data.Text as T import Data.Word (Word32, Word8) import Nix.Expr.ClosureTrim (trimClosures) import Nix.Expr.Resolve (resolveRelativePaths, resolveVars, staticGlobalNames)@@ -76,8 +79,27 @@ import Nix.Parser.Internal (ParseState (..), runParser) import Nix.Parser.Lexer (positionAfter, tokenize) import Nix.Parser.ParseError (ParseError (..))-import System.FilePath (takeDirectory) +-- | Source the parser has read: its expression, and the names in it in+-- the order upstream's parser interns them (its @symbols.create@ calls,+-- parser.y at 2.24.9).  A symbol's order is the order it was interned in,+-- and a set holds its attributes in symbol order, so interning these+-- before the expression compiles ('Nix.Eval.evalParsed') stores a set's+-- attributes in upstream's order.  The compiler alone could not: it never+-- interns the name of a variable bound in scope, and the parser has merged+-- the bindings of one attribute path written in several places.+data ParsedSource = ParsedSource ![Text] !Expr+  deriving (Show)++-- | The expression the source parsed to, its variables bound.+parsedExpr :: ParsedSource -> Expr+parsedExpr (ParsedSource _ expr) = expr++-- | Every name the parse met where upstream's parser interns one, in the+-- order it interns them, repeats included.+parsedNames :: ParsedSource -> [Text]+parsedNames (ParsedSource names _) = names+ -- | Why source text did not become an expression to evaluate. data SourceError   = -- | The text is not a Nix expression.@@ -110,7 +132,7 @@ -- same reason.  Pass the directory holding the file; for source with no file -- behind it (@--expr@) pass the working directory, which is what upstream -- parses against.-parseNix :: FilePath -> SourceOrigin -> ByteString -> Either SourceError Expr+parseNix :: FilePath -> SourceOrigin -> ByteString -> Either SourceError ParsedSource parseNix = parseNixWithScope staticGlobalNames  -- | 'parseNix' against the names the environment the source is evaluated in@@ -119,18 +141,14 @@ -- with a @scopedImport@ scope's attributes over them, which upstream binds -- in a static environment of their own over the base one.  Every one binds -- like a global, so a @with@ in the source cannot shadow it.-parseNixWithScope :: Set Text -> FilePath -> SourceOrigin -> ByteString -> Either SourceError Expr+parseNixWithScope :: Set Text -> FilePath -> SourceOrigin -> ByteString -> Either SourceError ParsedSource parseNixWithScope scope baseDir origin source = do   utf8 <- first SyntaxError (sourceUtf8 (sourceName origin) source)   tokens <- first SyntaxError (tokenize (sourceName origin) utf8)-  let st = ParseState {psTokens = tokens, psOrigin = origin}-  (expr, _remaining) <- first SyntaxError (runParser parseTopLevel st)+  let st = ParseState {psTokens = tokens, psOrigin = origin, psNames = []}+  (expr, final) <- first SyntaxError (runParser parseTopLevel st)   resolved <- first UndefinedVariable (resolveVars scope expr)-  pure (resolveRelativePaths baseDir (trimClosures resolved))---- | Parse a @.nix@ file from disk.-parseNixFile :: FilePath -> IO (Either SourceError Expr)-parseNixFile path = parseNix (takeDirectory path) (SourceFile (T.pack path)) <$> BS.readFile path+  pure (ParsedSource (reverse (psNames final)) (resolveRelativePaths baseDir (trimClosures resolved)))  -- --------------------------------------------------------------------------- -- Encoding detection
src/Nix/Parser/Expr.hs view
@@ -1,18 +1,28 @@ -- | Recursive descent expression parser for the Nix language. ----- 14 precedence levels, lowest (top) to highest (deepest):+-- Precedence levels, lowest (top) to highest (deepest), as upstream+-- Nix's grammar declares them: -- -- @ -- lambda / -> / || / && / == != / < > <= >= / // -- ! / + - / * \\/ / ++ / ? / negate / application / selection -- @ ----- Close to the C++ Nix parser (parser.y), with two inert deviations: here--- @++@ binds looser than multiplication\/addition (parser.y binds it tighter)--- and unary negate binds looser than @?@ (parser.y makes negate tightest).--- Both only affect mixed expressions that are type errors regardless, so no--- program that type-checks parses differently.+-- The infix operators are read by precedence climbing ('parseBounded'),+-- and a prefix operator's operand runs as far as the operators tighter+-- than it, as upstream Nix's parser reads one: @-x ? a@ is @(-x) ? a@,+-- and @a + !b + c@ is @a + !(b + c)@. -- Entirely pure. No IO, no Megaparsec, no Parsec.+--+-- The parser notes each name ('recordName') where upstream's parser+-- interns one, in the order it does.  Bison runs a rule's action once+-- the rule's whole right-hand side is parsed, so a name a rule's own+-- action interns comes after the names inside it: a function's argument+-- after its body, a formal after its default.  Upstream's GLR parser+-- defers the actions of a split stack and runs them in that same order+-- once one reading survives (glr.c in bison 3.8), so a split never+-- changes the order.  A reading this parser backtracks out of drops its+-- names with it. module Nix.Parser.Expr   ( -- * Entry point     parseTopLevel,@@ -59,7 +69,7 @@   case tok of     TokLBrace -> parseLambdaOrAttrSet     TokIdent _ -> parseLambdaOrIdent-    _ -> parseImplication+    _ -> parseOperators  -- --------------------------------------------------------------------------- -- Lambda detection@@ -82,21 +92,25 @@       case named of         Right body -> body         Left namedErr -> do-          plain <- tryParserKeepError parseImplication+          plain <- tryParserKeepError parseOperators           case plain of             Right e -> pure e             Left plainErr ->               failWithError (deeperError simpleErr (deeperError namedErr plainErr))  -- | The header of @x: body@; on success, returns the committed body parse.+-- The argument's name is noted after the body's names, as upstream's+-- rule interns it (@expr_function@ in parser.y). trySimpleLambdaHeader :: Parser (Parser Expr) trySimpleLambdaHeader = do   name <- expectIdent   expect TokColon-  pure ((\body -> ELambda (FormalName name) body NoCaptureInfo) <$> parseExpr)+  pure ((\body -> ELambda (FormalName name) body NoCaptureInfo) <$> parseExpr <* recordName name)  -- | The header of @name\@{ formals }: body@; on success, returns the--- committed body parse.+-- committed body parse.  The name is noted after the formals' and the+-- body's names, as upstream's rule interns it (@expr_function@ in+-- parser.y). tryNamedSetLambdaHeader :: Parser (Parser Expr) tryNamedSetLambdaHeader = do   name <- expectIdent@@ -104,14 +118,14 @@   expect TokLBrace   (formals, hasEllipsis) <- parseFormalsBody   expect TokColon-  pure ((\body -> ELambda (FormalNamedSet name formals hasEllipsis) body NoCaptureInfo) <$> parseExpr)+  pure ((\body -> ELambda (FormalNamedSet name formals hasEllipsis) body NoCaptureInfo) <$> parseExpr <* recordName name)  -- | Brace at start: could be @{ formals }: body@, @{ formals }\@name: body@, or attr set. -- Same commitment rule as 'parseLambdaOrIdent': @... } :@ and -- @... } \@ name :@ never follow an attr set, so a parsed lambda -- header commits, and a body failure is reported from its own--- position (a real error at line 410 of a formals-lambda file used to--- surface as an attr-set complaint at line 2).  When both readings+-- position (so a real error at line 410 of a formals-lambda file is not+-- reported as an attr-set complaint at line 2).  When both readings -- fail, the deeper failure wins, so a malformed formal beats the -- attr-set branch's earlier stumble over the first comma. parseLambdaOrAttrSet :: Parser Expr@@ -120,13 +134,15 @@   case headed of     Right body -> body     Left lambdaErr -> do-      alt <- tryParserKeepError parseImplication+      alt <- tryParserKeepError parseOperators       case alt of         Right e -> pure e         Left attrErr -> failWithError (deeperError lambdaErr attrErr)  -- | The header of @{ a, b ? default, ... }: body@ or -- @{ a, b }\@name: body@; on success, returns the committed body parse.+-- An \@-name is noted after the formals' and the body's names, as+-- upstream's rule interns it (@expr_function@ in parser.y). trySetLambdaHeader :: Parser (Parser Expr) trySetLambdaHeader = do   expect TokLBrace@@ -141,7 +157,7 @@       _ <- advance       name <- expectIdent       expect TokColon-      pure ((\body -> ELambda (FormalNamedSet name formals hasEllipsis) body NoCaptureInfo) <$> parseExpr)+      pure ((\body -> ELambda (FormalNamedSet name formals hasEllipsis) body NoCaptureInfo) <$> parseExpr <* recordName name)     _ -> parseError ("expected ':' or '@' after formals, got " <> showToken tok)  -- | Parse the inside of @{ ... }@ formals (comma-separated, optional defaults,@@ -171,6 +187,9 @@     if hasDefault       then Just <$> parseExpr       else pure Nothing+  -- Upstream interns a formal's name once the formal, its default+  -- included, is parsed (the formal rule of parser.y).+  recordName name   let formal = Formal {fName = name, fDefault = defVal}       newAcc = formal : acc   tok <- peek@@ -194,175 +213,135 @@     _ -> parseError ("expected ',' or '}' in formals, got " <> showToken tok)  -- ------------------------------------------------------------------------------ Precedence levels (lowest to highest)+-- Operators -- --------------------------------------------------------------------------- --- | Level 1: Implication (@->@, right-associative).-parseImplication :: Parser Expr-parseImplication = do-  lhs <- parseLogicalOr-  tok <- peekMaybe-  case tok of-    Just TokImpl -> do-      _ <- advance-      EBinary OpImpl lhs <$> parseImplication-    _ -> pure lhs+-- | How tightly an operator binds, loosest first: the precedence each+-- operator of upstream Nix's grammar declares.+data Level+  = LevelImplication+  | LevelOr+  | LevelAnd+  | LevelEquality+  | LevelComparison+  | LevelUpdate+  | LevelNot+  | LevelAddition+  | LevelMultiplication+  | LevelConcat+  | LevelHasAttr+  | LevelNegate+  deriving (Eq, Ord) --- | Level 2: Logical OR (@||@, left-associative).-parseLogicalOr :: Parser Expr-parseLogicalOr = do-  lhs <- parseLogicalAnd-  loopOr lhs-  where-    loopOr lhs = do-      found <- match TokOr-      if found-        then do-          rhs <- parseLogicalAnd-          loopOr (EBinary OpOr lhs rhs)-        else pure lhs+-- | How an infix operator meets another of its own level: grouped to the+-- left, grouped to the right, or refused.+data Grouping = GroupsLeft | GroupsRight | GroupsNone --- | Level 3: Logical AND (@&&@, left-associative).-parseLogicalAnd :: Parser Expr-parseLogicalAnd = do-  lhs <- parseEquality-  loopAnd lhs-  where-    loopAnd lhs = do-      found <- match TokAnd-      if found-        then do-          rhs <- parseEquality-          loopAnd (EBinary OpAnd lhs rhs)-        else pure lhs+-- | What an infix operator builds from its left operand and what follows.+data Operation+  = -- | A binary operator over two expressions.+    Binary !BinaryOp+  | -- | @?@, whose right operand is an attribute path.  Nothing can follow+    -- an attribute path inside it, so a @?@ after one applies to the+    -- whole, as it does upstream, where the grammar's no-chaining rule for+    -- @?@ never meets a second one: @a ? b ? c@ is @(a ? b) ? c@.+    HasAttr --- | Level 4: Equality (@==@, @!=@, non-associative).-parseEquality :: Parser Expr-parseEquality = do-  lhs <- parseComparison-  tok <- peekMaybe-  case tok of-    Just TokEq -> do-      _ <- advance-      EBinary OpEq lhs <$> parseComparison-    Just TokNeq -> do-      _ <- advance-      EBinary OpNeq lhs <$> parseComparison-    _ -> pure lhs+-- | An infix operator: its level, grouping and operation.+data Infix = Infix !Level !Grouping !Operation --- | Level 5: Comparison (@<@, @>@, @<=@, @>=@, non-associative).-parseComparison :: Parser Expr-parseComparison = do-  lhs <- parseUpdate-  tok <- peekMaybe-  case tok of-    Just TokLt -> do-      _ <- advance-      EBinary OpLt lhs <$> parseUpdate-    Just TokGt -> do-      _ <- advance-      EBinary OpGt lhs <$> parseUpdate-    Just TokLte -> do-      _ <- advance-      EBinary OpLte lhs <$> parseUpdate-    Just TokGte -> do-      _ <- advance-      EBinary OpGte lhs <$> parseUpdate-    _ -> pure lhs+-- | The infix operator a token is, if it is one.+infixOperator :: Token -> Maybe Infix+infixOperator tok = case tok of+  TokImpl -> Just (Infix LevelImplication GroupsRight (Binary OpImpl))+  TokOr -> Just (Infix LevelOr GroupsLeft (Binary OpOr))+  TokAnd -> Just (Infix LevelAnd GroupsLeft (Binary OpAnd))+  TokEq -> Just (Infix LevelEquality GroupsNone (Binary OpEq))+  TokNeq -> Just (Infix LevelEquality GroupsNone (Binary OpNeq))+  TokLt -> Just (Infix LevelComparison GroupsNone (Binary OpLt))+  TokGt -> Just (Infix LevelComparison GroupsNone (Binary OpGt))+  TokLte -> Just (Infix LevelComparison GroupsNone (Binary OpLte))+  TokGte -> Just (Infix LevelComparison GroupsNone (Binary OpGte))+  TokUpdate -> Just (Infix LevelUpdate GroupsRight (Binary OpUpdate))+  TokPlus -> Just (Infix LevelAddition GroupsLeft (Binary OpAdd))+  TokMinus -> Just (Infix LevelAddition GroupsLeft (Binary OpSub))+  TokStar -> Just (Infix LevelMultiplication GroupsLeft (Binary OpMul))+  TokSlash -> Just (Infix LevelMultiplication GroupsLeft (Binary OpDiv))+  TokConcat -> Just (Infix LevelConcat GroupsRight (Binary OpConcat))+  TokQuestion -> Just (Infix LevelHasAttr GroupsLeft HasAttr)+  _ -> Nothing --- | Level 6: Update (@//@, right-associative).-parseUpdate :: Parser Expr-parseUpdate = do-  lhs <- parseNot-  tok <- peekMaybe-  case tok of-    Just TokUpdate -> do-      _ <- advance-      EBinary OpUpdate lhs <$> parseUpdate-    _ -> pure lhs+-- | Which levels an operator expression takes in.+data Bound+  = -- | This level and every tighter one.+    AtLeast !Level+  | -- | Only the levels tighter than this one.+    Tighter !Level --- | Level 7: Logical NOT (@!@, prefix).-parseNot :: Parser Expr-parseNot = do-  tok <- peek-  case tok of-    TokNot -> do-      _ <- advance-      EUnary OpNot <$> parseNot-    _ -> parseConcat+-- | Whether a bound takes in an operator of a level.+admits :: Bound -> Level -> Bool+admits (AtLeast lowest) level = level >= lowest+admits (Tighter lowest) level = level > lowest --- | Level 8: List concatenation (@++@, right-associative).-parseConcat :: Parser Expr-parseConcat = do-  lhs <- parseAddSub-  tok <- peekMaybe-  case tok of-    Just TokConcat -> do-      _ <- advance-      EBinary OpConcat lhs <$> parseConcat-    _ -> pure lhs+-- | An operator expression: an operand and every infix operator after it.+parseOperators :: Parser Expr+parseOperators = parseBounded (AtLeast LevelImplication) --- | Level 9: Addition and subtraction (@+@, @-@, left-associative).-parseAddSub :: Parser Expr-parseAddSub = do-  lhs <- parseMulDiv-  loopAddSub lhs+-- | An operand and the infix operators the bound takes in after it, as+-- upstream's grammar resolves its precedences.  A prefix operator's+-- operand runs to the end of the tighter operators after it, so+-- @!a + b@ is @!(a + b)@, @1 + !a + b@ is @1 + !(a + b)@ and @-a ? b@ is+-- @(-a) ? b@.  Two operators of a level that groups neither way, such as+-- @a == b == c@ or @a < b > c@, are refused at the second.+parseBounded :: Bound -> Parser Expr+parseBounded bound = parseOperand >>= extend   where-    loopAddSub lhs = do-      tok <- peekMaybe-      case tok of-        Just TokPlus -> do-          _ <- advance-          rhs <- parseMulDiv-          loopAddSub (EBinary OpAdd lhs rhs)-        Just TokMinus -> do+    extend lhs = do+      next <- peekMaybe+      case next >>= infixOperator of+        Just (Infix level grouping operation)+          | admits bound level -> do               _ <- advance-          rhs <- parseMulDiv-          loopAddSub (EBinary OpSub lhs rhs)+              combined <- case operation of+                Binary op -> EBinary op lhs <$> parseBounded (rightBound grouping level)+                HasAttr -> EHasAttr lhs <$> parseAttrPath+              refuseRepeat grouping level+              extend combined         _ -> pure lhs --- | Level 10: Multiplication and division (@*@, @/@, left-associative).-parseMulDiv :: Parser Expr-parseMulDiv = do-  lhs <- parseNegate-  loopMulDiv lhs-  where-    loopMulDiv lhs = do-      tok <- peekMaybe-      case tok of-        Just TokStar -> do-          _ <- advance-          rhs <- parseNegate-          loopMulDiv (EBinary OpMul lhs rhs)-        Just TokSlash -> do-          _ <- advance-          rhs <- parseNegate-          loopMulDiv (EBinary OpDiv lhs rhs)-        _ -> pure lhs+-- | The bound of an infix operator's right operand.+rightBound :: Grouping -> Level -> Bound+rightBound grouping level = case grouping of+  GroupsRight -> AtLeast level+  GroupsLeft -> Tighter level+  GroupsNone -> Tighter level --- | Level 11: Arithmetic negation (@-@, prefix).-parseNegate :: Parser Expr-parseNegate = do-  tok <- peek-  case tok of-    TokMinus -> do-      _ <- advance-      EUnary OpNegate <$> parseNegate-    _ -> parseHasAttr+-- | Refuse an operator of the level just parsed when that level groups+-- neither way.+refuseRepeat :: Grouping -> Level -> Parser ()+refuseRepeat grouping level = case grouping of+  GroupsNone -> do+    next <- peekMaybe+    case next of+      Just tok+        | Just (Infix nextLevel _ _) <- infixOperator tok,+          nextLevel == level ->+            parseError ("unexpected " <> showToken tok <> ": the operator does not chain")+      _ -> pure ()+  GroupsLeft -> pure ()+  GroupsRight -> pure () --- | Level 12: Has-attribute (@?@, non-associative).--- Right operand is an attr path, not a full expression.-parseHasAttr :: Parser Expr-parseHasAttr = do-  lhs <- parseApp-  tok <- peekMaybe+-- | An operand: a prefix operator and its operand, or an application.+-- @!@'s operand takes in the operators tighter than it, and @-@'s none.+parseOperand :: Parser Expr+parseOperand = do+  tok <- peek   case tok of-    Just TokQuestion -> do-      _ <- advance-      EHasAttr lhs <$> parseAttrPath-    _ -> pure lhs+    TokNot -> advance *> (EUnary OpNot <$> parseBounded (Tighter LevelNot))+    TokMinus -> advance *> (EUnary OpNegate <$> parseBounded (Tighter LevelNegate))+    _ -> parseApp --- | Level 13: Function application (juxtaposition, left-associative).+-- | Function application (juxtaposition, left-associative). parseApp :: Parser Expr parseApp = do   func <- parseSelect@@ -376,7 +355,7 @@           loopApp (EApp func arg)         _ -> pure func --- | Level 14: Attribute selection (@e.a@, @e.a or default@).+-- | Attribute selection (@e.a@, @e.a or default@). parseSelect :: Parser Expr parseSelect = do   expr <- parseAtom@@ -420,8 +399,12 @@     TokUri u -> advance >> pure (ELit (NixUri u))     TokPath p -> advance >> pure (ELit (NixPath p))     TokPathInterpStart headPiece -> advance >> EPathStr headPiece <$> parsePathParts-    TokSearchPath p -> advance >> pure (ESearchPath p)-    TokIdent name -> advance >> pure (EVar name)+    TokSearchPath name -> advance >> pure (searchPathCall name)+    TokIdent name+      | name == curPosIdentifier -> EPos <$> currentPos <* advance+      -- Upstream interns a variable's name where it reads it+      -- (expr_simple in parser.y), however the variable is later bound.+      | otherwise -> advance >> EVar name <$ recordName name     TokStringOpen -> parseString     TokIndStringOpen -> parseIndString     TokLParen -> parseParen@@ -439,6 +422,29 @@     TokAssert -> parseAssert     _ -> parseError ("unexpected " <> showToken tok) +-- | The identifier upstream's parser reads as the position it is written+-- at rather than as a variable, wherever it is an expression (the @ID@+-- rule of @expr_simple@, parser.y at 2.24.9).  Only that rule checks the+-- name: an @inherit@ copies a variable of any name, @__curPos@ included.+curPosIdentifier :: Text+curPosIdentifier = "__curPos"++-- | The call a search path @\<name\>@ parses as, @__findFile __nixPath+-- "name"@, as upstream's parser makes it (the @SPATH@ rule of+-- @expr_simple@, parser.y at 2.24.9).  Both are variables, so a binding+-- of either in scope is the one the call uses.  Upstream interns both+-- names as its evaluator starts ("Nix.Eval.StartupSymbols"), so the+-- parser notes neither for the interning order.+searchPathCall :: Text -> Expr+searchPathCall name =+  EApp (EApp (EVar findFileVariable) (EVar nixPathVariable)) (EStr [StrLit (TE.encodeUtf8 name)])++-- | The variables a search path's call names: upstream's @findFile@ and+-- @nixPath@ symbols.+findFileVariable, nixPathVariable :: Text+findFileVariable = "__findFile"+nixPathVariable = "__nixPath"+ -- --------------------------------------------------------------------------- -- Strings -- ---------------------------------------------------------------------------@@ -681,43 +687,28 @@       expect TokSemicolon       pure [Inherit pos name (EVar name) | InheritedName pos name <- names] +-- | The names of an @inherit@, each noted as upstream's parser interns it+-- (the @attrs@ rule of parser.y). parseInheritNames :: Parser [InheritedName] parseInheritNames = go []   where     go acc = do       pos <- currentPos       tok <- peek+      let inherited name = recordName name >> go (InheritedName pos name : acc)       case tok of-        TokIdent name -> do-          _ <- advance-          go (InheritedName pos name : acc)-        -- Keywords are valid as inherit names: inherit if then else;-        _ | Just name <- keywordToText tok -> do-          _ <- advance-          go (InheritedName pos name : acc)-        -- Quoted strings for keywords used as attribute names: inherit "or";-        TokStringOpen -> do-          _ <- advance-          name <- parseQuotedInheritName pos-          go (InheritedName pos name : acc)+        TokIdent name -> advance >> inherited name+        _ | Just name <- identifierKeywordText tok -> advance >> inherited name+        _+          | startsStringAttr tok -> do+              key <- parseStringAttr+              case key of+                StaticKey name -> inherited name+                -- Upstream refuses the key once it is parsed, at its+                -- start (the attrs rule of parser.y).+                DynamicKey _ -> failAt pos "dynamic attributes not allowed in inherit"         _ -> pure (reverse acc) --- | Parse a quoted inherit name: a simple string literal (no interpolation),--- the string opening at the position given.  Used for keywords like @"or"@--- in @inherit (self.trivial) "or";@.-parseQuotedInheritName :: SrcPos -> Parser Text-parseQuotedInheritName pos = do-  tok <- peek-  case tok of-    TokStringLit s -> do-      _ <- advance-      expect TokStringClose-      attrNameText pos s-    TokStringClose -> do-      _ <- advance-      pure ""-    _ -> parseError ("expected string literal in inherit, got " <> showToken tok)- parseAttrPath :: Parser AttrPath parseAttrPath = do   first <- parseAttrKey@@ -740,74 +731,100 @@           go (key : acc)         else pure (reverse acc) +-- | One key of an attribute path, a static one's name noted as upstream's+-- parser interns it (the @attrpath@ rule of parser.y). parseAttrKey :: Parser AttrKey parseAttrKey = do   tok <- peek-  case tok of-    TokIdent name -> advance >> pure (StaticKey name)-    -- Keywords are valid as attribute names in Nix:-    -- { if = 1; }, a.then, { else = 2; }, etc.-    _ | Just name <- keywordToText tok -> advance >> pure (StaticKey name)-    TokStringOpen -> do+  key <- case tok of+    TokIdent name -> StaticKey name <$ advance+    _ | Just name <- identifierKeywordText tok -> StaticKey name <$ advance+    _ -> parseStringAttr+  key <$ noteStatic key+  where+    noteStatic (StaticKey name) = recordName name+    noteStatic (DynamicKey _) = pure ()++-- | Whether a token opens a key written as a string or as @${ expr }@.+startsStringAttr :: Token -> Bool+startsStringAttr TokStringOpen = True+startsStringAttr TokInterpOpen = True+startsStringAttr _ = False++-- | A key written as a string or as @${ expr }@ (upstream's @string_attr@+-- in parser.y).  Upstream's @attrpath@ and @attrs@ rules make such a key a+-- name when its expression is an @ExprString@, and dynamic otherwise+-- (parser.y), so @let ${\"x\"} = 1; in x@ and @inherit ${\"x\"};@ are legal.+-- A double-quoted string with no interpolation is one, and so is a URI+-- (@string_parts@ and @expr_simple@ in parser.y), parentheses around either+-- included, since upstream's parser and this one both make a parenthesized+-- expression the expression itself (@expr_simple@ in parser.y).  An indented+-- string is one when @stripIndentation@ (parser-state.hh) leaves it a single+-- piece; such a key stays dynamic here, since an indented string is held as+-- its unstripped pieces until it is evaluated.+parseStringAttr :: Parser AttrKey+parseStringAttr = do   pos <- currentPos-      strExpr <- parseString-      -- A string key with no interpolation is static, as in upstream Nix's-      -- parser (the string becomes a symbol at parse time) - which is also-      -- what makes @let "x" = 1; in x@ legal.-      case literalStringKey strExpr of-        Just bytes -> StaticKey <$> attrNameText pos bytes-        Nothing -> pure (DynamicKey strExpr)+  tok <- peek+  expr <- case tok of+    TokStringOpen -> parseString     TokInterpOpen -> do       _ <- advance-      expr <- parseExpr+      inner <- parseExpr       -- In expression context, the lexer doesn't track interpolation       -- mode - } is TokRBrace rather than TokInterpClose.       expect TokRBrace-      pure (DynamicKey expr)+      pure inner     _ -> parseError ("expected attribute key, got " <> showToken tok)+  case plainStringBytes expr of+    Just bytes -> StaticKey <$> attrNameText pos bytes+    Nothing -> pure (DynamicKey expr) --- | The bytes of a string expression that contains no interpolation; any--- 'StrInterp' makes the key dynamic.-literalStringKey :: Expr -> Maybe ByteString-literalStringKey (EStr parts) = mconcat <$> traverse literalPart parts+-- | The bytes of an expression upstream's parser builds as a plain string+-- (an @ExprString@): a double-quoted string with no interpolation, whose+-- parts become one string (@string_parts@ in parser.y), or a URI+-- (@expr_simple@ in parser.y).+plainStringBytes :: Expr -> Maybe ByteString+plainStringBytes (EStr parts) = mconcat <$> traverse literalPart parts   where     literalPart (StrLit bytes) = Just bytes     literalPart (StrEsc bytes) = Just bytes     literalPart (StrInterp _) = Nothing-literalStringKey _ = Nothing+plainStringBytes (ELit (NixUri uri)) = Just (TE.encodeUtf8 uri)+plainStringBytes _ = Nothing --- | The name a string attribute key spells, the string opening at the+-- | The name a string attribute key spells, the key starting at the -- position given.  Attribute names are text here, so a key whose bytes are--- not UTF-8 is a syntax error at the string, where upstream makes a symbol--- of any bytes (the @attrpath@ and @attrs@ rules, parser.y at 2.24.9).+-- not UTF-8 is a syntax error at the key, where upstream makes a symbol of+-- any bytes (the @attrpath@ and @attrs@ rules, parser.y at 2.24.9). attrNameText :: SrcPos -> ByteString -> Parser Text-attrNameText (SrcPos origin line col) bytes = case TE.decodeUtf8' bytes of+attrNameText pos bytes = case TE.decodeUtf8' bytes of   Right name -> pure name-  Left _ ->+  Left _ -> failAt pos "attribute name is not valid UTF-8"++-- | Fail at a position the parser has already read past.+failAt :: SrcPos -> Text -> Parser a+failAt (SrcPos origin line col) message =   failWithError     ParseError       { peFile = sourceName origin,         peLine = line,         peCol = col,-          peMessage = "attribute name is not valid UTF-8"+        peMessage = message       } --- | Convert keyword tokens to their text for use as attribute names.--- All Nix keywords are valid as attr keys in binding and select position.-keywordToText :: Token -> Maybe Text-keywordToText TokIf = Just "if"-keywordToText TokThen = Just "then"-keywordToText TokElse = Just "else"-keywordToText TokLet = Just "let"-keywordToText TokIn = Just "in"-keywordToText TokWith = Just "with"-keywordToText TokAssert = Just "assert"-keywordToText TokRec = Just "rec"-keywordToText TokInherit = Just "inherit"-keywordToText TokTrue = Just "true"-keywordToText TokFalse = Just "false"-keywordToText TokNull = Just "null"-keywordToText _ = Nothing+-- | The name of a token this lexer reads as a keyword and upstream's as+-- an identifier (its @ID@ rule in lexer.l): @true@, @false@ and @null@, which+-- upstream binds as names in its base environment.  An attribute name is an+-- identifier, @or@ among them here, or one of these, as upstream's @attr@+-- rule takes an @ID@ or @or@ (parser.y); every other keyword is upstream's+-- own token (lexer.l's keyword rules) and no attribute name, so an attribute+-- named like one is written as a string, @{ \"if\" = 1; }@.+identifierKeywordText :: Token -> Maybe Text+identifierKeywordText TokTrue = Just "true"+identifierKeywordText TokFalse = Just "false"+identifierKeywordText TokNull = Just "null"+identifierKeywordText _ = Nothing  parseLet :: Parser Expr parseLet = do
src/Nix/Parser/Internal.hs view
@@ -28,6 +28,9 @@     -- * Positions     currentPos, +    -- * Names+    recordName,+     -- * Errors     parseError, @@ -43,10 +46,12 @@ import Nix.Parser.ParseError (ParseError (..))  -- | Remaining tokens plus where they came from, for error messages and--- the positions the parser records.+-- the positions the parser records, and the names the parse has met. data ParseState = ParseState   { psTokens :: ![Located],-    psOrigin :: !SourceOrigin+    psOrigin :: !SourceOrigin,+    -- | The names 'recordName' has noted, latest first.+    psNames :: ![Text]   }  -- | The name errors give the source being parsed.@@ -147,10 +152,12 @@ -- | Of two competing failures, the one that got further into the -- input; upstream's LR parser never backtracks, so its errors sit at -- the true site, and reporting the deeper branch is the closest a--- backtracking parser comes to that.  End-of-input errors carry--- position (0,0) by construction and rank past every positioned--- error: end of input is the furthest a branch can get.  Ties keep--- the second error, matching the old fallback order.+-- backtracking parser comes to that.  End-of-input errors carry the+-- position of the lexer's closing 'TokEOF', just past the source's last+-- byte, so they rank past every error before it: end of input is the+-- furthest a branch can get.  An error raised with no token left carries+-- (0,0) and ranks past every positioned error.  Ties keep the second+-- error. deeperError :: ParseError -> ParseError -> ParseError deeperError a b   | rank a > rank b = a@@ -207,6 +214,13 @@ currentPos = Parser $ \st -> case psTokens st of   (Located ln col _ : _) -> Right (SrcPos (psOrigin st) ln col, st)   [] -> Left (makeEOF st)++-- | Note a name at a point where upstream's parser interns one (a+-- @symbols.create@ in parser.y at 2.24.9).  The names are parser state,+-- so a reading the parser backtracks out of takes its names with it, as+-- the actions of a stack bison's GLR parser drops never run.+recordName :: Text -> Parser ()+recordName name = Parser $ \st -> Right ((), st {psNames = name : psNames st})  -- --------------------------------------------------------------------------- -- Helpers
src/Nix/Parser/Lexer.hs view
@@ -3,23 +3,28 @@ -- Handles all Nix tokens including string interpolation via a mode stack. -- Entirely pure - no IO. ----- The source is bytes, as upstream's flex scanner reads it (lexer.l at--- 2.24.9).  Every token class is ASCII, as upstream's are, so a byte+-- The source is bytes, as upstream's flex scanner reads it.  Every token+-- class is ASCII, as upstream's are, so a byte -- outside ASCII never continues an identifier, number, path, URI or run of -- whitespace, while string literals and comments hold whatever bytes they -- hold: a string chunk is the source's bytes with its escapes resolved,--- which is what the eval string gets.  Bytes are matched as Latin-1+-- and in a double-quoted string each line ending read as one LF, which is+-- what the eval string gets.  Bytes are matched as Latin-1 -- 'Char's through "Data.ByteString.Char8" so the grammar reads as -- character literals, which is why no predicate here is one of -- "Data.Char"'s Unicode classes: 'Data.Char.isAlpha' calls the byte 0xE9 -- a letter. ----- A column counts characters: a byte that continues a UTF-8 sequence does--- not advance it, so valid UTF-8 advances one column per character.  A--- line ends at an LF, a CRLF or a bare CR, as upstream's position table--- splits a source (@Pos::LinesIterator@, position.cc).  Every byte the--- lexer takes passes through 'consume', which holds that rule, so no--- token, comment or string counts lines its own way.+-- A column counts bytes, as upstream's do: its lexer advances a location+-- by the length in bytes of everything it matches (@adjustLoc@,+-- lexer-helpers.cc at 2.24.9), and its position table makes a column from+-- a position's byte offset past the start of its line+-- (@PosTable::operator[]@, nixexpr.cc), so a character UTF-8 spells in two+-- bytes takes two columns.  A line+-- ends at an LF, a CRLF or a bare CR, as that table splits a source+-- (@Pos::LinesIterator@, position.cc).  Every byte the lexer takes passes+-- through 'consume', which holds both rules, so no token, comment or+-- string counts lines or columns its own way. module Nix.Parser.Lexer   ( -- * Tokens     Token (..),@@ -88,7 +93,8 @@   | TokStringClose   | TokIndStringOpen   | TokIndStringClose-  | -- | A literal chunk of a string: the source's bytes, escapes resolved.+  | -- | A literal chunk of a string: the source's bytes, escapes resolved,+    -- and in a double-quoted string each line ending read as LF.     TokStringLit !ByteString   | -- | Resolved escape text inside an indented string (@'''@, @''$@,     -- @''${@, @''\x@).  Kept apart from 'TokStringLit' because upstream's@@ -1057,10 +1063,6 @@ isUriChar :: Char -> Bool isUriChar c = isAsciiAlphaNum c || c `elem` ("%/?:@&=+$,-_.!~*'" :: [Char]) --- | A byte that continues a UTF-8 sequence, @10xxxxxx@.-isContinuationByte :: Char -> Bool-isContinuationByte c = c >= '\x80' && c < '\xC0'- -- | The text of bytes an ASCII class matched.  Latin-1 agrees with ASCII -- on every byte such a class admits, and 'TE.decodeLatin1' is total. asciiText :: ByteString -> Text@@ -1100,11 +1102,11 @@  -- | The position past bytes taken from the input, @rest@ being the input -- after them: each line that ends in them moves it to the start of the--- next line, and the bytes after the last ending add their columns.+-- next line, and each byte after the last ending adds a column. advanceOver :: ByteString -> ByteString -> LexState -> LexState advanceOver taken rest !st = case afterLineEnding rest taken of   Just nextLine -> advanceOver nextLine rest st {lsLine = lsLine st + 1, lsCol = 1}-  Nothing -> st {lsCol = lsCol st + charColumns taken}+  Nothing -> st {lsCol = lsCol st + BS.length taken}  -- | The bytes after the first line ending in bytes taken from the input, -- @rest@ being the input after them.  A line ends at an LF, and at a CR@@ -1119,12 +1121,6 @@     | (safeHead afterCr <|> safeHead rest) == Just '\n' -> afterLineEnding rest afterCr   Just (_, afterEnding) -> Just afterEnding   Nothing -> Nothing---- | The columns a run of bytes with no line ending in it takes: one per--- byte that does not continue a UTF-8 sequence, so one per character of--- valid UTF-8.-charColumns :: ByteString -> Int-charColumns = BC.foldl' (\n c -> if isContinuationByte c then n else n + 1) 0  safeHead :: ByteString -> Maybe Char safeHead = fmap fst . BC.uncons
+ src/Nix/Profile/Generation.hs view
@@ -0,0 +1,1002 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | A profile: a link to its current generation, which a switch made here+-- always makes the newest; each generation a link to a store path holding+-- the profile's tree and its @manifest.json@, and each a root the+-- collector keeps, in upstream Nix's layout.+--+-- A user's profiles are in @profiles@ under the state directory:+-- @$NIX_STATE_HOME@, else @$XDG_STATE_HOME\/nix@, else+-- @~\/.local\/state\/nix@, and on Windows @\<Local AppData\>\\nix\\state@+-- (@getStateDir@ in users.cc, @getStateHome@ in xdg-dirs.cc).  The default+-- profile is @profiles\/profile@, which @~\/.nix-profile@, or+-- @\<state\>\/profile@ under @use-xdg-base-directories@, links to+-- (@getDefaultProfile@ in profiles.cc).  Upstream keeps root's profiles under+-- its state directory instead; here every user's are where a user's are.+--+-- A profile named @P@ has generations @P-1-link@, @P-2-link@ and on beside+-- it, and @P@ links to one of them by its bare name.  A new generation is+-- one past the highest, unless the highest already names the path, which+-- it then stays (@createGeneration@ in profiles.cc).  Each is linked as+-- @nova-nix build@ links its output ('Nix.Store.Ops.soAddOutLinkRoot',+-- upstream's @addPermRoot@), so it is an indirect root of the store it names.+--+-- A change to a profile reads the profile's link, makes the new+-- generation's store path with no lock held, then takes the profile's+-- lock and starts again if the link moved meanwhile, as @nix-env@ does+-- (@createUserEnv@ in user-env.cc).  Upstream's @nix profile@ takes no lock,+-- so two changes at once can both start from one manifest and the later+-- switch drop what the earlier added.  The lock file stays once it is+-- released, as every lock file nova-nix takes does ("Nix.Store.Lock"), where+-- upstream deletes it.+--+-- A rollback switches the profile's link to the newest generation below+-- the current one, or to the one asked for, and wiping the history+-- deletes the link of every generation but the current one, or of those+-- made before a cutoff but the newest of them, each holding the+-- profile's lock, as upstream does.  A generation's time is its link's own+-- modification time.  A deleted generation's root record stays until the+-- next collection finds its link gone, removes the record, and takes what+-- only that generation kept.+--+-- The location, the names and the decisions are pure; the IO below lists+-- the profile's directory, reads its links and their times, takes its+-- lock, and makes and removes its links.+module Nix.Profile.Generation+  ( -- * Where profiles are+    StateHome (..),+    ProfileEnvironment (..),+    ProfileLinkPlace (..),+    stateDirectory,+    profilesDirectory,+    profileLinkPath,+    defaultProfilePath,+    absolutePath,+    readProfileEnvironment,+    resolveDefaultProfile,++    -- * Generations+    GenerationNumber (..),+    Generation (..),+    generationName,+    parseGenerationName,+    generationsIn,+    currentGeneration,+    NextGeneration (..),+    nextGeneration,+    listGenerations,++    -- * When generations were made+    EpochSeconds (..),+    DatedGeneration (..),+    generationDate,+    currentEpochSeconds,+    findGenerations,++    -- * Rolling back and wiping history+    Changes (..),+    RollbackTarget (..),+    rollbackPlan,+    readGenerationNumber,+    Days (..),+    parseOlderThan,+    cutoffBefore,+    WipeScope (..),+    WipeStep (..),+    wipePlan,+    switchGeneration,+    wipeHistory,++    -- * A generation's store path+    NarTargets (..),+    hostNarTargets,+    narLinkTarget,+    generationNar,+    generationStoreName,++    -- * Changing a profile+    ProfileFailure (..),+    Change (..),+    Updated (..),+    readManifest,+    checkProfileStore,+    updateProfile,+  )+where++import Control.Exception (IOException, bracket, catch, mask_, onException, try)+import Control.Monad (unless, when)+import Control.Monad.Except (ExceptT (..), runExceptT, throwError)+import Control.Monad.IO.Class (liftIO)+import Data.Bifunctor (first)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BS8+import Data.Char (isAsciiLower, isAsciiUpper, isDigit, toUpper)+import Data.Either (fromRight)+import Data.Foldable (traverse_)+import Data.Int (Int32, Int64)+import Data.List (isPrefixOf, sort, sortOn, stripPrefix, unsnoc)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe, isJust, listToMaybe, mapMaybe)+import Data.Text (Text)+import qualified Data.Text as T+import Data.Time.Clock.POSIX (getPOSIXTime, posixSecondsToUTCTime)+import Data.Time.Format (defaultTimeLocale, formatTime)+import Data.Word (Word64)+import Nix.Environment (EnvLookup (..), lookupEnvBytes)+import Nix.HostPath (absolutePath, hostPathBytes, hostPathFromBytes, hostPathText)+import Nix.Logger (Logger, logMessage, logWarning)+import Nix.Profile.Manifest (Conflict, Manifest, ManifestError, attributeConflict, emptyManifest, manifestPackages, manifestReferences, parseManifest, renderManifest)+import Nix.Profile.Tree (BuildEnvFailure (..), Built (..), Node (..), Package (..), Tree, buildProfile, storeTreeReader, warningText)+import Nix.Store.Handle (canonicalStoreDir)+import Nix.Store.Lock (LockMode (..), acquireLockFileWith, lockFileSuffix, releasePathLock)+import Nix.Store.Metadata (nodeModificationTime)+import Nix.Store.Ops (StoreOps (..))+import Nix.Store.Path (StoreDir (..), StorePath, parseStorePathPrefix, storePathToFilePath)+import qualified NovaCache.NAR as NAR+import qualified System.Directory.OsPath as OsDir+import System.IO.Error (isAlreadyExistsError, isDoesNotExistError)+import qualified System.Info+import System.OsPath (OsPath, (</>))+import qualified System.OsPath as OP+import Text.Read (readMaybe)+#if defined(mingw32_HOST_OS)+import Foreign.Ptr (nullPtr)+import System.Win32.Shell (cSIDL_LOCAL_APPDATA, sHGFP_TYPE_CURRENT, sHGetFolderPath)+#else+import Foreign.C.Error (Errno (..), eNOTDIR)+import GHC.IO.Exception (IOException (ioe_errno))+import System.Posix.Files.ByteString (fileOwner, getFileStatus)+import System.Posix.User (getEffectiveUserID)+import System.Posix.User.ByteString (getUserEntryForID, homeDirectory)+#endif++-- ---------------------------------------------------------------------------+-- Where profiles are+-- ---------------------------------------------------------------------------++-- | What names a user's state directory.+data StateHome+  = -- | @NIX_STATE_HOME@, which names it.+    NixStateHome !OsPath+  | -- | On Unix, when @NIX_STATE_HOME@ is unset: @XDG_STATE_HOME@, when+    -- that is set, under which it is @nix@.+    XdgStateHome !(Maybe OsPath)+  | -- | On Windows, when @NIX_STATE_HOME@ is unset: the Local AppData+    -- folder, under which it is @nix\\state@.+    LocalAppDataHome !OsPath+  deriving (Eq, Show)++-- | What decides where a user's profiles are.+data ProfileEnvironment = ProfileEnvironment+  { peStateHome :: !StateHome,+    -- | The user's home: upstream's @getHome@, @HOME@ on Unix and+    -- @USERPROFILE@ on Windows.+    peHome :: !OsPath+  }+  deriving (Eq, Show)++-- | Where the link to the default profile is, as+-- @use-xdg-base-directories@ chooses (@useXDGBaseDirectories@ in+-- globals.hh, @getDefaultProfile@ in profiles.cc).+data ProfileLinkPlace+  = -- | @~\/.nix-profile@, upstream's default.+    HomeProfileLink+  | -- | @\<state\>\/profile@.+    StateProfileLink+  deriving (Eq, Show)++-- | The state directory (@getStateDir@ in users.cc).  A variable is used+-- as it is set, an empty one included, as upstream's @getEnv@ reads it.+stateDirectory :: ProfileEnvironment -> OsPath+stateDirectory env = case peStateHome env of+  NixStateHome dir -> dir+  XdgStateHome (Just dir) -> dir </> ascii "nix"+  XdgStateHome Nothing -> peHome env </> ascii ".local" </> ascii "state" </> ascii "nix"+  LocalAppDataHome dir -> dir </> ascii "nix" </> ascii "state"++-- | The directory a user's profiles are in (@profilesDir@ in profiles.cc).+profilesDirectory :: ProfileEnvironment -> OsPath+profilesDirectory env = stateDirectory env </> ascii "profiles"++-- | The link to the default profile.+profileLinkPath :: ProfileLinkPlace -> ProfileEnvironment -> OsPath+profileLinkPath place env = case place of+  HomeProfileLink -> peHome env </> ascii ".nix-profile"+  StateProfileLink -> stateDirectory env </> ascii "profile"++-- | The default profile the link is made to: @profiles\/profile@.+defaultProfilePath :: ProfileEnvironment -> OsPath+defaultProfilePath env = profilesDirectory env </> ascii "profile"++-- | Read where this user's profiles are from the environment, as upstream+-- does: @NIX_STATE_HOME@, then on Unix @XDG_STATE_HOME@ and on Windows+-- the Local AppData known folder, which is asked only when+-- @NIX_STATE_HOME@ is unset; and the home, with any warning finding it+-- gives told to the logger.+readProfileEnvironment :: Logger -> IO (Either Text ProfileEnvironment)+readProfileEnvironment logger = runExceptT $ do+  nixStateHome <- ExceptT (variablePath "NIX_STATE_HOME")+  stateHome <- case nixStateHome of+    Just dir -> pure (NixStateHome dir)+    Nothing -> ExceptT hostStateHome+  ProfileEnvironment stateHome <$> ExceptT (readHome logger)++-- | A variable's value as a host path, 'Nothing' when it is unset.+variablePath :: ByteString -> IO (Either Text (Maybe OsPath))+variablePath name = do+  found <- lookupEnvBytes name+  pure $ case found of+    EnvUnset -> Right Nothing+    EnvValue bytes -> maybe (Left (variableName <> " is not valid UTF-8, so it names no Windows path")) (Right . Just) (hostPathFromBytes bytes)+    EnvUnpairedSurrogate -> Left (variableName <> " holds an unpaired UTF-16 surrogate, which has no UTF-8 form")+  where+    variableName = T.pack (BS8.unpack name)++-- | What names the state directory on this host when @NIX_STATE_HOME@+-- does not.+hostStateHome :: IO (Either Text StateHome)+#if defined(mingw32_HOST_OS)+hostStateHome = do+  -- SHGetFolderPath's CSIDL_LOCAL_APPDATA is the folder+  -- SHGetKnownFolderPath's FOLDERID_LocalAppData names, which upstream+  -- asks (getLocalAppData in windows/known-folders.cc); neither reads+  -- LOCALAPPDATA.+  found <- try (sHGetFolderPath nullPtr cSIDL_LOCAL_APPDATA nullPtr sHGFP_TYPE_CURRENT)+  case found of+    Left (failure :: IOException) -> pure (Left ("failed to get known folder path: " <> T.pack (show failure)))+    Right dir -> Right . LocalAppDataHome <$> OP.encodeFS dir+#else+hostStateHome = fmap XdgStateHome <$> variablePath "XDG_STATE_HOME"+#endif++-- | The user's home, as upstream's @getHome@ finds it, any warning told+-- to the logger.+readHome :: Logger -> IO (Either Text OsPath)+#if defined(mingw32_HOST_OS)+-- @USERPROFILE@, else the default user's profile, collapsed+-- (@getHome@ in windows/users.cc).+readHome _ = do+  found <- variablePath "USERPROFILE"+  cwd <- OsDir.getCurrentDirectory+  pure (absolutePath cwd . fromMaybe defaultUserProfile <$> found)+  where+    defaultUserProfile = ascii "C:\\Users\\Default"+#else+-- @HOME@, unless what it names exists and another user owns it, or its+-- status cannot be read for a reason other than its absence, which+-- @ENOENT@ and @ENOTDIR@ are (@maybeStat@ in file-system.cc), when the+-- password database's home is used, with upstream's warning (@getHome@ in+-- unix/users.cc).+readHome logger = do+  found <- lookupEnvBytes "HOME"+  case found of+    EnvValue bytes -> do+      probed <- try (getFileStatus bytes)+      user <- getEffectiveUserID+      case probed of+        Right status+          | fileOwner status /= user -> passwordHome (Just bytes)+          | otherwise -> pure (homePath bytes)+        Left (failure :: IOException)+          | isDoesNotExistError failure || fmap Errno (ioe_errno failure) == Just eNOTDIR -> pure (homePath bytes)+          | otherwise -> do+              logWarning logger ("couldn't stat $HOME ('" <> shown bytes <> "') for reason other than not existing, falling back to the one defined in the 'passwd' file: " <> T.pack (show failure))+              passwordHome Nothing+    _ -> passwordHome Nothing+  where+    homePath bytes = maybe (Left "HOME names no path") Right (hostPathFromBytes bytes)+    shown = T.pack . BS8.unpack+    passwordHome unowned = do+      entry <- tryIO (getUserEntryForID =<< getEffectiveUserID)+      case entry of+        Right found+          | not (BS.null (homeDirectory found)) -> do+              let home = homeDirectory found+              case unowned of+                Just given+                  | given /= home ->+                      logWarning logger ("$HOME ('" <> shown given <> "') is not owned by you, falling back to the one defined in the 'passwd' file ('" <> shown home <> "')")+                _ -> pure ()+              pure (homePath home)+        _ -> pure (Left "cannot determine user's home directory")+#endif++-- | Resolve the default profile, making its directory and its link when+-- they are absent, as upstream's @getDefaultProfile@ does+-- (profiles.cc): the link's target, made absolute against the link's+-- directory, or the link itself when the directory or the link cannot be made+-- or the link cannot be read.  Absence is by @lstat@ (@pathExists@ in+-- file-system.cc), so a link that leads nowhere is kept.  Under+-- 'StateProfileLink' the state directory is made first, and a failure to make+-- it is the result.+resolveDefaultProfile :: ProfileLinkPlace -> ProfileEnvironment -> IO (Either Text OsPath)+resolveDefaultProfile place env = do+  made <- case place of+    StateProfileLink -> first creating <$> tryIO (OsDir.createDirectoryIfMissing True (stateDirectory env))+    HomeProfileLink -> pure (Right ())+  case made of+    Left failure -> pure (Left failure)+    Right () -> do+      resolved <- try $ do+        OsDir.createDirectoryIfMissing True (profilesDirectory env)+        absent <- linkAbsent link+        linked <- if absent then replaceLink link (defaultProfilePath env) else pure (Right ())+        case linked of+          Left _ -> pure link+          Right () -> absolutePath (OP.takeDirectory link) <$> OsDir.getSymbolicLinkTarget link+      pure (Right (either (\(_ :: IOException) -> link) id resolved))+  where+    link = profileLinkPath place env+    creating failure = "creating directory \"" <> hostPathText (stateDirectory env) <> "\": " <> T.pack (show failure)++-- ---------------------------------------------------------------------------+-- Generations+-- ---------------------------------------------------------------------------++-- | A generation's number (upstream's @GenerationNumber@, a 64-bit+-- unsigned integer).+newtype GenerationNumber = GenerationNumber Word64+  deriving (Eq, Ord, Show)++-- | A generation: its number and its link's path.+data Generation = Generation+  { generationNumber :: !GenerationNumber,+    generationPath :: !OsPath+  }+  deriving (Eq, Show)++-- | The link of a profile's generation: the profile's path with+-- @-N-link@ appended (@makeName@ in profiles.cc).+generationName :: OsPath -> GenerationNumber -> OsPath+generationName profile (GenerationNumber n) = profile <> ascii ("-" <> show n <> "-link")++-- | The generation a name in the profile's directory is, given the+-- profile's own name, as upstream's @parseName@ reads one+-- (profiles.cc): the profile's name and @-@, then what precedes the+-- first @-link@ after them, read as a 64-bit unsigned number is by+-- @string2Int@ in util.cc, which takes digits after an optional+-- @+@.  Whatever follows the first @-link@ is ignored, so+-- @profile-3-link.tmp@ is generation 3 too.+parseGenerationName :: OsPath -> OsPath -> Maybe GenerationNumber+parseGenerationName profileName name = do+  rest <- stripPrefix (OP.unpack profileName ++ [OP.unsafeFromChar '-']) (OP.unpack name)+  let chars = map OP.toChar rest+  number <- listToMaybe [take n chars | n <- [0 .. length chars], linkSuffix `isPrefixOf` drop n chars]+  GenerationNumber <$> unsignedDecimal number+  where+    linkSuffix = "-link"++-- | A profile's current generation, from what its link names as the link+-- spells it: the generation that names when it parses as one of the+-- profile's, as a switch writes it, by the generation's bare name, and+-- none for an absolute or other target, or for a profile with no link,+-- as upstream reads it.+currentGeneration :: OsPath -> Maybe OsPath -> Maybe GenerationNumber+currentGeneration profile target = target >>= parseGenerationName (OP.takeFileName profile)++-- | Digits after an optional @+@, within 64 bits, as upstream reads an+-- unsigned number.+unsignedDecimal :: String -> Maybe Word64+unsignedDecimal given = within =<< decimal (fromMaybe given (stripPrefix "+" given))+  where+    within :: Integer -> Maybe Word64+    within n+      | n <= toInteger (maxBound :: Word64) = Just (fromInteger n)+      | otherwise = Nothing++-- | Digits after an optional @+@ or @-@, within 32 bits, as upstream reads+-- an int.+signedDecimal :: String -> Maybe Int32+signedDecimal given = within =<< signed+  where+    signed = case given of+      '-' : digits -> negate <$> decimal digits+      '+' : digits -> decimal digits+      digits -> decimal digits+    within :: Integer -> Maybe Int32+    within n+      | n >= toInteger (minBound :: Int32) && n <= toInteger (maxBound :: Int32) = Just (fromInteger n)+      | otherwise = Nothing++-- | One or more decimal digits, and nothing else.+decimal :: String -> Maybe Integer+decimal digits+  | not (null digits), all isDigit digits = readMaybe digits+  | otherwise = Nothing++-- | The generations of a profile among the names of its directory, in+-- order of number (@findGenerations@ in profiles.cc).  Names are taken in+-- sorted order, so of two names for one number, as @profile-3-link@ and+-- @profile-3-link.tmp@ are, the later in that order counts as the later+-- generation; upstream takes them in @readdir@ order.+generationsIn :: OsPath -> [OsPath] -> [Generation]+generationsIn profile names =+  sortOn generationNumber [Generation number (OP.takeDirectory profile </> name) | name <- sort names, Just number <- [parseGenerationName (OP.takeFileName profile) name]]++-- | What a new generation for a store path is.+data NextGeneration+  = -- | The newest generation, which already names the path.+    ReuseGeneration !Generation+  | -- | A new one, by number.+    NewGeneration !GenerationNumber+  deriving (Eq, Show)++-- | The generation a profile switches to for a store path, given its+-- newest generation with that generation's raw target, and the path as+-- the store spells it on disk (@createGeneration@ in profiles.cc).+nextGeneration :: Maybe (Generation, OsPath) -> OsPath -> NextGeneration+nextGeneration newest target = case newest of+  Just (generation, linked)+    | linked == target -> ReuseGeneration generation+    | GenerationNumber n <- generationNumber generation -> NewGeneration (GenerationNumber (n + 1))+  Nothing -> NewGeneration (GenerationNumber 1)++-- | A profile's generations, from a listing of its directory.+listGenerations :: OsPath -> IO (Either ProfileFailure [Generation])+listGenerations profile = do+  listed <- try (OsDir.listDirectory dir)+  pure $ case listed of+    Left (failure :: IOException) -> Left (ProfileIOFailed ("cannot read directory \"" <> hostPathText dir <> "\": " <> T.pack (show failure)))+    Right names -> Right (generationsIn profile names)+  where+    dir = OP.takeDirectory profile++-- ---------------------------------------------------------------------------+-- A generation's store path+-- ---------------------------------------------------------------------------++-- | The name a generation's store path has (@ProfileManifest::build@ in+-- profile.cc).+generationStoreName :: Text+generationStoreName = "profile"++-- | The file a generation's manifest is in (@ProfileManifest::build@ in+-- profile.cc).+manifestFileName :: String+manifestFileName = "manifest.json"++-- | The file a profile @nix-env@ made holds its manifest in+-- (the @ProfileManifest@ constructor in profile.cc).+nixEnvManifestFileName :: String+nixEnvManifestFileName = "manifest.nix"++-- | How a host's link targets are written in a NAR.+data NarTargets+  = -- | As their bytes, on every host but Windows.+    TargetBytes+  | -- | With @/@ for each @\\@, on Windows: a reparse point holds+    -- backslashes, and nova-cache's serialiser writes the target it reads+    -- from disk with slashes (@symlinkTargetBytes@), so a NAR is+    -- host-independent.+    SlashedTargets+  deriving (Eq, Show)++-- | How this host's link targets are written in a NAR.+hostNarTargets :: NarTargets+hostNarTargets+  | onWindows = SlashedTargets+  | otherwise = TargetBytes++-- | A link target's bytes as a NAR holds them.  A backslash is one byte,+-- @0x5C@, which no multi-byte UTF-8 sequence contains, so the replacement+-- is exact on a target's UTF-8.+narLinkTarget :: NarTargets -> ByteString -> ByteString+narLinkTarget targets bytes = case targets of+  TargetBytes -> bytes+  SlashedTargets -> BS8.map (\c -> if c == '\\' then '/' else c) bytes++-- | The NAR of a generation: the tree, and @manifest.json@ holding the+-- manifest's bytes, as upstream dumps the directory it makes+-- (@ProfileManifest::build@ in profile.cc).  A name and a link target are the+-- bytes the tree holds for them ('hostPathBytes'), a target written as the+-- host's serialiser writes it ('narLinkTarget'), so the NAR is the one the+-- tree unpacked from it serialises to.  'Left' for a name with no UTF-8 form.+generationNar :: NarTargets -> Tree -> ByteString -> Either Text NAR.NarEntry+generationNar targets tree manifest = NAR.NarDirectory . ((BS8.pack manifestFileName, NAR.NarRegular False manifest) :) <$> entries tree+  where+    entries sub = traverse entry (Map.toList sub)+    entry (name, node) = (,) <$> bytesOf name <*> nodeEntry node+    nodeEntry node = case node of+      Link target _ -> NAR.NarSymlink . narLinkTarget targets <$> bytesOf target+      Directory sub -> NAR.NarDirectory <$> entries sub+    bytesOf path = maybe (Left ("'" <> hostPathText path <> "' has no UTF-8 form")) Right (hostPathBytes path)++-- ---------------------------------------------------------------------------+-- Changing a profile+-- ---------------------------------------------------------------------------++-- | Why a profile could not be read or changed.+data ProfileFailure+  = -- | A file of the profile's could not be read or made, and why.+    ProfileIOFailed !Text+  | -- | The manifest, at this path, could not be read.+    ManifestFailed !OsPath !ManifestError+  | -- | A profile @nix-env@ made: it holds @manifest.nix@ and no+    -- @manifest.json@, and @nix-env@'s manifest is not read here.+    NixEnvProfile !OsPath+  | -- | A profile whose current generation is outside the opened store:+    -- the profile, and the path its links lead to.+    ForeignGeneration !OsPath !OsPath+  | -- | The tree could not be built.+    TreeFailed !BuildEnvFailure+  | -- | Two files of one priority conflict, by the elements they came from.+    TreeConflict !Conflict+  | -- | The store refused the generation's path or its root.+    StoreRefused !Text+  | -- | A rollback to a generation the profile does not have.+    NoSuchGeneration !GenerationNumber+  | -- | A rollback to the generation before the current one, which the+    -- profile does not have: the current one, when there is one.+    NoOlderGeneration !(Maybe GenerationNumber)+  deriving (Eq, Show)++-- | What a change makes of a profile's manifest.+data Change+  = -- | Nothing: the profile keeps its generation.+    Unchanged+  | -- | The manifest of the profile's next generation.+    Changed !Manifest+  deriving (Eq, Show)++-- | What a change to a profile did.+data Updated+  = -- | Nothing: the change made none.+    NothingChanged+  | -- | The profile links to this generation.+    SwitchedTo !Generation+  deriving (Eq, Show)++-- | How one attempt at a change ends.+data Attempt = Restart | Finished !Updated++-- | Read a profile's manifest (the @ProfileManifest@ constructor in+-- profile.cc): @manifest.json@ through the profile's links, none for a+-- profile that is not there or holds neither manifest, and a refusal for one+-- only @nix-env@'s @manifest.nix@ describes.+readManifest :: OsPath -> IO (Either ProfileFailure Manifest)+readManifest profile = do+  contents <- try (OP.decodeFS path >>= BS.readFile)+  case contents of+    Right bytes -> pure (first (ManifestFailed path) (parseManifest bytes))+    Left (failure :: IOException)+      | isDoesNotExistError failure -> do+          nixEnv <- OsDir.doesPathExist (profile </> ascii nixEnvManifestFileName)+          pure (if nixEnv then Left (NixEnvProfile profile) else Right emptyManifest)+      | otherwise -> pure (Left (ProfileIOFailed ("reading file \"" <> hostPathText path <> "\": " <> T.pack (show failure))))+  where+    path = profile </> ascii manifestFileName++-- | Change a profile: read its link and its manifest, apply the change,+-- make the new generation's store path, then under the profile's lock+-- make and switch to the generation, starting again, with upstream's+-- line, when the link moved since it was read (@createUserEnv@ in+-- user-env.cc).  A profile whose current generation lies outside the store+-- ('checkProfileStore') is refused before anything is made: a generation of+-- another store read against this one would name paths it does not hold.  The+-- store directory is taken in the spelling the store's handle keys it by+-- ('canonicalStoreDir'), which the tree's links and the generations' targets+-- are written in.  The line, the tree's warnings and a wait on the+-- profile's lock go to the logger.+updateProfile :: Logger -> StoreOps IO -> StoreDir -> OsPath -> (Manifest -> IO Change) -> IO (Either ProfileFailure Updated)+updateProfile logger ops givenStoreDir profile change = canonicalStoreDir givenStoreDir >>= attempting+  where+    attempting storeDir = do+      attempted <- runExceptT (attempt storeDir)+      case attempted of+        Left failure -> pure (Left failure)+        Right (Finished updated) -> pure (Right updated)+        Right Restart -> do+          logMessage logger ("profile \"" <> hostPathText profile <> "\" changed while we were busy; restarting")+          attempting storeDir+    attempt storeDir = do+      token <- ExceptT (profileToken profile)+      ExceptT (checkProfileStore storeDir profile)+      manifest <- ExceptT (readManifest profile)+      changed <- liftIO (change manifest)+      case changed of+        Unchanged -> pure (Finished NothingChanged)+        Changed next -> do+          path <- makeGeneration logger ops storeDir profile next+          ExceptT . withProfileLock logger profile . runExceptT $ do+            now <- ExceptT (profileToken profile)+            if now /= token+              then pure Restart+              else do+                generation <- createGeneration ops storeDir profile path+                ExceptT (first ProfileIOFailed <$> replaceLink profile (OP.takeFileName (generationPath generation)))+                pure (Finished (SwitchedTo generation))++-- | What a profile's link names, its raw target, or 'Nothing' when there+-- is no link: upstream's @optimisticLockProfile@ in profiles.cc.+profileToken :: OsPath -> IO (Either ProfileFailure (Maybe OsPath))+profileToken profile = do+  absent <- try (linkAbsent profile)+  case absent of+    Left (failure :: IOException) -> pure (Left (readingLink failure))+    Right True -> pure (Right Nothing)+    Right False -> do+      target <- tryIO (OsDir.getSymbolicLinkTarget profile)+      pure (either (Left . readingLink) (Right . Just) target)+  where+    readingLink failure = ProfileIOFailed ("reading symbolic link \"" <> hostPathText profile <> "\": " <> T.pack (show failure))++-- | Refuse a profile whose current generation, the path its links lead+-- to, exists outside the store.  The store directory is resolved through+-- its links as the profile is, so a store reached through a linked+-- directory, as macOS's @\/tmp@ and @\/var@ are, is its own.  A profile+-- that is not there, or whose links lead nowhere, has no generation to+-- refuse.+checkProfileStore :: StoreDir -> OsPath -> IO (Either ProfileFailure ())+checkProfileStore storeDir profile = do+  resolved <- tryIO (OsDir.canonicalizePath profile)+  case resolved of+    Left _ -> pure (Right ())+    Right path -> do+      present <- OsDir.doesPathExist path+      spelled <- OP.decodeFS path+      store <- resolvedStoreDir storeDir+      pure $+        if not present || isJust (parseStorePathPrefix store (T.pack spelled))+          then Right ()+          else Left (ForeignGeneration profile path)++-- | A store directory with every link on it resolved, as+-- @canonicalizePath@ resolves one, which is how the tree resolves a link+-- it expands; the directory as given when it cannot be resolved.+resolvedStoreDir :: StoreDir -> IO StoreDir+resolvedStoreDir storeDir = StoreDir . fromRight (unStoreDir storeDir) <$> tryIO (OP.encodeFS (unStoreDir storeDir) >>= OsDir.canonicalizePath >>= OP.decodeFS)++-- | Make a generation's store path from its manifest: the tree of its+-- active elements' paths, with the warnings the tree gives logged, and+-- @manifest.json@, added as 'generationStoreName' with every element's+-- paths as its references (@ProfileManifest::build@ in profile.cc).  The+-- tree's warnings name entries under the profile's path.  A conflict is+-- attributed under the store directory as given and as the tree resolves it.+makeGeneration :: Logger -> StoreOps IO -> StoreDir -> OsPath -> Manifest -> ExceptT ProfileFailure IO StorePath+makeGeneration logger ops storeDir profile manifest = do+  packages <- liftIO (traverse package (manifestPackages manifest))+  Built warnings built <- liftIO (buildProfile (storeTreeReader storeDir) profile packages)+  liftIO (mapM_ (logWarning logger . warningText) warnings)+  tree <- case built of+    Right tree -> pure tree+    Left (FileConflict existing incoming priority) -> do+      resolvedDir <- liftIO (resolvedStoreDir storeDir)+      throwError (maybe (TreeFailed (FileConflict existing incoming priority)) TreeConflict (attributeConflict storeDir resolvedDir manifest existing incoming priority))+    Left failure -> throwError (TreeFailed failure)+  nar <- either (throwError . ProfileIOFailed) pure (generationNar hostNarTargets tree (renderManifest manifest))+  ExceptT (first StoreRefused <$> soAddSourceTree ops generationStoreName (manifestReferences manifest) nar)+  where+    package (path, priority) = (`Package` priority) <$> OP.encodeFS (storePathToFilePath storeDir path)++-- | The generation a profile switches to for a store path: the newest,+-- when it already names the path, or the next, linked and rooted as an+-- out-link is (@createGeneration@ in profiles.cc).+createGeneration :: StoreOps IO -> StoreDir -> OsPath -> StorePath -> ExceptT ProfileFailure IO Generation+createGeneration ops storeDir profile path = do+  generations <- ExceptT (listGenerations profile)+  target <- liftIO (OP.encodeFS (storePathToFilePath storeDir path))+  newest <- traverse withTarget (listToMaybe (reverse generations))+  case nextGeneration newest target of+    ReuseGeneration generation -> pure generation+    NewGeneration number -> do+      let link = generationName profile number+      linkText <- liftIO (OP.decodeFS link)+      rooted <- liftIO (soAddOutLinkRoot ops linkText path)+      either (throwError . StoreRefused) (const (pure (Generation number link))) rooted+  where+    withTarget :: Generation -> ExceptT ProfileFailure IO (Generation, OsPath)+    withTarget generation = do+      linked <- liftIO (tryIO (OsDir.getSymbolicLinkTarget (generationPath generation)))+      case linked of+        Left failure -> throwError (ProfileIOFailed ("reading symbolic link \"" <> hostPathText (generationPath generation) <> "\": " <> T.pack (show failure)))+        Right target -> pure (generation, target)++-- | Run an action holding a profile's lock, @\<profile\>.lock@+-- (@PathLocks::lockPaths@ in unix\/pathlocks.cc), with upstream's line+-- when another holds it (@lockProfile@ in profiles.cc).  A lock file that+-- cannot be opened, as in a directory that is not there, is the failure.+withProfileLock :: Logger -> OsPath -> IO (Either ProfileFailure a) -> IO (Either ProfileFailure a)+withProfileLock logger profile action = do+  lockPath <- OP.decodeFS (profile <> ascii lockFileSuffix)+  bracket (tryIO (acquireLockFileWith logger LockExclusive waiting lockPath)) (traverse_ releasePathLock) (either (pure . Left . opening lockPath) (const action))+  where+    waiting = "waiting for lock on profile \"" <> hostPathText profile <> "\""+    opening lockPath failure = ProfileIOFailed ("opening lock file \"" <> T.pack lockPath <> "\": " <> T.pack (show failure))++-- ---------------------------------------------------------------------------+-- When generations were made+-- ---------------------------------------------------------------------------++-- | A moment, in whole seconds since the epoch.+newtype EpochSeconds = EpochSeconds Int64+  deriving (Eq, Ord, Show)++-- | A generation and when it was made: its link's own modification time.+data DatedGeneration = DatedGeneration+  { datedGeneration :: !Generation,+    datedTime :: !EpochSeconds+  }+  deriving (Eq, Show)++-- | The day a moment falls on in UTC, as @YYYY-MM-DD@, which a profile's+-- history shows for each generation.+generationDate :: EpochSeconds -> Text+generationDate (EpochSeconds seconds) = T.pack (formatTime defaultTimeLocale "%Y-%m-%d" (posixSecondsToUTCTime (fromIntegral seconds)))++-- | Now, rounded down to its second.+currentEpochSeconds :: IO EpochSeconds+currentEpochSeconds = EpochSeconds . floor <$> getPOSIXTime++-- | A profile's generations in order of number, each with its link's own+-- modification time, and its current generation, as upstream finds them:+-- the directory is listed first, each generation's link read without+-- following it, and then the profile's link.+findGenerations :: OsPath -> IO (Either ProfileFailure ([DatedGeneration], Maybe GenerationNumber))+findGenerations profile = runExceptT $ do+  generations <- ExceptT (listGenerations profile)+  dated <- traverse dating generations+  current <- currentGeneration profile <$> ExceptT (profileToken profile)+  pure (dated, current)+  where+    dating :: Generation -> ExceptT ProfileFailure IO DatedGeneration+    dating generation = do+      let path = generationPath generation+      time <- liftIO (tryIO (OP.decodeFS path >>= nodeModificationTime))+      case time of+        Left failure -> throwError (ProfileIOFailed ("getting status of \"" <> hostPathText path <> "\": " <> T.pack (show failure)))+        Right seconds -> pure (DatedGeneration generation (EpochSeconds seconds))++-- ---------------------------------------------------------------------------+-- Rolling back and wiping history+-- ---------------------------------------------------------------------------++-- | Whether a command changes the profile, or with @--dry-run@ only says+-- what it would change.+data Changes = MakeChanges | DryRun+  deriving (Eq, Show)++-- | The generation a rollback switches to.+data RollbackTarget+  = -- | The newest below the current one.+    PreviousGeneration+  | -- | The one of this number, which @--to@ gives.+    GenerationAt !GenerationNumber+  deriving (Eq, Show)++-- | The generation a rollback switches to among a profile's generations+-- in order of number, given its current one: the last listed that the+-- target names, as upstream picks it.  A profile with no current+-- generation has none below it.+rollbackPlan :: RollbackTarget -> Maybe GenerationNumber -> [Generation] -> Either ProfileFailure Generation+rollbackPlan target current generations = case reverse (filter (named target . generationNumber) generations) of+  chosen : _ -> Right chosen+  [] -> Left (refusal target)+  where+    named PreviousGeneration number = maybe False (number <) current+    named (GenerationAt wanted) number = number == wanted+    refusal PreviousGeneration = NoOlderGeneration current+    refusal (GenerationAt wanted) = NoSuchGeneration wanted++-- | A @--to@ value, as upstream reads one: an unsigned number of 64 bits,+-- whose last character, when it is a letter, is a binary unit, @K@, @M@,+-- @G@ or @T@ in either case, the number before it multiplied by 2^10,+-- 2^20, 2^30 or 2^40 and wrapping past 64 bits as upstream's unsigned+-- product does.  Any other letter, or a number that does not read, is+-- refused in upstream's words, the number named without its unit.+readGenerationNumber :: String -> Either Text GenerationNumber+readGenerationNumber given = case unsnoc given of+  Just (number, unit)+    | isAsciiUpper unit || isAsciiLower unit -> do+        let spelled = toUpper unit+        multiplier <- maybe (Left ("invalid unit specifier '" <> T.singleton spelled <> "'")) Right (lookup spelled unitMultipliers)+        GenerationNumber . (* multiplier) <$> unsigned number+  _ -> GenerationNumber <$> unsigned given+  where+    unsigned number = maybe (Left ("'" <> T.pack number <> "' is not an integer")) Right (unsignedDecimal number)++-- | The binary units a number upstream reads may end in, each with what+-- it multiplies by.+unitMultipliers :: [(Char, Word64)]+unitMultipliers = [('K', 2 ^ (10 :: Int)), ('M', 2 ^ (20 :: Int)), ('G', 2 ^ (30 :: Int)), ('T', 2 ^ (40 :: Int))]++-- | A number of days, as @--older-than@ gives one.+newtype Days = Days Int32+  deriving (Eq, Show)++-- | An @--older-than@ value, as upstream reads one: a number of days,+-- an int of at least 1, followed by @d@, refused in upstream's two+-- messages otherwise.+parseOlderThan :: String -> Either Text Days+parseOlderThan spec = case unsnoc spec of+  Just (count, 'd') -> maybe (Left ("invalid number of days specifier '" <> T.pack spec <> "'")) (Right . Days) (signedDecimal count >>= atLeastOne)+  _ -> Left ("invalid number of days specifier '" <> T.pack spec <> "', expected something like '14d'")+  where+    atLeastOne days+      | days >= 1 = Just days+      | otherwise = Nothing++-- | The moment a number of days before another.  The product is taken in+-- 64 bits, where upstream takes it in an int, which more than 24855 days+-- overflow.+cutoffBefore :: EpochSeconds -> Days -> EpochSeconds+cutoffBefore (EpochSeconds now) (Days days) = EpochSeconds (now - fromIntegral days * secondsPerDay)+  where+    secondsPerDay = 24 * 60 * 60++-- | Which generations wiping a profile's history deletes.+data WipeScope+  = -- | Every one but the current one.+    WipeEveryOld+  | -- | Those made before this moment but the newest of them, and never+    -- the current one.+    WipeOlderThan !EpochSeconds+  deriving (Eq, Show)++-- | One step of wiping a profile's history.+data WipeStep+  = -- | Delete this generation.+    RemoveGeneration !GenerationNumber+  | -- | Keep this generation, made after the cutoff though a later one+    -- was made before it, with upstream's warning.+    KeepNewerGeneration !GenerationNumber+  deriving (Eq, Show)++-- | The steps of wiping a profile's history, given its generations in+-- order of number with when each was made, and its current one, as+-- upstream takes them.  Every generation but the current one goes, in+-- order of number, or under a cutoff the generations are taken newest+-- first: those down to the newest made before the cutoff stay, that one+-- too, since the profile held it at the cutoff and can be rolled back to+-- it, and of those after it each made before the cutoff goes, unless it+-- is the current one, and each made after it stays with a warning, as a+-- clock that was wrong or a copy that dropped the times leaves one.  A+-- profile with no current generation keeps none for being current.+wipePlan :: WipeScope -> Maybe GenerationNumber -> [DatedGeneration] -> [WipeStep]+wipePlan scope current dated = case scope of+  WipeEveryOld -> [RemoveGeneration number | number <- map numberOf dated, notCurrent number]+  WipeOlderThan cutoff ->+    let older entry = datedTime entry < cutoff+        pastNewestOlder = drop 1 (dropWhile (not . older) (reverse dated))+     in mapMaybe (olderStep older) pastNewestOlder+  where+    numberOf = generationNumber . datedGeneration+    notCurrent number = Just number /= current+    olderStep older entry+      | not (older entry) = Just (KeepNewerGeneration (numberOf entry))+      | notCurrent (numberOf entry) = Just (RemoveGeneration (numberOf entry))+      | otherwise = Nothing++-- | Switch a profile to the generation a rollback names, holding its lock,+-- with upstream's line naming the two generations, the current one 0 when+-- there is none; with 'DryRun' only the line.  The line and a wait on the+-- lock go to the logger.+switchGeneration :: Logger -> OsPath -> RollbackTarget -> Changes -> IO (Either ProfileFailure ())+switchGeneration logger profile target changes = withProfileLock logger profile . runExceptT $ do+  (dated, current) <- ExceptT (findGenerations profile)+  destination <- ExceptT (pure (rollbackPlan target current (map datedGeneration dated)))+  liftIO (logMessage logger ("switching profile from version " <> numberText (fromMaybe (GenerationNumber 0) current) <> " to " <> numberText (generationNumber destination)))+  case changes of+    DryRun -> pure ()+    MakeChanges -> ExceptT (first ProfileIOFailed <$> replaceLink profile (OP.takeFileName (generationPath destination)))++-- | Wipe a profile's history as 'wipePlan' plans it, holding its lock,+-- with upstream's line for each generation deleted and its warning for+-- each kept; with 'DryRun' the line says the generation would be deleted,+-- and none is.  A generation is deleted by its name for its number, as+-- upstream deletes one.  The lines, the warnings and a wait on the lock go+-- to the logger.+wipeHistory :: Logger -> OsPath -> WipeScope -> Changes -> IO (Either ProfileFailure ())+wipeHistory logger profile scope changes = withProfileLock logger profile . runExceptT $ do+  (dated, current) <- ExceptT (findGenerations profile)+  traverse_ apply (wipePlan scope current dated)+  where+    apply step = case (step, changes) of+      (KeepNewerGeneration number, _) ->+        liftIO (logWarning logger ("not removing profile version " <> numberText number <> " because it is newer than the cutoff, even though a later version is older"))+      (RemoveGeneration number, DryRun) -> liftIO (logMessage logger ("would remove profile version " <> numberText number))+      (RemoveGeneration number, MakeChanges) -> do+        liftIO (logMessage logger ("removing profile version " <> numberText number))+        ExceptT (removeGenerationLink (generationName profile number))++-- | A generation's number, as a message shows it.+numberText :: GenerationNumber -> Text+numberText (GenerationNumber n) = T.pack (show n)++-- | Unlink what is at a generation's name, as upstream does: a link+-- itself and never what it leads to, or a file, and nothing when nothing+-- is there.  No call made here removes a directory's contents, so one+-- that stands there, even put there while this runs, is a failure, as+-- unlinking it is.  On Windows a directory link goes by RemoveDirectory,+-- and anything else there by DeleteFile, which a directory refuses.+removeGenerationLink :: OsPath -> IO (Either ProfileFailure ())+removeGenerationLink path = do+  removed <-+    try $+      if onWindows+        then OsDir.removeDirectoryLink path `catch` \(failure :: IOException) -> unless (isDoesNotExistError failure) (OsDir.removeFile path)+        else OsDir.removeFile path+  pure $ case removed of+    Right () -> Right ()+    Left (failure :: IOException)+      | isDoesNotExistError failure -> Right ()+      | otherwise -> Left (ProfileIOFailed ("removing \"" <> hostPathText path <> "\": " <> T.pack (show failure)))++-- ---------------------------------------------------------------------------+-- Links+-- ---------------------------------------------------------------------------++-- | Whether nothing is at a path, by @lstat@: a link that leads nowhere is+-- there.+linkAbsent :: OsPath -> IO Bool+linkAbsent path = do+  probed <- try (OsDir.pathIsSymbolicLink path)+  case probed of+    Right _ -> pure False+    Left (failure :: IOException)+      | isDoesNotExistError failure -> pure True+      | otherwise -> ioError failure++-- | Point a link at a target, replacing what is there.  Every link here+-- leads to a directory, so on Windows each is a directory link whether+-- or not its target exists yet.  On Unix the link is made under a+-- temporary name beside it and renamed over the path, upstream's+-- @replaceSymlink@ in file-system.cc, which, as @rename@ does,+-- replaces a link or a file there and fails on a directory.  On Windows a+-- rename cannot replace a directory link, so a link there is removed and+-- the new one made, as an out-link is replaced ("Nix.Store.GC"), and+-- anything else there is refused.  The two steps run with asynchronous+-- exceptions masked, and a link that cannot be made puts the old one+-- back, so a profile is absent only while the switch runs.  The callers+-- replace only a link or nothing: the default profile's link is made+-- only where nothing is, and a profile's link is switched only after its+-- target was read ('profileToken'), which fails on anything but a link.+replaceLink :: OsPath -> OsPath -> IO (Either Text ())+replaceLink link target+  | onWindows = do+      absent <- linkAbsent link+      isLink <- if absent then pure False else OsDir.pathIsSymbolicLink link+      if not absent && not isLink+        then pure (Left ("cannot replace \"" <> hostPathText link <> "\", which is not a symbolic link"))+        else mask_ $ do+          previous <- if isLink then Just <$> OsDir.getSymbolicLinkTarget link else pure Nothing+          when isLink (OsDir.removePathForcibly link)+          made <- tryIO (OsDir.createDirectoryLink target link)+          case made of+            Right () -> pure (Right ())+            Left failure -> do+              traverse_ (\old -> tryIO (OsDir.createDirectoryLink old link)) previous+              pure (Left (creatingLink link failure))+  | otherwise = viaRename (0 :: Int)+  where+    viaRename n = do+      let staging = OP.takeDirectory link </> (ascii ("." <> show n <> "_") <> OP.takeFileName link)+      made <- try (OsDir.createDirectoryLink target staging)+      case made of+        Left failure+          | isAlreadyExistsError failure -> viaRename (n + 1)+          | otherwise -> pure (Left (creatingLink staging failure))+        Right () -> do+          renamed <- try (OsDir.renamePath staging link `onException` OsDir.removeFile staging)+          pure (first (\failure -> "renaming \"" <> hostPathText staging <> "\" to \"" <> hostPathText link <> "\": " <> T.pack (show (failure :: IOException))) renamed)+    creatingLink path failure = "creating symlink \"" <> hostPathText path <> "\" -> \"" <> hostPathText target <> "\": " <> T.pack (show (failure :: IOException)) <> windowsHint+    windowsHint+      | onWindows = " (on Windows this needs Developer Mode or elevation)"+      | otherwise = ""++-- | Whether this is Windows, where a link's flavour and its replacement+-- differ.  A plain comparison rather than CPP, so both branches are+-- checked on every host.+onWindows :: Bool+onWindows = System.Info.os == "mingw32"++-- | 'try' for the one exception file system calls throw.+tryIO :: IO a -> IO (Either IOException a)+tryIO = try++-- | An 'OsPath' spelled from ASCII, which 'OP.unsafeFromChar' narrows to+-- one path unit per character without loss.+ascii :: String -> OsPath+ascii = OP.pack . map OP.unsafeFromChar
+ src/Nix/Profile/Manifest.hs view
@@ -0,0 +1,543 @@+-- | A profile's manifest, the @manifest.json@ every generation holds:+-- each element of the profile by its name, with the store paths it adds,+-- whether it is active and its priority, as upstream's @nix profile@+-- keeps it (@ProfileManifest@ in src\/nix\/profile.cc).+--+-- Versions 1 to 3 are read and version 3 is written, through+-- 'renderJson', which is nlohmann's @dump()@: members in name order,+-- each element's paths in store-path order, in the canonical+-- @\/nix\/store@ spelling.  An element a flake made keeps the fields it+-- was read with, where upstream parses its flake references and renders+-- them again.  What changed from one manifest to the next is what a+-- profile's history shows of each generation.+--+-- Everything here is pure: reading the file, building the tree and+-- making the generation are "Nix.Profile.Generation"'s.+module Nix.Profile.Manifest+  ( -- * Manifests+    Manifest (..),+    Element (..),+    FlakeSource (..),+    emptyManifest,+    defaultPriority,++    -- * Reading and writing+    ManifestError (..),+    parseManifest,+    manifestJson,+    renderManifest,+    manifestErrorText,++    -- * Names+    elementIdentifier,+    flakeAttribute,+    drvNameName,+    addElement,++    -- * What a generation is made of+    manifestPackages,+    manifestReferences,++    -- * Selecting elements+    Selector (..),+    Matcher (..),+    regexMatcher,+    matcherTitle,+    Selection (..),+    selectElements,++    -- * Conflicts+    ConflictSide (..),+    Conflict (..),+    attributeConflict,++    -- * Between generations+    ElementChange (..),+    manifestChanges,+    changeLine,+    elementVersions,+  )+where++import Control.Monad (foldM)+import Data.Bifunctor (first)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import Data.Foldable (toList)+import Data.Int (Int32)+import Data.List.NonEmpty (NonEmpty)+import qualified Data.Map.Merge.Strict as Merge+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Nix.Builder.Buildenv (Activity (..))+import Nix.Daemon.Protocol (OutputName (..), OutputsSpec (AllOutputs), namedOutputs, outputsSpecNames)+import Nix.DrvName (drvNameDash)+import Nix.HostPath (hostPathText)+import Nix.Json (Json (..), parseJson, renderJson)+import Nix.Store.Path (StoreDir, StorePath (spName), defaultStoreDir, parseStorePath, storePathBasename, storePathToFilePath, storePathToText)+import System.OsPath (OsPath)+import qualified Text.Regex.TDFA as RE+import Text.Regex.TDFA.ByteString ()++-- ---------------------------------------------------------------------------+-- Manifests+-- ---------------------------------------------------------------------------++-- | What a profile holds: its elements by name, in name order.+newtype Manifest = Manifest {manifestElements :: Map Text Element}+  deriving (Eq, Show)++-- | One thing a profile holds.+data Element = Element+  { -- | The store paths it adds to the profile's tree.+    elementPaths :: !(Set StorePath),+    -- | Whether its paths go into the tree.  An inactive element's paths+    -- are still the generation's references.+    elementActivity :: !Activity,+    -- | Its priority: of two files at one path, the one whose element has+    -- the lower number stays.+    elementPriority :: !Int,+    -- | The flake it came from, for an element a flake made.+    elementSource :: !(Maybe FlakeSource)+  }+  deriving (Eq, Show)++-- | Where an element a flake made came from, as the manifest records it.+data FlakeSource = FlakeSource+  { -- | The flake reference as it was given.+    sourceOriginalUrl :: !Text,+    -- | The flake reference it was locked to.+    sourceUrl :: !Text,+    -- | The attribute it was taken from.+    sourceAttrPath :: !Text,+    -- | The outputs it was asked for: 'Nothing' for the default ones.+    sourceOutputs :: !(Maybe OutputsSpec)+  }+  deriving (Eq, Show)++-- | A profile with nothing in it, which a profile with no manifest is.+emptyManifest :: Manifest+emptyManifest = Manifest Map.empty++-- | The priority an element has when nothing gives it another+-- (@defaultPriority@ in profile.cc).+defaultPriority :: Int+defaultPriority = 5++-- | The version 'renderManifest' writes (@ProfileManifest::toJSON@ in+-- profile.cc).+writtenVersion :: Integer+writtenVersion = 3++-- ---------------------------------------------------------------------------+-- Reading and writing+-- ---------------------------------------------------------------------------++-- | Why a manifest could not be read.+data ManifestError+  = -- | The file is not UTF-8 JSON or not a JSON object, or its @version@+    -- is not a number or its @elements@ neither an object nor an array.+    ManifestNotJson !Text+  | -- | A version other than 1, 2 and 3 (the @ProfileManifest@ constructor+    -- in profile.cc).+    UnsupportedVersion !Integer+  | -- | An element, by the key or index it was read under, that is not+    -- what upstream reads, and why.+    MalformedElement !Text !Text+  | -- | An element of a version 1 or 2 manifest that a flake made, which+    -- upstream names from its flake reference's URL (the @ProfileManifest@+    -- constructor in profile.cc) and which is not read here, by its index.+    UnnamedFlakeElement !Text+  deriving (Eq, Show)++-- | The members a manifest's version names a flake element's references+-- under: version 1's, then those of versions 2 and 3 (the+-- @ProfileManifest@ constructor in profile.cc).+data UrlKeys = UrlKeys !Text !Text++-- | Read a manifest's bytes, as upstream's @ProfileManifest@ constructor+-- in profile.cc reads @manifest.json@: the version, 0 when it is+-- missing, then each element, by its key in an object or its index in+-- the array versions 1 and 2 hold.  A missing @elements@ or @storePaths@+-- is empty, @active@ is required, and @priority@ defaults to+-- 'defaultPriority'.  An element whose @url@ is not empty came from a+-- flake.+parseManifest :: ByteString -> Either ManifestError Manifest+parseManifest bytes = do+  text <- first (const (ManifestNotJson "it is not UTF-8")) (TE.decodeUtf8' bytes)+  json <- first ManifestNotJson (parseJson text)+  members <- case json of+    JsonObject members -> Right members+    _ -> Left (ManifestNotJson "it is not a JSON object")+  version <- case Map.lookup "version" members of+    Nothing -> Right 0+    Just (JsonInt n) -> Right n+    Just _ -> Left (ManifestNotJson "its version is not a number")+  keys <- case version of+    1 -> Right (UrlKeys "uri" "originalUri")+    2 -> Right (UrlKeys "url" "originalUrl")+    3 -> Right (UrlKeys "url" "originalUrl")+    other -> Left (UnsupportedVersion other)+  case Map.lookup "elements" members of+    Nothing -> Right emptyManifest+    Just JsonNull -> Right emptyManifest+    Just (JsonObject elements) -> foldM (keyed keys) emptyManifest (Map.toAscList elements)+    Just (JsonArray elements) -> foldM (indexed keys) emptyManifest (zip [0 :: Int ..] elements)+    Just _ -> Left (ManifestNotJson "its elements are neither an object nor an array")+  where+    keyed keys manifest (name, value) = (\element -> addElement name element manifest) <$> parseElement keys name value+    indexed keys manifest (index, value) = do+      let label = T.pack (show index)+      element <- parseElement keys label value+      case elementSource element of+        Just _ -> Left (UnnamedFlakeElement label)+        Nothing -> Right (addElement (elementIdentifier element) element manifest)++-- | One element of a manifest.+parseElement :: UrlKeys -> Text -> Json -> Either ManifestError Element+parseElement (UrlKeys urlKey originalUrlKey) label value = case value of+  JsonObject fields -> do+    paths <- case Map.lookup "storePaths" fields of+      Nothing -> Right Set.empty+      Just JsonNull -> Right Set.empty+      Just (JsonArray items) -> Set.fromList <$> traverse storePath items+      Just _ -> malformed "its storePaths are not an array"+    activity <- case Map.lookup "active" fields of+      Just (JsonBool True) -> Right Active+      Just (JsonBool False) -> Right Inactive+      _ -> malformed "its active is not a Boolean"+    priority <- maybe (Right defaultPriority) priorityOf (Map.lookup "priority" fields)+    source <- case Map.lookup urlKey fields of+      Nothing -> Right Nothing+      Just (JsonString "") -> Right Nothing+      Just (JsonString url) -> Just <$> flakeSource fields url+      Just _ -> malformed ("its " <> urlKey <> " is not a string")+    Right (Element paths activity priority source)+  _ -> malformed "it is not an object"+  where+    malformed = Left . MalformedElement label+    storePath item = case item of+      JsonString text -> maybe (malformed ("path '" <> text <> "' is not in the Nix store")) Right (parseStorePath defaultStoreDir text)+      _ -> malformed "a store path is not a string"+    priorityOf priority = case priority of+      JsonInt n+        | n >= toInteger (minBound :: Int32) && n <= toInteger (maxBound :: Int32) -> Right (fromInteger n)+      _ -> malformed "its priority is not an int"+    flakeSource fields url = do+      original <- stringField fields originalUrlKey+      attrPath <- stringField fields "attrPath"+      outputs <- case Map.lookup "outputs" fields of+        Nothing -> Right Nothing+        Just JsonNull -> Right Nothing+        Just (JsonArray [JsonString "*"]) -> Right (Just AllOutputs)+        Just (JsonArray names) -> do+          spelled <- traverse outputName names+          maybe (malformed "its outputs name none") (Right . Just) (namedOutputs (Set.fromList spelled))+        Just _ -> malformed "its outputs are not an array"+      Right (FlakeSource original url attrPath outputs)+    stringField fields key = case Map.lookup key fields of+      Just (JsonString text) -> Right text+      _ -> malformed ("its " <> key <> " is not a string")+    outputName name = case name of+      JsonString text -> Right (OutputName text)+      _ -> malformed "an output name is not a string"++-- | A manifest as version 3 holds it (@ProfileManifest::toJSON@ in+-- profile.cc).+manifestJson :: Manifest -> Json+manifestJson (Manifest elements) =+  JsonObject+    ( Map.fromList+        [ ("elements", JsonObject (Map.map elementJson elements)),+          ("version", JsonInt writtenVersion)+        ]+    )+  where+    elementJson element =+      JsonObject+        ( Map.fromList+            ( [ ("active", JsonBool (elementActivity element == Active)),+                ("priority", JsonInt (toInteger (elementPriority element))),+                ("storePaths", JsonArray [JsonString (storePathToText defaultStoreDir path) | path <- Set.toAscList (elementPaths element)])+              ]+                ++ maybe [] sourceFields (elementSource element)+            )+        )+    sourceFields source =+      [ ("originalUrl", JsonString (sourceOriginalUrl source)),+        ("url", JsonString (sourceUrl source)),+        ("attrPath", JsonString (sourceAttrPath source)),+        ("outputs", outputsJson (sourceOutputs source))+      ]+    outputsJson = maybe JsonNull (JsonArray . map JsonString . outputsSpelled)++-- | The bytes of @manifest.json@: 'manifestJson' as nlohmann's @dump()@+-- writes it, with no newline after (@ProfileManifest::build@ in+-- profile.cc).+renderManifest :: Manifest -> ByteString+renderManifest = renderJson . manifestJson++-- | A failure as a message naming the manifest's path.+manifestErrorText :: OsPath -> ManifestError -> Text+manifestErrorText path failure = case failure of+  ManifestNotJson reason -> "profile manifest " <> quoted <> " cannot be read: " <> reason+  UnsupportedVersion version -> "profile manifest " <> quoted <> " has unsupported version " <> T.pack (show version)+  MalformedElement label reason -> "profile manifest " <> quoted <> " has an element " <> label <> " that cannot be read: " <> reason+  UnnamedFlakeElement label ->+    "profile manifest " <> quoted <> " has an element " <> label <> " that a flake made, which upstream names from its URL and nova-nix cannot"+  where+    quoted = "\"" <> hostPathText path <> "\""++-- ---------------------------------------------------------------------------+-- Names+-- ---------------------------------------------------------------------------++-- | What identifies an element in messages and in what @--regex@ matches+-- (@ProfileElement::identifier@ in profile.cc): for an element a flake made,+-- its flake reference, @#@ and its attribute, then its outputs after @^@;+-- otherwise the name part of each path's name ('drvNameName'), each once, in+-- byte order, joined by a comma and a space, an empty one left out.+elementIdentifier :: Element -> Text+elementIdentifier element = case elementSource element of+  Just source -> sourceOriginalUrl source <> "#" <> flakeAttribute source+  Nothing -> T.intercalate ", " (filter (not . T.null) (Set.toAscList (Set.map (drvNameName . spName) (elementPaths element))))++-- | An element's flake attribute and the outputs it was asked for, after+-- @^@ when it was asked for some (@ProfileElementSource::to_string@ in+-- profile.cc): what @profile list@ prints as its flake attribute.+flakeAttribute :: FlakeSource -> Text+flakeAttribute source = sourceAttrPath source <> maybe "" (("^" <>) . T.intercalate "," . outputsSpelled) (sourceOutputs source)++-- | Outputs as upstream spells them: @*@ for every output, else the+-- names in order.+outputsSpelled :: OutputsSpec -> [Text]+outputsSpelled spec = maybe ["*"] (\names -> [name | OutputName name <- Set.toAscList names]) (outputsSpecNames spec)++-- | The name part of a derivation name: everything before the dash it+-- splits at ('drvNameDash'), or the whole name when nothing splits it.+drvNameName :: Text -> Text+drvNameName = fst . splitDrvName++-- | A derivation name split at the dash it splits at ('drvNameDash'),+-- into the name before it and the version after it; the whole name and+-- an empty version when nothing splits it.+splitDrvName :: Text -> (Text, Text)+splitDrvName name = maybe (name, "") (\at -> (T.take at name, T.drop (at + 1) name)) (drvNameDash T.uncons name)++-- | Add an element under a name, or under the name with @-1@, @-2@ and+-- on appended when it is taken (@ProfileManifest::addElement@ in+-- profile.cc).+addElement :: Text -> Element -> Manifest -> Manifest+addElement candidate element (Manifest elements) = Manifest (Map.insert (free candidates) element elements)+  where+    candidates = candidate : [candidate <> "-" <> T.pack (show n) | n <- [1 :: Int ..]]+    free names = case dropWhile (`Map.member` elements) names of+      name : _ -> name+      [] -> candidate++-- ---------------------------------------------------------------------------+-- What a generation is made of+-- ---------------------------------------------------------------------------++-- | Each active element's paths with its priority, the packages of the+-- generation's tree (@ProfileManifest::build@ in profile.cc).+manifestPackages :: Manifest -> [(StorePath, Int)]+manifestPackages (Manifest elements) =+  [(path, elementPriority element) | element <- Map.elems elements, elementActivity element == Active, path <- Set.toAscList (elementPaths element)]++-- | Every element's paths, the inactive ones' too: the generation's+-- references (@ProfileManifest::build@ in profile.cc).+manifestReferences :: Manifest -> Set StorePath+manifestReferences (Manifest elements) = foldMap elementPaths elements++-- ---------------------------------------------------------------------------+-- Selecting elements+-- ---------------------------------------------------------------------------++-- | What selects elements, as @profile remove@ names them+-- (@Matcher@ and its four kinds in profile.cc).  Upstream refuses none at+-- all and @--all@ beside anything+-- (@MixProfileElementMatchers::getMatchingElementNames@); neither is a+-- selector here.+data Selector+  = -- | @--all@: every element.+    SelectAll+  | -- | The elements any of these select.+    SelectSome !(NonEmpty Matcher)++-- | One way to select elements.+data Matcher+  = -- | The element with this name.+    MatchName !Text+  | -- | Every element holding this path.+    MatchStorePath !StorePath+  | -- | Every element whose identifier the pattern matches as a whole,+    -- with the pattern as it was given.+    MatchRegex !Text !RE.Regex++-- | A @--regex@ pattern: a POSIX extended regular expression that+-- ignores case, as upstream compiles one (@std::regex::extended |+-- std::regex::icase@ in @RegexMatcher@, profile.cc), over the pattern's+-- bytes, as @builtins.match@ compiles one.  'Nothing' when it does not+-- compile.+regexMatcher :: Text -> Maybe Matcher+regexMatcher given = MatchRegex given <$> RE.makeRegexOptsM options RE.defaultExecOpt (TE.encodeUtf8 given)+  where+    options = RE.defaultCompOpt {RE.multiline = False, RE.caseSensitive = False}++-- | How a warning names a matcher (each matcher's @getTitle@ in+-- profile.cc).+matcherTitle :: Matcher -> Text+matcherTitle matcher = case matcher of+  MatchName name -> "Package name '" <> name <> "'"+  MatchStorePath path -> "Store path '" <> storePathBasename path <> "'"+  MatchRegex given _ -> "Regex '" <> given <> "'"++-- | Whether a matcher selects an element, by its name.+matches :: Matcher -> Text -> Element -> Bool+matches matcher name element = case matcher of+  MatchName wanted -> name == wanted+  MatchStorePath path -> Set.member path (elementPaths element)+  MatchRegex _ regex -> wholeMatch regex (TE.encodeUtf8 (elementIdentifier element))++-- | Whether a pattern matches the whole of a subject, as @std::regex_match@+-- asks: the leftmost-longest match spans it exactly when a match of the+-- whole exists.+wholeMatch :: RE.Regex -> ByteString -> Bool+wholeMatch regex subject = case RE.matchOnceText regex subject of+  Just (before, _, after) -> BS.null before && BS.null after+  Nothing -> False++-- | What matchers select.+data Selection = Selection+  { -- | The names selected, in name order.+    selectedNames :: !(Set Text),+    -- | Upstream's warnings, in order.+    selectionWarnings :: ![Text]+  }+  deriving (Eq, Show)++-- | The elements a selector selects+-- (@MixProfileElementMatchers::getMatchingElementNames@ in profile.cc): a+-- profile with no elements selects nothing, with upstream's warning, and a+-- matcher that selects nothing is warned of.+selectElements :: Selector -> Manifest -> Selection+selectElements selector (Manifest elements)+  | Map.null elements = Selection Set.empty ["There are no packages in the profile."]+  | otherwise = case selector of+      SelectAll -> Selection (Map.keysSet elements) []+      SelectSome matchers -> foldl' select (Selection Set.empty []) matchers+  where+    select (Selection names warnings) matcher =+      case Map.keys (Map.filterWithKey (matches matcher) elements) of+        [] -> Selection names (warnings ++ [matcherTitle matcher <> " does not match any packages in the profile."])+        found -> Selection (Set.union names (Set.fromList found)) warnings++-- ---------------------------------------------------------------------------+-- Conflicts+-- ---------------------------------------------------------------------------++-- | The element a conflicting file came from: the file, the element's+-- name, and its paths as the store spells them, which @profile add@ takes.+data ConflictSide = ConflictSide !OsPath !Text !(Set Text)+  deriving (Eq, Show)++-- | Two files of equal priority at one path of the tree, each with the+-- element it came from, and their priority.+data Conflict = Conflict+  { conflictExisting :: !ConflictSide,+    conflictNew :: !ConflictSide,+    conflictPriority :: !Int+  }+  deriving (Eq, Show)++-- | The elements two conflicting files came from, as upstream finds them+-- (@CmdProfileAdd::run@ in profile.cc): searching the elements in name order,+-- the first holding a path either file lies in is the existing one, and+-- searching them the other way, the first is the new one.  'Nothing' when no+-- element holds either, where upstream reports the tree's own conflict.  The+-- files are the tree's: one it links directly is under the store directory as+-- the store spells it, the first directory given, and one inside a directory+-- it expanded under the second, the store directory resolved through its+-- links as the tree resolves a link it expands+-- ('Nix.Profile.Tree.trResolve').  A path is looked for under both, so a+-- store reached through a linked directory names the right elements; an+-- element's paths are shown in the store's spelling.+attributeConflict :: StoreDir -> StoreDir -> Manifest -> OsPath -> OsPath -> Int -> Maybe Conflict+attributeConflict storeDir resolvedDir (Manifest elements) fileA fileB priority =+  Conflict <$> side (Map.toAscList elements) <*> side (Map.toDescList elements) <*> pure priority+  where+    side ordered = case [found | (name, element) <- ordered, path <- Set.toAscList (elementPaths element), found <- toList (holding name element path)] of+      found : _ -> Just found+      [] -> Nothing+    holding name element path+      | path `under` fileA = Just (ConflictSide fileA name (installables element))+      | path `under` fileB = Just (ConflictSide fileB name (installables element))+      | otherwise = Nothing+    under path file = any (\dir -> spelledIn dir path `T.isPrefixOf` hostPathText file) [storeDir, resolvedDir]+    installables element = Set.map (spelledIn storeDir) (elementPaths element)+    spelledIn dir = T.pack . storePathToFilePath dir++-- ---------------------------------------------------------------------------+-- Between generations+-- ---------------------------------------------------------------------------++-- | How an element differs from one generation's manifest to the next,+-- by its name in both.+data ElementChange+  = -- | One only the later manifest holds: its identifier and versions.+    ElementAdded !Text !Text+  | -- | One only the earlier manifest holds: its identifier and versions.+    ElementRemoved !Text !Text+  | -- | One both hold at different versions: its identifier in the earlier,+    -- and its versions in each.+    ElementUpgraded !Text !Text !Text+  deriving (Eq, Show)++-- | What changed from one manifest to the next, element by element in+-- name order, as a profile's history shows it: an element only one of+-- them holds is added or removed, and one both hold has changed when its+-- versions ('elementVersions') differ, whatever else about it did.+manifestChanges :: Manifest -> Manifest -> [ElementChange]+manifestChanges (Manifest earlier) (Manifest later) =+  Map.elems (Merge.merge (Merge.mapMissing (const removed)) (Merge.mapMissing (const added)) (Merge.zipWithMaybeMatched (const upgraded)) earlier later)+  where+    removed element = ElementRemoved (elementIdentifier element) (elementVersions element)+    added element = ElementAdded (elementIdentifier element) (elementVersions element)+    upgraded before after+      | elementVersions before == elementVersions after = Nothing+      | otherwise = Just (ElementUpgraded (elementIdentifier before) (elementVersions before) (elementVersions after))++-- | A change as a profile's history prints it, with the empty-set sign+-- for the versions of an element that is not there.+changeLine :: ElementChange -> Text+changeLine change = case change of+  ElementAdded identifier versions -> identifier <> ": " <> emptySetSign <> " -> " <> versions+  ElementRemoved identifier versions -> identifier <> ": " <> versions <> " -> " <> emptySetSign+  ElementUpgraded identifier before after -> identifier <> ": " <> before <> " -> " <> after++-- | An element's versions, as a profile's history shows them: the version+-- part of each of its paths' names, each once, an empty one shown as an+-- epsilon, in byte order and joined by a comma and a space, or the+-- empty-set sign for an element with no paths.+elementVersions :: Element -> Text+elementVersions element+  | Set.null versions = emptySetSign+  | otherwise = T.intercalate ", " (Set.toAscList (Set.map shown versions))+  where+    versions = Set.map (snd . splitDrvName . spName) (elementPaths element)+    shown version+      | T.null version = emptyVersionSign+      | otherwise = version++-- | What a profile's history shows for no versions at all, U+2205 EMPTY+-- SET, and for an empty version, U+03B5 GREEK SMALL LETTER EPSILON, as+-- upstream shows them.+emptySetSign, emptyVersionSign :: Text+emptySetSign = "\x2205"+emptyVersionSign = "\x03B5"
+ src/Nix/Profile/Tree.hs view
@@ -0,0 +1,525 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE TupleSections #-}++-- | The tree a user environment is: every package's files linked into one+-- directory, as upstream's @buildProfile@ makes it+-- (builtins\/buildenv.cc), the output of+-- @builtin:buildenv@ ("Nix.Builder.Buildenv").+--+-- Packages are taken in order of priority, where a lower number wins,+-- then of path, each path once.  Each package's+-- @nix-support\/propagated-user-env-packages@ queues the packages it+-- names, which are taken after every package given, at priority 1000 and+-- up, one number per path in path order.  In each directory an entry is+-- linked in where nothing stands.  A directory where a link to a directory+-- stands turns the link into a directory of the tree's own, holding what+-- the link led to at the link's priority and then the new entries at+-- theirs.  A file where a link stands replaces it when its priority number+-- is lower, leaves it when higher, and conflicts with it when equal.  A+-- name starting with @.@, an entry whose link leads nowhere, and the files+-- upstream keeps out of profiles are skipped.+--+-- Reading the packages is the only effect, and it reaches the core+-- through a t'TreeReader', so the core runs over an in-memory store in+-- tests.  The tree comes back as a value: 'storeTreeReader' reads the+-- packages in a store on disk, and 'writeTree' makes the tree there.+--+-- Upstream lists a directory in @readdir@ order and this lists it sorted.+-- The tree does not depend on the order, but when several entries+-- conflict, which pair the failure names can.+module Nix.Profile.Tree+  ( -- * Packages+    Package (..),++    -- * Reading the packages+    TreeReader (..),+    Listing (..),+    EntryKind (..),+    ReadFailure (..),+    storeTreeReader,+    storePackagePath,+    propagatedTokens,++    -- * The tree+    Tree,+    Node (..),+    Built (..),+    Warning (..),+    BuildEnvFailure (..),+    buildProfile,+    warningText,+    buildEnvFailureText,++    -- * Writing the tree+    writeTree,+  )+where++import Control.Applicative ((<|>))+import Control.Exception (try)+import Control.Monad (foldM)+import Control.Monad.Except (ExceptT (..), runExceptT, throwError)+import Control.Monad.State.Strict (StateT, modify', runStateT)+import Control.Monad.Trans (lift)+import Data.Bifunctor (first)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BS8+import Data.Foldable (traverse_)+import Data.List (sort, sortOn)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Foreign.C.Error (Errno (..), eNOTDIR)+import GHC.IO.Exception (IOException (ioe_description, ioe_errno))+import Nix.HostPath (hostPathText)+import Nix.Store.Path (StoreDir, defaultStoreDir, parseStorePath, storePathToFilePath)+import Nix.Store.Symlink (createSymlinkOfKind)+import qualified System.Directory.OsPath as OsDir+import System.IO.Error (isDoesNotExistError)+import System.OsPath (OsPath, (</>))+import qualified System.OsPath as OP+#if defined(mingw32_HOST_OS)+import Control.Exception (bracket)+import Data.Bits ((.&.), (.|.))+import Nix.Store.Win32Path (win32FilePath)+import System.Win32.File+  ( BY_HANDLE_FILE_INFORMATION (..),+    closeHandle,+    createFile,+    fILE_ATTRIBUTE_DIRECTORY,+    fILE_FLAG_BACKUP_SEMANTICS,+    fILE_SHARE_DELETE,+    fILE_SHARE_READ,+    fILE_SHARE_WRITE,+    getFileInformationByHandle,+    oPEN_EXISTING,+  )+#else+import System.Posix.Files.ByteString (getFileStatus, isDirectory)+#endif++-- ---------------------------------------------------------------------------+-- Packages+-- ---------------------------------------------------------------------------++-- | A package to link into the tree.+data Package = Package+  { -- | Where the package is, as the t'TreeReader' reads it and as the+    -- tree's links name what is inside it.+    pkgPath :: !OsPath,+    -- | Its priority: of two files at one path, the one with the lower+    -- number stays.+    pkgPriority :: !Int+  }+  deriving (Eq, Show)++-- ---------------------------------------------------------------------------+-- Reading the packages+-- ---------------------------------------------------------------------------++-- | How the core reads the packages.  Each call follows links, as the+-- @stat@ and @opendir@ upstream calls do, and fails where upstream throws.+data TreeReader m = TreeReader+  { -- | The names in a directory, or 'NotADirectory' when what is at the+    -- path is not one.+    trEntries :: OsPath -> m (Either ReadFailure Listing),+    -- | What is at a path, or 'Nothing' when nothing is: upstream's+    -- @maybeStat@, which reads @ENOENT@ and @ENOTDIR@ as absence and+    -- fails on anything else.+    trKind :: OsPath -> m (Either ReadFailure (Maybe EntryKind)),+    -- | The path with every link on it resolved: upstream's+    -- @canonPath(path, true)@.+    trResolve :: OsPath -> m (Either ReadFailure OsPath),+    -- | The packages a package's @nix-support\/propagated-user-env-packages@+    -- names, in its order, or none when it has no such file.+    trPropagated :: OsPath -> m (Either ReadFailure [OsPath])+  }++-- | What listing a directory finds.+data Listing+  = -- | The directory's names, in any order.+    Entries ![OsPath]+  | -- | Something other than a directory is at the path.+    NotADirectory+  deriving (Eq, Show)++-- | What a path holds once its links are followed: upstream tells a+-- directory from everything else.+data EntryKind = DirectoryEntry | NonDirectoryEntry+  deriving (Eq, Show)++-- | Why a read failed, in words a build failure prints.+newtype ReadFailure = ReadFailure Text+  deriving (Eq, Show)++-- | A t'TreeReader' for packages in a store on disk, which names a+-- propagated package as 'storePackagePath' does.+storeTreeReader :: StoreDir -> TreeReader IO+storeTreeReader storeDir =+  TreeReader+    { trEntries = listEntries,+      trKind = entryKind,+      trResolve = \path -> first (readFailure "resolving the links in" path) <$> tryIO (OsDir.canonicalizePath path),+      trPropagated = propagatedPackages storeDir+    }++-- | The path a package's text names on disk: a store path, in the+-- canonical @\/nix\/store@ spelling a derivation holds or in the store's+-- own, which a builder writes, rendered through the store directory.+-- 'Nothing' for anything else.  Store paths are ASCII, so bytes that are+-- not UTF-8 name none.+storePackagePath :: StoreDir -> ByteString -> IO (Maybe OsPath)+storePackagePath storeDir bytes = case TE.decodeUtf8' bytes of+  Right text+    | Just sp <- parseStorePath defaultStoreDir text <|> parseStorePath storeDir text ->+        Just <$> OP.encodeFS (storePathToFilePath storeDir sp)+  _ -> pure Nothing++-- | The tokens of a @propagated-user-env-packages@ file: what lies between+-- spaces and newlines, with the empty ones dropped, as upstream's+-- @tokenizeString(contents, " \\n")@ gives them (@buildProfile@ in+-- buildenv.cc).+propagatedTokens :: ByteString -> [ByteString]+propagatedTokens = filter (not . BS.null) . BS8.splitWith (\c -> c == ' ' || c == '\n')++-- | List a directory.  A listing that fails where something other than a+-- directory is at the path is upstream's @ENOTDIR@, which it warns of+-- rather than fails on.+listEntries :: OsPath -> IO (Either ReadFailure Listing)+listEntries dir = do+  listed <- tryIO (OsDir.listDirectory dir)+  case listed of+    Right names -> pure (Right (Entries names))+    Left failure -> do+      kind <- entryKind dir+      pure $ case kind of+        Right (Just NonDirectoryEntry) -> Right NotADirectory+        _ -> Left (readFailure "cannot read directory" dir failure)++-- | What is at a path, following links.+entryKind :: OsPath -> IO (Either ReadFailure (Maybe EntryKind))+entryKind path = do+  probed <- tryIO (followedKind path)+  pure $ case probed of+    Right kind -> Right (Just kind)+    Left failure+      | absent failure -> Right Nothing+      | otherwise -> Left (readFailure "getting status of" path failure)++-- | 'trPropagated' for a package in the store: its file read, split into+-- 'propagatedTokens', and each token named through 'storePackagePath'.+propagatedPackages :: StoreDir -> OsPath -> IO (Either ReadFailure [OsPath])+propagatedPackages storeDir pkg = do+  -- The path is a store path's, which came from a 'FilePath', and the+  -- fixed names below it, so spelling it as one again is exact.+  contents <- tryIO (OP.decodeFS file >>= BS.readFile)+  case contents of+    Left failure+      | absent failure -> pure (Right [])+      | otherwise -> pure (Left (readFailure "reading file" file failure))+    Right bytes -> sequenceA <$> traverse named (propagatedTokens bytes)+  where+    file = pkg </> asciiPath nixSupportName </> asciiPath propagatedPackagesName+    named token = maybe (Left (notAStorePath token)) Right <$> storePackagePath storeDir token+    notAStorePath token =+      ReadFailure (quoted file <> " names '" <> TE.decodeUtf8Lenient token <> "', which is not a store path")++-- | Whether a failure says nothing is at the path: @ENOENT@ or @ENOTDIR@,+-- which upstream's @maybeStat@ and its read of the propagated packages+-- take as absence.  On Windows a failure carries the C runtime's error+-- number for the Win32 one, so the same test holds.+absent :: IOException -> Bool+absent failure = isDoesNotExistError failure || fmap Errno (ioe_errno failure) == Just eNOTDIR++-- | A failed read in upstream's form: what was being done, the path, and+-- the system's reason.+readFailure :: Text -> OsPath -> IOException -> ReadFailure+readFailure doing path failure =+  ReadFailure (doing <> " " <> quoted path <> ": " <> T.pack (ioe_description failure))++-- | 'try' for the one exception file system calls throw.+tryIO :: IO a -> IO (Either IOException a)+tryIO = try++-- | What is at a path once its links are followed, failing as @stat@+-- does.+followedKind :: OsPath -> IO EntryKind+#if defined(mingw32_HOST_OS)+-- @directory@'s own probe: opening the path without+-- @FILE_FLAG_OPEN_REPARSE_POINT@ follows a link to what it names, and+-- backup semantics let the open reach a directory.+followedKind path = do+  target <- OP.decodeFS path >>= win32FilePath+  info <-+    bracket+      (createFile target 0 (fILE_SHARE_READ .|. fILE_SHARE_WRITE .|. fILE_SHARE_DELETE) Nothing oPEN_EXISTING fILE_FLAG_BACKUP_SEMANTICS Nothing)+      closeHandle+      getFileInformationByHandle+  pure $+    if bhfiFileAttributes info .&. fILE_ATTRIBUTE_DIRECTORY /= 0+      then DirectoryEntry+      else NonDirectoryEntry+#else+followedKind path = do+  status <- getFileStatus (BS8.pack (map OP.toChar (OP.unpack path)))+  pure (if isDirectory status then DirectoryEntry else NonDirectoryEntry)+#endif++-- ---------------------------------------------------------------------------+-- The tree+-- ---------------------------------------------------------------------------++-- | A directory of the tree: each entry by its name.+type Tree = Map OsPath Node++-- | One entry of the tree.+data Node+  = -- | A link to a path, with the priority it was linked at.+    Link !OsPath !Int+  | -- | A directory of the tree's own, made where entries from more than+    -- one place meet.+    Directory !Tree+  deriving (Eq, Show)++-- | What building a tree gives: the warnings upstream prints on the way,+-- in order, whether or not the build fails, and the tree or why there is+-- none.+data Built = Built+  { builtWarnings :: ![Warning],+    builtTree :: !(Either BuildEnvFailure Tree)+  }+  deriving (Eq, Show)++-- | Something left out of the tree, with a warning.+data Warning+  = -- | A package that is not a directory (@createLinks@ in buildenv.cc).+    NotIncluded !OsPath+  | -- | An entry whose link leads nowhere, by the path it would have had+    -- in the tree (@createLinks@ in buildenv.cc).+    DanglingLink !OsPath+  deriving (Eq, Show)++-- | Why there is no tree.+data BuildEnvFailure+  = -- | Two files at one path with the same priority: what the link there+    -- already names, the file that came second, and their priority+    -- (@BuildEnvFileConflictError@ in buildenv.hh).+    FileConflict !OsPath !OsPath !Int+  | -- | A directory where a link to something other than a directory+    -- stands: the directory and what the link resolves to+    -- (@createLinks@ in buildenv.cc).+    LinkToNonDirectory !OsPath !OsPath+  | -- | A file where a directory of the tree's own stands: the file and the+    -- directory's path in the tree (@createLinks@ in buildenv.cc).+    FileOverDirectory !OsPath !OsPath+  | -- | A package could not be read.+    ReadFailed !ReadFailure+  deriving (Eq, Show)++-- | The first priority a propagated package takes (@buildProfile@ in+-- buildenv.cc).+firstPropagatedPriority :: Int+firstPropagatedPriority = 1000++-- | The names upstream keeps out of profiles wherever they are, as useless+-- or as files every package of a kind brings (@createLinks@ in+-- buildenv.cc).+leftOutNames :: [OsPath]+leftOutNames =+  map+    asciiPath+    [ "propagated-build-inputs",+      nixSupportName,+      "perllocal.pod",+      "log",+      "manifest.nix",+      "manifest.json"+    ]++-- | The directory a package's support files are in, skipped in the tree.+nixSupportName :: String+nixSupportName = "nix-support"++-- | The file in 'nixSupportName' naming the packages a package propagates.+propagatedPackagesName :: String+propagatedPackagesName = "propagated-user-env-packages"++-- | Build the tree for packages, its links named under the directory+-- @out@ in warnings and failures.+buildProfile :: (Monad m) => TreeReader m -> OsPath -> [Package] -> m Built+buildProfile reader out packages = do+  (tree, warnings) <- runStateT (runExceptT linkAll) []+  pure (Built (reverse warnings) tree)+  where+    linkAll = do+      given <- foldM (\progress p -> addPackage reader out progress (pkgPath p) (pkgPriority p)) noProgress (sortOn order packages)+      propagate reader out firstPropagatedPriority given+    order p = (pkgPriority p, pathKey (pkgPath p))+    noProgress = Progress Map.empty Set.empty Map.empty++-- | The build in progress: a failure ends it, and its warnings are kept+-- newest first.+type Building m = ExceptT BuildEnvFailure (StateT [Warning] m)++-- | What the packages added so far have made.+data Progress = Progress+  { progressTree :: !Tree,+    -- | Each package path added, by its 'pathKey'.+    progressDone :: !(Set [OsPath]),+    -- | The propagated packages waiting to be added, in path order.+    progressQueued :: !(Map [OsPath] OsPath)+  }++-- | A path as upstream orders and compares the paths of packages, as a+-- @std::filesystem::path@: component by component.+pathKey :: OsPath -> [OsPath]+pathKey = OP.splitDirectories++-- | Add a package not added already: link its entries in, then queue the+-- packages it propagates that are not added (@buildProfile@ in+-- buildenv.cc).+addPackage :: (Monad m) => TreeReader m -> OsPath -> Progress -> OsPath -> Int -> Building m Progress+addPackage reader out progress path priority+  | Set.member key (progressDone progress) = pure progress+  | otherwise = do+      tree <- linkInto reader path out priority (progressTree progress)+      propagated <- readStep (trPropagated reader path)+      let done = Set.insert key (progressDone progress)+          queued = foldl' (queue done) (progressQueued progress) propagated+      pure (Progress tree done queued)+  where+    key = pathKey path+    queue done waiting next+      | Set.member (pathKey next) done = waiting+      | otherwise = Map.insertWith (\_ earlier -> earlier) (pathKey next) next waiting++-- | Add the queued propagated packages, round by round, each at the next+-- priority in path order.  A package added since it was queued is passed+-- over but still takes its number, as upstream's counter counts it+-- (@buildProfile@ in buildenv.cc).+propagate :: (Monad m) => TreeReader m -> OsPath -> Int -> Progress -> Building m Tree+propagate reader out priority progress+  | Map.null (progressQueued progress) = pure (progressTree progress)+  | otherwise = do+      (next, nextPriority) <- foldM step (progress {progressQueued = Map.empty}, priority) (Map.elems (progressQueued progress))+      propagate reader out nextPriority next+  where+    step (current, !numbered) path = (,numbered + 1) <$> addPackage reader out current path numbered++-- | Link the entries of the directory @srcDir@ into the tree's directory+-- @tree@, which is at @dstDir@ (upstream's @createLinks@ in+-- buildenv.cc).+linkInto :: (Monad m) => TreeReader m -> OsPath -> OsPath -> Int -> Tree -> Building m Tree+linkInto reader srcDir dstDir priority tree = do+  listing <- readStep (trEntries reader srcDir)+  case listing of+    NotADirectory -> tree <$ warn (NotIncluded srcDir)+    Entries names -> foldM (linkEntry reader srcDir dstDir priority) tree (sort names)++-- | Link one entry of @srcDir@ into @tree@.+linkEntry :: (Monad m) => TreeReader m -> OsPath -> OsPath -> Int -> Tree -> OsPath -> Building m Tree+linkEntry reader srcDir dstDir priority tree name+  | isHidden name = pure tree+  | otherwise = do+      kind <- readStep (trKind reader srcFile)+      case kind of+        Nothing -> tree <$ warn (DanglingLink dstFile)+        Just _ | isLeftOut srcDir name -> pure tree+        Just DirectoryEntry -> directory+        Just NonDirectoryEntry -> file+  where+    srcFile = srcDir </> name+    dstFile = dstDir </> name+    linked = Map.insert name (Link srcFile priority) tree+    merged sub = Map.insert name (Directory sub) tree+    directory = case Map.lookup name tree of+      Just (Directory sub) -> merged <$> linkInto reader srcFile dstFile priority sub+      Just (Link target linkPriority) -> do+        resolved <- readStep (trResolve reader target)+        resolvedKind <- readStep (trKind reader resolved)+        case resolvedKind of+          Just DirectoryEntry -> do+            expanded <- linkInto reader resolved dstFile linkPriority Map.empty+            merged <$> linkInto reader srcFile dstFile priority expanded+          _ -> throwError (LinkToNonDirectory srcFile resolved)+      Nothing -> pure linked+    file = case Map.lookup name tree of+      Just (Link target linkPriority)+        | linkPriority == priority -> throwError (FileConflict target srcFile priority)+        | linkPriority < priority -> pure tree+        | otherwise -> pure linked+      Just (Directory _) -> throwError (FileOverDirectory srcFile dstFile)+      Nothing -> pure linked++-- | Whether a name is one a shell glob leaves out, which upstream skips.+isHidden :: OsPath -> Bool+isHidden name = case OP.unpack name of+  lead : _ -> OP.toChar lead == '.'+  [] -> False++-- | Whether upstream keeps an entry of @srcDir@ out of profiles: its path+-- ends in one of 'leftOutNames', or in @info\/dir@ (@createLinks@ in+-- buildenv.cc).+isLeftOut :: OsPath -> OsPath -> Bool+isLeftOut srcDir name =+  name `elem` leftOutNames+    || (name == asciiPath "dir" && OP.takeFileName srcDir == asciiPath "info")++-- | Run one read of the t'TreeReader', its failure ending the build.+readStep :: (Monad m) => m (Either ReadFailure a) -> Building m a+readStep action = ExceptT (first ReadFailed <$> lift action)++-- | Record a warning.+warn :: (Monad m) => Warning -> Building m ()+warn warning = modify' (warning :)++-- | A warning in upstream's words.+warningText :: Warning -> Text+warningText warning = case warning of+  NotIncluded path -> "not including " <> quoted path <> " in the user environment because it's not a directory"+  DanglingLink path -> "skipping dangling symlink '" <> hostPathText path <> "'"++-- | A failure in upstream's words.+buildEnvFailureText :: BuildEnvFailure -> Text+buildEnvFailureText failure = case failure of+  FileConflict existing incoming _ ->+    "Unable to build profile. There is a conflict for the following files:\n\n  "+      <> quoted existing+      <> "\n  "+      <> quoted incoming+  LinkToNonDirectory dir target -> "collision between " <> quoted dir <> " and non-directory " <> quoted target+  FileOverDirectory file dir -> "collision between non-directory '" <> hostPathText file <> "' and directory '" <> hostPathText dir <> "'"+  ReadFailed (ReadFailure reason) -> reason++-- | A path as upstream's @PathFmt@ prints it, in double quotes+-- (its @operator\<\<@ in fmt.hh).+quoted :: OsPath -> Text+quoted path = "\"" <> hostPathText path <> "\""++-- | An 'OsPath' spelled from ASCII, which 'OP.unsafeFromChar' narrows to+-- one path unit per character without loss.+asciiPath :: String -> OsPath+asciiPath = OP.pack . map OP.unsafeFromChar++-- ---------------------------------------------------------------------------+-- Writing the tree+-- ---------------------------------------------------------------------------++-- | Make the tree's entries in the directory @dir@, which exists.  Each+-- link's Windows flavour is read off its target ('createSymlinkOfKind').+writeTree :: OsPath -> Tree -> IO (Either Text ())+writeTree dir tree = runExceptT (traverse_ place (Map.toList tree))+  where+    place (name, node) =+      let path = dir </> name+       in case node of+            Link target _ -> ExceptT (createSymlinkOfKind path target)+            Directory sub -> do+              ExceptT (first (creating path) <$> tryIO (OsDir.createDirectory path))+              ExceptT (writeTree path sub)+    creating path failure = "creating directory '" <> hostPathText path <> "': " <> T.pack (ioe_description failure)
src/Nix/Push.hs view
@@ -1,11 +1,14 @@ {-# LANGUAGE ScopedTypeVariables #-} --- | Push store paths to a nova-cache binary cache.+-- | Push store paths to a nova-cache binary cache.  "Nix.Push.Directory"+-- writes them to a binary cache in a local directory instead, from the+-- same pieces. -- -- == The push choreography -- -- 1. Compute the full reference closure of the requested paths from the---    store database - a cache must never hold a path without its+--    records of the t'PushSource' - the store's database, or a daemon's+--    answers - because a cache must never hold a path without its --    dependencies, or substitution 404s on cold machines. -- 2. Fetch @\/narinfo-hashes@ from the cache and skip paths already there. -- 3. Upload every missing NAR, then every narinfo.  NARs go first@@ -14,6 +17,15 @@ -- 4. Verify one round-trip: fetch a narinfo back and check the server --    signed it. --+-- == Where a push reads+--+-- A t'PushSource' ("Nix.Push.Source") is what a push reads: each path's+-- references, NAR hash and deriver, which the source records, and its+-- files, which are read from the source's store directory.  A store opened+-- directly gives its database's records, and a store reached through a+-- daemon ("Nix.Daemon.ClientStore") asks the daemon for them and reads the+-- files from the directory the daemon's store keeps them in.+-- -- == Path forms -- -- The store database and filesystem use the platform store dir@@ -32,17 +44,65 @@ -- fields describe the compressed artifact, its object name carries -- the compressed file hash, and the substituter decompresses under -- the declared NarSize bound.+--+-- == Uploading in parts+--+-- A proxy in front of a cache can refuse a request body over its own+-- limit, as Cloudflare in front of the public cache refuses one over+-- 100 MB with 413.  A NAR up to 'pcPartSize' goes in one+-- @PUT nar\/\<file\>@; a larger one goes through nova-cache's multipart+-- upload: @POST nar\/\<file\>\/uploads@ begins it, each+-- @PUT nar\/\<file\>\/uploads\/\<id\>\/\<n\>@ sends one part in order,+-- and @POST nar\/\<file\>\/uploads\/\<id\>@ completes it with the part+-- count and the total size.  A cache that answers the beginning with+-- 404, as a nova-cache without multipart upload does, gets the NAR in+-- one @PUT@.+--+-- The retries follow nova-cache's rule for a client.  A part, or the+-- request that begins an upload, is sent again under 'pcRetry' when it+-- fails as upstream's transfer layer retries a transfer, its response+-- lost or an error status such as 503 ('Nix.Http.exceptionFailure',+-- 'Nix.Http.statusError'): the server replaces a part it holds, and a+-- repeated beginning only leaves an empty upload it reclaims.  A part+-- answered 404 or 409 means the server no longer holds the parts before+-- it, so a new upload begins.  A completion answered with anything but+-- 200, or not at all, may still have joined the NAR, so the push goes+-- on and the narinfo decides: the server checks its FileSize and+-- FileHash against the NAR it holds, and when it refuses the narinfo,+-- the NAR is uploaded again.  A push stops after a fixed number of+-- uploads of one NAR, so a cache that keeps losing parts cannot hold it+-- in a loop.+--+-- The NAR is held whole, as for one @PUT@, and each part is a slice of+-- it.  Holding one part at a time would need a streaming zstd encoder,+-- which nova-cache's one-shot 'Zstd.compress' is not, and two passes+-- over the path, since an upload is begun under the object's name and a+-- zstd object is named by the hash of the whole compressed file. module Nix.Push   ( -- * Configuration     PushConfig (..),     PushCompression (..),     PushSummary (..),+    PartSize,+    mkPartSize,+    partSizeBytes,+    defaultPartSize,      -- * Pushing     pushPaths,     computeClosure,-    loadApiKeyFile,+    preparePath,+    loadKeyFile, +    -- * Cache layout+    narInfoFileName,+    narDirSegment,++    -- * Progress lines+    logSkipped,+    logNar,+    logPushed,+     -- * Pure pieces (exported for tests)     parsePushCompression,     pushCompressionValues,@@ -57,36 +117,37 @@     storePathBasename,     checkRecordedNarHash,     narHashMatches,+    splitParts,   ) where -import Control.Exception (IOException, try)+import Control.Exception (IOException, displayException, try) import Control.Monad (foldM, forM, forM_, unless, when) import Control.Monad.Except (ExceptT (..), liftEither, runExceptT, throwError) import Control.Monad.IO.Class (liftIO)+import Data.Bifunctor (first) import qualified Data.ByteString as BS+import Data.Char (isDigit) import Data.List (sort) import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as TE-import qualified Data.Text.IO as TIO import qualified Network.HTTP.Client as HTTP import qualified Network.HTTP.Client.TLS as HTTPS import qualified Network.HTTP.Types as HTTP import Nix.Compression (compressionNameNone, compressionNameZstd)-import Nix.Http (catchSync, withTransfer, withUserAgent)-import Nix.Store (Store (..), queryDeriver, queryPathInfo, queryReferences, volumeCaseHack)-import qualified Nix.Store.DB as DB+import Nix.Http (AttemptFailure (..), FetchRetryPolicy, TransferError (..), attemptFailureMessage, catchSync, exceptionFailure, ioRetryEffects, retryTransient, statusError, withTransfer, withUserAgent)+import Nix.Logger (Logger, logMessage)+import Nix.Push.Source (PushSource (..), PushedPath (..)) import qualified Nix.Store.ExecBit as ExecBit-import Nix.Store.Path (StorePath (spHash, spName), defaultStoreDir, parseStorePath, storePathToFilePath, storePathToText)+import Nix.Store.Path (StorePath (spHash, spName), defaultStoreDir, storePathBasename, storePathToFilePath, storePathToText) import qualified NovaCache.Hash as Hash import qualified NovaCache.NAR as NAR import NovaCache.NarInfo (NarInfo (..), parseNarInfo, renderNarInfo) import NovaCache.Signing (normalizeKeyText) import qualified NovaCache.Zstd as Zstd-import System.IO (stderr)  -- --------------------------------------------------------------------------- -- Named constants@@ -96,7 +157,8 @@ narinfoHashesEndpoint :: Text narinfoHashesEndpoint = "narinfo-hashes" --- | URL path segment under which NAR files live.+-- | The directory of a cache, and the first segment of a NAR's URL, under+-- which NAR files live. narDirSegment :: Text narDirSegment = "nar" @@ -116,10 +178,33 @@ bearerPrefix :: BS.ByteString bearerPrefix = "Bearer " --- | HTTP success status code.-httpStatusOk :: Int-httpStatusOk = 200+-- | The most characters of a server's error message an error quotes.+errorBodyChars :: Int+errorBodyChars = 200 +-- | Path segment under @nar\/\<file\>@ where nova-cache keeps the file's+-- multipart uploads.+uploadsSegment :: Text+uploadsSegment = "uploads"++-- | Keys of the body that completes a multipart upload, as nova-cache+-- reads them.+partsField, fileSizeField :: Text+partsField = "Parts"+fileSizeField = "FileSize"++-- | Hex digits in the id nova-cache issues for an upload: 128 random+-- bits, in lowercase.+uploadIdDigits :: Int+uploadIdDigits = 32++-- | The most uploads of one NAR a push begins.  A part answered 404 or+-- 409, or a narinfo refused after a completion that was not answered+-- with 200, begins one more; past this many the push fails, so a cache+-- that keeps losing parts cannot hold it in a loop.+maxNarUploads :: Int+maxNarUploads = 3+ -- --------------------------------------------------------------------------- -- Configuration and results -- ---------------------------------------------------------------------------@@ -159,10 +244,42 @@     -- Authorization header (only useful against an open-writes server).     pcApiKey :: !(Maybe Text),     -- | Artifact packaging for this destination (see 'PushCompression').-    pcCompression :: !PushCompression+    pcCompression :: !PushCompression,+    -- | The most bytes of a NAR one request carries: a NAR up to this+    -- size goes in one @PUT@, a larger one in parts of this size.  A+    -- property of the destination, whose proxy sets the limit.+    pcPartSize :: !PartSize,+    -- | How often a request of a multipart upload that is safe to send+    -- again is tried, and the wait between tries.+    pcRetry :: !FetchRetryPolicy   }   deriving (Eq, Show) +-- | The most bytes of a NAR one request carries, at least one.  The+-- constructor is not exported, so every value is 'defaultPartSize' or+-- one 'mkPartSize' accepted.+newtype PartSize = PartSize Int+  deriving (Eq, Show)++-- | A part size of the given number of bytes; 'Nothing' below one, where+-- no part could carry any of a NAR.+mkPartSize :: Int -> Maybe PartSize+mkPartSize bytes+  | bytes >= 1 = Just (PartSize bytes)+  | otherwise = Nothing++-- | The bytes a part size allows.+partSizeBytes :: PartSize -> Int+partSizeBytes (PartSize bytes) = bytes++-- | 64 MiB.  Cloudflare in front of the public cache refuses a request+-- body over 100 MB with 413, and 64 MiB is under that whether the limit+-- counts 10^8 bytes or 100 MiB.  nova-cache holds a NAR to 4 GiB and an+-- upload to 10,000 parts, so a NAR at its cap takes 64 parts of this+-- size.+defaultPartSize :: PartSize+defaultPartSize = PartSize (64 * 1024 * 1024)+ -- | What a push accomplished. data PushSummary = PushSummary   { -- | Paths uploaded (NAR + narinfo).@@ -176,16 +293,17 @@ -- Key loading -- --------------------------------------------------------------------------- --- | Read an API key from a file, dropping byte-order marks and surrounding--- whitespace.  Key files written by Windows tooling are a known source of--- BOM contamination; 'normalizeKeyText' makes the transfer byte-clean.+-- | Read a key from a file, a cache's API key or a secret signing key's+-- text, dropping byte-order marks and surrounding whitespace.  Key files+-- written by Windows tooling are a known source of BOM contamination;+-- 'normalizeKeyText' makes the transfer byte-clean. -- -- The bytes are decoded as UTF-8 EXPLICITLY: locale text IO decodes by -- console code page, which turns the BOM bytes into codepage characters -- that no normalizer recognizes - on the very consoles the BOM handling -- exists for.-loadApiKeyFile :: FilePath -> IO (Either Text Text)-loadApiKeyFile path = do+loadKeyFile :: FilePath -> IO (Either Text Text)+loadKeyFile path = do   attempt <- try (BS.readFile path)   pure $ case attempt of     Left (e :: IOException) -> Left ("cannot read key file: " <> T.pack (show e))@@ -201,28 +319,28 @@ -- Closure computation -- --------------------------------------------------------------------------- --- | Compute the full reference closure of the given paths from the store--- database, in reverse-topological order: every path's references precede--- it (postorder over @Refs@; a self-reference or already-visited path is--- skipped).  Publishing narinfos in this order never announces a path--- whose references are not yet visible.  Fails if a recorded reference--- does not parse as a store path - that would mean a corrupt database,--- and pushing a closure with holes would poison the cache.-computeClosure :: Store -> [StorePath] -> IO (Either Text [StorePath])-computeClosure store roots =+-- | Compute the full reference closure of the given paths from the+-- source's records, in reverse-topological order: every path's references+-- precede it (postorder over the references; a self-reference or+-- already-visited path is skipped).  Publishing narinfos in this order+-- never announces a path whose references are not yet visible.  Only the+-- references are asked of the source, so a path that is not sent needs no+-- other record.  A path the source does not hold has no references here,+-- and 'preparePath' refuses it.  Fails if the source cannot give a path's+-- references, such as one that does not parse as a store path: that would+-- mean a corrupt database, and pushing a closure with holes would poison+-- the cache.+computeClosure :: PushSource -> [StorePath] -> IO (Either Text [StorePath])+computeClosure source roots =   runExceptT (reverse . snd <$> foldM visit (Set.empty, []) roots)   where     visit :: (Set Text, [StorePath]) -> StorePath -> ExceptT Text IO (Set Text, [StorePath])     visit (seen, acc) sp       | spHash sp `Set.member` seen = pure (seen, acc)       | otherwise = do-          refTexts <- liftIO (queryReferences (stDB store) sp)-          refs <- liftEither (traverse parseRef refTexts)+          refs <- ExceptT (psReferences source sp)           (seenAfterRefs, accAfterRefs) <- foldM visit (Set.insert (spHash sp) seen, acc) refs           pure (seenAfterRefs, sp : accAfterRefs)-    parseRef txt = case parseStorePath (stDir store) txt of-      Just sp -> Right sp-      Nothing -> Left ("unparseable reference in store DB: " <> txt)  -- --------------------------------------------------------------------------- -- Pure planning and rendering@@ -249,17 +367,16 @@ derivationExtension :: Text derivationExtension = ".drv" --- | The basename form used in narinfo @References@ and @Deriver@ fields:--- @\<hash\>-\<name\>@ with no store dir.-storePathBasename :: StorePath -> Text-storePathBasename sp = spHash sp <> "-" <> spName sp- -- | Drop a @\<algo\>:@ prefix from a formatted hash, leaving the digest. stripHashPrefix :: Text -> Text stripHashPrefix h = case T.breakOn ":" h of   (_, rest) | not (T.null rest) -> T.drop 1 rest   _ -> h +-- | The name of a path's narinfo in a cache, @\<hash\>.narinfo@.+narInfoFileName :: StorePath -> Text+narInfoFileName sp = spHash sp <> narInfoExtension+ -- | The NAR object filename for a given (uncompressed) NAR hash. narFileName :: Text -> Text narFileName narHash = stripHashPrefix narHash <> narExtension@@ -267,8 +384,7 @@ -- | The uploadable artifact for one NAR under the configured -- compression: the bytes the cache stores, the file fields the -- narinfo declares, and the object name.  With 'PushNone' every field--- equals the NAR's own, byte-identical to what this module always--- pushed.+-- equals the NAR's own. data PushArtifact = PushArtifact   { paBytes :: !BS.ByteString,     paFileHash :: !Text,@@ -317,14 +433,19 @@ -- is internally consistent by construction.  The @StorePath@ uses -- the canonical @\/nix\/store@ form; references and the deriver are -- basenames, matching the wire format.+--+-- The file hash and size are forced into their @Just@, as the other+-- fields taken from the artifact are by their strictness, so a narinfo+-- holds no thunk over the artifact, whose bytes are the whole NAR: a+-- push that keeps its narinfos until every NAR is in place keeps no NAR. mkNarInfo :: PushArtifact -> StorePath -> [StorePath] -> Maybe StorePath -> NarInfo mkNarInfo artifact sp refs deriver =   NarInfo     { niStorePath = storePathToText defaultStoreDir sp,       niUrl = narDirSegment <> "/" <> paObjectName artifact,       niCompression = paCompressionText artifact,-      niFileHash = Just (paFileHash artifact),-      niFileSize = Just (fromIntegral (paFileSize artifact)),+      niFileHash = Just $! paFileHash artifact,+      niFileSize = Just $! fromIntegral (paFileSize artifact),       niNarHash = paNarHash artifact,       niNarSize = fromIntegral (paNarSize artifact),       niReferences = sort (map storePathBasename refs),@@ -333,6 +454,16 @@       niCA = Nothing     } +-- | A NAR's bytes as the parts of a multipart upload, in order: each+-- holds the part size but the last, which holds the rest.  A part is a+-- slice of the bytes, not a copy.+splitParts :: PartSize -> BS.ByteString -> [BS.ByteString]+splitParts size bytes+  | BS.null bytes = []+  | otherwise = part : splitParts size rest+  where+    (part, rest) = BS.splitAt (partSizeBytes size) bytes+ -- --------------------------------------------------------------------------- -- Push orchestration -- ---------------------------------------------------------------------------@@ -341,40 +472,50 @@ -- -- Serializes one NAR at a time (bounded memory), uploads all NARs before -- any narinfo, and finishes with a signed round-trip check.  Any failure--- aborts with an error; a partial push leaves only orphaned NARs behind,--- which are invisible to clients.  An interrupt is not a failure: it--- stops the push and propagates.-pushPaths :: PushConfig -> Store -> [StorePath] -> IO (Either Text PushSummary)-pushPaths cfg store roots =+-- aborts with an error.  One before the first narinfo leaves only NARs no+-- narinfo names, which are invisible to clients; one after it leaves the+-- narinfos already published as well.  An interrupt is not a failure: it+-- stops the push and propagates.  Its progress lines go to the source's+-- logger.+pushPaths :: PushConfig -> PushSource -> [StorePath] -> IO (Either Text PushSummary)+pushPaths cfg source roots =   -- Every synchronous exception: the push raises sqlite-simple's from the-  -- database and IO errors from the serialiser and the log, and each is a-  -- failed push to report.-  runExceptT run `catchSync` \e -> pure (Left ("push failed: " <> T.pack (show e)))+  -- database, walk failures and IO errors from the serialiser, and IO+  -- errors from the logger, and each is a failed push, reported as its+  -- exception says, as every other failure here is, for the command to+  -- word.+  runExceptT run `catchSync` \e -> pure (Left (T.pack (displayException e)))   where+    logger = psLogger source     run :: ExceptT Text IO PushSummary     run = do       manager <- liftIO newPushManager-      closure <- ExceptT (computeClosure store roots)+      closure <- ExceptT (computeClosure source roots)       remote <- fetchRemoteHashes manager cfg       let missing = planMissing remote closure           skipped = length closure - length missing-      when (skipped > 0) $-        logLine ("[skip]  " <> T.pack (show skipped) <> " path(s) already cached")-      -- Phase 1: NARs.  One at a time; bytes are dropped after upload.-      pairs <- forM missing $ \sp -> do-        narInfo <- uploadNar manager cfg store sp-        pure (sp, narInfo)+      logSkipped logger skipped+      -- Phase 1: NARs, one at a time.  What is kept for phase 2 is each+      -- path's narinfo and how its upload ended, and neither holds the+      -- NAR's bytes ('mkNarInfo' forces what it takes from the artifact),+      -- so each NAR is dropped once uploaded.+      uploaded <- forM missing $ \sp -> do+        (narInfo, upload) <- uploadNar logger manager cfg source 0 sp+        pure (sp, narInfo, upload)       -- Phase 2: narinfos, only after every NAR is in place, in the       -- closure's deps-first order: a freshly announced path's references-      -- are always already announced.-      forM_ pairs $ \(sp, narInfo) -> do-        uploadNarInfo manager cfg sp narInfo-        logLine ("[push]  " <> storePathBasename sp)+      -- are always already announced.  A NAR whose upload was not+      -- confirmed is checked here, by its narinfo, and not in phase 1,+      -- since a narinfo accepted there would announce a path before its+      -- references.+      forM_ uploaded $ \(sp, narInfo, upload) -> do+        publishNarInfo logger manager cfg source sp narInfo upload+        logPushed logger sp       -- Round-trip: the first pushed narinfo must come back signed.-      case pairs of-        ((sp, _) : _) -> verifySignedRoundTrip manager cfg sp+      case uploaded of+        ((sp, _, _) : _) -> verifySignedRoundTrip logger manager cfg sp         [] -> pure ()-      pure PushSummary {psPushed = length pairs, psSkipped = skipped}+      pure PushSummary {psPushed = length uploaded, psSkipped = skipped}  -- | HTTP manager for pushes.  Large NAR uploads over residential uplinks -- can take many minutes, so the response timeout is disabled rather than@@ -391,48 +532,42 @@ fetchRemoteHashes manager cfg = do   let url = pcCacheUrl cfg <> "/" <> narinfoHashesEndpoint   response <- httpRequest manager "GET" url (authHeaders cfg) Nothing-  let code = HTTP.statusCode (HTTP.responseStatus response)-  unless (code == httpStatusOk) $-    throwError ("GET " <> narinfoHashesEndpoint <> " returned HTTP " <> T.pack (show code))-  body <- decodeUtf8Lenient (responseBytes response)-  pure (Set.fromList (filter (not . T.null) (map T.strip (T.lines body))))+  expectOk ("GET " <> narinfoHashesEndpoint) response+  pure (Set.fromList (filter (not . T.null) (map T.strip (T.lines (responseText response))))) --- | Serialize a store path to a NAR, cross-check the database NAR hash,--- and upload the bytes.  Returns the narinfo to publish in phase 2.-uploadNar :: HTTP.Manager -> PushConfig -> Store -> StorePath -> ExceptT Text IO NarInfo-uploadNar manager cfg store sp = do-  let physicalPath = storePathToFilePath (stDir store) sp-  narEntry <- liftIO (ExecBit.serialiseFromPath (volumeCaseHack (stCaseSensitivity store)) physicalPath)+-- | Serialize a store path to a NAR, cross-check the source's NAR hash,+-- and upload the bytes, given how many uploads of the NAR this push has+-- begun before.  Returns the narinfo to publish in phase 2, and whether+-- the cache confirmed the NAR.+uploadNar :: Logger -> HTTP.Manager -> PushConfig -> PushSource -> Int -> StorePath -> ExceptT Text IO (NarInfo, NarUpload)+uploadNar logger manager cfg source begun sp = do+  (artifact, narInfo) <- preparePath (pcCompression cfg) source sp+  logNar logger sp artifact+  upload <- sendNar logger manager cfg begun (niUrl narInfo) (paBytes artifact)+  pure (narInfo, upload)++-- | What a push uploads for one store path: its NAR, packaged as the+-- compression asks, and the narinfo that describes it.  The NAR is+-- serialized from the source's store directory and held to the NAR hash+-- the source records ('checkRecordedNarHash'); the references and the+-- deriver come from the same record, which is asked for once.+preparePath :: PushCompression -> PushSource -> StorePath -> ExceptT Text IO (PushArtifact, NarInfo)+preparePath compression source sp = do+  narEntry <- liftIO (ExecBit.serialiseFromPath (psCaseHack source) (storePathToFilePath (psStoreDir source) sp))   let narBytes = NAR.serialise narEntry       narHash = Hash.formatNixHash (Hash.hashBytes narBytes)-      narSize = BS.length narBytes-  recorded <- liftIO (queryPathInfo (stDB store) sp)+  recorded <- ExceptT (psPathInfo source sp)   liftEither (checkRecordedNarHash recorded narHash sp)-  refTexts <- liftIO (queryReferences (stDB store) sp)-  refs <- liftEither (traverse (parseRefText store) refTexts)-  deriverText <- liftIO (queryDeriver (stDB store) sp)-  let deriver = deriverText >>= parseStorePath (stDir store)-      artifact = mkPushArtifact (pcCompression cfg) narHash narBytes-      narInfo = mkNarInfo artifact sp refs deriver-      url = pcCacheUrl cfg <> "/" <> niUrl narInfo-  logLine-    ( "[nar]   "-        <> storePathBasename sp-        <> " ("-        <> T.pack (show narSize)-        <> " bytes)"-    )-  response <- httpRequest manager "PUT" url (authHeaders cfg) (Just (paBytes artifact))-  expectOk ("PUT " <> niUrl narInfo) response-  pure narInfo+  let artifact = mkPushArtifact compression narHash narBytes+  pure (artifact, mkNarInfo artifact sp (foldMap ppReferences recorded) (recorded >>= ppDeriver)) --- | Pre-upload integrity gate.  The store DB recorded the path's NAR hash+-- | Pre-upload integrity gate.  The source recorded the path's NAR hash -- at registration; a mismatch now means the path changed on disk - refuse -- to publish corruption.  An on-disk path with NO registration (an -- interrupted build) is refused too: its references are unknown, so -- publishing would fabricate an empty-reference narinfo and serve a -- closure with holes.-checkRecordedNarHash :: Maybe DB.PathInfo -> Text -> StorePath -> Either Text ()+checkRecordedNarHash :: Maybe PushedPath -> Text -> StorePath -> Either Text () checkRecordedNarHash recorded narHash sp = case recorded of   Nothing ->     Left@@ -441,67 +576,236 @@           <> " is on disk but not registered as valid; refusing to publish it with unknown references"       )   Just info-    | not (narHashMatches (DB.piNarHash info) narHash) ->+    | not (narHashMatches (ppNarHash info) narHash) ->         Left           ( "store integrity: "               <> storePathBasename sp               <> " hashes to "               <> narHash               <> " but the DB recorded "-              <> DB.piNarHash info+              <> ppNarHash info           )     | otherwise -> Right ()  -- | Recorded and computed NAR hashes match when both parse as -- @sha256:@ and nix-base32 and their decoded digests agree.  A recorded--- value that does not parse, such as a foreign cache's base16, falls--- back to exact text equality, keeping legacy rows comparable rather--- than un-checkable.+-- value that does not parse, such as base16, falls back to exact text+-- equality, so it stays comparable rather than un-checkable. narHashMatches :: Text -> Text -> Bool narHashMatches recorded computed =   case (Hash.parseNixHash recorded, Hash.parseNixHash computed) of     (Right a, Right b) -> a == b     _ -> recorded == computed --- | Upload a rendered narinfo (the server validates and signs it).-uploadNarInfo :: HTTP.Manager -> PushConfig -> StorePath -> NarInfo -> ExceptT Text IO ()-uploadNarInfo manager cfg sp narInfo = do-  let object = spHash sp <> narInfoExtension-      url = pcCacheUrl cfg <> "/" <> object-      body = TE.encodeUtf8 (renderNarInfo narInfo)-  response <- httpRequest manager "PUT" url (authHeaders cfg) (Just body)-  expectOk ("PUT " <> object) response+-- | Upload a rendered narinfo (the server validates and signs it).  The+-- server checks a narinfo's FileSize and FileHash against the NAR it+-- holds and refuses one whose NAR it does not hold, or holds otherwise,+-- with 400.  After a NAR's upload was not confirmed, a 400 is that+-- refusal, so the NAR is uploaded again, while fewer than+-- 'maxNarUploads' uploads of it have been begun, and the narinfo is+-- sent after it.+publishNarInfo :: Logger -> HTTP.Manager -> PushConfig -> PushSource -> StorePath -> NarInfo -> NarUpload -> ExceptT Text IO ()+publishNarInfo logger manager cfg source sp narInfo upload = do+  let body = TE.encodeUtf8 (renderNarInfo narInfo)+  response <- httpRequest manager "PUT" (cacheUrl cfg object) (authHeaders cfg) (Just body)+  let status = HTTP.responseStatus response+      refused = describeResponse label response+  unless (status == HTTP.status200) $ case upload of+    NarUnconfirmed begun completion+      | status == HTTP.status400 && begun < maxNarUploads -> do+          logLine logger (retryTag <> refused <> "; uploading the NAR again")+          (resent, reupload) <- uploadNar logger manager cfg source begun sp+          publishNarInfo logger manager cfg source sp resent reupload+      | otherwise ->+          throwError (refused <> "; the NAR's last completion: " <> completion <> " (" <> countedUploads begun <> " begun)")+    NarStored -> throwError refused+  where+    object = narInfoFileName sp+    label = "PUT " <> object  -- | Fetch a just-pushed narinfo back and require a signature on it.-verifySignedRoundTrip :: HTTP.Manager -> PushConfig -> StorePath -> ExceptT Text IO ()-verifySignedRoundTrip manager cfg sp = do-  let object = spHash sp <> narInfoExtension+verifySignedRoundTrip :: Logger -> HTTP.Manager -> PushConfig -> StorePath -> ExceptT Text IO ()+verifySignedRoundTrip logger manager cfg sp = do+  let object = narInfoFileName sp       url = pcCacheUrl cfg <> "/" <> object   response <- httpRequest manager "GET" url [] Nothing   expectOk ("GET " <> object) response-  body <- decodeUtf8Lenient (responseBytes response)-  narInfo <- liftEither (either (Left . T.pack) Right (parseNarInfo body))+  narInfo <- liftEither (either (Left . T.pack) Right (parseNarInfo (responseText response)))   when (null (niSigs narInfo)) $     throwError ("round-trip check failed: " <> object <> " came back unsigned")-  logLine "[ok]    round-trip verified, signature present"+  logLine logger "[ok]    round-trip verified, signature present"  -- ---------------------------------------------------------------------------+-- Sending a NAR+-- ---------------------------------------------------------------------------++-- | Whether the cache is known to hold a NAR once its upload ends.+data NarUpload+  = -- | The cache answered the upload with 200.+    NarStored+  | -- | A multipart upload's completion was answered with something+    -- other than 200, or not at all, so the NAR may or may not be in+    -- place, and its narinfo decides.  (uploads of the NAR begun so far,+    -- the completion's answer)+    NarUnconfirmed !Int !Text++-- | An upload, by the id nova-cache issued for it: 'uploadIdDigits'+-- lowercase hex digits, checked before the id goes into a request path.+newtype UploadId = UploadId Text++-- | The id in a response that begins an upload, or 'Nothing' for text+-- that is not one nova-cache issues.+parseUploadId :: Text -> Maybe UploadId+parseUploadId txt+  | T.length txt == uploadIdDigits && T.all isLowerHex txt = Just (UploadId txt)+  | otherwise = Nothing+  where+    isLowerHex c = isDigit c || (c >= 'a' && c <= 'f')++-- | How the cache answered the request that begins an upload.+data Begun+  = -- | 201, with the upload's id.+    Begun !UploadId+  | -- | 404: the cache has no multipart upload.+    NoMultipart++-- | How the cache answered the parts of an upload sent so far.+data PartsAnswer+  = -- | 200 to each: the cache holds them.+    PartsHeld+  | -- | 404 or 409 to the last: the cache no longer holds the parts+    -- before it, so the upload cannot be completed.  (the answer)+    PartsLost !Text++-- | Send a NAR's bytes to its object: in one @PUT@ when they fit in one+-- part, in parts otherwise.+sendNar :: Logger -> HTTP.Manager -> PushConfig -> Int -> Text -> BS.ByteString -> ExceptT Text IO NarUpload+sendNar logger manager cfg begun object bytes+  | BS.length bytes <= partSizeBytes (pcPartSize cfg) = putWholeNar manager cfg object bytes+  | otherwise = uploadInParts logger manager cfg begun object bytes++-- | Send a NAR's bytes in one @PUT@.+putWholeNar :: HTTP.Manager -> PushConfig -> Text -> BS.ByteString -> ExceptT Text IO NarUpload+putWholeNar manager cfg object bytes = do+  response <- httpRequest manager "PUT" (cacheUrl cfg object) (authHeaders cfg) (Just bytes)+  NarStored <$ expectOk ("PUT " <> object) response++-- | Send a NAR's bytes through a multipart upload, given how many uploads+-- of it this push has begun before: begin one, send the parts, and+-- complete it.  An upload whose parts the cache lost is begun again, up+-- to 'maxNarUploads' in all.+uploadInParts :: Logger -> HTTP.Manager -> PushConfig -> Int -> Text -> BS.ByteString -> ExceptT Text IO NarUpload+uploadInParts logger manager cfg begun object bytes = do+  started <- beginUpload logger manager cfg uploads+  case started of+    NoMultipart -> do+      logLine logger (narTag <> "POST " <> uploads <> " returned HTTP 404, so the NAR goes in one request")+      putWholeNar manager cfg object bytes+    Begun (UploadId uploadId) -> do+      let upload = uploads <> "/" <> uploadId+      answer <- sendParts logger manager cfg upload parts+      case answer of+        PartsHeld -> completeUpload logger manager cfg (begun + 1) upload (length parts) (BS.length bytes)+        PartsLost lost+          | begun + 1 < maxNarUploads -> do+              logLine logger (retryTag <> lost <> "; beginning a new upload")+              uploadInParts logger manager cfg (begun + 1) object bytes+          | otherwise ->+              throwError (lost <> " (" <> countedUploads maxNarUploads <> " begun)")+  where+    uploads = object <> "/" <> uploadsSegment+    parts = splitParts (pcPartSize cfg) bytes++-- | Begin an upload, again under the retry policy while the response is+-- lost or is one a retry could outlive.+beginUpload :: Logger -> HTTP.Manager -> PushConfig -> Text -> ExceptT Text IO Begun+beginUpload logger manager cfg uploads =+  retrying logger cfg (answer <$> tryRequest manager "POST" (cacheUrl cfg uploads) (authHeaders cfg) Nothing)+  where+    label = "POST " <> uploads+    answer (Left err) = Left (transportFailure label err)+    answer (Right response)+      | status == HTTP.status201 =+          maybe+            (Left (FatalFailure (label <> " answered with no upload id: " <> T.take errorBodyChars (responseText response))))+            (Right . Begun)+            (parseUploadId (T.strip (responseText response)))+      | status == HTTP.status404 = Right NoMultipart+      | otherwise = Left (statusFailure label response)+      where+        status = HTTP.responseStatus response++-- | Send the parts in order from part 1, stopping at the first the cache+-- answers with 'PartsLost'.+sendParts :: Logger -> HTTP.Manager -> PushConfig -> Text -> [BS.ByteString] -> ExceptT Text IO PartsAnswer+sendParts logger manager cfg upload = go . zip [1 :: Int ..]+  where+    go [] = pure PartsHeld+    go ((number, part) : rest) = do+      answer <- sendPart logger manager cfg (upload <> "/" <> T.pack (show number)) part+      case answer of+        PartsHeld -> go rest+        lost@(PartsLost _) -> pure lost++-- | Send one part, again under the retry policy while the response is+-- lost or is one a retry could outlive: the cache replaces a part it+-- holds, so a part that did arrive is not doubled.+sendPart :: Logger -> HTTP.Manager -> PushConfig -> Text -> BS.ByteString -> ExceptT Text IO PartsAnswer+sendPart logger manager cfg path part =+  retrying logger cfg (answer <$> tryRequest manager "PUT" (cacheUrl cfg path) (authHeaders cfg) (Just part))+  where+    label = "PUT " <> path+    answer (Left err) = Left (transportFailure label err)+    answer (Right response)+      | status == HTTP.status200 = Right PartsHeld+      | status `elem` [HTTP.status404, HTTP.status409] = Right (PartsLost (describeResponse label response))+      | otherwise = Left (statusFailure label response)+      where+        status = HTTP.responseStatus response++-- | Complete an upload, declaring how many parts it holds and how many+-- bytes they join to.  Never sent again here: the server joins the whole+-- NAR before it answers, so an answer other than 200, or none, leaves+-- the NAR unconfirmed for its narinfo to decide, and fails nothing.  The+-- HTTP client itself sends a request once more when a connection it kept+-- open turns out closed before any answer; a completion that arrives+-- twice gets an error or joins the same parts, and the narinfo decides+-- either way.+completeUpload :: Logger -> HTTP.Manager -> PushConfig -> Int -> Text -> Int -> Int -> ExceptT Text IO NarUpload+completeUpload logger manager cfg begun upload count size = do+  answer <- liftIO (tryRequest manager "POST" (cacheUrl cfg upload) (authHeaders cfg) (Just totals))+  case answer of+    Right response | HTTP.responseStatus response == HTTP.status200 -> pure NarStored+    unconfirmed -> do+      let completion = either (attemptFailureMessage . transportFailure label) (describeResponse label) unconfirmed+      logLine logger (narTag <> completion <> "; the narinfo decides whether the NAR is stored")+      pure (NarUnconfirmed begun completion)+  where+    label = "POST " <> upload+    totals =+      TE.encodeUtf8+        ( T.unlines+            [ partsField <> ": " <> T.pack (show count),+              fileSizeField <> ": " <> T.pack (show size)+            ]+        )++-- --------------------------------------------------------------------------- -- HTTP plumbing -- --------------------------------------------------------------------------- --- | Issue an HTTP request with optional body, converting a failure of the--- request into a push error.  The body is read through 'withTransfer', so--- a connection lost mid-body is an 'HTTP.HttpException' like every other--- failure of the request, and that is the one exception caught.-httpRequest ::+-- | Issue an HTTP request with optional body.  The body is read through+-- 'withTransfer', so a connection lost mid-body is an+-- 'HTTP.HttpException' like every other failure of the request, and that+-- is the one exception caught.+tryRequest ::   HTTP.Manager ->   BS.ByteString ->   Text ->   [(HTTP.HeaderName, BS.ByteString)] ->   Maybe BS.ByteString ->-  ExceptT Text IO (HTTP.Response BS.ByteString)-httpRequest manager method url headers body = ExceptT $ do-  attempt <- try $ do+  IO (Either HTTP.HttpException (HTTP.Response BS.ByteString))+tryRequest manager method url headers body = try $ do   request0 <- HTTP.parseRequest (T.unpack url)   let request =         withUserAgent@@ -513,10 +817,70 @@   withTransfer request manager $ \response -> do     chunks <- HTTP.brConsume (HTTP.responseBody response)     pure (BS.concat chunks <$ response)-  pure $ case attempt of-    Left (e :: HTTP.HttpException) -> Left ("HTTP error for " <> url <> ": " <> T.pack (show e))-    Right response -> Right response +-- | 'tryRequest', with a failure of the request as a push error.+httpRequest ::+  HTTP.Manager ->+  BS.ByteString ->+  Text ->+  [(HTTP.HeaderName, BS.ByteString)] ->+  Maybe BS.ByteString ->+  ExceptT Text IO (HTTP.Response BS.ByteString)+httpRequest manager method url headers body =+  ExceptT (first failed <$> tryRequest manager method url headers body)+  where+    failed = attemptFailureMessage . exceptionFailure (\detail -> "HTTP error for " <> url <> ": " <> T.pack detail)++-- | Run a request that is safe to send again under the push's retry+-- policy: a 'TransientFailure' is sent again after upstream's backoff,+-- which upstream's transfer layer applies to an upload as to a download+-- (@TransferItem::finish@ in @filetransfer.cc@ at 2.24.9), and a+-- 'FatalFailure', or the last attempt's failure, fails the push.  A+-- retry is announced to the logger.+retrying :: Logger -> PushConfig -> IO (Either AttemptFailure a) -> ExceptT Text IO a+retrying logger cfg attempt =+  ExceptT (first attemptFailureMessage <$> retryTransient (pcRetry cfg) (ioRetryEffects logger) attempt)++-- | A response the protocol gives no meaning, as an attempt's failure:+-- transient when it is an error upstream's transfer layer retries+-- ('statusError'), fatal when it is any other error or no error at all.+statusFailure :: Text -> HTTP.Response BS.ByteString -> AttemptFailure+statusFailure label response+  | not (HTTP.statusIsClientError status || HTTP.statusIsServerError status) = FatalFailure message+  | otherwise = case statusError status of+      Transient -> TransientFailure message+      NotFound -> FatalFailure message+      Forbidden -> FatalFailure message+      Misc -> FatalFailure message+  where+    status = HTTP.responseStatus response+    message = describeResponse label response++-- | A request that got no response, as an attempt's failure, classified+-- as upstream classifies a transfer's ('exceptionFailure'), with a+-- message naming the request and the client's failure.+transportFailure :: Text -> HTTP.HttpException -> AttemptFailure+transportFailure label = exceptionFailure (\detail -> label <> " failed: " <> T.pack detail)++-- | A count of uploads with its noun.+countedUploads :: Int -> Text+countedUploads 1 = "1 upload"+countedUploads n = T.pack (show n) <> " uploads"++-- | A response as an error: the request, the status, and the start of+-- the server's message.+describeResponse :: Text -> HTTP.Response BS.ByteString -> Text+describeResponse label response =+  label+    <> " returned HTTP "+    <> T.pack (show (HTTP.statusCode (HTTP.responseStatus response)))+    <> ": "+    <> T.take errorBodyChars (responseText response)++-- | The URL of a path under the cache.+cacheUrl :: PushConfig -> Text -> Text+cacheUrl cfg path = pcCacheUrl cfg <> "/" <> path+ -- | Authorization headers for authenticated writes. authHeaders :: PushConfig -> [(HTTP.HeaderName, BS.ByteString)] authHeaders cfg = case pcApiKey cfg of@@ -525,26 +889,49 @@  -- | Require a 200 response, with a readable error otherwise. expectOk :: Text -> HTTP.Response BS.ByteString -> ExceptT Text IO ()-expectOk label response = do-  let code = HTTP.statusCode (HTTP.responseStatus response)-  unless (code == httpStatusOk) $ do-    body <- decodeUtf8Lenient (responseBytes response)-    throwError (label <> " returned HTTP " <> T.pack (show code) <> ": " <> T.take 200 body)+expectOk label response =+  unless (HTTP.responseStatus response == HTTP.status200) $+    throwError (describeResponse label response) --- | The response body bytes.-responseBytes :: HTTP.Response BS.ByteString -> BS.ByteString-responseBytes = HTTP.responseBody+-- | The response body as text, decoded leniently: an error body need not+-- be UTF-8, and what the protocol answers otherwise is ASCII.+responseText :: HTTP.Response BS.ByteString -> Text+responseText = TE.decodeUtf8With (\_ _ -> Just '\xFFFD') . HTTP.responseBody --- | Decode response bytes leniently (error bodies may not be UTF-8).-decodeUtf8Lenient :: (Monad m) => BS.ByteString -> ExceptT Text m Text-decodeUtf8Lenient = pure . TE.decodeUtf8With (\_ _ -> Just '\xFFFD')+-- | Tell the logger a progress line.+logLine :: Logger -> Text -> ExceptT Text IO ()+logLine logger = liftIO . logMessage logger --- | Parse a reference path text from the database.-parseRefText :: Store -> Text -> Either Text StorePath-parseRefText store txt = case parseStorePath (stDir store) txt of-  Just sp -> Right sp-  Nothing -> Left ("unparseable reference in store DB: " <> txt)+-- ---------------------------------------------------------------------------+-- Progress lines+-- --------------------------------------------------------------------------- --- | Progress line on stderr (stdout stays reserved for results).-logLine :: Text -> ExceptT Text IO ()-logLine = liftIO . TIO.hPutStrLn stderr+-- | The tag of the line for paths a cache holds already.+skipTag :: Text+skipTag = "[skip]  "++-- | The tag of a NAR's lines.+narTag :: Text+narTag = "[nar]   "++-- | The tag of the line for a path a cache now holds.+pushTag :: Text+pushTag = "[push]  "++-- | The tag of the line for a NAR upload the push begins again.+retryTag :: Text+retryTag = "[retry] "++-- | Report how many paths of the closure the cache holds already, if any.+logSkipped :: Logger -> Int -> ExceptT Text IO ()+logSkipped logger skipped =+  when (skipped > 0) $+    logLine logger (skipTag <> T.pack (show skipped) <> " path(s) already cached")++-- | Report a path's NAR, packaged for the cache, with the NAR's size.+logNar :: Logger -> StorePath -> PushArtifact -> ExceptT Text IO ()+logNar logger sp artifact = logLine logger (narTag <> storePathBasename sp <> " (" <> T.pack (show (paNarSize artifact)) <> " bytes)")++-- | Report a path whose narinfo the cache now holds.+logPushed :: Logger -> StorePath -> ExceptT Text IO ()+logPushed logger sp = logLine logger (pushTag <> storePathBasename sp)
+ src/Nix/Push/Directory.hs view
@@ -0,0 +1,209 @@+{-# LANGUAGE ScopedTypeVariables #-}++-- | Push store paths to a binary cache in a local directory, as upstream's+-- @nix copy --to file:\/\/\/DIR@ writes one, signing each narinfo with a+-- secret key read here rather than leaving the signing to a server.+--+-- == Layout+--+-- The directory gets the layout upstream's @file:\/\/@ store writes and its+-- HTTP substituter reads, so any static web server or file share can serve+-- it, and nova-nix's substituter reads it through a @file:\/\/@ URL too.+-- The push opens it first as either reader opens it ("Nix.CacheDirectory"),+-- which makes its directories and its @nix-cache-info@, then makes the+-- realisations directory under its older name too, and then writes:+--+-- * @\<hash\>.narinfo@ for each path, its fields in the order upstream+--   writes them.+-- * The NAR at the narinfo's @URL@, @nar\/\<filehash\>.nar@, or @.nar.zst@+--   compressed with zstd, named by the nix-base32 hash of the file, as+--   upstream names it.+--+-- Each narinfo carries an Ed25519 signature by the secret key, as+-- upstream's binary cache store signs every narinfo it writes with the key+-- its @secret-key@ setting names: over upstream's fingerprint of the path,+-- as @name:base64@.  nova-cache computes both.  Its verification of that+-- fingerprint accepts cache.nixos.org's signatures, and Ed25519 signing is+-- deterministic, so with a key whose second half is the public key of its+-- seed, the only keys 'loadSecretKeyFile' accepts, a signature here is the+-- one upstream's signer makes.+--+-- == Writes+--+-- A path whose narinfo is in the directory is skipped, as upstream takes+-- it to be in the cache, and a NAR whose file is there is not written+-- again.  Every NAR is written before any narinfo, and the narinfos in the+-- closure's order, as "Nix.Push" uploads them, so no narinfo names a NAR or+-- a reference that is not there yet.  Each file is written whole beside its+-- name and renamed onto it ('writeCacheFile'), so a reader never meets a+-- torn one.+module Nix.Push.Directory+  ( -- * Where a push writes+    PushTarget (..),+    pushTarget,++    -- * Pushing to a directory+    DirectoryPush (..),+    pushToDirectory,+    loadSecretKeyFile,+    ed25519SeedBytes,++    -- * Pure pieces (exported for tests)+    signNarInfo,+  )+where++import Control.Exception (displayException)+import Control.Monad (filterM, forM, forM_, unless)+import Control.Monad.Except (ExceptT (..), liftEither, runExceptT, withExceptT)+import Control.Monad.IO.Class (liftIO)+import Data.Bifunctor (first)+import qualified Data.ByteString as BS+import Data.List (isPrefixOf)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Nix.CacheDirectory (cacheOpenFailureMessage, directoryUrl, fileUrlDirectory, openCacheDirectory, realisationsDirName, writeCacheFile)+import Nix.Http (catchSync)+import Nix.Push (PushArtifact (..), PushCompression, PushSummary (..), computeClosure, loadKeyFile, logNar, logPushed, logSkipped, narInfoFileName, preparePath)+import Nix.Push.Source (PushSource (..))+import Nix.Store.Path (StorePath)+import NovaCache.NarInfo (NarInfo (..), renderNarInfo)+import NovaCache.Signing (SecretKey)+import qualified NovaCache.Signing as Signing+import System.Directory (createDirectoryIfMissing, doesFileExist)+import System.FilePath ((</>))++-- ---------------------------------------------------------------------------+-- Where a push writes+-- ---------------------------------------------------------------------------++-- | Where a push writes, with the file holding the key it needs there.+data PushTarget+  = -- | A nova-cache server, by its base URL with no trailing slash, and+    -- the file holding its API key, if it takes one.+    ServerTarget !Text !(Maybe FilePath)+  | -- | A directory, and the file holding the secret key that signs its+    -- narinfos.+    DirectoryTarget !FilePath !FilePath+  deriving (Eq, Show)++-- | The schemes of a nova-cache server's URL.+serverSchemes :: [String]+serverSchemes = ["http://", "https://"]++-- | What @push --cache URL@ writes to, given the files @--key-file@ and+-- @--secret-key-file@ name.  An @http:\/\/@ or @https:\/\/@ URL is a+-- nova-cache server, which signs what it receives, so it takes no secret+-- key.  A @file:\/\/@ URL is a directory ('fileUrlDirectory'), which takes+-- no API key and needs the secret key: a substituter refuses a narinfo+-- with no signature, nova-nix's and upstream's alike, unless+-- @require-sigs@ is off, the path is content-addressed, or, for+-- upstream's, the cache is marked trusted.+pushTarget :: String -> Maybe FilePath -> Maybe FilePath -> Either Text PushTarget+pushTarget url apiKeyFile secretKeyFile+  | Just named <- fileUrlDirectory "sign and compress with --secret-key-file and --compression" url = do+      dir <- named+      case (apiKeyFile, secretKeyFile) of+        (Just _, _) -> Left "--key-file is a nova-cache server's API key; a file:// cache is signed with --secret-key-file"+        (Nothing, Nothing) -> Left "a file:// cache needs --secret-key-file, the secret key that signs its narinfos"+        (Nothing, Just keyFile) -> Right (DirectoryTarget dir keyFile)+  | any (`isPrefixOf` url) serverSchemes = case secretKeyFile of+      Just _ -> Left "--secret-key-file signs a file:// cache; a nova-cache server signs what it receives"+      Nothing -> Right (ServerTarget (T.dropWhileEnd (== '/') (T.pack url)) apiKeyFile)+  | otherwise = Left ("--cache takes the http:// or https:// URL of a nova-cache server, or a file:// URL of a directory, not " <> T.pack url)++-- ---------------------------------------------------------------------------+-- Pushing to a directory+-- ---------------------------------------------------------------------------++-- | Where and how a push writes a directory cache.+data DirectoryPush = DirectoryPush+  { -- | The cache's directory, created if it is not there.+    dpDirectory :: !FilePath,+    -- | The key that signs every narinfo the push writes.+    dpSecretKey :: !SecretKey,+    -- | How each NAR is packaged, as for a server.+    dpCompression :: !PushCompression+  }+  deriving (Eq, Show)++-- | Write the closure of the given paths to the directory cache.  A path+-- the cache holds is skipped.+--+-- Any failure stops the push with an error.  What it leaves is NARs no+-- narinfo names, which no reader asks for, and narinfos for some of the+-- paths, written deps first, so each names a NAR and references that are+-- there.  An interrupt is not a failure: it stops the push and+-- propagates.  Its progress lines go to the source's logger.+pushToDirectory :: DirectoryPush -> PushSource -> [StorePath] -> IO (Either Text PushSummary)+pushToDirectory cfg source roots =+  -- Every synchronous exception, as for a server: the database's, the+  -- serialiser's, and the directory's IO errors are each a failed push.+  runExceptT run `catchSync` \e -> pure (Left (T.pack (displayException e)))+  where+    inCache relative = dpDirectory cfg </> T.unpack relative+    run = do+      _ <- withExceptT cacheOpenFailureMessage (ExceptT (openCacheDirectory (directoryUrl (dpDirectory cfg)) (dpDirectory cfg)))+      liftIO (createDirectoryIfMissing True (dpDirectory cfg </> realisationsDirName))+      closure <- ExceptT (computeClosure source roots)+      missing <- liftIO (filterM (fmap not . doesFileExist . inCache . narInfoFileName) closure)+      let skipped = length closure - length missing+      logSkipped (psLogger source) skipped+      -- NARs first, one at a time.  Each path's narinfo is signed and+      -- rendered as its NAR is written, and only the rendered bytes are+      -- kept, forced, so what the second phase holds reaches no NAR.+      written <- forM missing $ \sp -> do+        (artifact, narInfo) <- preparePath (dpCompression cfg) source sp+        logNar (psLogger source) sp artifact+        liftIO (writeUnlessPresent (inCache (niUrl narInfo)) (paBytes artifact))+        signed <- liftEither (signNarInfo (dpSecretKey cfg) narInfo)+        let !rendered = TE.encodeUtf8 (renderNarInfo signed)+        pure (sp, rendered)+      -- Then the narinfos, in the closure's deps-first order.+      forM_ written $ \(sp, rendered) -> do+        liftIO (writeCacheFile (inCache (narInfoFileName sp)) rendered)+        logPushed (psLogger source) sp+      pure PushSummary {psPushed = length written, psSkipped = skipped}++-- | Read a secret signing key from a file, in the form+-- @nix-store --generate-binary-cache-key@ writes: @name:base64@, the+-- base64 of the 64-byte Ed25519 secret key, its seed and then the seed's+-- public key.  A key whose second half is not its seed's public key is+-- refused, before anything is written: upstream's signer, libsodium's,+-- signs with that half as the public key, so its signatures verify under+-- no key, where nova-cache's, which derives the public key from the+-- seed, would verify under one the key file does not hold.  No message+-- carries the key's bytes.+loadSecretKeyFile :: FilePath -> IO (Either Text SecretKey)+loadSecretKeyFile path = (>>= parse) <$> loadKeyFile path+  where+    parse text = do+      key <- first refused (Signing.parseSecretKey text)+      derived <- first refused (Signing.toPublicKey key)+      key <$ unless (Signing.pkBytes derived == BS.drop ed25519SeedBytes (Signing.skBytes key)) (Left (refused "its second half is not the public key of its seed"))+    refused err = "secret key file " <> T.pack path <> ": " <> T.pack err++-- | The bytes of an Ed25519 seed, the first half of a secret key: the+-- @ed25519SeedSize@ of nova-cache 0.13.0.0's @NovaCache.Signing@, which it+-- does not export.+ed25519SeedBytes :: Int+ed25519SeedBytes = 32++-- | The narinfo with the key's signature added to those it carries, which+-- upstream keeps as a sorted set (@ValidPathInfo::sign@ in path-info.cc).+signNarInfo :: SecretKey -> NarInfo -> Either Text NarInfo+signNarInfo key narInfo = do+  sig <- first (\err -> "cannot sign the narinfo of " <> niStorePath narInfo <> ": " <> T.pack err) (Signing.sign key narInfo)+  pure narInfo {niSigs = Set.toAscList (Set.insert sig (Set.fromList (niSigs narInfo)))}++-- ---------------------------------------------------------------------------+-- Writing files+-- ---------------------------------------------------------------------------++-- | Write a file of the cache unless one is there under its name.+writeUnlessPresent :: FilePath -> BS.ByteString -> IO ()+writeUnlessPresent target bytes = do+  present <- doesFileExist target+  unless present (writeCacheFile target bytes)
+ src/Nix/Push/Source.hs view
@@ -0,0 +1,97 @@+-- | What a push reads: a t'PushSource' gives the records of the paths it+-- sends and says where their files are.  "Nix.Push" and+-- "Nix.Push.Directory" push from one.  'localPushSource' reads the records+-- from an opened store's database, and a store reached through a daemon+-- ("Nix.Daemon.ClientStore") asks the daemon for them.+--+-- A source gives the records a push needs of a path in two ways, so that+-- computing the closure asks only the references: 'psReferences', and+-- 'psPathInfo' for the NAR hash and deriver of a path that is sent.+module Nix.Push.Source+  ( PushSource (..),+    PushedPath (..),+    localPushSource,+  )+where++import Data.Text (Text)+import Nix.Logger (Logger)+import Nix.Store (Store (..), queryAllValidPaths, queryPathInfo, queryReferences, volumeCaseHack)+import qualified Nix.Store.DB as DB+import Nix.Store.Path (StoreDir, StorePath, parseStorePath)+import qualified NovaCache.NAR as NAR++-- | What a source records of a path a push sends: the NAR hash it was+-- registered under, the paths it refers to and the derivation that built+-- it, if known.+data PushedPath = PushedPath+  { -- | The hash of the path's NAR serialisation, as a store's database+    -- spells it ('Hash.formatNixHash').+    ppNarHash :: !Text,+    -- | The paths it refers to.+    ppReferences :: ![StorePath],+    -- | The derivation that built it.+    ppDeriver :: !(Maybe StorePath)+  }+  deriving (Eq, Show)++-- | What a push reads: where the files of the paths are, and what is+-- recorded of each.  A record the source cannot give is a 'Left' with the+-- reason, which fails the push.+data PushSource = PushSource+  { -- | The directory the files of the paths are read from.+    psStoreDir :: !StoreDir,+    -- | How the NAR of a tree is made on this volume+    -- ('volumeCaseHack').+    psCaseHack :: !NAR.CaseHack,+    -- | Where the push's progress lines go.+    psLogger :: !Logger,+    -- | The paths a path refers to, none for a path the source does not+    -- hold.  Computing a closure asks only this, so a record of a path+    -- that is not sent need not read.+    psReferences :: !(StorePath -> IO (Either Text [StorePath])),+    -- | What is recorded of a path, or 'Nothing' for a path the source+    -- does not hold as valid.+    psPathInfo :: !(StorePath -> IO (Either Text (Maybe PushedPath))),+    -- | Every valid path.+    psAllValid :: !(IO (Either Text [StorePath]))+  }++-- | A store opened directly as a source: its records are its database's,+-- parsed under its directory, which under @--store@ is not the platform's.+-- A reference that does not parse fails the read, and so does a valid+-- path that does not; a deriver that does not parse is dropped.+localPushSource :: Store -> PushSource+localPushSource store =+  PushSource+    { psStoreDir = stDir store,+      psCaseHack = volumeCaseHack (stCaseSensitivity store),+      psLogger = stLogger store,+      psReferences = localReferences store,+      psPathInfo = localPathInfo store,+      psAllValid = traverse parseValidPath <$> queryAllValidPaths (stDB store)+    }+  where+    parseValidPath txt = maybe (Left ("unparseable store DB path: " <> txt)) Right (parseStorePath (stDir store) txt)++-- | The references of a path in a store's database, none for a path it+-- does not register.+localReferences :: Store -> StorePath -> IO (Either Text [StorePath])+localReferences store sp = traverse (parseReference store) <$> queryReferences (stDB store) sp++-- | The record of a path in a store's database.+localPathInfo :: Store -> StorePath -> IO (Either Text (Maybe PushedPath))+localPathInfo store sp = do+  recorded <- queryPathInfo (stDB store) sp+  case recorded of+    Nothing -> pure (Right Nothing)+    Just info -> do+      refTexts <- queryReferences (stDB store) sp+      pure $ do+        refs <- traverse (parseReference store) refTexts+        Right (Just PushedPath {ppNarHash = DB.piNarHash info, ppReferences = refs, ppDeriver = DB.piDeriver info >>= parseStorePath (stDir store)})++-- | A reference as the database spells it, parsed under the store's+-- directory.+parseReference :: Store -> Text -> Either Text StorePath+parseReference store txt = maybe (Left ("unparseable reference in store DB: " <> txt)) Right (parseStorePath (stDir store) txt)
src/Nix/Realise.hs view
@@ -1,323 +1,1332 @@--- | Deciding how to realise a derivation graph: what to substitute, what to--- build, and in what order, root first.------ Upstream tries a derivation's outputs before its inputs, so a package a--- cache holds never pulls in what it was built from--- (@DerivationGoal::haveDerivation@ at 2.24.9).  A substituted path needs its--- references instead, and those arrive first, so the store stays closed under--- references at every step (@PathSubstitutionGoal::init@).------ A cache that lacks a path and one that fails are told apart, as upstream--- tells them apart.  What no cache holds builds.  A substitute that a cache--- offers and fails to deliver stops the build, unless 'BuildFromSource'--- (upstream's @fallback@) says to build instead--- (@DerivationGoal::outputsSubstitutionTried@).  A cache that cannot be asked--- stops the build at once ('QueryFailed'); under 'BuildFromSource' the caller--- asks the next cache instead, so that failure never arrives here.------ Every effect is a record field, so the decisions run in tests over a fake--- cache and store.  "Nix.Builder" supplies the real ones.-module Nix.Realise-  ( -- * Substituting a closure-    SubstEffects (..),-    Offer (..),-    FetchOutcome (..),-    ClosureOutcome (..),-    substituteClosure,--    -- * Realising a graph-    Fallback (..),-    RealiseEffects (..),-    Realised (..),-    RealiseFailure (..),-    realiseFailureMessage,-    realise,-  )-where--import Control.Monad (filterM, void)-import Control.Monad.Except (ExceptT (..), runExceptT)-import qualified Data.Map.Strict as Map-import Data.Set (Set)-import qualified Data.Set as Set-import Data.Text (Text)-import Nix.DependencyGraph (DepGraph (..), DepNode (..), directDeps)-import Nix.Derivation (Derivation (..), DerivationOutput (..))-import Nix.Store.Path (StorePath, defaultStoreDir, storePathToText)---- ------------------------------------------------------------------------------ Substituting a closure--- ------------------------------------------------------------------------------- | What substitution needs from the store and the caches.-data SubstEffects m = SubstEffects-  { -- | Is this path already valid in the store?-    seValid :: !(StorePath -> m Bool),-    -- | What the caches say about a path before anything is fetched.-    seReferences :: !(StorePath -> m Offer),-    -- | Fetch and register these paths, all of them or none.-    seFetch :: !([StorePath] -> m FetchOutcome)-  }---- | What the caches answer for one path, before anything is fetched.-data Offer-  = -- | A cache serves the path, with these references.-    Offered ![StorePath]-  | -- | No cache serves it.-    NotOffered-  | -- | A cache could not be asked, and why.  Upstream rethrows a failed-    -- narinfo query unless @fallback@ is set, which ends the whole build-    -- (@PathSubstitutionGoal::init@ at 2.24.9).-    QueryFailed !Text-  deriving (Eq, Show)---- | How fetching a batch of paths ended.-data FetchOutcome-  = -- | Every path is valid.-    Fetched-  | -- | No cache supplied some path, and none failed to.-    FetchMissed-  | -- | A cache that offered a path failed to deliver it, and no other cache-    -- delivered it: upstream's failed substitution.-    FetchFailed-  deriving (Eq, Show)---- | How an attempt to substitute a set of paths ended.-data ClosureOutcome-  = -- | The paths and everything they reference are valid.-    ClosureComplete-  | -- | No cache could supply the paths themselves.-    ClosureUnavailable-  | -- | A cache has the paths but not something they reference.  Building-    -- the inputs can supply the hole, so substitution is worth retrying-    -- afterwards.-    ClosureIncomplete-  | -- | A substitute for the paths, or for something they reference, failed-    -- ('FetchFailed').-    ClosureFailed-  | -- | A cache could not be asked about one of them ('QueryFailed').-    ClosureQueryFailed !Text-  deriving (Eq, Show)---- | Substitute paths with their closure, references first.------ The paths arrive together through 'seFetch', because the outputs of one--- derivation may reference each other and a batch that cannot land whole--- registers nothing.  Anything else they reference arrives first, each path--- on its own, as upstream's does: a reference that lands before a later--- failure stays, a valid path like any other, and so can leave its own--- derivation with only some outputs valid.-substituteClosure :: (Monad m) => SubstEffects m -> [StorePath] -> m ClosureOutcome-substituteClosure effects paths =-  fst <$> closureOf effects (Set.fromList paths) paths---- | 'substituteClosure', threading the paths already visited.  A cache's--- declared references are not trusted to be acyclic: a cycle ends here at the--- visited set, and the registration it reaches refuses the unregistered--- referent.-closureOf ::-  (Monad m) =>-  SubstEffects m ->-  Set StorePath ->-  [StorePath] ->-  m (ClosureOutcome, Set StorePath)-closureOf effects visited paths = do-  missing <- filterM (fmap not . seValid effects) paths-  -- A failed query ends the build, so it is the last one asked.-  declared <- runExceptT (traverse (ExceptT . fmap offeredReferences . seReferences effects) missing)-  case (missing, sequence <$> declared) of-    ([], _) -> pure (ClosureComplete, visited)-    (_, Left failure) -> pure (ClosureQueryFailed failure, visited)-    (_, Right Nothing) -> pure (ClosureUnavailable, visited)-    (_, Right (Just references)) -> do-      let outside = Set.fromList (concat references) `Set.difference` Set.fromList missing-      (held, deeper) <- referencesFirst effects visited (Set.toAscList outside)-      case held of-        ClosureComplete -> do-          fetched <- seFetch effects missing-          pure (fetchedClosure fetched, deeper)-        _ -> pure (held, deeper)---- | An offer's references, 'Nothing' when no cache serves the path, or the--- failure of a query that could not be asked.-offeredReferences :: Offer -> Either Text (Maybe [StorePath])-offeredReferences (Offered references) = Right (Just references)-offeredReferences NotOffered = Right Nothing-offeredReferences (QueryFailed failure) = Left failure---- | What a batch fetch makes of paths whose references are all valid.-fetchedClosure :: FetchOutcome -> ClosureOutcome-fetchedClosure Fetched = ClosureComplete-fetchedClosure FetchMissed = ClosureUnavailable-fetchedClosure FetchFailed = ClosureFailed---- | Realise references one at a time, stopping at the first that fails.  A--- reference no cache supplies is a hole the inputs may fill, so the paths--- naming it are incomplete.  A reference whose substitute or query failed--- passes that failure on, as upstream's goal for a path fails when a--- reference's goal does (@PathSubstitutionGoal::tryToRun@ at 2.24.9).-referencesFirst ::-  (Monad m) =>-  SubstEffects m ->-  Set StorePath ->-  [StorePath] ->-  m (ClosureOutcome, Set StorePath)-referencesFirst _ visited [] = pure (ClosureComplete, visited)-referencesFirst effects visited (reference : rest)-  | reference `Set.member` visited = referencesFirst effects visited rest-  | otherwise = do-      (outcome, deeper) <- closureOf effects (Set.insert reference visited) [reference]-      case outcome of-        ClosureComplete -> referencesFirst effects deeper rest-        ClosureUnavailable -> pure (ClosureIncomplete, deeper)-        ClosureIncomplete -> pure (ClosureIncomplete, deeper)-        ClosureFailed -> pure (ClosureFailed, deeper)-        ClosureQueryFailed failure -> pure (ClosureQueryFailed failure, deeper)---- ------------------------------------------------------------------------------ Realising a graph--- ------------------------------------------------------------------------------- | What a failed substitute leads to: upstream's @fallback@ setting, which--- its @--fallback@ flag turns on.-data Fallback-  = -- | The build stops and names @--fallback@, upstream's default.-    NoFallback-  | -- | The derivation builds from source instead.-    BuildFromSource-  deriving (Eq, Show)---- | Why realising a graph stopped.-data RealiseFailure-  = -- | A derivation failed to build, with the builder's report.-    BuildFailed !Text-  | -- | A cache could not be asked about a path ('QueryFailed').-    CacheQueryFailed !Text-  | -- | A substitute for this derivation's outputs, or for something they-    -- reference, failed under 'NoFallback'.-    SubstitutesFailed !StorePath-  deriving (Eq, Show)---- | A failure as the build reports it.  A failed substitute reads as--- upstream's (@DerivationGoal::outputsSubstitutionTried@ at 2.24.9), less--- the space its format string ends in.  The @.drv@ is named under the--- logical store directory, wherever the store's files live, as upstream's--- @printStorePath@ names it: a store kept elsewhere still has @/nix/store@--- as its @storeDir@ and only its @realStoreDir@ moves.-realiseFailureMessage :: RealiseFailure -> Text-realiseFailureMessage (BuildFailed report) = report-realiseFailureMessage (CacheQueryFailed failure) = failure-realiseFailureMessage (SubstitutesFailed drvPath) =-  "some substitutes for the outputs of derivation '"-    <> storePathToText defaultStoreDir drvPath-    <> "' failed (usually happens due to networking issues); try '--fallback' to build derivation from source"---- | How one derivation came to be realised.-data Realised-  = -- | Every output was already valid.-    AlreadyValid-  | -- | Every output came from a cache.-    Substituted-  | -- | The derivation was built here.-    Built-  deriving (Eq, Show)---- | What realising a graph needs from the outside.-data RealiseEffects m = RealiseEffects-  { reSubst :: !(SubstEffects m),-    -- | Are all of this derivation's outputs valid?-    reAllValid :: !(Derivation -> m Bool),-    -- | Build one derivation, whose inputs are realised, given its @.drv@-    -- path.-    reBuild :: !(Derivation -> StorePath -> m (Either Text ())),-    -- | Report how a derivation was realised.-    reReport :: !(Realised -> Derivation -> m ())-  }---- | Realise a graph from its root.  A derivation that is valid or substituted--- takes its inputs out of the work, and what remains builds leaves first.------ The graph has to be acyclic ('Nix.DependencyGraph.topoSort' decides that).-realise :: (Monad m) => Fallback -> RealiseEffects m -> DepGraph -> StorePath -> m (Either RealiseFailure ())-realise fallback effects graph root = void <$> realiseNode fallback effects graph Set.empty root---- | Realise one node, threading the nodes already visited, so a derivation--- several others depend on is handled once.-realiseNode ::-  (Monad m) =>-  Fallback ->-  RealiseEffects m ->-  DepGraph ->-  Set StorePath ->-  StorePath ->-  m (Either RealiseFailure (Set StorePath))-realiseNode fallback effects graph visited node-  | node `Set.member` visited = pure (Right visited)-  | otherwise = case Map.lookup node (unDepGraph graph) of-      -- A node outside the graph has nothing to realise.-      Nothing -> pure (Right visited)-      Just depNode -> do-        let drv = dnDerivation depNode-            seen = Set.insert node visited-        allValid <- reAllValid effects drv-        if allValid-          then reported AlreadyValid drv seen-          else do-            firstTry <- substituteOutputs drv-            case (firstTry, stopFor firstTry) of-              (ClosureComplete, _) -> reported Substituted drv seen-              (_, Just failure) -> pure (Left failure)-              (_, Nothing) -> buildFromInputs firstTry drv seen-  where-    stopFor = substitutionStop fallback node-    reported status drv done = Right done <$ reReport effects status drv-    substituteOutputs drv = substituteClosure (reSubst effects) (map doPath (drvOutputs drv))-    buildFromInputs firstTry drv seen = do-      inputs <- realiseAll fallback effects graph seen (directDeps graph node)-      case inputs of-        Left err -> pure (Left err)-        Right realised -> do-          -- The inputs may have supplied what the closure lacked, and then-          -- the substitute is still good (upstream's retrySubstitution).-          retried <- case firstTry of-            ClosureIncomplete -> substituteOutputs drv-            other -> pure other-          case (retried, stopFor retried) of-            (ClosureComplete, _) -> reported Substituted drv realised-            (_, Just failure) -> pure (Left failure)-            (_, Nothing) -> do-              built <- reBuild effects drv node-              case built of-                Left err -> pure (Left (BuildFailed err))-                Right () -> reported Built drv realised---- | The failure a substitution attempt for a derivation stops the build--- with, if it stops it: a failed query always, and a failed substitute--- unless the derivation may build from source.  Upstream retries a--- substitution after the inputs only when every failure was a hole in the--- closure, so a failed substitute that falls back is not retried.-substitutionStop :: Fallback -> StorePath -> ClosureOutcome -> Maybe RealiseFailure-substitutionStop fallback drvPath outcome = case outcome of-  ClosureQueryFailed failure -> Just (CacheQueryFailed failure)-  ClosureFailed -> case fallback of-    NoFallback -> Just (SubstitutesFailed drvPath)-    BuildFromSource -> Nothing-  ClosureComplete -> Nothing-  ClosureUnavailable -> Nothing-  ClosureIncomplete -> Nothing---- | Realise nodes in order, stopping at the first failure.-realiseAll ::-  (Monad m) =>-  Fallback ->-  RealiseEffects m ->-  DepGraph ->-  Set StorePath ->-  [StorePath] ->-  m (Either RealiseFailure (Set StorePath))-realiseAll _ _ _ visited [] = pure (Right visited)-realiseAll fallback effects graph visited (node : rest) = do-  realised <- realiseNode fallback effects graph visited node-  case realised of-    Left err -> pure (Left err)-    Right deeper -> realiseAll fallback effects graph deeper rest+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE TupleSections #-}++-- | Deciding how to realise a derivation graph: what to substitute, what to+-- build, and in what order, root first.+--+-- Upstream tries a derivation's outputs before its inputs, so a package a+-- cache holds never pulls in what it was built from+-- (@DerivationGoal::haveDerivation@ at 2.24.9).  A substituted path needs its+-- references instead, and those arrive first, so the store stays closed under+-- references at every step (@PathSubstitutionGoal::init@).  The references+-- realised are the ones the cache the path then comes from declares.+--+-- A cache that lacks a path and one that fails are told apart, as upstream+-- tells them apart.  What no cache holds builds.  A substitute that a cache+-- offers and fails to deliver passes the path to the caches after it, and+-- when none of them delivers it the build stops, unless 'BuildFromSource'+-- (upstream's @fallback@) says to build instead.  A cache that cannot be+-- asked stops the build at once ('QueryFailed'); under 'BuildFromSource' the+-- caller asks the next cache instead, so that failure arrives here only as+-- a refusal to substitute at all ('noWriteAccessMessage'), or as a trust+-- check that cannot be made, such as a trusted key that does not read, and+-- each stops the build too.+--+-- A derivation whose @allowSubstitutes@ attribute is false builds here even+-- when a cache holds its outputs, unless @always-allow-substitutes@ is set+-- ('substitutesAllowed').  Its attributes are read first, as upstream Nix+-- reads them ('derivationAttrs').+--+-- Under 'BuildCheck' the derivation asked for is not realised but checked:+-- built again beside its valid outputs, each compared with the one the+-- store holds ('checkRoot').  This is upstream's @bmCheck@, which+-- @nix-build --check@ selects, and it covers that derivation alone: its+-- inputs are realised as under 'BuildNormal'.+--+-- Several derivations can be realised in one call, each for the outputs a+-- request asks of it, as upstream's @Store::buildPaths@ realises several+-- requests with one worker ('realiseRequests').+--+-- Every effect is a record field, so the decisions run in tests over a fake+-- cache and store.  "Nix.Builder" supplies the real ones.+module Nix.Realise+  ( -- * Substituting a closure+    SubstEffects (..),+    Offer (..),+    Registration (..),+    FetchOutcome (..),+    Undelivered (..),+    ClosureOutcome (..),+    substituteClosure,+    noWriteAccessMessage,++    -- * Whether a derivation may be substituted+    DerivationAttrs (..),+    derivationAttrs,+    derivationBoolAttr,+    derivationStringAttr,+    derivationStringsAttr,+    SubstitutesSetting (..),+    Substitutes (..),+    substitutesAllowed,++    -- * Realising a graph+    Fallback (..),+    BuildMode (..),+    RealiseSettings (..),+    RealiseEffects (..),+    CheckVerdict (..),+    DifferingRebuild (..),+    checkedOutputPath,+    Realised (..),+    RealiseFailure (..),+    FailedBuild (..),+    realiseFailureMessage,+    realiseFailureStatus,+    realise,++    -- * Realising several requests+    RequestsFailure (..),+    requestsFailureMessage,+    requestsFailureStatus,+    realiseRequests,+    RequestOutcome (..),+    realiseEach,++    -- * What realising would take+    Wanted (..),+    OutputSelection (..),+    MissingEffects (..),+    MissingPaths (..),+    planMissing,+  )+where++import Control.Monad (filterM)+import Control.Monad.Except (ExceptT (..), runExceptT)+import Data.Bifunctor (bimap, first)+import Data.Bool (bool)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import Data.Functor ((<&>))+import Data.List (sortOn)+import Data.List.NonEmpty (NonEmpty)+import qualified Data.List.NonEmpty as NE+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Word (Word64)+import Nix.DependencyGraph (DepGraph (..), DepNode (..))+import Nix.Derivation (Derivation (..), DerivationOutput (..))+import Nix.Derivation.StructuredAttrs (structuredAttrsKey)+import Nix.Json (Json (..), expectJson, parseJson)+import Nix.Store.Path (StoreDir, StorePath (spName), defaultStoreDir, storePathBasename, storePathToFilePath, storePathToText)++-- ---------------------------------------------------------------------------+-- Substituting a closure+-- ---------------------------------------------------------------------------++-- | What substitution needs from the store and the caches.  A cache that+-- offers a path hands over a substitute @s@ with the references it+-- declares, and the path is fetched from that substitute, so what arrives+-- first and the path that names it are the same cache's account.+-- Upstream's substitution goal copies a path from the substituter whose+-- path info it realised the references of (@PathSubstitutionGoal::init@+-- and @tryToRun@ at 2.24.9).+data SubstEffects s m = SubstEffects+  { -- | Is this path already valid in the store?+    seValid :: !(StorePath -> m Bool),+    -- | What the first cache that serves a path says about it, before+    -- anything is fetched.+    seReferences :: !(StorePath -> m (Offer s)),+    -- | What the caches after this substitute's say about the path, asked+    -- once the substitute did not arrive.  Only caches after the given+    -- one are asked, so a path runs out of caches.+    seNextOffer :: !(StorePath -> s -> m (Offer s)),+    -- | Fetch these paths, each from its substitute, and register them as+    -- the 'Registration' says.  The paths an outcome names are among these.+    seFetch :: !(Registration -> NonEmpty (StorePath, s) -> m FetchOutcome)+  }++-- | What a fetch registers of the paths that arrive.+data Registration+  = -- | Every one of them if every one arrives, and none otherwise.+    RegisterAll+  | -- | None: another path of the batch has no cache left to offer it, so+    -- the batch cannot land.  The fetch learns which of these a cache+    -- delivers, which decides whether the substitution failed.+    RegisterNone+  deriving (Eq, Show)++-- | What the caches answer for one path, before anything is fetched.+data Offer s+  = -- | A cache serves the path with these references, and this substitute+    -- fetches it from that cache.+    Offered !s ![StorePath]+  | -- | No cache serves it.+    NotOffered+  | -- | A cache could not be asked, and why.  Upstream rethrows a failed+    -- narinfo query unless @fallback@ is set, which ends the whole build+    -- (@PathSubstitutionGoal::init@ at 2.24.9), and a refusal to substitute+    -- or a trust check that cannot be made ends it whatever @fallback@+    -- says.+    QueryFailed !Text+  deriving (Eq, Show)++-- | How fetching a batch of paths ended.+data FetchOutcome+  = -- | Every path arrived, and under 'RegisterAll' is valid.+    Fetched+  | -- | Nothing was registered.  These paths did not arrive from their+    -- substitutes, and the others of the batch did.+    NotFetched !(NonEmpty (StorePath, Undelivered))+  deriving (Eq, Show)++-- | Why a path did not arrive from the cache that offered it.+data Undelivered+  = -- | The cache no longer holds it.  Upstream treats such a substitute+    -- as one that never existed (@SubstituteGone@ in+    -- @PathSubstitutionGoal::tryToRun@ at 2.24.9).+    Gone+  | -- | The cache failed to deliver it, or its registration was refused:+    -- upstream's @substituterFailed@.+    DeliveryFailed+  deriving (Eq, Show)++-- | How an attempt to substitute a set of paths ended.+data ClosureOutcome+  = -- | The paths and everything they reference are valid.+    ClosureComplete+  | -- | No cache could supply the paths themselves.+    ClosureUnavailable+  | -- | A cache has the paths but not something they reference.  Building+    -- the inputs can supply the hole, so substitution is worth retrying+    -- afterwards.+    ClosureIncomplete+  | -- | A substitute for the paths, or for something they reference, failed+    -- ('DeliveryFailed'), and no later cache delivered it.+    ClosureFailed+  | -- | A cache could not be asked about one of them ('QueryFailed').+    ClosureQueryFailed !Text+  deriving (Eq, Show)++-- | Substitute paths with their closure, references first.+--+-- The paths arrive together through 'seFetch', because the outputs of one+-- derivation may reference each other and a batch that cannot land whole+-- registers nothing.  Anything else they reference arrives first, each path+-- on its own, as upstream's does: a reference that lands before a later+-- failure stays, a valid path like any other, and so can leave its own+-- derivation with only some outputs valid.+substituteClosure :: (Monad m) => SubstEffects s m -> [StorePath] -> m ClosureOutcome+substituteClosure effects paths =+  fst <$> closureOf effects (Set.fromList paths) paths++-- | 'substituteClosure', threading the paths already visited.  A cache's+-- declared references are not trusted to be acyclic: a cycle ends here at the+-- visited set, and the registration it reaches refuses the unregistered+-- referent.  A batch is asked about in 'substitutionOrder', so the first+-- cache that fails, or the first refusal, is the one upstream reports.+closureOf ::+  (Monad m) =>+  SubstEffects s m ->+  Set StorePath ->+  [StorePath] ->+  m (ClosureOutcome, Set StorePath)+closureOf effects visited paths = do+  missing <- filterM (fmap not . seValid effects) (sortOn substitutionOrder paths)+  case NE.nonEmpty missing of+    Nothing -> pure (ClosureComplete, visited)+    Just batch -> do+      offered <- offersFor (fmap (\path -> (path, seReferences effects path)) batch)+      case offered of+        Left failure -> pure (ClosureQueryFailed failure, visited)+        Right Nothing -> pure (ClosureUnavailable, visited)+        Right (Just pending) -> fetchRounds effects visited (fmap (Offering NoneFailed) pending)++-- | One path of a batch with the substitute a cache offered it as, and the+-- references that cache declares.+data Pending s = Pending+  { pendingPath :: !StorePath,+    pendingSubstitute :: !s,+    pendingReferences :: ![StorePath]+  }++-- | Whether a cache has failed to deliver a path, which upstream's goal for+-- the path records as @substituterFailed@.+data Attempts = NoneFailed | SomeFailed++-- | Where one path of a batch stands between fetches.+data Standing s+  = -- | A cache offers it, and none it was asked of before has delivered it.+    Offering !Attempts !(Pending s)+  | -- | It arrived from its substitute, and was not registered.+    Arrived !Attempts !(Pending s)+  | -- | No cache is left to offer it: 'DeliveryFailed' when one failed to+    -- deliver it, and 'Gone' when none did.+    RanOut !StorePath !Undelivered++-- | The path a standing is about.+standingPath :: Standing s -> StorePath+standingPath (Offering _ pending) = pendingPath pending+standingPath (Arrived _ pending) = pendingPath pending+standingPath (RanOut path _) = path++-- | Each path's offer, asked in order.  A failed query ends the build, so it+-- is the last one asked; a path no cache offers does not stop the others+-- being asked, and makes the answer 'Nothing'.+offersFor :: (Monad m) => NonEmpty (StorePath, m (Offer s)) -> m (Either Text (Maybe (NonEmpty (Pending s))))+offersFor asks = fmap sequence <$> runExceptT (traverse (\(path, ask) -> ExceptT (pendingFor path <$> ask)) asks)+  where+    pendingFor path (Offered substitute references) = Right (Just (Pending path substitute references))+    pendingFor _ NotOffered = Right Nothing+    pendingFor _ (QueryFailed failure) = Left failure++-- | Fetch a batch until it lands or can tell why not.  Each fetch realises+-- what the paths it takes reference first; a reference that cannot be+-- realised ends the batch, whatever later caches offer, as upstream's goal+-- for a path is done once a reference's goal fails+-- (@PathSubstitutionGoal::tryToRun@ at 2.24.9).+--+-- While every path has a cache to offer it, the whole batch is fetched and+-- registered if it all arrives.  A path that does not arrive is asked of+-- the caches after the one that offered it, that cache's references come+-- first, and the batch is fetched again, the paths that arrived included,+-- since nothing was registered: upstream's goal for each path moves on to+-- its next substituter (@PathSubstitutionGoal::init@).  Once a path has no+-- cache left the batch cannot land, and the paths still offered are+-- fetched, registering nothing, until each arrives or runs out too, as each+-- of upstream's goals runs its own course.  The batch then failed when a+-- path ran out after a cache failed to deliver it, and is otherwise+-- unavailable, as a path no cache delivers and none failed to counts as one+-- no cache offered: upstream's derivation fails only when a goal failed+-- other than for want of a substitute or a reference+-- (@DerivationGoal::outputsSubstitutionTried@ in derivation-goal.cc at+-- 2.24.9).+fetchRounds ::+  (Monad m) =>+  SubstEffects s m ->+  Set StorePath ->+  NonEmpty (Standing s) ->+  m (ClosureOutcome, Set StorePath)+fetchRounds effects visited standings =+  case NE.nonEmpty (concatMap fetching standings) of+    Nothing -> pure (exhaustedOutcome standings, visited)+    Just batch -> do+      let outside = Set.fromList (concatMap pendingReferences batch) `Set.difference` Set.fromList (map standingPath (NE.toList standings))+      (held, deeper) <- referencesFirst effects visited (Set.toAscList outside)+      case held of+        ClosureComplete -> do+          fetched <- seFetch effects registration (fmap (\each -> (pendingPath each, pendingSubstitute each)) batch)+          case (registration, fetched) of+            (RegisterAll, Fetched) -> pure (ClosureComplete, deeper)+            _ -> do+              next <- runExceptT (traverse (ExceptT . afterFetch effects (undeliveredIn fetched)) standings)+              either (\failure -> pure (ClosureQueryFailed failure, deeper)) (fetchRounds effects deeper) next+        _ -> pure (held, deeper)+  where+    whole = not (any ranOut standings)+    registration+      | whole = RegisterAll+      | otherwise = RegisterNone+    fetching (Offering _ pending) = [pending]+    fetching (Arrived _ pending) = [pending | whole]+    fetching (RanOut _ _) = []+    ranOut (RanOut _ _) = True+    ranOut _ = False++-- | The paths a fetch names as not delivered.+undeliveredIn :: FetchOutcome -> Map StorePath Undelivered+undeliveredIn Fetched = Map.empty+undeliveredIn (NotFetched undelivered) = Map.fromList (NE.toList undelivered)++-- | Where a path stands after a fetch that registered nothing.  One the fetch+-- took has arrived unless it is named, and one named is asked of the caches+-- after its substitute's.  A path the fetch did not take stands as it did.+afterFetch :: (Monad m) => SubstEffects s m -> Map StorePath Undelivered -> Standing s -> m (Either Text (Standing s))+afterFetch effects undelivered standing = case standing of+  Offering attempts pending -> fetched attempts pending+  Arrived attempts pending -> fetched attempts pending+  RanOut _ _ -> pure (Right standing)+  where+    fetched attempts pending@(Pending path substitute _) = case Map.lookup path undelivered of+      Nothing -> pure (Right (Arrived attempts pending))+      Just why -> fromNext path (attemptsAfter why attempts) <$> seNextOffer effects path substitute+    fromNext path attempts (Offered substitute references) = Right (Offering attempts (Pending path substitute references))+    fromNext path attempts NotOffered = Right (RanOut path (ranOutBecause attempts))+    fromNext _ _ (QueryFailed failure) = Left failure++-- | A path's attempts once a cache has not delivered it, for this reason.+attemptsAfter :: Undelivered -> Attempts -> Attempts+attemptsAfter DeliveryFailed _ = SomeFailed+attemptsAfter Gone attempts = attempts++-- | Why a path with no cache left did not arrive.+ranOutBecause :: Attempts -> Undelivered+ranOutBecause SomeFailed = DeliveryFailed+ranOutBecause NoneFailed = Gone++-- | What a batch comes to when it cannot land and nothing is left to fetch:+-- failed when some path ran out after a cache failed to deliver it, and+-- otherwise unavailable.+exhaustedOutcome :: NonEmpty (Standing s) -> ClosureOutcome+exhaustedOutcome standings+  | any failedPath standings = ClosureFailed+  | otherwise = ClosureUnavailable+  where+    failedPath (RanOut _ DeliveryFailed) = True+    failedPath _ = False++-- | Realise references one at a time, stopping at the first that fails.  A+-- reference no cache supplies is a hole the inputs may fill, so the paths+-- naming it are incomplete.  A reference whose substitute or query failed+-- passes that failure on, as upstream's goal for a path fails when a+-- reference's goal does (@PathSubstitutionGoal::tryToRun@ at 2.24.9).+referencesFirst ::+  (Monad m) =>+  SubstEffects s m ->+  Set StorePath ->+  [StorePath] ->+  m (ClosureOutcome, Set StorePath)+referencesFirst _ visited [] = pure (ClosureComplete, visited)+referencesFirst effects visited (reference : rest)+  | reference `Set.member` visited = referencesFirst effects visited rest+  | otherwise = do+      (outcome, deeper) <- closureOf effects (Set.insert reference visited) [reference]+      case outcome of+        ClosureComplete -> referencesFirst effects deeper rest+        ClosureUnavailable -> pure (ClosureIncomplete, deeper)+        ClosureIncomplete -> pure (ClosureIncomplete, deeper)+        ClosureFailed -> pure (ClosureFailed, deeper)+        ClosureQueryFailed failure -> pure (ClosureQueryFailed failure, deeper)++-- | The order upstream's worker runs the substitution goals of a batch in:+-- by key, @a$@ then the path's name, @$@ and the path+-- (@PathSubstitutionGoal::key@ in substitution-goal.hh, @Worker::run@ in+-- worker.cc).  A @$@ sorts before every character a store path name may+-- hold, so the keys sort as the names do and then as the paths do.+substitutionOrder :: StorePath -> (Text, StorePath)+substitutionOrder path = (spName path, path)++-- | Upstream's refusal to substitute a path where nothing may be written,+-- which its substitution goal throws in a read-only evaluation before it+-- asks any cache (@PathSubstitutionGoal::init@ in substitution-goal.cc).+-- The path is named under the logical store directory, as upstream's+-- @printStorePath@ names it.+noWriteAccessMessage :: StorePath -> Text+noWriteAccessMessage path = "cannot substitute path '" <> storePathToText defaultStoreDir path <> "' - no write access to the Nix store"++-- ---------------------------------------------------------------------------+-- Whether a derivation may be substituted+-- ---------------------------------------------------------------------------++-- | Where a derivation's attributes are read from, as upstream's+-- @ParsedDerivation@ holds them.+data DerivationAttrs+  = -- | The structured attributes of a derivation that has them, parsed.+    AttrsInJson !Json+  | -- | The environment of a derivation without structured attributes.+    AttrsInEnvironment !(Map Text ByteString)+  deriving (Eq, Show)++-- | Upstream's @ParsedDerivation@ constructor at 2.24.9, for the derivation+-- at a @.drv@ path: structured attributes are parsed as JSON, and ones that+-- are not JSON are an error naming the derivation.  Upstream constructs one+-- for every derivation it has a goal for, before it looks at the outputs+-- (@DerivationGoal::haveDerivation@).+derivationAttrs :: StorePath -> Derivation -> Either Text DerivationAttrs+derivationAttrs drvPath drv = case Map.lookup structuredAttrsKey env of+  Nothing -> Right (AttrsInEnvironment env)+  Just encoded -> AttrsInJson <$> first unreadable (first (const "invalid UTF-8") (TE.decodeUtf8' encoded) >>= parseJson)+  where+    env = drvEnv drv+    unreadable reason =+      "cannot process " <> structuredAttrsKey <> " attribute of '" <> storePathBasename drvPath <> "': " <> reason++-- | Upstream's @always-allow-substitutes@ setting.+data SubstitutesSetting+  = -- | A derivation's @allowSubstitutes@ attribute decides, upstream's+    -- default.+    HeedAllowSubstitutes+  | -- | Every derivation may be substituted, whatever its attribute says.+    AlwaysAllowSubstitutes+  deriving (Eq, Show)++-- | Whether a derivation's own outputs may come from a cache.+data Substitutes+  = MaySubstitute+  | MustBuild+  deriving (Eq, Show)++-- | The attribute a derivation forbids substitutes with.+allowSubstitutesAttr :: Text+allowSubstitutesAttr = "allowSubstitutes"++-- | The one environment value upstream's @getBoolAttr@ reads as true, which+-- is how evaluation writes @true@; @false@ is written as the empty string.+environmentTrue :: ByteString+environmentTrue = "1"++-- | Upstream's @ParsedDerivation::getBoolAttr@ in parsed-derivations.cc at+-- 2.24.9 (@getBoolAttr@ in derivation-options.cc at 2.36.0), for the+-- derivation at a @.drv@ path: the default when the derivation lacks the+-- attribute.  In structured attributes it is a JSON Boolean, and any other+-- value there is an error; in the environment only @1@ is true.  Structured+-- attributes that are not a JSON object hold no attribute, as nlohmann's+-- @find@ finds nothing in such a value.+derivationBoolAttr :: StorePath -> Text -> Bool -> DerivationAttrs -> Either Text Bool+derivationBoolAttr _ name def (AttrsInEnvironment env) =+  Right (maybe def (== environmentTrue) (Map.lookup name env))+derivationBoolAttr drvPath name def (AttrsInJson (JsonObject members)) =+  maybe (Right def) fromJson (Map.lookup name members)+  where+    fromJson (JsonBool flag) = Right flag+    fromJson _ =+      Left ("attribute '" <> name <> "' of derivation '" <> storePathBasename drvPath <> "' must be a Boolean")+derivationBoolAttr _ _ def (AttrsInJson _) = Right def++-- | Upstream's @getStringAttr@ (derivation-options.cc at 2.36.0), for+-- the derivation at a @.drv@ path: 'Nothing' when the derivation lacks+-- the attribute.  In the environment it is the variable's bytes; in+-- structured attributes it is a JSON string, its UTF-8 bytes, and any+-- other value there is upstream's refusal ('attributeRefusal').+derivationStringAttr :: StorePath -> Text -> DerivationAttrs -> Either Text (Maybe ByteString)+derivationStringAttr _ name (AttrsInEnvironment env) = Right (Map.lookup name env)+derivationStringAttr drvPath name (AttrsInJson (JsonObject members)) =+  traverse (first (attributeRefusal drvPath name) . fmap TE.encodeUtf8 . expectJson "string" jsonString) (Map.lookup name members)+derivationStringAttr _ _ (AttrsInJson _) = Right Nothing++-- | Upstream's @getStringSetAttr@ (derivation-options.cc at 2.36.0), for+-- the derivation at a @.drv@ path: 'Nothing' when the derivation lacks+-- the attribute.  In the environment it is the variable's bytes split at+-- spaces, tabs, carriage returns and newlines, upstream's+-- @tokenizeString@ separators, with no empty token; in structured+-- attributes it is a JSON array of strings, and anything else there is+-- upstream's refusal of the first value of the wrong type+-- ('attributeRefusal').+derivationStringsAttr :: StorePath -> Text -> DerivationAttrs -> Either Text (Maybe [ByteString])+derivationStringsAttr _ name (AttrsInEnvironment env) =+  Right (filter (not . BS.null) . BS.splitWith (`BS.elem` tokenSeparators) <$> Map.lookup name env)+  where+    tokenSeparators = " \t\n\r"+derivationStringsAttr drvPath name (AttrsInJson (JsonObject members)) =+  traverse (first (attributeRefusal drvPath name) . strings) (Map.lookup name members)+  where+    strings value = expectJson "array" jsonArray value >>= traverse (fmap TE.encodeUtf8 . expectJson "string" jsonString)+    jsonArray value = case value of+      JsonArray items -> Just items+      _ -> Nothing+derivationStringsAttr _ _ (AttrsInJson _) = Right Nothing++-- | A JSON value's text, when it is a string.+jsonString :: Json -> Maybe Text+jsonString value = case value of+  JsonString text -> Just text+  _ -> Nothing++-- | Upstream's refusal of an attribute of the wrong type in structured+-- attributes, with the two lines of context upstream puts before it, the+-- derivation's and the attribute's (@derivationOptionsFromStructuredAttrs@+-- and its caller in derivation-building-goal.cc at 2.36.0), on one line+-- as nova-nix reports such context.+attributeRefusal :: StorePath -> Text -> Text -> Text+attributeRefusal drvPath name refusal =+  "while parsing derivation '" <> storePathToText defaultStoreDir drvPath <> "': while parsing attribute \"" <> name <> "\": " <> refusal++-- | Upstream's @ParsedDerivation::substitutesAllowed@ at 2.24.9, for the+-- derivation at a @.drv@ path.  Under 'AlwaysAllowSubstitutes' every+-- derivation may be substituted and the attribute is not read.  Otherwise+-- @allowSubstitutes@ decides ('derivationBoolAttr'), and a derivation+-- without it may be substituted.+--+-- The rule covers a derivation's own outputs alone.  A path that another+-- substituted output references is substituted as a path, whichever+-- derivation built it: upstream's @PathSubstitutionGoal@ never reads the+-- attribute.+substitutesAllowed :: SubstitutesSetting -> StorePath -> DerivationAttrs -> Either Text Substitutes+substitutesAllowed AlwaysAllowSubstitutes _ _ = Right MaySubstitute+substitutesAllowed HeedAllowSubstitutes drvPath attrs =+  (\allowed -> if allowed then MaySubstitute else MustBuild) <$> derivationBoolAttr drvPath allowSubstitutesAttr True attrs++-- ---------------------------------------------------------------------------+-- Realising a graph+-- ---------------------------------------------------------------------------++-- | What a failed substitute leads to: upstream's @fallback@ setting, which+-- its @--fallback@ flag turns on.+data Fallback+  = -- | The build stops and names @--fallback@, upstream's default.+    NoFallback+  | -- | The derivation builds from source instead.+    BuildFromSource+  deriving (Eq, Show)++-- | What a build does with the derivation it was asked for: upstream's+-- @BuildMode@, less @bmRepair@.+data BuildMode+  = -- | Make its outputs valid, upstream's @bmNormal@.+    BuildNormal+  | -- | Build it again beside its valid outputs and compare each with the+    -- one the store holds: upstream's @bmCheck@.+    BuildCheck+  deriving (Eq, Show)++-- | The settings that decide how a graph is realised, as upstream's+-- @fallback@ and @always-allow-substitutes@ do.  What is done with the+-- derivation asked for is the 'BuildMode' a call to 'realise' is given,+-- as upstream's @Store::buildPaths@ is given its mode with each call.+data RealiseSettings = RealiseSettings+  { rsFallback :: !Fallback,+    rsSubstitutes :: !SubstitutesSetting+  }+  deriving (Eq, Show)++-- | Why realising a graph stopped.+data RealiseFailure+  = -- | A derivation failed to build, with the builder's report.+    BuildFailed !Text+  | -- | A cache could not be asked about a path ('QueryFailed').+    CacheQueryFailed !Text+  | -- | A substitute for this derivation's outputs, or for something they+    -- reference, failed under 'NoFallback'.+    SubstitutesFailed !StorePath+  | -- | A derivation's attributes could not be read ('derivationAttrs',+    -- 'substitutesAllowed').+    InvalidDerivation !Text+  | -- | Under 'BuildCheck', this derivation has an output that is not+    -- valid and that no cache supplied, so a rebuild has nothing to be+    -- compared with.+    OutputsNotValid !StorePath+  | -- | Under 'BuildCheck', rebuilding this derivation gave this output+    -- other contents than the store holds, and the rebuild was kept or+    -- discarded ('OutputDiffers').+    NotDeterministic !StorePath !StorePath !DifferingRebuild+  | -- | Under 'BuildCheck', the graph holds no derivation at the root, so+    -- nothing was built again or compared.+    MissingDerivation !StorePath+  | -- | A dependent asked this derivation for outputs it does not have,+    -- named in order.+    MissingOutputs !StorePath !(NonEmpty Text)+  | -- | A fixed-output derivation's output was refused, with the+    -- builder's report: upstream's @HashMismatch@.+    FixedOutputRejected !Text+  deriving (Eq, Show)++-- | How a derivation's build failed ('reBuild').+data FailedBuild+  = -- | The builder failed, or what it left was refused, with the report.+    BuilderStopped !Text+  | -- | A fixed output had other contents than the derivation fixes, or+    -- referenced a store path, with the report.+    FixedOutputMismatch !Text+  deriving (Eq, Show)++-- | A failure as the build reports it, given the directory the store's+-- files are in, each in upstream's words: a failed substitute less the+-- space upstream's message ends in, a check that cannot start, a check+-- that found a difference, with each path in double quotes as upstream+-- quotes a path and the rebuilt output named where it was kept, a root+-- the graph does not hold as upstream reports a derivation it cannot+-- load, and an output asked of a derivation that does not have it.+--+-- A @.drv@ is named under the logical store directory, wherever the+-- store's files live, as upstream names one: a store kept elsewhere+-- still has @/nix/store@ as its store directory, and only the directory+-- its files are in moves.  The output that differs is named where its+-- files are, as upstream names it, which is also how a build prints the+-- output it made.+realiseFailureMessage :: StoreDir -> RealiseFailure -> Text+realiseFailureMessage realDir failure = case failure of+  BuildFailed report -> report+  FixedOutputRejected report -> report+  CacheQueryFailed queryFailure -> queryFailure+  InvalidDerivation problem -> problem+  SubstitutesFailed drvPath ->+    "some substitutes for the outputs of derivation '"+      <> logical drvPath+      <> "' failed (usually happens due to networking issues); try '--fallback' to build derivation from source"+  OutputsNotValid drvPath ->+    "some outputs of '" <> logical drvPath <> "' are not valid, so checking is not possible"+  NotDeterministic drvPath output rebuild ->+    "derivation '"+      <> logical drvPath+      <> "' may not be deterministic: output "+      <> quotedPath (storePathToFilePath realDir output)+      <> " differs"+      <> case rebuild of+        RebuildDiscarded -> ""+        RebuildKept -> " from " <> quotedPath (checkedOutputPath realDir output)+  MissingDerivation drvPath ->+    "cannot build missing derivation '" <> logical drvPath <> "'"+  MissingOutputs drvPath names ->+    "derivation '" <> logical drvPath <> "' does not have wanted outputs " <> T.intercalate ", " ["'" <> name <> "'" | name <- NE.toList names]+  where+    logical = storePathToText defaultStoreDir+    quotedPath path = "\"" <> T.pack path <> "\""++-- | Upstream's exit status for a build whose one failure is a check that+-- found a difference: the check-mismatch bit and the two bits every status+-- @Worker::failingExitStatus@ composes carries, @0x08 | 0x60@ (worker.cc at+-- 2.24.9).+checkMismatchStatus :: Int+checkMismatchStatus = 104++-- | The exit status of a build that failed any other way.+failureStatus :: Int+failureStatus = 1++-- | The exit status of a build that stopped with this failure.  A check+-- that found a difference exits with upstream's status for one, so a+-- caller can tell it from a build that broke.  Every other failure exits+-- 1, as upstream's does except a failed build's ('BuildFailed'), whose+-- status there says more: 100 when the builder of a derivation that is not+-- fixed-output fails, 102 when a fixed output has the wrong hash.+realiseFailureStatus :: RealiseFailure -> Int+realiseFailureStatus failure = case failure of+  NotDeterministic {} -> checkMismatchStatus+  BuildFailed _ -> failureStatus+  FixedOutputRejected _ -> failureStatus+  CacheQueryFailed _ -> failureStatus+  SubstitutesFailed _ -> failureStatus+  InvalidDerivation _ -> failureStatus+  OutputsNotValid _ -> failureStatus+  MissingDerivation _ -> failureStatus+  MissingOutputs _ _ -> failureStatus++-- | How one derivation came to be realised.+data Realised+  = -- | Every output asked of it was already valid.+    AlreadyValid+  | -- | Every output asked of it came from a cache.+    Substituted+  | -- | The derivation was built here.+    Built+  | -- | The derivation was built again here, and every output came out as+    -- the store holds it ('BuildCheck').+    Checked+  deriving (Eq, Show)++-- | What building a derivation again beside its valid outputs found.+data CheckVerdict+  = -- | Every output came out as the store holds it.+    OutputsMatch+  | -- | This output came out with other contents, and its rebuild was+    -- kept or discarded.  It is the first that did, in the order the+    -- outputs are compared in.+    OutputDiffers !StorePath !DifferingRebuild+  deriving (Eq, Show)++-- | What became of a rebuilt output that differs from the valid one.+data DifferingRebuild+  = -- | It was discarded with everything else the rebuild wrote.+    RebuildDiscarded+  | -- | It was kept beside the valid output ('checkedOutputPath'), as+    -- upstream keeps it under @keep-failed@.+    RebuildKept+  deriving (Eq, Show)++-- | Where a check keeps the rebuild of an output that differs, given the+-- directory the store's files are in: the output's path with @.check@+-- after it, where upstream keeps it.  Nothing registers it, so it is not+-- a valid path.+checkedOutputPath :: StoreDir -> StorePath -> FilePath+checkedOutputPath realDir output = storePathToFilePath realDir output <> ".check"++-- | What realising a graph needs from the outside.+data RealiseEffects s m = RealiseEffects+  { -- | The store and caches, which also say whether an output is valid.+    reSubst :: !(SubstEffects s m),+    -- | Build one derivation, whose inputs are realised, given its @.drv@+    -- path and the outputs the request that led to the build asks of it.+    -- A build makes every output, so the store's builder leaves those+    -- unread; they say what the build was for.+    reBuild :: !(Derivation -> StorePath -> Set Text -> m (Either FailedBuild ())),+    -- | Build one derivation, whose outputs are valid and whose inputs are+    -- realised, again beside those outputs, given its @.drv@ path, and+    -- compare what comes out with what the store holds.  It registers+    -- nothing, and keeps nothing it built but a rebuild that differs,+    -- where the verdict says it was kept.+    reCheck :: !(Derivation -> StorePath -> m (Either Text CheckVerdict)),+    -- | Report how a derivation was realised.+    reReport :: !(Realised -> Derivation -> m ())+  }++-- | Realise a graph from its root, or under 'BuildCheck' check the root+-- ('checkRoot').  Every other derivation in the graph is realised as+-- under 'BuildNormal', whatever the mode.  A derivation that is valid or+-- substituted takes its inputs out of the work, and what remains builds+-- leaves first.+--+-- Each derivation is realised for the outputs asked of it, as upstream's+-- goal for it is (@DerivationGoal@'s @wantedOutputs@ at 2.24.9): the root+-- for every output, and each input for the outputs its dependent names+-- ('dnDeps').  Only those are checked for validity and substituted+-- (@checkPathValidity@, @haveDerivation@), so an output nothing asks for+-- is neither fetched nor a reason to build, and asking for one the+-- derivation does not have fails ('MissingOutputs').  A build makes+-- every output.+--+-- The graph has to be acyclic ('Nix.DependencyGraph.topoSort' decides that).+realise :: (Monad m) => RealiseSettings -> BuildMode -> RealiseEffects s m -> DepGraph -> StorePath -> m (Either RealiseFailure ())+realise settings mode effects graph root = case mode of+  BuildNormal -> bimap stoppedFailure (const ()) <$> realiseNode settings effects graph nothingRealised (root, everyOutput)+  BuildCheck -> first stoppedFailure <$> checkRoot settings effects graph root+  where+    everyOutput = maybe Set.empty (outputNames . dnDerivation) (Map.lookup root (unDepGraph graph))++-- | What has been realised so far: the outputs of each derivation, those+-- a request for them found valid or substituted and every output of one+-- that was built, and how each derivation was last realised.+data RealisedOutputs = RealisedOutputs+  { roOutputs :: !(Map StorePath (Set Text)),+    roStatuses :: !(Map StorePath Realised)+  }++-- | Nothing realised yet.+nothingRealised :: RealisedOutputs+nothingRealised = RealisedOutputs Map.empty Map.empty++-- | Record outputs of a derivation as realised.+withOutputs :: StorePath -> Set Text -> RealisedOutputs -> RealisedOutputs+withOutputs node outputs realised = realised {roOutputs = Map.insertWith Set.union node outputs (roOutputs realised)}++-- | Where realising stopped: the derivation whose own realisation+-- failed, why, and what had been realised by then.+data Stopped = Stopped !StorePath !RealiseFailure !RealisedOutputs++-- | Why realising stopped.+stoppedFailure :: Stopped -> RealiseFailure+stoppedFailure (Stopped _ failure _) = failure++-- | The names of a derivation's outputs.+outputNames :: Derivation -> Set Text+outputNames = Set.fromList . map doName . drvOutputs++-- | The paths of a derivation's outputs that have one of the names.+namedOutputPaths :: Set Text -> Derivation -> [StorePath]+namedOutputPaths names drv = [doPath output | output <- drvOutputs drv, doName output `Set.member` names]++-- | Whether every one of the paths is valid.+allValid :: (Monad m) => RealiseEffects s m -> [StorePath] -> m Bool+allValid effects = fmap and . traverse (seValid (reSubst effects))++-- | Check the root: upstream's @DerivationGoal@ under @bmCheck@ at 2.24.9.+--+-- An output that is not valid is substituted first, as under any mode+-- (@haveDerivation@ starts the substitution goals before it looks at the+-- mode again), and a derivation still short of an output cannot be checked+-- (@outputsSubstitutionTried@).  That error comes before any input is+-- looked at, so a substitute with a hole in its closure is not retried+-- here as 'realiseNode' retries it.+--+-- With every output valid the inputs are realised as under 'BuildNormal'+-- (@gaveUpOnSubstitution@ gives each input's goal @bmNormal@): the rebuild+-- needs them, and a root that was substituted never fetched them.  Then+-- the derivation is built again and compared ('reCheck').+--+-- @allowSubstitutes@ is read whether or not the outputs are valid, where+-- 'realiseNode' leaves it unread for a valid derivation: upstream reads it+-- before it starts a substitution goal for each output, a valid one+-- included, and such a goal ends at once.+--+-- A root the graph does not hold fails the check, where 'realiseNode' has+-- nothing to realise for such a node: a check that compared nothing has+-- not passed.+checkRoot :: (Monad m) => RealiseSettings -> RealiseEffects s m -> DepGraph -> StorePath -> m (Either Stopped ())+checkRoot settings effects graph root = case Map.lookup root (unDepGraph graph) of+  Nothing -> pure (rootFailed (MissingDerivation root))+  Just depNode ->+    let drv = dnDerivation depNode+     in either (pure . rootFailed . InvalidDerivation) (checkAllowed depNode) $+          derivationAttrs root drv >>= substitutesAllowed (rsSubstitutes settings) root+  where+    rootFailed failure = Left (Stopped root failure nothingRealised)+    checkAllowed depNode allowed = do+      let drv = dnDerivation depNode+          outputs = map doPath (drvOutputs drv)+      valid <- allValid effects outputs+      if valid+        then rebuild depNode+        else do+          substituted <- outputsFromCaches effects allowed outputs+          case (substituted, substitutionStop (rsFallback settings) root substituted) of+            (ClosureComplete, _) -> reReport effects Substituted drv *> rebuild depNode+            (_, Just failure) -> pure (rootFailed failure)+            (_, Nothing) -> pure (rootFailed (OutputsNotValid root))+    rebuild depNode = do+      let drv = dnDerivation depNode+      inputs <- realiseAll settings effects graph (withOutputs root (outputNames drv) nothingRealised) (Map.toList (dnDeps depNode))+      case inputs of+        Left stopped -> pure (Left stopped)+        Right _ -> reCheck effects drv root >>= either (pure . rootFailed . BuildFailed) (checked drv)+    checked drv OutputsMatch = Right () <$ reReport effects Checked drv+    checked _ (OutputDiffers output differing) = pure (rootFailed (NotDeterministic root output differing))++-- | Substitute outputs of a derivation, if it may be substituted.  One+-- that must build asks no cache, which leaves it where one that no cache+-- holds is: upstream starts no substitution for it.+outputsFromCaches :: (Monad m) => RealiseEffects s m -> Substitutes -> [StorePath] -> m ClosureOutcome+outputsFromCaches _ MustBuild _ = pure ClosureUnavailable+outputsFromCaches effects MaySubstitute outputs = substituteClosure (reSubst effects) outputs++-- | Where a request for some of a derivation's outputs stands before+-- anything is substituted or built for it.+data Assessment+  = -- | Nothing is left to realise: the graph does not hold the+    -- derivation, or the outputs asked of it are realised already.+    NothingToRealise+  | -- | Every output asked of the derivation is valid.+    OutputsValid !DepNode+  | -- | Some output asked of the derivation is not valid.  The paths are+    -- those of every output asked, and the derivation may or may not be+    -- substituted.+    OutputsWanted !DepNode ![StorePath] !Substitutes++-- | Assess a request against what has been realised so far, reading what+-- upstream's goal for it reads before it asks any cache+-- (@DerivationGoal::haveDerivation@ at 2.24.9): the derivation's+-- attributes, whether it has every output asked, whether those are valid,+-- and, when one is not, whether the derivation may be substituted.  A node+-- outside the graph has nothing to realise.+assess ::+  (Monad m) =>+  RealiseSettings ->+  RealiseEffects s m ->+  DepGraph ->+  RealisedOutputs ->+  (StorePath, Set Text) ->+  m (Either RealiseFailure Assessment)+assess settings effects graph realised (node, wanted) = case Map.lookup node (unDepGraph graph) of+  Nothing -> pure (Right NothingToRealise)+  Just depNode+    | wanted `Set.isSubsetOf` Map.findWithDefault Set.empty node (roOutputs realised) -> pure (Right NothingToRealise)+    | otherwise -> either (pure . Left . InvalidDerivation) (parsed depNode) (derivationAttrs node (dnDerivation depNode))+  where+    parsed depNode attrs = case NE.nonEmpty (Set.toAscList (wanted `Set.difference` outputNames drv)) of+      Just absent -> pure (Left (MissingOutputs node absent))+      Nothing -> do+        valid <- allValid effects outputs+        pure $+          if valid+            then Right (OutputsValid depNode)+            else first InvalidDerivation (OutputsWanted depNode outputs <$> substitutesAllowed (rsSubstitutes settings) node attrs)+      where+        drv = dnDerivation depNode+        outputs = namedOutputPaths wanted drv++-- | Realise one node for the outputs asked of it, threading what has been+-- realised so far.  A request for outputs already realised does nothing,+-- so a derivation several others ask the same of is realised once.  One+-- asking for an output not yet realised realises the node again, for the+-- outputs it asks for: upstream's worker drops a goal once it is done+-- (@Goal::amDone@ at 2.24.9), so a later request for the derivation starts+-- a goal of its own (@Worker::makeDerivationGoalCommon@).  A request is+-- recorded before the inputs are realised, so a cycle, which+-- 'Nix.DependencyGraph.topoSort' refuses, still ends.+realiseNode ::+  (Monad m) =>+  RealiseSettings ->+  RealiseEffects s m ->+  DepGraph ->+  RealisedOutputs ->+  (StorePath, Set Text) ->+  m (Either Stopped RealisedOutputs)+realiseNode settings effects graph realised request@(node, wanted) =+  assess settings effects graph realised request >>= either (pure . failedWith realised) realiseAssessed+  where+    failedWith done failure = Left (Stopped node failure done)+    seen = withOutputs node wanted realised+    stopFor = substitutionStop (rsFallback settings) node+    reported status drv done = Right done {roStatuses = Map.insert node status (roStatuses done)} <$ reReport effects status drv+    realiseAssessed NothingToRealise = pure (Right realised)+    realiseAssessed (OutputsValid depNode) = reported AlreadyValid (dnDerivation depNode) seen+    realiseAssessed (OutputsWanted depNode outputs allowed) = substituteOrBuild depNode outputs allowed+    substituteOrBuild depNode outputs allowed = do+      let substituteOutputs = outputsFromCaches effects allowed outputs+      firstTry <- substituteOutputs+      case (firstTry, stopFor firstTry) of+        (ClosureComplete, _) -> reported Substituted (dnDerivation depNode) seen+        (_, Just failure) -> pure (failedWith realised failure)+        (_, Nothing) -> buildFromInputs substituteOutputs firstTry depNode+    buildFromInputs substituteOutputs firstTry depNode = do+      let drv = dnDerivation depNode+      inputs <- realiseAll settings effects graph seen (Map.toList (dnDeps depNode))+      case inputs of+        Left stopped -> pure (Left stopped)+        Right done -> do+          -- The inputs may have supplied what the closure lacked, and then+          -- the substitute is still good (upstream's retrySubstitution).+          retried <- case firstTry of+            ClosureIncomplete -> substituteOutputs+            other -> pure other+          case (retried, stopFor retried) of+            (ClosureComplete, _) -> reported Substituted drv done+            (_, Just failure) -> pure (failedWith done failure)+            (_, Nothing) -> do+              built <- reBuild effects drv node wanted+              case built of+                Left (BuilderStopped report) -> pure (failedWith done (BuildFailed report))+                Left (FixedOutputMismatch report) -> pure (failedWith done (FixedOutputRejected report))+                Right () -> reported Built drv done {roOutputs = Map.insert node (outputNames drv) (roOutputs done)}++-- | The failure a substitution attempt for a derivation stops the build+-- with, if it stops it: a failed query always, and a failed substitute+-- unless the derivation may build from source.  Upstream retries a+-- substitution after the inputs only when every failure was a hole in the+-- closure, so a failed substitute that falls back is not retried.+substitutionStop :: Fallback -> StorePath -> ClosureOutcome -> Maybe RealiseFailure+substitutionStop fallback drvPath outcome = case outcome of+  ClosureQueryFailed failure -> Just (CacheQueryFailed failure)+  ClosureFailed -> case fallback of+    NoFallback -> Just (SubstitutesFailed drvPath)+    BuildFromSource -> Nothing+  ClosureComplete -> Nothing+  ClosureUnavailable -> Nothing+  ClosureIncomplete -> Nothing++-- | Realise nodes in order, each for the outputs asked of it, stopping at+-- the first failure.+realiseAll ::+  (Monad m) =>+  RealiseSettings ->+  RealiseEffects s m ->+  DepGraph ->+  RealisedOutputs ->+  [(StorePath, Set Text)] ->+  m (Either Stopped RealisedOutputs)+realiseAll _ _ _ realised [] = pure (Right realised)+realiseAll settings effects graph realised (request : rest) = do+  outcome <- realiseNode settings effects graph realised request+  case outcome of+    Left stopped -> pure (Left stopped)+    Right deeper -> realiseAll settings effects graph deeper rest++-- ---------------------------------------------------------------------------+-- Realising several requests+-- ---------------------------------------------------------------------------++-- | Why realising several requests stopped, as upstream's+-- @Store::buildPaths@ reports it (entry-points.cc at 2.24.9,+-- @Worker::buildPaths@ there at 2.36.0).+data RequestsFailure+  = -- | The call failed with this, reported as it is: a failure that ends+    -- the whole call, as one upstream's goals throw does, or one that ended+    -- a request when every other request was realised.+    FailedWith !RealiseFailure+  | -- | The request for this derivation failed with this, and left the+    -- requests for these others unrealised.  Upstream logs the failure,+    -- then fails the call naming every request its worker did not finish.+    FailedLeaving !RealiseFailure !StorePath !(NonEmpty StorePath)+  deriving (Eq, Show)++-- | A failure as the call reports it, given the directory the store's+-- files are in: the failure's own message ('realiseFailureMessage'), or+-- upstream's @build of %s failed@, which names the request that failed+-- and the others it left unrealised in the order of their paths, as+-- upstream's sorted set of them lists them, each under the logical store+-- directory.  The failure that left them is what upstream logs before it.+requestsFailureMessage :: StoreDir -> RequestsFailure -> Text+requestsFailureMessage realDir (FailedWith failure) = realiseFailureMessage realDir failure+requestsFailureMessage _ (FailedLeaving _ failed others) =+  "build of " <> T.intercalate ", " (map quoted (Set.toAscList (Set.fromList (failed : NE.toList others)))) <> " failed"+  where+    quoted drvPath = "'" <> storePathToText defaultStoreDir drvPath <> "'"++-- | The exit status of a call that stopped with this failure: the+-- failure's own ('realiseFailureStatus'), however it is reported.+-- Upstream gives a failed request's report the status its worker composes+-- from what failed in the call (@Worker::failingExitStatus@ in worker.cc+-- at 2.24.9, @ExitStatusFlags::failingExitStatus@ in build-result.cc at+-- 2.36.0), and a call here stops at its first failure, so that is the one+-- failure's.  An error upstream's goals throw keeps its own status, 1+-- (@ErrorInfo@'s @status@ in error.hh), which 'realiseFailureStatus'+-- gives each of them.+requestsFailureStatus :: RequestsFailure -> Int+requestsFailureStatus (FailedWith failure) = realiseFailureStatus failure+requestsFailureStatus (FailedLeaving failure _ _) = realiseFailureStatus failure++-- | How far a failure reaches in upstream's worker.+data FailureReach+  = -- | It ends the request it arose in, and with it the call, as a failed+    -- goal does, and @Store::buildPaths@ reports it among the requests+    -- its worker left unrealised.+    EndsRequest+  | -- | It ends the call where it arises, as an error upstream's goals+    -- throw does: its worker does not catch one (@Worker::run@ in+    -- worker.cc), so it leaves @buildPaths@ as it is.+    EndsCall++-- | How far a failure reaches.  A cache that cannot be asked is rethrown+-- (@PathSubstitutionGoal::init@ in substitution-goal.cc at 2.24.9), and+-- attributes that cannot be read, an output a derivation does not have and+-- a check of outputs that are not valid are thrown (@haveDerivation@,+-- @checkPathValidity@ and @outputsSubstitutionTried@ of @DerivationGoal@+-- in derivation-goal.cc at 2.24.9).  A failed build or check, a failed+-- substitute and a derivation that cannot be loaded end their goal+-- (@buildDone@, @outputsSubstitutionTried@ and @loadDerivation@ there).+failureReach :: RealiseFailure -> FailureReach+failureReach failure = case failure of+  BuildFailed _ -> EndsRequest+  FixedOutputRejected _ -> EndsRequest+  SubstitutesFailed _ -> EndsRequest+  NotDeterministic {} -> EndsRequest+  MissingDerivation _ -> EndsRequest+  CacheQueryFailed _ -> EndsCall+  InvalidDerivation _ -> EndsCall+  MissingOutputs _ _ -> EndsCall+  OutputsNotValid _ -> EndsCall++-- | Realise several derivations, each for the outputs a request asks of+-- it, with one record of what is realised, so that a derivation is not+-- realised again for outputs one request, or an input of one, has+-- already realised.  Upstream's @Store::buildPaths@ makes a goal for each+-- request and runs them with one worker (entry-points.cc at 2.24.9),+-- which keeps one goal for a derivation: requests that name the same+-- derivation share it, and it wants every output any of them asks for+-- (@Worker::makeDerivationGoalCommon@ in worker.cc at 2.24.9).  Such+-- requests are realised here as one request for all those outputs.+--+-- Every request is assessed before any is realised, as the worker's first+-- pass works every goal until it waits for a substitute, an input or a+-- build (@Worker::run@ in worker.cc): one whose outputs are valid is realised+-- there, and one whose derivation's attributes cannot be read, that asks for+-- an output the derivation does not have, or that has an output that is not+-- valid and an @allowSubstitutes@ that cannot be read stops the call before+-- any substitute or build has finished (@DerivationGoal::haveDerivation@ in+-- derivation-goal.cc at 2.24.9).  Both passes take the requests in the order+-- upstream's worker takes their goals, by the derivation's name and then its+-- path (@DerivationGoal::key@ in derivation-goal.cc), so a failure two+-- requests could report is the one upstream's reports.+--+-- The first failure stops the call, as a failed goal ends every other+-- unless @keep-going@ is set (@Worker::removeGoal@ in worker.cc),+-- which nova-nix does not offer.  One that upstream's goals throw, such+-- as a cache that cannot be asked, is reported as it is.  Any other is+-- reported as it is when every other request was realised, and otherwise+-- with the request that failed and each after it whose outputs are not+-- valid, which upstream's worker had not finished (@Store::buildPaths@ in+-- entry-points.cc at 2.24.9).  That worker runs the goals that wait for+-- substitutes and builds together, so which of them it has finished when one+-- fails depends on how their work interleaves; realising them in turn answers+-- as upstream does when each request's work ends before the next one's+-- begins.+--+-- The requests are realised and never checked, as import from derivation+-- builds its requests under @bmNormal@ (@EvalState::realiseContext@ in+-- primops.cc): a check is of one derivation, which 'realise' checks+-- under 'BuildCheck'.  A derivation the graph does not hold has nothing+-- to realise, as for 'realise', and the graph has to be acyclic.+realiseRequests ::+  (Monad m) =>+  RealiseSettings ->+  RealiseEffects s m ->+  DepGraph ->+  [(StorePath, Set Text)] ->+  m (Either RequestsFailure ())+realiseRequests settings effects graph requests = maybe (Right ()) Left . runStop <$> realiseRun settings effects graph requests++-- | How a request ended.+data RequestOutcome+  = -- | Its outputs were realised, as this says.+    RequestRealised !Realised+  | -- | It failed with this.+    RequestFailed !RealiseFailure+  | -- | The derivation at this path, one it needs and no request asked+    -- for, failed with this, so it was not realised.+    RequestDependencyFailed !StorePath !RealiseFailure+  deriving (Eq, Show)++-- | Realise several requests as 'realiseRequests' does, and say how each+-- derivation asked for ended, as upstream's results for them say: realised,+-- as the last of its realisations in the call says, which for one built+-- as another's input is built; failed; or not realised because a+-- derivation it needs failed.  Under 'BuildCheck' each derivation is+-- checked instead, every output of it, as 'realise' checks one, in the+-- order the requests are realised in.  A request left unrealised when+-- another failed is not there, as upstream leaves out of its results a+-- goal that never finished, and neither is one that needs a derivation+-- another request asked for that failed.  A failure that ends the whole+-- call, as one upstream's goals throw does, is the answer itself.+realiseEach ::+  (Monad m) =>+  RealiseSettings ->+  BuildMode ->+  RealiseEffects s m ->+  DepGraph ->+  [(StorePath, Set Text)] ->+  m (Either RealiseFailure (Map StorePath RequestOutcome))+realiseEach settings mode effects graph requests = case mode of+  BuildNormal -> outcomesOf <$> realiseRun settings effects graph requests+  BuildCheck -> checkInTurn Map.empty (sortOn goalOrder (Set.toList (Set.fromList (map fst requests))))+  where+    outcomesOf run = case runStop run of+      Just (FailedWith failure) | EndsCall <- failureReach failure -> Left failure+      _ -> Right (runOutcomes run)+    checkInTurn outcomes [] = pure (Right outcomes)+    checkInTurn outcomes (root : rest) =+      checkRoot settings effects graph root >>= \case+        Left (Stopped failedAt failure _)+          | EndsCall <- failureReach failure -> pure (Left failure)+          | failedAt == root -> pure (Right (Map.insert root (RequestFailed failure) outcomes))+          | otherwise -> pure (Right (Map.insert root (RequestDependencyFailed failedAt failure) outcomes))+        Right () -> checkInTurn (Map.insert root (RequestRealised Checked) outcomes) rest++-- | The order upstream's worker takes derivations' goals in: by the+-- derivation's name, then its path.+goalOrder :: StorePath -> (Text, StorePath)+goalOrder drvPath = (spName drvPath, drvPath)++-- | What realising several requests came to: how each derivation asked+-- for that ended did, and the failure that stopped the call, if one did.+data RequestsRun = RequestsRun+  { runOutcomes :: !(Map StorePath RequestOutcome),+    runStop :: !(Maybe RequestsFailure)+  }++-- | Realise several requests ('realiseRequests'), keeping how each ended.+realiseRun ::+  (Monad m) =>+  RealiseSettings ->+  RealiseEffects s m ->+  DepGraph ->+  [(StorePath, Set Text)] ->+  m RequestsRun+realiseRun settings effects graph requests = do+  firstPass <- runExceptT (traverse assessRequest (sortOn (goalOrder . fst) (Map.toList (Map.fromListWith Set.union requests))))+  case firstPass of+    Left (node, failure) -> pure (RequestsRun (Map.singleton node (RequestFailed failure)) (Just (FailedWith failure)))+    Right assessments -> do+      let valid = [(request, depNode) | (request, OutputsValid depNode) <- assessments]+      mapM_ (reReport effects AlreadyValid . dnDerivation . snd) valid+      inTurn+        (RealisedOutputs (Map.fromList (map fst valid)) (Map.fromList [(node, AlreadyValid) | ((node, _), _) <- valid]))+        (Map.fromList [(node, RequestRealised AlreadyValid) | ((node, _), _) <- valid])+        [(request, outputs) | (request, OutputsWanted _ outputs _) <- assessments]+  where+    assessRequest request@(node, _) = (,) request <$> ExceptT (first (node,) <$> assess settings effects graph nothingRealised request)+    asked = Set.fromList (map fst requests)+    inTurn _ outcomes [] = pure (RequestsRun outcomes Nothing)+    inTurn realised outcomes ((request@(node, _), _) : rest) =+      realiseNode settings effects graph realised request >>= \case+        Left (Stopped failedAt failure progress) -> RequestsRun (failedOutcome node failedAt failure (finishedAmong progress rest outcomes)) . Just <$> stoppedAt request rest failure+        Right advanced -> inTurn advanced (Map.insert node (RequestRealised (statusOf node advanced)) outcomes) rest+    -- A failure is the request's whose own derivation failed: this one's,+    -- or an input's another request asked for, which leaves this one+    -- unfinished, as upstream's worker stops once a requested goal fails;+    -- an input no request asked for leaves this one not realised.+    failedOutcome node failedAt failure+      | failedAt == node || failedAt `Set.member` asked = Map.insert failedAt (RequestFailed failure)+      | otherwise = Map.insert node (RequestDependencyFailed failedAt failure)+    -- A request with nothing to realise has its outputs valid already.+    statusOf node = Map.findWithDefault AlreadyValid node . roStatuses+    -- The requests after a failure whose outputs were realised already,+    -- as inputs of earlier ones or of the one that failed, which+    -- upstream's goals for them finished.+    finishedAmong realised rest outcomes =+      foldr+        (\((node, wanted), _) -> if wanted `Set.isSubsetOf` Map.findWithDefault Set.empty node (roOutputs realised) then Map.insert node (RequestRealised (statusOf node realised)) else id)+        outcomes+        rest+    stoppedAt (node, _) rest failure = case failureReach failure of+      EndsCall -> pure (FailedWith failure)+      EndsRequest -> do+        unrealised <- filterM (fmap not . allValid effects . snd) rest+        pure (maybe (FailedWith failure) (FailedLeaving failure node) (NE.nonEmpty (map (fst . fst) unrealised)))++-- ---------------------------------------------------------------------------+-- What realising would take+-- ---------------------------------------------------------------------------++-- | Something to realise: a store path as it is, or outputs of the+-- derivation at a path.+data Wanted+  = WantedPath !StorePath+  | WantedOutputs !StorePath !OutputSelection+  deriving (Eq, Ord, Show)++-- | Which outputs of a derivation.+data OutputSelection+  = EveryOutput+  | TheseOutputs !(Set Text)+  deriving (Eq, Ord, Show)++-- | What working out what realising would take asks: whether a path is+-- valid, the derivation at a path the store holds, the first offer of a+-- path a cache makes ('seReferences'), and how many bytes a substitute+-- downloads and unpacks.+data MissingEffects s m = MissingEffects+  { meValid :: !(StorePath -> m Bool),+    meDerivation :: !(StorePath -> m (Either Text Derivation)),+    meOffer :: !(StorePath -> m (Offer s)),+    meSizes :: !(s -> (Word64, Word64))+  }++-- | What realising some paths would take: the derivations to build, the+-- paths to substitute, and those neither valid nor offered, with the+-- bytes substituting downloads and unpacks.+data MissingPaths = MissingPaths+  { mpBuild :: !(Set StorePath),+    mpSubstitute :: !(Set StorePath),+    mpUnknown :: !(Set StorePath),+    mpDownloadSize :: !Word64,+    mpNarSize :: !Word64+  }+  deriving (Eq, Show)++-- | Work out what realising some paths would take, as upstream's+-- @queryMissing@ does, over the closure of what each needs.  A valid path+-- needs nothing; another one a cache offers is substituted, and what it+-- references is needed too; one no cache offers is unknown.  A+-- derivation's outputs need nothing when the wanted ones are valid, and+-- are substituted when a cache offers every one that is not and the+-- derivation allows substitutes ('substitutesAllowed'); otherwise the+-- derivation is built, and the outputs of the derivations it takes as+-- inputs are needed.  A derivation the store does not hold is unknown.+-- A cache that could not be asked, or a derivation or its attributes+-- that cannot be read, stops the work with why.+planMissing :: (Monad m) => SubstitutesSetting -> MissingEffects s m -> [Wanted] -> m (Either Text MissingPaths)+planMissing setting effects = runExceptT . walk Set.empty (MissingPaths Set.empty Set.empty Set.empty 0 0)+  where+    walk _ plan [] = pure plan+    walk visited plan (wanted : rest)+      | wanted `Set.member` visited = walk visited plan rest+      | otherwise = step plan wanted >>= \(advanced, needed) -> walk (Set.insert wanted visited) advanced (needed ++ rest)+    valid = ExceptT . fmap Right . meValid effects+    step plan = \case+      WantedPath path ->+        valid path >>= \case+          True -> pure (plan, [])+          False ->+            offered path >>= \case+              Nothing -> pure (plan {mpUnknown = Set.insert path (mpUnknown plan)}, [])+              Just (substitute, references) ->+                let (download, unpacked) = meSizes effects substitute+                 in pure+                      ( plan+                          { mpSubstitute = Set.insert path (mpSubstitute plan),+                            mpDownloadSize = mpDownloadSize plan + download,+                            mpNarSize = mpNarSize plan + unpacked+                          },+                        map WantedPath references+                      )+      WantedOutputs drvPath selection ->+        valid drvPath >>= \case+          False -> pure (plan {mpUnknown = Set.insert drvPath (mpUnknown plan)}, [])+          True -> do+            drv <- ExceptT (meDerivation effects drvPath)+            invalid <- filterM (fmap not . valid) [doPath output | output <- drvOutputs drv, selected selection (doName output)]+            let build = pure (plan {mpBuild = Set.insert drvPath (mpBuild plan)}, [WantedOutputs input (TheseOutputs (Set.fromList outputs)) | (input, outputs) <- Map.toList (drvInputDrvs drv)])+            case invalid of+              [] -> pure (plan, [])+              _ ->+                ExceptT (pure (derivationAttrs drvPath drv >>= substitutesAllowed setting drvPath)) >>= \case+                  MustBuild -> build+                  MaySubstitute -> allOffered invalid >>= bool build (pure (plan, map WantedPath invalid))+    selected EveryOutput _ = True+    selected (TheseOutputs names) name = name `Set.member` names+    offered path =+      ExceptT+        ( meOffer effects path <&> \case+            Offered substitute references -> Right (Just (substitute, references))+            NotOffered -> Right Nothing+            QueryFailed why -> Left why+        )+    -- Stops at the first output no cache offers, as upstream stops+    -- asking once one is not substitutable.+    allOffered = \case+      [] -> pure True+      path : rest -> offered path >>= maybe (pure False) (const (allOffered rest))
+ src/Nix/Signals.hs view
@@ -0,0 +1,37 @@+{-# LANGUAGE CPP #-}++-- | The signals nova-nix takes as an interrupt.+--+-- Upstream takes SIGINT, SIGTERM and SIGHUP alike as an interrupt: each+-- stops what runs, its builds with it, and the command ends saying it was+-- interrupted.  The GHC runtime throws 'UserInterrupt' to the main thread+-- at SIGINT, but lets SIGTERM and SIGHUP end the process at once, which+-- would leave a builder, in a session of its own, running on.  Windows+-- has neither signal.+module Nix.Signals+  ( interruptOnTermination,+  )+where++#if !defined(mingw32_HOST_OS)+import Control.Concurrent (mkWeakThreadId, myThreadId, throwTo)+import Control.Exception (AsyncException (UserInterrupt))+import Data.Foldable (for_, traverse_)+import System.Mem.Weak (deRefWeak)+import System.Posix.Signals (Handler (Catch), installHandler, sigHUP, sigTERM)+#endif++-- | Have SIGTERM and SIGHUP throw 'UserInterrupt' to the calling thread,+-- as the GHC runtime throws it to the main thread at SIGINT, for the rest+-- of the process's life.  Called from the main thread, which the handler+-- holds weakly, as the runtime's own does, so that it may still be found+-- deadlocked.+interruptOnTermination :: IO ()+#if defined(mingw32_HOST_OS)+interruptOnTermination = pure ()+#else+interruptOnTermination = do+  mainThread <- myThreadId >>= mkWeakThreadId+  let interrupt = Catch (deRefWeak mainThread >>= traverse_ (`throwTo` UserInterrupt))+  for_ [sigTERM, sigHUP] $ \signal -> installHandler signal interrupt Nothing+#endif
src/Nix/Store.hs view
@@ -1,1271 +1,1628 @@-{-# LANGUAGE ScopedTypeVariables #-}---- | The Nix store: content-addressed, immutable package storage.------ == What the store actually does------ When Nix builds a package, the output goes into the store:------ 1. Builder runs in a temp directory, produces output files--- 2. Output is scanned for references to other store paths--- 3. Output is moved to @\/nix\/store\/\<hash\>-\<name\>@--- 4. Path is registered in the SQLite DB with its references--- 5. Directory permissions set to read-only (immutability)------ When Nix SUBSTITUTES (downloads from a binary cache):------ 1. Fetch @\<hash\>.narinfo@ from cache - contains NAR hash, size, refs--- 2. Fetch the @.nar.xz@ file--- 3. Verify file hash matches narinfo--- 4. Decompress and unpack NAR into store path--- 5. Verify NAR hash matches narinfo--- 6. Register path in DB with references from narinfo------ Both paths end the same way: a registered, immutable store path.------ == Garbage collection------ A GC root is an explicit "keep this" marker: the out-link--- @build --out-link@ creates, or a file the operator drops under the--- store's @gcroots@ directory.  The collector walks every root, follows--- references transitively, and deletes everything not reachable; a--- single-path delete refuses a path that walk reaches.  "Nix.Store.GC"--- holds the roots model, the walk, the sweep, and the lock that keeps a--- collection and a concurrent writer apart; "Nix.Store.Handle" holds the--- open handle and its lease on that lock.-module Nix.Store-  ( -- * Queries-    isValid,-    pathExists,--    -- * Deletion-    DeleteOutcome (..),-    deleteStorePathRaw,-    deleteStorePathChecked,-    resolveDeleteTarget,--    -- * Store operations-    addToStore,-    copyPathInto,-    placeInStore,-    registrationFor,-    materializeEvalSources,-    materializeEvalStoreWrites,-    rewriteBytes,-    rewriteStoreHashes,-    scanReferences,-    setReadOnly,-    unpackNarEntry,-    writeDrv,-    writeDrvAterm,-    writeDrvClosure,--    -- * Streaming NAR unpacking-    NarUnpackSink,-    newNarUnpackSink,-    sinkNarEvent,-    finishNarUnpack,-    abortNarUnpack,-    NarStreamFailure (..),-    sinkNarStream,--    -- * Link ordering (exposed for testing)-    orderLinks,--    -- * Case-hack naming (exposed for testing)-    onDiskNameKey,-    caseHackDiskNames,--    -- * Re-exports-    module Nix.Store.Path,-    module Nix.Store.DB,-    module Nix.Store.Lock,-    module Nix.Store.CaseSensitive,-    module Nix.Store.Handle,-    module Nix.Store.GC,-  )-where--import Control.Exception (IOException, bracket, catch, finally, onException, throwIO, try, tryJust)-import Control.Monad (guard, join, unless, when)-import Data.Bool (bool)-import qualified Data.ByteString as BS-import qualified Data.ByteString.Char8 as BS8-import Data.Char (toUpper)-import Data.Foldable (traverse_)-import Data.IORef (IORef, newIORef, readIORef, writeIORef)-import Data.List (inits, stripPrefix)-import Data.Map.Strict (Map)-import qualified Data.Map.Strict as Map-import Data.Maybe (catMaybes)-import qualified Data.Set as Set-import Data.Text (Text)-import qualified Data.Text as T-import qualified Data.Text.Encoding as TE-import Nix.Derivation (Derivation (..), fromATerm, toATerm)-import Nix.Hash (makeFixedOutputPath, makeTextPath, sha256Digest)-import Nix.Store.CaseSensitive (CaseSensitivity (..), processCaseHack, trySetCaseSensitiveDir, volumeCaseHack)-import Nix.Store.DB-import Nix.Store.EntryName (checkEntryName, entryNamePath, hostNameRules, linkTargetPath, shownBytes)-import Nix.Store.Exclusive (Occupant (..), directoryTakenMessage, fileTakenMessage, openNewBinaryFile, symlinkTakenMessage)-import qualified Nix.Store.ExecBit as ExecBit-import Nix.Store.GC-import Nix.Store.Handle-import Nix.Store.Lock-import Nix.Store.Path-import Nix.Store.Symlink (WalkNode (..), classifyWalkNode, createSymlinkOfKind)-import qualified NovaCache.Hash as Hash-import qualified NovaCache.NAR as NAR-import qualified NovaCache.NAR.Stream as Stream-import System.Directory-  ( createDirectoryIfMissing,-    doesDirectoryExist,-    doesPathExist,-    listDirectory,-    renamePath,-    setPermissions,-  )-import qualified System.Directory as Dir-import qualified System.Directory.OsPath as OsDir-import System.FilePath ((</>))-import System.IO (Handle, IOMode (ReadMode), hClose, withBinaryFile)-import System.IO.Error (isAlreadyExistsError)-import System.OsPath (OsPath)-import qualified System.OsPath as OP---- | Check if a store path is registered as valid in the database.-isValid :: Store -> StorePath -> IO Bool-isValid = isValidPath . stDB---- | Check if a store path exists on disk (file or directory, regardless of DB).-pathExists :: Store -> StorePath -> IO Bool-pathExists store sp = doesPathExist (storePathToFilePath (stDir store) sp)---- ------------------------------------------------------------------------------ Deletion--- ------------------------------------------------------------------------------- | What 'deleteStorePathRaw' removed.-data DeleteOutcome = DeleteOutcome-  { -- | A ValidPaths row (with its outgoing reference edges) was removed.-    doRowRemoved :: !Bool,-    -- | An on-disk tree was removed.-    doTreeRemoved :: !Bool-  }-  deriving (Eq, Show)---- | Resolve a @store delete@ argument to the basename it names: a bare--- @hash-name@ basename, or a full path spelled under the opened store's--- directory, the platform store, or the canonical store.  The basename is--- NOT validated as a store path - the entries deletion exists to remove--- are the ones current name rules reject - so only traversal shapes are--- refused: separators (excluded by construction), dot-leading names (the--- store's metadata directory lives at a dot name), and colons (an NTFS--- alternate-data-stream spelling).  Lock files are refused too, but not--- here: names like @flake.lock@ are legal store-path names, so telling a--- lock file from a store object needs the registration rows, and that--- decision lives in 'deleteStorePathRaw'.-resolveDeleteTarget :: StoreDir -> Text -> Either Text Text-resolveDeleteTarget storeDir raw-  | T.null basename = Left (raw <> ": empty store path name")-  | T.isPrefixOf "." basename =-      Left (basename <> ": dot-leading names are not store paths")-  | T.any (== ':') basename =-      Left (basename <> ": ':' is not valid in a store path name")-  | not dirOk = Left (raw <> ": not a path under this store")-  | otherwise = Right basename-  where-    basename = T.takeWhileEnd (\c -> c /= '/' && c /= '\\') raw-    dirPart =-      normalizeSeps-        (T.dropWhileEnd (\c -> c == '/' || c == '\\') (T.dropEnd (T.length basename) raw))-    dirOk =-      T.null dirPart-        || dirPart-          `elem` [ normalizeSeps (T.pack (unStoreDir storeDir)),-                   normalizeSeps (T.pack (unStoreDir platformStoreDir)),-                   normalizeSeps (T.pack (unStoreDir defaultStoreDir))-                 ]-    normalizeSeps = T.map (\c -> if c == '\\' then '/' else c)---- | Delete one store entry by basename: the registration row (refused--- while a root keeps it alive, or while other valid paths reference it)--- and the on-disk tree.  One checked delete under its own collector--- lock and live set; a batch shares both through 'withLiveSet' and--- 'deleteStorePathChecked'.-deleteStorePathRaw :: Store -> Text -> IO (Either Text DeleteOutcome)-deleteStorePathRaw store basename =-  join <$> withLiveSet store (\live -> deleteStorePathChecked store live basename)---- | The checked delete of one entry, given the live set, which also--- stands for the collector lock being held.  Row first, tree second: an--- orphan tree left by a failed removal is inert debris, while a--- still-registered row whose tree is gone would be adopted as valid by--- existence checks.  A row without a tree and a tree without a row both--- delete (the repair cases); only a target with neither is an error.------ Liveness is upstream's rule for a specific delete: a path reachable--- from a root is refused with its words.  The referrer refusal that--- follows is this tool's own in wording and in shape.  Upstream refuses--- a path with an unrooted referrer with the same still-alive line--- unless that referrer is named in the same invocation (its--- @pathsToDelete@ set in 2.24.9's @deleteReferrersClosure@), in which--- case the named set deletes referrer-first; this delete removes--- exactly the path named and lists the referrers that stand in the way,--- so a chain deletes leaf-first in argument order.  Inside the collector--- lock the sequence also holds the target's per-path lock - the same--- file a substituter of the path locks, as upstream's deletePath does ---- so a holder that is not a store handle (nothing in this tool, but--- nothing forbids one) still cannot have its delete-materialize-register--- torn apart by this delete.-deleteStorePathChecked :: Store -> LiveSet -> Text -> IO (Either Text DeleteOutcome)-deleteStorePathChecked store live basename-  | isLive live (T.pack target) = pure (Left (stillAliveMessage (T.pack target)))-  | otherwise = deleteUnderPathLock-  where-    target = unStoreDir (stDir store) </> T.unpack basename-    deleteUnderPathLock = withLockFile (target <> lockFileSuffix) $ \_ -> do-      -- A holder never deletes a lock file (the 'Nix.Store.Lock'-      -- header), and neither does this delete.  A target is one when-      -- stripping the suffix leaves a well-formed store basename AND no-      -- registration row bears the full name: names like @flake.lock@-      -- are legal store-path names, so a registered object of this-      -- exact name deletes normally, and only the rows can tell the two-      -- apart.  The check precedes the row removal below, which is-      -- destructive.-      registered <- case parseStorePathBaseName basename of-        Just sp -> isValidPath (stDB store) sp-        Nothing -> pure False-      case (registered, lockedPathOf basename) of-        (False, Just guardedPath) ->-          pure-            ( Left-                ( basename-                    <> ": names the lock file of "-                    <> guardedPath-                    <> "; lock files coordinate concurrent store access"-                    <> " and are never deleted here (store gc removes it,"-                    <> " and any unregistered store object of this exact"-                    <> " name, once "-                    <> guardedPath-                    <> " is not live)"-                )-            )-        _ -> deleteRowAndTree-    deleteRowAndTree = do-      rowResult <- unregisterPathRow (stDB store) (T.pack target)-      case rowResult of-        RowReferenced referrers ->-          pure-            ( Left-                ( basename-                    <> " is referenced by:"-                    <> T.concat ["\n  " <> r | r <- referrers]-                )-            )-        _ -> do-          -- 'doesPathExist' follows links, so a dangling top-level symlink-          -- would read as absent; links are leaves here (as in store walks),-          -- and leftover link debris must still be removable.-          treeExisted <- do-            onDisk <- doesPathExist target-            if onDisk-              then pure True-              else Dir.pathIsSymbolicLink target `catch` \(_ :: IOException) -> pure False-          when treeExisted (Dir.removePathForcibly target)-          let rowRemoved = rowResult == RowUnregistered-          if rowRemoved || treeExisted-            then pure (Right DeleteOutcome {doRowRemoved = rowRemoved, doTreeRemoved = treeExisted})-            else pure (Left (basename <> ": not in this store (no registration row, no tree on disk)"))---- ------------------------------------------------------------------------------ Store operations--- ------------------------------------------------------------------------------- | Move a build output (file or directory) to the store path, set read-only,--- and register.------ If @renamePath@ fails (cross-device move), falls back to copy + remove.-addToStore ::-  Store ->-  FilePath ->-  StorePath ->-  Maybe Text ->-  [StorePath] ->-  IO ()-addToStore store srcPath sp deriver refs = do-  reg <- placeInStore store srcPath sp deriver refs-  registerPath (stDB store) reg---- | Move a build output into the store (read-only) and compute its--- registration (NAR hash, size, references) WITHOUT writing to the database.------ Splitting placement from registration lets a multi-output build place every--- output first and then register them together, so intra-derivation--- cross-output references are preserved (see 'registerPaths').-placeInStore ::-  Store ->-  FilePath ->-  StorePath ->-  Maybe Text ->-  [StorePath] ->-  IO PathRegistration-placeInStore store srcPath sp deriver refs = do-  let destPath = storePathToFilePath (stDir store) sp-  moveOutput srcPath destPath-  setReadOnly destPath-  registrationFor store sp deriver refs---- | Compute the registration metadata for a store path already present on--- disk, without moving anything.  Used by 'placeInStore' after its move,--- and by 'materializeEvalSources' to register a verified adopted tree.-registrationFor :: Store -> StorePath -> Maybe Text -> [StorePath] -> IO PathRegistration-registrationFor store sp deriver refs = do-  let destPath = storePathToFilePath (stDir store) sp-  -- Compute the NAR hash and size of the final store contents.  The NAR-  -- serialization is canonical (entries sorted, 8-byte padding), so this is-  -- exactly the NarHash/NarSize a binary cache reports for the path.-  narEntry <- ExecBit.serialiseFromPath (volumeCaseHack (stCaseSensitivity store)) destPath-  let narBytes = NAR.serialise narEntry-  pure-    PathRegistration-      { prPath = sp,-        prNarHash = Hash.formatNixHash (Hash.hashBytes narBytes),-        prNarSize = BS.length narBytes,-        prDeriver = deriver,-        prReferences = refs-      }---- | Cross-device safe move for files or directories.--- Tries 'renamePath' first; on IOException falls back to copy + remove.--- The fallback copies via 'copyPathInto', which preserves symlinks as--- symlinks: a dereferencing copy here would make the stored bytes - and--- so the NAR hash a cache signs - depend on whether the source and the--- store share a volume.-moveOutput :: FilePath -> FilePath -> IO ()-moveOutput src dest-  -- A build writes into its own output path, so the usual case is a move-  -- onto itself.  POSIX rename(a,a) is a benign no-op, but MoveFileEx is-  -- documented as unusable when either name is a directory, and the-  -- IOException fallback below would then copy a tree into itself and-  -- delete the result.  Answering here settles both platforms.-  | src == dest = pure ()-  | otherwise =-      renamePath src dest `catch` \(_ :: IOException) -> do-        copyPathInto src dest-        Dir.removePathForcibly src---- | Byte-scan a tree for store path references.------ Searches each scan unit ('collectScanUnits': regular file bytes,--- symlink target strings and entry names) for each candidate's bare--- 32-character hash - the same needle upstream Nix scans for.  Matching--- the hash rather than a store-dir-prefixed path keeps the scan--- independent of the spelling the builder embedded (canonical--- @\/nix\/store\/...@, @C:\\nix\\store\\...@, MSYS2 forms): eval injects--- canonical forward-slash text into builder environments, which a--- platform-store-dir prefix never matches on Windows.-scanReferences :: [StorePath] -> FilePath -> IO [StorePath]-scanReferences candidates dir = do-  let candidateSet = Set.fromList [(spHash sp, sp) | sp <- candidates]-      needles = [(TE.encodeUtf8 h, h) | (h, _) <- Set.toList candidateSet]-  units <- collectScanUnits dir-  foundHashes <- foldlIO Set.empty units $ \acc unit -> do-    contents <- scanUnitBytes unit-    pure (Set.union acc (Set.fromList [h | (needle, h) <- needles, needle `BS.isInfixOf` contents]))-  pure [sp | (h, sp) <- Set.toList candidateSet, Set.member h foundHashes]---- | Replace store path hashes across a tree: file bytes, symlink targets and--- entry names, every place a NAR carries one.  Upstream rewrites the serialized--- NAR and so reaches all three (@rewriteOutput@ in--- @local-derivation-goal.cc@ at 2.24.9).  A store path hash has one length, so--- no offset inside a file moves.-rewriteStoreHashes :: [(Text, Text)] -> FilePath -> IO ()-rewriteStoreHashes [] _ = pure ()-rewriteStoreHashes rewrites root = rewriteAt id root-  where-    byteRewrites = [(TE.encodeUtf8 from, TE.encodeUtf8 to) | (from, to) <- rewrites]-    nameRewrites = [(T.unpack from, T.unpack to) | (from, to) <- rewrites]-    rewriteName name = foldl' (\acc (from, to) -> replaceInName from to acc) name nameRewrites-    -- Replacing a link edits its parent, so the guard for a read-only parent-    -- comes from the caller: the root's parent is the store, not the output.-    rewriteAt parentGuard path = do-      node <- classifyWalkNode path-      case node of-        WalkSymlink -> do-          target <- Dir.getSymbolicLinkTarget path-          let updated = rewriteName target-          unless (updated == target) (parentGuard (replaceLink path updated))-        WalkDirectory -> do-          entries <- listDirectory path-          mapM_ (rewriteEntry path) entries-        WalkRegular -> do-          bytes <- BS.readFile path-          let updated = rewriteBytes byteRewrites bytes-          unless (updated == bytes) (whileWritable path (BS.writeFile path updated))-        WalkAbsent -> pure ()-    rewriteEntry dir entry = do-      rewriteAt (whileWritable dir) (dir </> entry)-      let renamed = rewriteName entry-      unless (renamed == entry) $ do-        taken <- doesPathExist (dir </> renamed)-        when taken (ioError (userError ("rewriting a store hash would overwrite " <> (dir </> renamed))))-        whileWritable dir (renamePath (dir </> entry) (dir </> renamed))---- | Point a symlink somewhere else.  'Dir.removePathForcibly' removes a file--- link or a directory link alike, which differ on Windows.-replaceLink :: FilePath -> FilePath -> IO ()-replaceLink path target = do-  linkOs <- OP.encodeFS path-  targetOs <- OP.encodeFS target-  Dir.removePathForcibly path-  created <- createSymlinkOfKind linkOs targetOs-  either (ioError . userError . T.unpack) pure created---- | Run an action on a path with write permission, then put its permissions--- back.  A builder may mark its output read-only before registration does.-whileWritable :: FilePath -> IO a -> IO a-whileWritable path action = do-  permissions <- Dir.getPermissions path-  setPermissions path (Dir.setOwnerWritable True permissions)-  action `finally` setPermissions path permissions---- | Apply each replacement to bytes, in order.  An empty needle matches--- nothing.-rewriteBytes :: [(BS.ByteString, BS.ByteString)] -> BS.ByteString -> BS.ByteString-rewriteBytes rewrites bytes = foldl' (\acc (from, to) -> replaceInBytes from to acc) bytes rewrites--replaceInBytes :: BS.ByteString -> BS.ByteString -> BS.ByteString -> BS.ByteString-replaceInBytes from to bytes-  | BS.null from = bytes-  | otherwise = BS.concat (pieces bytes)-  where-    pieces remaining = case BS.breakSubstring from remaining of-      (before, rest)-        | BS.null rest -> [before]-        | otherwise -> before : to : pieces (BS.drop (BS.length from) rest)---- | 'replaceInBytes' on a path component.  The rest of the name is left as--- the operating system spelled it, so no decoding step can damage it.-replaceInName :: String -> String -> String -> String-replaceInName from to name = case name of-  _ | null from -> name-  [] -> []-  c : rest -> case stripPrefix from name of-    Just after -> to ++ replaceInName from to after-    Nothing -> c : replaceInName from to rest---- | One scannable unit of a walked tree: a regular file's bytes read--- from disk, a symlink's target string, or an entry's name.  The NAR--- serialization carries all three and upstream scans that serialization,--- so reference scanning covers all three - a link into a dependency--- (@bin\/tool -> \/nix\/store\/\<hash\>-dep\/tool@) references the--- dependency even when no file byte does.-data ScanUnit = ScanFile !FilePath | ScanText !BS.ByteString---- | Collect the scannable units under a path: regular files, symlink--- targets and the names of a directory's entries, links never followed.--- A path that is itself a regular file or link is its own single unit.-collectScanUnits :: FilePath -> IO [ScanUnit]-collectScanUnits path = do-  node <- classifyWalkNode path-  case node of-    WalkSymlink -> do-      target <- Dir.getSymbolicLinkTarget path-      pure [ScanText (TE.encodeUtf8 (T.pack target))]-    WalkDirectory -> do-      entries <- listDirectory path-      nested <- concat <$> mapM (collectScanUnits . (path </>)) entries-      pure (map (ScanText . TE.encodeUtf8 . T.pack) entries ++ nested)-    WalkRegular -> pure [ScanFile path]-    WalkAbsent -> pure []---- | The bytes a 'ScanUnit' contributes to the scan.-scanUnitBytes :: ScanUnit -> IO BS.ByteString-scanUnitBytes (ScanFile path) = BS.readFile path-scanUnitBytes (ScanText text) = pure text---- | Strict left fold over a list in IO.  The accumulator is forced to--- WHNF each step - without it, the scan retains every scanned file's--- bytes in Set.union thunks until the end (peak memory ~ total tree--- size).  Set's spine-strict nodes make WHNF force the whole union.-foldlIO :: a -> [b] -> (a -> b -> IO a) -> IO a-foldlIO z [] _ = pure z-foldlIO z (x : xs) f = do-  !acc <- f z x-  foldlIO acc xs f---- | Recursively mark a store path and its contents read-only after a build.------ On Windows the directory read-only attribute does not prevent adding or--- removing entries - only the per-file read-only attribute protects a file.--- Immutability here is therefore enforced at FILE granularity (every file is--- made read-only); hardening the directory itself against entry changes would--- require ACLs and is deferred.-setReadOnly :: FilePath -> IO ()-setReadOnly path = do-  node <- classifyWalkNode path-  case node of-    -- A symlink is a leaf: descending would mark content outside the-    -- tree (or loop on a link cycle), and a permission change applied-    -- to the link resolves through to its target.-    WalkSymlink -> pure ()-    WalkDirectory -> do-      entries <- listDirectory path-      mapM_ (setReadOnly . (path </>)) entries-      perms <- Dir.getPermissions path-      Dir.setPermissions path (Dir.setOwnerWritable False perms)-    WalkRegular -> do-      perms <- Dir.getPermissions path-      setPermissions path (Dir.setOwnerWritable False perms)-    WalkAbsent -> pure ()---- | Write an already-serialized derivation ATerm to its store path.  Used to--- materialize the input @.drv@ closure (root plus every transitive input)--- before a dependency-aware build: evaluation computes these ATerms but does--- no store IO, so the build driver writes them here.-writeDrvAterm :: Store -> StorePath -> BS.ByteString -> IO ()-writeDrvAterm store sp aterm = do-  let destPath = storePathToFilePath (stDir store) sp-  createDirectoryIfMissing True (unStoreDir (stDir store))-  -- Raw bytes, not text-mode IO: the path was computed from exactly these-  -- bytes, and a locale-dependent or newline-translating write would store-  -- bytes that no longer match their content address.-  BS.writeFile destPath aterm---- | Serialize a derivation to ATerm, write it to the store, and register--- it: a @.drv@ is a store object like any other, so it gets a ValidPaths--- row with its NAR hash and its references.  Reference scans may name a--- @.drv@ (one in a build's input closure, where a @drvPath@'s context puts--- it), and an unregistered referent fails the whole registration batch.-writeDrv :: Store -> Derivation -> StorePath -> IO ()-writeDrv store drv sp = do-  writeDrvAterm store sp (toATerm drv)-  reg <- registrationFor store sp Nothing (drvReferences drv)-  registerPath (stDB store) reg---- | A @.drv@'s references: its input sources and input @.drv@ paths ---- the same set upstream records when writing a derivation to the store.-drvReferences :: Derivation -> [StorePath]-drvReferences drv = drvInputSrcs drv ++ Map.keys (drvInputDrvs drv)---- | Write every recorded @.drv@ ATerm (keyed by its store-path text) to--- the store and register the whole closure in one batch: rows all land--- before edges ('registerPaths'), so references between the closure's--- own @.drv@ files resolve regardless of map order.  Input SOURCES must--- already be registered - the build driver runs 'materializeEvalSources'--- first.------ Keys come from evaluation via 'storePathToText' so they always parse;--- an unparseable key is skipped defensively.  The ATerm bytes were--- rendered by evaluation, so a re-parse failure is an invariant break--- and throws rather than registering a recipe with dropped references.-writeDrvClosure :: Store -> Map Text BS.ByteString -> IO ()-writeDrvClosure store closure = do-  regs <- mapM writeOne (Map.toList closure)-  registerPaths (stDB store) (catMaybes regs)-  where-    writeOne (pathText, aterm) =-      case parseStorePath defaultStoreDir pathText of-        Nothing -> pure Nothing-        Just sp -> do-          writeDrvAterm store sp aterm-          case fromATerm aterm of-            Right drv -> Just <$> registrationFor store sp Nothing (drvReferences drv)-            Left err ->-              throwIO-                ( userError-                    ( "writeDrvClosure: recorded ATerm for "-                        <> T.unpack pathText-                        <> " does not re-parse: "-                        <> T.unpack err-                    )-                )---- ------------------------------------------------------------------------------ Exclusive creation--- ------------------------------------------------------------------------------- Every regular file and directory a tree materializes is created--- exclusively: a name already taken refuses the write instead of--- landing on the earlier entry.  'onDiskNameKey' predicts which--- siblings a folding volume merges, but only the volume knows its own--- fold table, so the create is what catches a pair the key misses.--- Upstream's restore creates the same way (@RestoreSink@ in--- fs-sink.cc at 2.24.9: @O_CREAT | O_EXCL@ for a regular file, a--- refused @create_directory@ for a directory), and the refusals carry--- its words ("Nix.Store.Exclusive").  Symlinks need nothing extra:--- @symlink(2)@ and CreateSymbolicLinkW never replace an existing name,--- and 'createSymlinkOfKind' words that refusal as upstream does.---- | Run a create that must find its name free, its refusal becoming the--- failure the given action describes.  Only the refusal becomes a--- value: it is a property of the tree being written, where any other--- I\/O failure (permissions, a full disk) is one of the machine and--- stays an exception.-refuseTaken :: IO Text -> IO a -> IO (Either Text a)-refuseTaken describe create = do-  attempt <- tryJust (guard . isAlreadyExistsError) create-  either (const (Left <$> describe)) (pure . Right) attempt---- | Create a regular file of a materialized tree exclusively and write--- it through the handle, closed on the way out.-withNewTreeFile :: OsPath -> (Handle -> IO a) -> IO (Either Text a)-withNewTreeFile path write =-  bracket (openNewTreeFile path) (traverse_ hClose) (traverse write)---- | Open a regular file of a materialized tree, created exclusively.-openNewTreeFile :: OsPath -> IO (Either Text Handle)-openNewTreeFile path = refuseTaken (fileTakenMessage <$> OP.decodeFS path) (openNewBinaryFile path)---- | Create a directory of a materialized tree exclusively.  Its parent--- is created first if missing, which only the root can need.  A--- refusal asks what holds the name, as @create_directory@ does before--- it chooses between returning false and throwing.-createTreeDirectory :: OsPath -> IO (Either Text ())-createTreeDirectory path = do-  OsDir.createDirectoryIfMissing True (OP.takeDirectory path)-  refuseTaken describe (OsDir.createDirectory path)-  where-    describe = do-      occupant <- bool OccupiedByOther OccupiedByDirectory <$> OsDir.doesDirectoryExist path-      directoryTakenMessage occupant <$> OP.decodeFS path---- ------------------------------------------------------------------------------ NAR unpacking--- ------------------------------------------------------------------------------- | Unpack a NarEntry tree to a filesystem destination.  Returns @Left@--- on an entry name or link target the host cannot hold--- ("Nix.Store.EntryName"); these can come from untrusted cache data, so--- a typed failure is used instead of a partial 'error'.------ Names and targets reach the filesystem as the bytes the NAR carries,--- as upstream's restore writes them on POSIX: the tree is walked in--- 'OsPath's, a POSIX path being bytes.  Only the destination enters as--- a 'FilePath', spelled as every 'FilePath' API spells it.------ The sensitivity is the destination volume's ('stCaseSensitivity' for--- a store path) and decides whether case-variant siblings need the--- case-hack ('onDiskNameKey').------ Regular files and directories are written in one pass; symlinks are--- created in a second pass, after their targets are materialized.  Windows--- symlinks are typed (file vs directory) and the NAR format does not record--- the target's kind, so the only reliable way to pick the flavor is to look--- at the target on disk - which may sort after the link within the tree.-unpackNarEntry :: CaseSensitivity -> FilePath -> NAR.NarEntry -> IO (Either Text ())-unpackNarEntry sensitivity path entry = do-  root <- OP.encodeFS path-  walked <- unpackTree sensitivity root entry-  case walked of-    Left err -> pure (Left err)-    Right links -> createSymlinks links---- | First unpack pass: write regular files and directories, recording--- symlinks as (link path, target) for the second pass.-unpackTree :: CaseSensitivity -> OsPath -> NAR.NarEntry -> IO (Either Text [(OsPath, OsPath)])-unpackTree sensitivity path entry = case entry of-  NAR.NarRegular isExec contents -> do-    OsDir.createDirectoryIfMissing True (OP.takeDirectory path)-    written <- withNewTreeFile path (`BS.hPut` contents)-    case written of-      Left err -> pure (Left err)-      Right () -> do-        when isExec (ExecBit.markExecutableOsPath path)-        pure (Right [])-  NAR.NarSymlink target -> fmap (\targetPath -> [(path, targetPath)]) <$> linkTargetPath target-  NAR.NarDirectory entries -> do-    created <- createTreeDirectory path-    case created of-      Left err -> pure (Left err)-      Right () -> unpackChildren sensitivity path entries---- | The on-disk identity a NAR entry name occupies on a volume of the--- given case sensitivity.  Two sibling entries sharing a key name ONE--- file on that volume, so the unpack keeps them apart--- (@unpackNamedChildren@).  A folding volume (the default APFS format,--- NTFS through Win32) keys a name by its uppercase; a sensitive one--- (Linux, a case-sensitive APFS volume) keys it byte-for-byte.  The--- fold is per-character uppercase, which keeps apart the collisions--- real trees carry (@Makefile@\/@makefile@) but not every pair the--- volume folds: APFS reads U+00DF and U+1E9E as one name while--- 'toUpper' leaves U+00DF unchanged, so that pair takes two keys and--- the exclusive create refuses the second at the write (#234), as--- upstream's restore does.  The reverse miss (U+0131 uppercases to--- @I@, which APFS keeps distinct) only spells a name with a suffix it--- did not need.  A name that is not UTF-8 has no characters to fold--- and keys as its bytes; no host whose volumes fold admits one--- ("Nix.Store.EntryName"), and the create would catch what the key--- missed.  Win32 strips a trailing dot or space on create, which would--- merge names this key keeps apart, but Windows refuses such names--- before any is keyed.------ Upstream decides this per process, not per volume: its--- @use-case-hack@ setting defaults to on for Darwin and off elsewhere--- (archive.cc at 2.24.9), so a case-sensitive macOS volume still has--- @makefile@ restored as @makefile~nix~case~hack~1@ (observed from--- @nix-store --restore@ 2.33.2).  The hack exists to work around--- folding, and a volume that does not fold needs none, so nova-nix--- keys by the probed answer and materializes true names there.  The--- divergence is in on-disk spelling only: either tree re-serialises--- to the same NAR.-onDiskNameKey :: CaseSensitivity -> BS.ByteString -> BS.ByteString-onDiskNameKey sensitivity name = case sensitivity of-  CaseSensitive -> name-  CaseInsensitive -> either (const name) (TE.encodeUtf8 . T.map toUpper) (TE.decodeUtf8' name)---- | The first pair of sibling names folding to the same on-disk file,--- if any: (earlier entry, colliding later entry).-firstNameCollision :: CaseSensitivity -> [BS.ByteString] -> Maybe (BS.ByteString, BS.ByteString)-firstNameCollision sensitivity = go Map.empty-  where-    go !_ [] = Nothing-    go !seen (name : rest) =-      let key = onDiskNameKey sensitivity name-       in case Map.lookup key seen of-            Just earlier -> Just (earlier, name)-            Nothing -> go (Map.insert key name seen) rest---- | Whether a tree on a volume of the given case sensitivity is read--- back with the case-hack suffix stripped ('volumeCaseHack').  Where--- it is, an INCOMING entry name carrying the suffix must be rejected:--- materialized verbatim it would re-serialise under a different name--- and fail its own hash recheck.  Upstream's restore accepts such a--- name and its dump then strips the suffix (archive.cc at 2.24.9), so--- the tree fails there as well, only later; refusing at the write--- boundary surfaces the same failure before anything is materialized.--- A volume that keeps names apart reads every name as spelled, so the--- name materializes and round-trips there.-volumeStripsCaseHack :: CaseSensitivity -> Bool-volumeStripsCaseHack sensitivity = volumeCaseHack sensitivity == NAR.CaseHackEnabled---- | Refuse an entry name before any sibling is written: one the host--- cannot hold ('checkEntryName'), or one carrying the case-hack suffix--- where the destination volume's serialiser would strip it.-admitEntryName :: CaseSensitivity -> BS.ByteString -> Either Text ()-admitEntryName sensitivity name = do-  checkEntryName hostNameRules name-  when (volumeStripsCaseHack sensitivity && NAR.caseHackSuffix `BS.isInfixOf` name) $-    Left ("NAR entry name contains the case-hack suffix: " <> shownBytes name)---- | The case-hacked disk name for the given occurrence of a key.-caseHackName :: BS.ByteString -> Int -> BS.ByteString-caseHackName name occurrence = name <> NAR.caseHackSuffix <> BS8.pack (show occurrence)---- | Disk names for a sibling list on a volume of the given case--- sensitivity, WITHOUT per-directory case sensitivity: upstream's--- case-hack where names fold, every name as spelled where they do not.--- The first occurrence of each key keeps its spelling; every later--- name with the same key gains the reversible suffix and a per-name--- counter, which the serialiser strips on the way back out--- ('volumeCaseHack').  Order is preserved; result pairs are (NAR--- name, on-disk name).-caseHackDiskNames :: CaseSensitivity -> [BS.ByteString] -> [(BS.ByteString, BS.ByteString)]-caseHackDiskNames sensitivity = reverse . snd . foldl' step (Map.empty, [])-  where-    step (!seen, !acc) name =-      let key = onDiskNameKey sensitivity name-       in case Map.lookup key seen of-            Nothing -> (Map.insert key (0 :: Int) seen, (name, name) : acc)-            Just occurrences ->-              let next = occurrences + 1-               in (Map.insert key next seen, (name, caseHackName name next) : acc)---- | Unpack directory children.  Entry names arrive as the raw bytes--- the NAR carries, and every sibling's name is admitted--- ('admitEntryName') before the first is written, so a name the host--- cannot hold leaves no partial directory behind it.-unpackChildren :: CaseSensitivity -> OsPath -> [(BS.ByteString, NAR.NarEntry)] -> IO (Either Text [(OsPath, OsPath)])-unpackChildren sensitivity path entries = case traverse_ (admitEntryName sensitivity . fst) entries of-  Left err -> pure (Left err)-  Right () -> unpackNamedChildren sensitivity path entries---- | Unpack admitted directory children.------ On a volume the probe reports sensitive (Linux, case-sensitive APFS)--- no two sibling names share an on-disk identity and every entry--- materializes as spelled.  Sibling names folding to one on-disk name--- (NTFS, default APFS) take the TRUE-NAME path when the platform--- provides one: the just-created empty directory gains NTFS--- per-directory case sensitivity and the tree materializes under its--- real names.  Where the flag is unavailable (a non-NTFS store volume,--- a folding APFS volume) the collision falls back to upstream's--- case-hack renaming, which the volume's serialiser reverses.  Either--- way a registered path re-serialises to its NAR byte-for-byte - the--- substituter's on-disk recheck verifies it.  The name spelled on disk--- is the one the host is asked to hold, suffix included.-unpackNamedChildren :: CaseSensitivity -> OsPath -> [(BS.ByteString, NAR.NarEntry)] -> IO (Either Text [(OsPath, OsPath)])-unpackNamedChildren sensitivity path entries = do-  diskNames <- resolveDiskNames-  walkChildren (zip diskNames (map snd entries))-  where-    names = map fst entries-    resolveDiskNames = case firstNameCollision sensitivity names of-      Nothing -> pure names-      Just _ -> do-        trueNames <- trySetCaseSensitiveDir =<< OP.decodeFS path-        pure-          ( if trueNames-              then names-              else map snd (caseHackDiskNames sensitivity names)-          )-    walkChildren [] = pure (Right [])-    walkChildren ((diskName, child) : rest) = do-      spelled <- entryNamePath diskName-      case spelled of-        Left err -> pure (Left err)-        Right component -> do-          result <- unpackTree sensitivity (path OP.</> component) child-          case result of-            Left err -> pure (Left err)-            Right links -> do-              restResult <- walkChildren rest-              case restResult of-                Left err -> pure (Left err)-                Right moreLinks -> pure (Right (links <> moreLinks))---- | Second unpack pass: create the recorded symlinks in dependency--- order - each link is created after every pending link its target--- resolves at or through - so the Windows link flavor (file vs--- directory) is read off the real target with one probe per link.--- (The previous ready-set rounds re-stat'd every remaining link per--- round: quadratic filesystem stats on a link chain.)  Links on a--- dependency cycle have no knowable kind and default to file links,--- exactly as dangling links always have.-createSymlinks :: [(OsPath, OsPath)] -> IO (Either Text ())-createSymlinks pending = createAll (orderLinks pending)-  where-    createAll [] = pure (Right ())-    createAll (link : rest) = do-      made <- uncurry createSymlink link-      case made of-        Left err -> pure (Left err)-        Right () -> createAll rest---- | Order pending links so each follows every pending link its target--- path resolves at or through: the target itself, or a link standing on--- one of the target's ancestor directories.  Purely textual over the--- same @takeDirectory linkPath \</\> target@ resolution 'createSymlink'--- probes - no filesystem access.  Kahn's ordering, deterministic:--- ready links leave in input order, and cycle members keep input order--- at the end.  Exported for testing (the ordering property is pure).-orderLinks :: [(OsPath, OsPath)] -> [(OsPath, OsPath)]-orderLinks pending =-  let indexed = zip [0 :: Int ..] pending-      linkByIndex = Map.fromList indexed-      indexByKey =-        Map.fromList [(normalisedComponents linkPath, i) | (i, (linkPath, _)) <- indexed]-      -- The pending links this link's resolved target lands on or-      -- passes through (every nonempty component prefix).-      depsOf (linkPath, target) =-        let resolved = normalisedComponents (OP.takeDirectory linkPath OP.</> target)-         in Set.fromList-              [j | prefix <- drop 1 (inits resolved), Just j <- [Map.lookup prefix indexByKey]]-      dependsOn = Map.fromList [(i, depsOf link) | (i, link) <- indexed]-      dependents =-        Map.fromListWith-          (flip (++))-          [(dep, [i]) | (i, deps) <- Map.toList dependsOn, dep <- Set.toList deps]-      initialCounts = Map.map Set.size dependsOn-      initialReady = [i | (i, count) <- Map.toList initialCounts, count == 0]-      -- Kahn's ordering with a two-list queue (amortized O(1) pops).-      run !emittedRev !counts front back = case front of-        [] -> case back of-          [] -> reverse emittedRev-          _ -> run emittedRev counts (reverse back) []-        (i : rest) ->-          let (updatedCounts, readied) = release counts (Map.findWithDefault [] i dependents)-           in run (i : emittedRev) updatedCounts rest (readied ++ back)-      release !counts deps = case deps of-        [] -> (counts, [])-        (d : more) ->-          let updated = Map.adjust (subtract 1) d counts-              (finalCounts, readied) = release updated more-           in (finalCounts, [d | Map.lookup d updated == Just 0] ++ readied)-      emittedOrder = run [] initialCounts initialReady []-      emittedSet = Set.fromList emittedOrder-      cycleRemainder = [link | (i, link) <- indexed, not (Set.member i emittedSet)]-   in [link | i <- emittedOrder, Just link <- [Map.lookup i linkByIndex]] ++ cycleRemainder---- | Path components with @.@ dropped and @..@ collapsed textually - the--- spelling-insensitive key that matches a link target against pending--- link paths ('OP.splitDirectories' accepts both separator spellings--- on Windows).  A @..@ with nothing left to pop stays, matching no real--- path.-normalisedComponents :: OsPath -> [OsPath]-normalisedComponents path = reverse (foldl' step [] (OP.splitDirectories path))-  where-    step stack comp-      | comp == currentDirectory = stack-      | comp == parentDirectory = case stack of-          (top : rest) | top /= parentDirectory -> rest-          _ -> comp : stack-      | otherwise = comp : stack-    currentDirectory = OP.pack [dot]-    parentDirectory = OP.pack [dot, dot]-    dot = OP.unsafeFromChar '.'---- | Create one unpacked symlink, parents first, with the Windows flavor--- read off the target ('createSymlinkOfKind').  A creation failure is--- loud, and failing lets the caller fall back to a local build.-createSymlink :: OsPath -> OsPath -> IO (Either Text ())-createSymlink linkPath target = do-  OsDir.createDirectoryIfMissing True (OP.takeDirectory linkPath)-  createSymlinkOfKind linkPath target---- ------------------------------------------------------------------------------ Streaming NAR unpacking--- ------------------------------------------------------------------------------- | One open directory in the streaming unpack: its on-disk path and--- the sibling names materialized so far, keyed by their on-disk--- identity ('onDiskNameKey') for collision handling.-data UnpackFrame = UnpackFrame-  { ufPath :: !OsPath,-    ufSeen :: !(Map BS.ByteString Int)-  }---- | Mutable state behind a t'NarUnpackSink' - the same deliberate IO--- boundary as the store's other materializers.  'nusTargets' is the--- stack of on-disk paths the NEXT node materializes at: the--- destination at the root, plus one pushed per open directory entry.-data NarUnpackState = NarUnpackState-  { -- | The destination volume's case sensitivity, keying sibling-    -- names exactly as the strict path does.-    nusCaseSensitivity :: !CaseSensitivity,-    nusFrames :: ![UnpackFrame],-    nusTargets :: ![OsPath],-    nusOpen :: !(Maybe (Handle, OsPath, Bool)),-    nusLinks :: ![(OsPath, OsPath)]-  }---- | A push sink materializing 'Stream.NarEvent's under a destination--- path as they arrive, so a substituted NAR unpacks in the same pass--- that downloads it.  Semantics mirror 'unpackNarEntry' - the same--- name bytes and host checks, executable bit, and second-pass--- symlink creation - with one divergence: sibling names colliding on--- a folding volume always take upstream's case-hack renaming, never--- the NTFS true-name path, because per-directory case sensitivity can--- only be enabled on an EMPTY directory and a stream cannot know a--- directory's siblings before materializing the first.  On a volume--- the probe reports sensitive nothing collides, as in the strict path.--- Upstream's own streaming restore behaves identically, and the--- substituter's on-disk recheck proves the tree re-serialises to its--- NAR either way.-newtype NarUnpackSink = NarUnpackSink (IORef NarUnpackState)---- | A sink for one NAR unpack under the given destination path, on a--- volume of the given case sensitivity.-newNarUnpackSink :: CaseSensitivity -> FilePath -> IO NarUnpackSink-newNarUnpackSink sensitivity destPath = do-  root <- OP.encodeFS destPath-  NarUnpackSink <$> newIORef (NarUnpackState sensitivity [] [root] Nothing [])---- | Feed one event.  On 'Left' the partial tree stays for the caller--- to remove - 'abortNarUnpack' first, so no handle stays open on it.-sinkNarEvent :: NarUnpackSink -> Stream.NarEvent -> IO (Either Text ())-sinkNarEvent (NarUnpackSink ref) event = do-  narState <- readIORef ref-  outcome <- applyNarEvent narState event-  case outcome of-    Left err -> pure (Left err)-    Right updated -> do-      writeIORef ref updated-      pure (Right ())---- | One event's filesystem effects plus the state that follows it.--- The stream machine already proved grammar well-formedness, so the--- mismatch arms guard sink-state desync, not archive syntax.-applyNarEvent :: NarUnpackState -> Stream.NarEvent -> IO (Either Text NarUnpackState)-applyNarEvent narState event = case event of-  Stream.EventRegularBegin isExec _declaredSize -> withNodeTarget narState $ \path -> do-    OsDir.createDirectoryIfMissing True (OP.takeDirectory path)-    opened <- openNewTreeFile path-    pure (fmap (\fileHandle -> narState {nusOpen = Just (fileHandle, path, isExec)}) opened)-  Stream.EventRegularChunk slice -> case nusOpen narState of-    Nothing -> pure (Left "NAR stream sink: file contents outside an open file")-    Just (fileHandle, _, _) -> do-      BS.hPut fileHandle slice-      pure (Right narState)-  Stream.EventRegularEnd -> case nusOpen narState of-    Nothing -> pure (Left "NAR stream sink: file close without an open file")-    Just (fileHandle, path, isExec) -> do-      hClose fileHandle-      when isExec (ExecBit.markExecutableOsPath path)-      pure (Right narState {nusOpen = Nothing})-  Stream.EventSymlink targetBytes -> withNodeTarget narState $ \path ->-    fmap (\target -> narState {nusLinks = (path, target) : nusLinks narState})-      <$> linkTargetPath targetBytes-  Stream.EventDirectoryBegin -> withNodeTarget narState $ \path -> do-    created <- createTreeDirectory path-    pure (narState {nusFrames = UnpackFrame path Map.empty : nusFrames narState} <$ created)-  Stream.EventEntryBegin name -> case nusFrames narState of-    [] -> pure (Left "NAR stream sink: entry outside a directory")-    (frame : outer) -> case admitEntryName (nusCaseSensitivity narState) name of-      Left err -> pure (Left err)-      Right () -> do-        -- Sequential case-hack: the disk name of entry N depends only-        -- on the siblings before it, the same sequence-        -- 'caseHackDiskNames' folds over a whole list.-        let key = onDiskNameKey (nusCaseSensitivity narState) name-            (diskName, occurrences) = case Map.lookup key (ufSeen frame) of-              Nothing -> (name, 0)-              Just seen -> (caseHackName name (seen + 1), seen + 1)-            updatedFrame = frame {ufSeen = Map.insert key occurrences (ufSeen frame)}-        spelled <- entryNamePath diskName-        pure $-          fmap-            ( \component ->-                narState-                  { nusFrames = updatedFrame : outer,-                    nusTargets = (ufPath frame OP.</> component) : nusTargets narState-                  }-            )-            spelled-  Stream.EventEntryEnd -> case nusTargets narState of-    -- The root destination never pops; only entry-pushed paths do.-    (_ : rest@(_ : _)) -> pure (Right narState {nusTargets = rest})-    _ -> pure (Left "NAR stream sink: entry close without an open entry")-  Stream.EventDirectoryEnd -> case nusFrames narState of-    [] -> pure (Left "NAR stream sink: directory close without an open directory")-    (_ : outer) -> pure (Right narState {nusFrames = outer})---- | Run an action on the path the next node materializes at.-withNodeTarget :: NarUnpackState -> (OsPath -> IO (Either Text NarUnpackState)) -> IO (Either Text NarUnpackState)-withNodeTarget narState act = case nusTargets narState of-  (path : _) -> act path-  [] -> pure (Left "NAR stream sink: node with no destination")---- | Finish after 'Stream.NarDone': every node must be closed, then--- the recorded symlinks are created - the same dependency ordering--- and flavor probing as the strict path's second pass.-finishNarUnpack :: NarUnpackSink -> IO (Either Text ())-finishNarUnpack (NarUnpackSink ref) = do-  narState <- readIORef ref-  case (nusOpen narState, nusFrames narState) of-    (Just _, _) -> pure (Left "NAR stream sink: stream ended inside a file")-    (Nothing, _ : _) -> pure (Left "NAR stream sink: stream ended inside a directory")-    (Nothing, []) -> createSymlinks (reverse (nusLinks narState))---- | Close any open handle so the caller can remove the partial tree;--- Windows will not delete a file a handle still holds open.-abortNarUnpack :: NarUnpackSink -> IO ()-abortNarUnpack (NarUnpackSink ref) = do-  narState <- readIORef ref-  case nusOpen narState of-    Nothing -> pure ()-    Just (fileHandle, _, _) ->-      hClose fileHandle `catch` \(_ :: IOException) -> pure ()-  writeIORef ref narState {nusOpen = Nothing}---- | Why a streamed archive stopped short of its end.-data NarStreamFailure-  = -- | The store refused what the archive holds (a name, a taken-    -- path): a property of the archive, not of how it arrived.-    NarStreamRefused !Text-  | -- | The bytes do not parse as a NAR.  A truncated or torn transfer-    -- reads the same as a malformed archive.-    NarStreamMalformed !Text-  deriving (Eq, Show)---- | Feed a chunk source through the streaming NAR parser into a sink,--- hashing and counting exactly the bytes the parser consumes, and--- return the archive's SHA-256 and size once its root node closes.--- The recorded symlinks are not created yet ('finishNarUnpack'), so a--- caller checks the digest before any link exists.  On a failure the--- sink is already aborted.-sinkNarStream :: NarUnpackSink -> IO BS.ByteString -> IO (Either NarStreamFailure (Hash.NixHash, Int))-sinkNarStream sink source = go Hash.hashInit 0 Stream.narStream `onException` abortNarUnpack sink-  where-    go !ctx !count step = case step of-      Stream.NarAwait continue -> do-        chunk <- source-        go (Hash.hashUpdate ctx chunk) (count + BS.length chunk) (continue chunk)-      Stream.NarYield event next -> do-        sunk <- sinkNarEvent sink event-        either (stopWith . NarStreamRefused) (const (go ctx count next)) sunk-      Stream.NarFail msg -> stopWith (NarStreamMalformed (T.pack msg))-      Stream.NarDone -> pure (Right (Hash.hashFinalize ctx, count))-    stopWith failure = Left failure <$ abortNarUnpack sink---- ------------------------------------------------------------------------------ Eval source materialization--- ------------------------------------------------------------------------------- | Restore eval-coerced source paths into the store and register them.--- The evaluator's source-path cache maps each coerced filesystem path to--- its @source@ fixed-output store path (text only - eval performs no--- store writes).  Each entry not already valid is restored from a dump--- of its source ('restoreSource'), made read-only, and registered.  A--- source carries no references.-materializeEvalSources :: Store -> Map Text Text -> IO ()-materializeEvalSources store sourceCache = mapM_ adopt (Map.toList sourceCache)-  where-    -- Each source registers IMMEDIATELY after its restore (sources carry-    -- no cross-references, so there is nothing to batch).  A tree already-    -- on disk is adopted only after verification: its NAR digest must-    -- reproduce the store path being registered - an interrupted earlier-    -- restore leaves a partial tree, and registering it as-is validates-    -- content that does not match its address.  A verified adoption never-    -- touches the files (rewriting a read-only tree fails on Windows and-    -- would wedge the store permanently); a failed one clears and-    -- restores.  Mirrors the builder's own prepareOutput recovery.-    -- The whole check-then-act runs under the path's cross-process-    -- lock, validity re-checked once held: without it, two processes-    -- materializing the same source raced isValid, and the loser's-    -- removePathForcibly deleted the tree the winner had just-    -- registered.  Same protocol as the builder's withOutputLocks.-    adopt (rawPath, spText) =-      case parseStorePath defaultStoreDir spText of-        Nothing -> pure ()-        Just sp -> withPathLock (stDir store) sp $ \_ -> do-          valid <- isValid store sp-          unless valid $ do-            let dest = storePathToFilePath (stDir store) sp-            onDisk <- doesPathExist dest-            adoptable <- if onDisk then adoptedTreeMatches (stCaseSensitivity store) dest sp else pure False-            reg <--              if adoptable-                then registrationFor store sp Nothing []-                else do-                  when onDisk (Dir.removePathForcibly dest)-                  restoreSource store (T.unpack rawPath) sp >>= either (refuse spText) pure-            registerPath (stDB store) reg-    refuse spText reason =-      throwIO (userError (T.unpack ("refusing to register " <> spText <> ": " <> reason)))---- | Restore a source tree at the store path evaluation named it by,--- from a dump of the source, as upstream's @addToStoreFromDump@--- restores the dump it hashed (@restorePath@, local-store.cc at--- 2.24.9) rather than copying files: the source's NAR streams out of--- the walk, through the hash and into an unpack sink in one pass, so a--- sibling pair the store's volume folds takes the case-hack on the way--- in, and no file's contents are ever held whole.  The source is read--- as evaluation read it to name the path, under the process's--- case-hack setting, and the restored tree as a store path, under its--- volume's.------ Evaluation hashed the source earlier, so the dump is held to that--- address before any link is created: a source that changed in between--- is refused, never registered under a hash its bytes no longer have.--- The restored tree is then rechecked on disk, as the substituter--- rechecks an unpacked one, since the volume decides the final--- spelling of every name.  Any failure removes the tree.-restoreSource :: Store -> FilePath -> StorePath -> IO (Either Text PathRegistration)-restoreSource store src sp = do-  outcome <- restore `onException` Dir.removePathForcibly dest-  either (\reason -> Left reason <$ Dir.removePathForcibly dest) (pure . Right) outcome-  where-    dest = storePathToFilePath (stDir store) sp-    restore = do-      sink <- newNarUnpackSink (stCaseSensitivity store) dest-      streamed <- ExecBit.withNarSource processCaseHack src (sinkNarStream sink)-      case streamed of-        Left (NarStreamRefused reason) -> pure (Left reason)-        Left (NarStreamMalformed reason) -> pure (Left ("the dump of " <> T.pack src <> " does not parse: " <> reason))-        Right (digest, size)-          | not (recursiveDigestNames sp digest) -> do-              abortNarUnpack sink-              pure (Left (T.pack src <> " changed after evaluation hashed it, so it no longer reproduces its store path; re-evaluate"))-          | otherwise -> do-              finished <- finishNarUnpack sink-              either (pure . Left) (const (sealAndRecheck digest size)) finished-    sealAndRecheck digest size = do-      setReadOnly dest-      onDisk <- ExecBit.narHashOfPath (volumeCaseHack (stCaseSensitivity store)) dest-      pure $-        if onDisk /= digest-          then Left "the restored tree does not reproduce its store path on disk"-          else-            Right-              PathRegistration-                { prPath = sp,-                  prNarHash = Hash.formatNixHash digest,-                  prNarSize = size,-                  prDeriver = Nothing,-                  prReferences = []-                }---- | Whether a recursive NAR digest and a store path's own name derive--- exactly that path, as a @source@ path's address is derived.-recursiveDigestNames :: StorePath -> Hash.NixHash -> Bool-recursiveDigestNames sp (Hash.NixHash digest) =-  makeFixedOutputPath (spName sp) "sha256" "recursive" digest == Right sp---- | Register the store objects evaluation wrote: makes each read-only--- and records it in the DB.  Batched so a write referring to another--- resolves.  Covers every eval-time writer, not only @builtins.toFile@:--- an unregistered write reaches @drvInputSrcs@ and fails the build.-materializeEvalStoreWrites :: Store -> Map Text ([StorePath], StoreWriteMode) -> IO ()-materializeEvalStoreWrites store storeWrites = do-  regs <- catMaybes <$> mapM prepare (Map.toList storeWrites)-  unless (null regs) (registerPaths (stDB store) regs)-  where-    -- Checked and sealed under the path's lock, validity re-checked-    -- once held, so a peer mid-producing the same path is waited out-    -- rather than torn-read (and refused).  The lock releases before-    -- the batched registration: registration is an upsert over content-    -- both holders verified reproduces the same path, so the winner-    -- and loser record the same row.-    prepare (spText, (refs, mode)) =-      case parseStorePath defaultStoreDir spText of-        Nothing -> pure Nothing-        Just sp -> withPathLock (stDir store) sp $ \_ -> do-          valid <- isValid store sp-          if valid-            then pure Nothing-            else do-              let dest = storePathToFilePath (stDir store) sp-              onDisk <- doesPathExist dest-              -- Absent means removed since eval; nothing to register.-              if not onDisk-                then pure Nothing-                else do-                  -- The writers verified (or rewrote) this content at-                  -- write time; a mismatch here means the tree changed-                  -- between evaluation and registration, and registering-                  -- it would record a hash its bytes do not have, then-                  -- seal the lie read-only.  Refuse loudly instead.-                  reproduces <- writeReproducesPath (stCaseSensitivity store) dest sp refs mode-                  unless reproduces $-                    throwIO-                      ( userError-                          ( "refusing to register "-                              <> T.unpack spText-                              <> ": the on-disk content does not reproduce its store path; "-                              <> "delete the path and re-evaluate"-                          )-                      )-                  setReadOnly dest-                  Just <$> registrationFor store sp Nothing refs---- | Whether on-disk content re-derives exactly the store path it is--- about to be registered under, under the scheme that named the write.--- An unreadable destination counts as a mismatch.-writeReproducesPath :: CaseSensitivity -> FilePath -> StorePath -> [StorePath] -> StoreWriteMode -> IO Bool-writeReproducesPath sensitivity dest sp refs mode = case mode of-  WriteRecursive -> adoptedTreeMatches sensitivity dest sp-  WriteFlat ->-    withFileBytes (\bytes -> makeFixedOutputPath (spName sp) "sha256" "flat" (sha256Digest bytes) == Right sp)-  WriteText ->-    withFileBytes (\bytes -> makeTextPath (spName sp) (sha256Digest bytes) refs == Right sp)-  where-    withFileBytes check = do-      result <- try (BS.readFile dest) :: IO (Either IOException BS.ByteString)-      pure (either (const False) check result)---- | Whether an on-disk tree reproduces the source store path it is about to--- be registered under: its recursive NAR digest and the path's own name must--- derive exactly this path.  An unreadable tree counts as a mismatch.  The--- sensitivity is the store volume's, which decides the case-hack mode the--- tree is read back under.-adoptedTreeMatches :: CaseSensitivity -> FilePath -> StorePath -> IO Bool-adoptedTreeMatches sensitivity dest sp = do-  result <- try (ExecBit.serialiseFromPath (volumeCaseHack sensitivity) dest)-  pure $ case result of-    Left (_ :: IOException) -> False-    Right entry -> recursiveDigestNames sp (NAR.narHash entry)+{-# LANGUAGE CPP #-}+{-# LANGUAGE ExistentialQuantification #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | The Nix store: content-addressed, immutable package storage.+--+-- == What the store actually does+--+-- When Nix builds a package, the output goes into the store:+--+-- 1. Builder runs in a build directory under the store's state directory+--    and writes the output at its store path, or for a Linux sandboxed+--    build at that path beneath its chroot ("Nix.Builder")+-- 2. Output is scanned for references to other store paths+-- 3. A Linux sandboxed build's output is moved to+--    @\/nix\/store\/\<hash\>-\<name\>@; any other build's is there+--    already+-- 4. Its files' modes and times are made canonical: read-only, and one+--    modification time ("Nix.Store.Metadata")+-- 5. Path is registered in the SQLite DB with its references+--+-- When Nix SUBSTITUTES (downloads from a binary cache):+--+-- 1. Fetch @\<hash\>.narinfo@ from cache - contains NAR hash, size, refs+-- 2. Fetch the NAR file the narinfo's @URL@ names, compressed with xz,+--    zstd or bzip2, or not at all+-- 3. Decompress and unpack NAR into store path, checking its NAR hash+--    and size against the narinfo as it streams+-- 4. Make its files' modes and times canonical, as a build's+-- 5. Verify NAR hash matches narinfo, on disk+-- 6. Register path in DB with references from narinfo+--+-- Both paths end the same way: a registered, immutable store path.+--+-- == Garbage collection+--+-- A GC root is an explicit "keep this" marker: the out-link @build@+-- makes to its output, or a file the operator drops under the+-- store's @gcroots@ directory.  The collector walks every root, follows+-- references transitively, and deletes everything not reachable; a+-- delete of named paths refuses a path that walk reaches.+-- "Nix.Store.GC" holds the roots model, the walk, the sweep, the delete+-- of named paths, and the lock that keeps a collection and a concurrent+-- writer apart; "Nix.Store.Handle" holds the open handle and its lease+-- on that lock.+module Nix.Store+  ( -- * Queries+    isValid,+    pathExists,++    -- * Deletion+    resolveDeleteTarget,++    -- * The process+    useStoreFileMask,++    -- * Store operations+    addToStore,+    addSourceTree,+    copyPathInto,+    placeInStore,+    moveOutput,+    registrationFor,+    materializeEvalSources,+    materializeEvalStoreWrites,+    replaceWithCopy,+    freshCopyPath,+    rewriteBytes,+    rewriteStoreHashes,+    scanReferences,+    canonicalizeMetadata,+    unpackNarEntry,+    writeDrv,+    writeDrvAterm,+    writeDrvClosure,+    drvReferences,++    -- * Streaming NAR unpacking+    NarUnpackSink,+    newNarUnpackSink,+    sinkNarEvent,+    finishNarUnpack,+    NarLinks,+    closeNarUnpack,+    moveNarUnpack,+    abortNarUnpack,+    NarStreamFailure (..),+    ArchiveEnd (..),+    NarFeed,+    NarFed (..),+    startNarFeed,+    feedNar,+    endNar,+    sinkNarStream,+    checkNarClaim,+    narHashMismatch,+    narSizeMismatch,++    -- * Paths copied in+    SignatureRequirement (..),+    AddressedPath (..),+    addressMakesPath,+    addressRegistrable,+    fixedReferencesRefusal,+    notContentAddressed,++    -- * Link ordering (exposed for testing)+    orderLinks,++    -- * Rewriting a file in place (exposed for testing)+    rewriteRegularFile,++    -- * Case-hack naming (exposed for testing)+    onDiskNameKey,+    caseHackDiskNames,++    -- * Re-exports+    module Nix.Store.Path,+    module Nix.Store.DB,+    module Nix.Store.Lock,+    module Nix.Store.CaseSensitive,+    module Nix.Store.Handle,+    module Nix.Store.GC,+    module Nix.Store.Upstream,+  )+where++import Control.Exception (IOException, bracket, catch, finally, onException, throwIO, try, tryJust)+import Control.Monad (guard, unless, when)+import Data.Bool (bool)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BS8+import Data.Char (toUpper)+import Data.Foldable (fold, traverse_)+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.List (inits, stripPrefix)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (catMaybes)+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Nix.Daemon.Protocol (ContentAddress, ContentAddressMethod (..), caAlgo, caDigest, caMethod, contentAddressFromParts)+import Nix.Derivation (Derivation (..), fromATerm, toATerm)+import Nix.Hash (FileIngestionMethod (..), makeFixedOutputPath, makeSourcePath, makeStorePath, makeTextPath, sha256Digest)+import Nix.Logger (Level (..), Logger (..))+import Nix.Store.CaseSensitive (CaseSensitivity (..), pathCaseHack, trySetCaseSensitiveDir, volumeCaseHack)+import Nix.Store.DB+import Nix.Store.EntryName (checkEntryName, entryNamePath, hostNameRules, linkTargetPath, shownBytes)+import Nix.Store.Exclusive (Occupant (..), directoryTakenMessage, fileTakenMessage, openNewBinaryFile, symlinkTakenMessage)+import qualified Nix.Store.ExecBit as ExecBit+import Nix.Store.GC+import Nix.Store.Handle+import Nix.Store.Lock+import Nix.Store.Metadata (canonicalizeMetadata)+import Nix.Store.Path+import Nix.Store.Symlink (WalkNode (..), classifyWalkNode, createSymlinkOfKind)+import Nix.Store.Upstream+import qualified NovaCache.Base64 as B64+import qualified NovaCache.Hash as Hash+import qualified NovaCache.NAR as NAR+import qualified NovaCache.NAR.Stream as Stream+import qualified NovaCache.Signing as Signing+import System.Directory+  ( doesDirectoryExist,+    doesPathExist,+    listDirectory,+    renamePath,+    setPermissions,+  )+import qualified System.Directory as Dir+import qualified System.Directory.OsPath as OsDir+import System.FilePath ((</>))+import qualified System.FilePath.Windows as Windows+import System.IO (Handle, IOMode (ReadMode), hClose, withBinaryFile)+import System.IO.Error (isAlreadyExistsError)+import System.OsPath (OsPath)+import qualified System.OsPath as OP+#if !defined(mingw32_HOST_OS)+import Data.Bits ((.&.), (.|.))+import Data.Functor (void)+import Foreign.C.Error (Errno (..), eXDEV)+import GHC.IO.Exception (IOException (ioe_errno))+import System.Posix.Files (FileStatus, deviceID, fileID, fileMode, fileSize, getFdStatus, getSymbolicLinkStatus, groupWriteMode, isDirectory, isRegularFile, otherWriteMode, ownerWriteMode, setFdMode, setFdSize, setFileCreationMask, setFileMode)+import System.Posix.IO (OpenFileFlags (..), OpenMode (..), closeFd, defaultFileFlags, openFd)+import qualified System.Posix.IO.ByteString as PosixBytes+import System.Posix.Types (Fd)+#endif++-- | Give the process upstream's file-creation mask, 0022, as every+-- upstream command does (@initNix@ in shared.cc): what it writes, and what a+-- builder it starts writes, is then readable by everybody and writable by its+-- owner alone, so no build's output is refused as one others could have+-- changed (@registerOutputs@).  Windows has no such mask.+useStoreFileMask :: IO ()+#if defined(mingw32_HOST_OS)+useStoreFileMask = pure ()+#else+useStoreFileMask = void (setFileCreationMask (groupWriteMode .|. otherWriteMode))+#endif++-- | Check if a store path is registered as valid in the database.+isValid :: Store -> StorePath -> IO Bool+isValid = isValidPath . stDB++-- | Check if a store path exists on disk (file or directory, regardless of DB).+pathExists :: Store -> StorePath -> IO Bool+pathExists store sp = doesPathExist (storePathToFilePath (stDir store) sp)++-- ---------------------------------------------------------------------------+-- Deletion+-- ---------------------------------------------------------------------------++-- | Resolve a @store delete@ argument to the store entry it names: a bare+-- @hash-name@ basename, or a full path spelled under the opened store's+-- directory, the platform store, or the canonical store, with either+-- separator.  The name after the last separator is refused as+-- 'storeEntryName' refuses a library caller's, in its words, so the+-- command and the library delete refuse the same names; like it, this+-- does not check the name as a store path name.  Lock files are refused+-- too, but not here: names like @flake.lock@ are legal store-path names,+-- so telling a lock file from a store object needs the registration+-- rows, and that decision lives in 'deleteStorePathRaw'.+resolveDeleteTarget :: StoreDir -> Text -> Either Text StoreEntryName+resolveDeleteTarget storeDir raw = storeEntryName basename >>= underThisStore+  where+    underThisStore name+      | dirOk = Right name+      | otherwise = Left (raw <> ": not a path under this store")+    basename = T.takeWhileEnd (not . Windows.isPathSeparator) raw+    dirPart =+      normalizeSeps+        (T.dropWhileEnd Windows.isPathSeparator (T.dropEnd (T.length basename) raw))+    dirOk =+      T.null dirPart+        || dirPart+          `elem` [ normalizeSeps (T.pack (unStoreDir storeDir)),+                   normalizeSeps (T.pack (unStoreDir platformStoreDir)),+                   normalizeSeps (T.pack (unStoreDir defaultStoreDir))+                 ]+    normalizeSeps = T.map (\c -> if c == '\\' then '/' else c)++-- ---------------------------------------------------------------------------+-- Store operations+-- ---------------------------------------------------------------------------++-- | Move a build output (file or directory) to the store path, make its+-- metadata canonical ('canonicalizeMetadata'), and register.+--+-- If @renamePath@ fails across volumes (on Windows, for any reason), falls+-- back to copy + remove.+addToStore ::+  Store ->+  FilePath ->+  StorePath ->+  Maybe Text ->+  [StorePath] ->+  IO ()+addToStore store srcPath sp deriver refs = do+  reg <- placeInStore store srcPath sp deriver refs+  registerPath (stDB store) reg++-- | Move a build output into the store, make its metadata canonical+-- ('canonicalizeMetadata'), and compute its registration (NAR hash, size,+-- references) WITHOUT writing to the database.+--+-- Splitting placement from registration lets a multi-output build place every+-- output first and then register them together, so intra-derivation+-- cross-output references are preserved (see 'registerPaths').+placeInStore ::+  Store ->+  FilePath ->+  StorePath ->+  Maybe Text ->+  [StorePath] ->+  IO PathRegistration+placeInStore store srcPath sp deriver refs = do+  let destPath = storePathToFilePath (stDir store) sp+  moveOutput srcPath destPath+  canonicalizeMetadata destPath+  registrationFor store sp deriver refs++-- | Compute the registration metadata for a store path already present on+-- disk, without moving anything.  Used by 'placeInStore' after its move,+-- and by 'materializeEvalSources' to register a verified adopted tree.+-- The path is not ultimately trusted and has no signatures or content+-- address; a caller that knows better says so in the registration.+registrationFor :: Store -> StorePath -> Maybe Text -> [StorePath] -> IO PathRegistration+registrationFor store sp deriver refs = do+  let destPath = storePathToFilePath (stDir store) sp+  -- Compute the NAR hash and size of the final store contents.  The NAR+  -- serialization is canonical (entries sorted, 8-byte padding), so this is+  -- exactly the NarHash/NarSize a binary cache reports for the path.+  narEntry <- ExecBit.serialiseFromPath (volumeCaseHack (stCaseSensitivity store)) destPath+  let narBytes = NAR.serialise narEntry+  pure+    PathRegistration+      { prPath = sp,+        prNarHash = Hash.formatNixHash (Hash.hashBytes narBytes),+        prNarSize = BS.length narBytes,+        prDeriver = deriver,+        prReferences = refs,+        prUltimate = NotUltimate,+        prSignatures = Set.empty,+        prContentAddress = Nothing,+        prRegistrationTime = RegisteredNow+      }++-- | Move a file or directory, by a rename, as upstream's @movePath@+-- does (local-derivation-goal.cc at 2.24.9, unix\/file-system.cc at 2.36.0):+-- a directory its owner may not write, as a canonical one is, is given owner+-- write for the rename, which needs it to change the directory's @..@, and+-- its mode back after.  A rename that fails fails the move, so a tree keeps+-- its inodes and hard links, except across volumes, where the move copies and+-- removes ('copyPathInto', which keeps symlinks as symlinks: a dereferencing+-- copy would make the stored bytes, and the NAR hash a cache signs, depend on+-- where the source was).  On Windows every failure copies.+moveOutput :: FilePath -> FilePath -> IO ()+moveOutput src dest+  -- A build writes into its own output path, so the usual case is a move+  -- onto itself.  POSIX rename(a,a) is a benign no-op, but MoveFileEx is+  -- documented as unusable when either name is a directory, and the+  -- IOException fallback below would then copy a tree into itself and+  -- delete the result.  Answering here settles both platforms.+  | src == dest = pure ()+#if defined(mingw32_HOST_OS)+  | otherwise =+      renamePath src dest `catch` \(_ :: IOException) -> do+        copyPathInto src dest+        Dir.removePathForcibly src+#else+  | otherwise = do+      status <- getSymbolicLinkStatus src+      let mode = fileMode status+      if isDirectory status && mode .&. ownerWriteMode == 0+        then do+          setFileMode src (mode .|. ownerWriteMode)+          rename `onException` setFileMode src mode+          setFileMode dest mode+        else rename+  where+    rename =+      renamePath src dest `catch` \(failure :: IOException) ->+        if ioe_errno failure == Just (case eXDEV of Errno number -> number)+          then copyPathInto src dest *> Dir.removePathForcibly src+          else throwIO failure+#endif++-- | Byte-scan a tree for store path references.+--+-- Searches each scan unit ('collectScanUnits': regular file bytes,+-- symlink target strings and entry names) for each candidate's bare+-- 32-character hash - the same needle upstream Nix scans for.  Matching+-- the hash rather than a store-dir-prefixed path keeps the scan+-- independent of the spelling the builder embedded (canonical+-- @\/nix\/store\/...@, @C:\\nix\\store\\...@, @C:\/nix\/store\/...@):+-- a builder is handed its store paths under the store's real directory+-- (the derivation's canonical spelling is rewritten at the spawn, in+-- "Nix.Builder"), and what it writes from them may spell that directory+-- any of these ways.+scanReferences :: [StorePath] -> FilePath -> IO [StorePath]+scanReferences candidates dir = do+  let candidateSet = Set.fromList [(spHash sp, sp) | sp <- candidates]+      needles = [(TE.encodeUtf8 h, h) | (h, _) <- Set.toList candidateSet]+  units <- collectScanUnits dir+  foundHashes <- foldlIO Set.empty units $ \acc unit -> do+    contents <- scanUnitBytes unit+    pure (Set.union acc (Set.fromList [h | (needle, h) <- needles, needle `BS.isInfixOf` contents]))+  pure [sp | (h, sp) <- Set.toList candidateSet, Set.member h foundHashes]++-- | Replace store path hashes across a tree: file bytes, symlink targets and+-- entry names, every place a NAR carries one.  Upstream rewrites the serialized+-- NAR and so reaches all three (@rewriteOutput@ in+-- @local-derivation-goal.cc@ at 2.24.9).  A store path hash has one length, so+-- no offset inside a file moves.+rewriteStoreHashes :: [(Text, Text)] -> FilePath -> IO ()+rewriteStoreHashes [] _ = pure ()+rewriteStoreHashes rewrites root = rewriteAt id root+  where+    byteRewrites = [(TE.encodeUtf8 from, TE.encodeUtf8 to) | (from, to) <- rewrites]+    nameRewrites = [(T.unpack from, T.unpack to) | (from, to) <- rewrites]+    rewriteName name = foldl' (\acc (from, to) -> replaceInName from to acc) name nameRewrites+    -- Replacing a link edits its parent, so the guard for a read-only parent+    -- comes from the caller: the root's parent is the store, not the output.+    rewriteAt parentGuard path = do+      node <- classifyWalkNode path+      case node of+        WalkSymlink -> do+          target <- Dir.getSymbolicLinkTarget path+          let updated = rewriteName target+          unless (updated == target) (parentGuard (replaceLink path updated))+        WalkDirectory -> do+          entries <- listDirectory path+          mapM_ (rewriteEntry path) entries+        WalkRegular -> rewriteRegularFile (rewriteBytes byteRewrites) path+        WalkAbsent -> pure ()+    rewriteEntry dir entry = do+      rewriteAt (whileWritable dir) (dir </> entry)+      let renamed = rewriteName entry+      unless (renamed == entry) $ do+        taken <- doesPathExist (dir </> renamed)+        when taken (ioError (userError ("rewriting a store hash would overwrite " <> (dir </> renamed))))+        whileWritable dir (renamePath (dir </> entry) (dir </> renamed))++-- | Change a regular file's bytes in place.  On POSIX it never follows a+-- link: the file is opened without following one, read and written+-- through descriptors that name the inode the first open found, a second+-- open that finds another refused, and made writable for the write+-- through its own descriptor, its mode put back after: a link put at the+-- name after the walk's @lstat@ fails the rewrite, where a path-based read+-- and write would follow it out of the tree.+rewriteRegularFile :: (BS.ByteString -> BS.ByteString) -> FilePath -> IO ()+#if defined(mingw32_HOST_OS)+rewriteRegularFile change path = do+  bytes <- BS.readFile path+  let updated = change bytes+  unless (updated == bytes) (whileWritable path (BS.writeFile path updated))+#else+rewriteRegularFile change path =+  bracket (openFd path ReadOnly noFollow) closeFd $ \reader -> do+    status <- getFdStatus reader+    unless (isRegularFile status) (ioError (userError ("'" <> path <> "' is not a regular file")))+    -- The file is canonical by now, so only its owner may write it, and+    -- what its size says is the bytes there are to read.+    bytes <- readSize reader (fromIntegral (fileSize status))+    let updated = change bytes+    unless (updated == bytes) $+      bracket (setFdMode reader (fileMode status .|. ownerWriteMode)) (\() -> setFdMode reader (fileMode status)) $ \() ->+        bracket (openFd path WriteOnly noFollow) closeFd $ \writer -> do+          reopened <- getFdStatus writer+          unless (sameNode status reopened) (ioError (userError ("'" <> path <> "' was replaced while it was rewritten")))+          writeWhole writer updated+          setFdSize writer (fromIntegral (BS.length updated))+  where+    noFollow = defaultFileFlags {nofollow = True, cloexec = True}++-- | Whether two statuses are of one inode.+sameNode :: FileStatus -> FileStatus -> Bool+sameNode one other = deviceID one == deviceID other && fileID one == fileID other++-- | The bytes a read makes at most at once from a descriptor.+readChunkBytes :: Int+readChunkBytes = 65536++-- | Read a number of bytes from a descriptor, failing at an end before+-- them.+readSize :: Fd -> Int -> IO BS.ByteString+readSize fd = go []+  where+    go chunks 0 = pure (BS.concat (reverse chunks))+    go chunks remaining = do+      chunk <- PosixBytes.fdRead fd (fromIntegral (min remaining readChunkBytes))+      go (chunk : chunks) (remaining - BS.length chunk)++-- | Write all of some bytes to a descriptor, from where it is.+writeWhole :: Fd -> BS.ByteString -> IO ()+writeWhole fd bytes+  | BS.null bytes = pure ()+  | otherwise = do+      written <- PosixBytes.fdWrite fd bytes+      writeWhole fd (BS.drop (fromIntegral written) bytes)+#endif++-- | Replace a node with a fresh copy of itself, as upstream replaces a+-- fixed-output output before it hashes one: a+-- descriptor the builder passed out of its build names the old inode, which+-- the copy leaves behind, so nothing written through it reaches what is+-- registered.  The copy is made beside the node ('freshCopyPath'), the+-- node is removed and the copy renamed to its name, and the copy is+-- removed should the replacement fail.+replaceWithCopy :: FilePath -> IO ()+replaceWithCopy path = do+  let copy = freshCopyPath path+  Dir.removePathForcibly copy+  ( do+      copyPathInto path copy+      Dir.removePathForcibly path+      renamePath copy path+    )+    `onException` Dir.removePathForcibly copy++-- | Where 'replaceWithCopy' copies a node, upstream's name beside it.+freshCopyPath :: FilePath -> FilePath+freshCopyPath path = path <> ".tmp"++-- | Point a symlink somewhere else.  'Dir.removePathForcibly' removes a file+-- link or a directory link alike, which differ on Windows.+replaceLink :: FilePath -> FilePath -> IO ()+replaceLink path target = do+  linkOs <- OP.encodeFS path+  targetOs <- OP.encodeFS target+  Dir.removePathForcibly path+  created <- createSymlinkOfKind linkOs targetOs+  either (ioError . userError . T.unpack) pure created++-- | Run an action on a path with write permission, then put its permissions+-- back.  A builder may mark its output read-only before registration does.+whileWritable :: FilePath -> IO a -> IO a+whileWritable path action = do+  permissions <- Dir.getPermissions path+  setPermissions path (Dir.setOwnerWritable True permissions)+  action `finally` setPermissions path permissions++-- | Apply each replacement to bytes, in order.  An empty needle matches+-- nothing.+rewriteBytes :: [(BS.ByteString, BS.ByteString)] -> BS.ByteString -> BS.ByteString+rewriteBytes rewrites bytes = foldl' (\acc (from, to) -> replaceInBytes from to acc) bytes rewrites++replaceInBytes :: BS.ByteString -> BS.ByteString -> BS.ByteString -> BS.ByteString+replaceInBytes from to bytes+  | BS.null from = bytes+  | otherwise = BS.concat (pieces bytes)+  where+    pieces remaining = case BS.breakSubstring from remaining of+      (before, rest)+        | BS.null rest -> [before]+        | otherwise -> before : to : pieces (BS.drop (BS.length from) rest)++-- | 'replaceInBytes' on a path component.  The rest of the name is left as+-- the operating system spelled it, so no decoding step can damage it.+replaceInName :: String -> String -> String -> String+replaceInName from to name = case name of+  _ | null from -> name+  [] -> []+  c : rest -> case stripPrefix from name of+    Just after -> to ++ replaceInName from to after+    Nothing -> c : replaceInName from to rest++-- | One scannable unit of a walked tree: a regular file's bytes read+-- from disk, a symlink's target string, or an entry's name.  The NAR+-- serialization carries all three and upstream scans that serialization,+-- so reference scanning covers all three - a link into a dependency+-- (@bin\/tool -> \/nix\/store\/\<hash\>-dep\/tool@) references the+-- dependency even when no file byte does.+data ScanUnit = ScanFile !FilePath | ScanText !BS.ByteString++-- | Collect the scannable units under a path: regular files, symlink+-- targets and the names of a directory's entries, links never followed.+-- A path that is itself a regular file or link is its own single unit.+collectScanUnits :: FilePath -> IO [ScanUnit]+collectScanUnits path = do+  node <- classifyWalkNode path+  case node of+    WalkSymlink -> do+      target <- Dir.getSymbolicLinkTarget path+      pure [ScanText (TE.encodeUtf8 (T.pack target))]+    WalkDirectory -> do+      entries <- listDirectory path+      nested <- concat <$> mapM (collectScanUnits . (path </>)) entries+      pure (map (ScanText . TE.encodeUtf8 . T.pack) entries ++ nested)+    WalkRegular -> pure [ScanFile path]+    WalkAbsent -> pure []++-- | The bytes a 'ScanUnit' contributes to the scan.+scanUnitBytes :: ScanUnit -> IO BS.ByteString+scanUnitBytes (ScanFile path) = BS.readFile path+scanUnitBytes (ScanText text) = pure text++-- | Strict left fold over a list in IO.  The accumulator is forced to+-- WHNF each step - without it, the scan retains every scanned file's+-- bytes in Set.union thunks until the end (peak memory ~ total tree+-- size).  Set's spine-strict nodes make WHNF force the whole union.+foldlIO :: a -> [b] -> (a -> b -> IO a) -> IO a+foldlIO z [] _ = pure z+foldlIO z (x : xs) f = do+  !acc <- f z x+  foldlIO acc xs f++-- | Write an already-serialized derivation ATerm to its store path and make+-- its metadata canonical ('canonicalizeMetadata'), as upstream Nix adds a+-- @.drv@.  Used to materialize the input @.drv@+-- closure (root plus every transitive input) before a dependency-aware build:+-- evaluation computes these ATerms and records them without writing them,+-- so the build driver writes them here.  A file that already holds exactly+-- these bytes is kept as it is, read-only from the write that made it; one+-- holding anything else, which an interrupted write can leave, is replaced.+writeDrvAterm :: Store -> StorePath -> BS.ByteString -> IO ()+writeDrvAterm store sp aterm = do+  let destPath = storePathToFilePath (stDir store) sp+  existing <- try (BS.readFile destPath)+  unless (either (\(_ :: IOException) -> False) (== aterm) existing) $ do+    Dir.removePathForcibly destPath+    -- Raw bytes, not text-mode IO: the path was computed from exactly these+    -- bytes, and a locale-dependent or newline-translating write would store+    -- bytes that no longer match their content address.+    BS.writeFile destPath aterm+  canonicalizeMetadata destPath++-- | Serialize a derivation to ATerm, write it to the store, and register+-- it: a @.drv@ is a store object like any other, so it gets a ValidPaths+-- row with its NAR hash, its references and the text address its path is+-- made from ('textAddress').  Reference scans may name a @.drv@ (one in a+-- build's input closure, where a @drvPath@'s context puts it), and an+-- unregistered referent fails the whole registration batch.+writeDrv :: Store -> Derivation -> StorePath -> IO ()+writeDrv store drv sp = do+  let aterm = toATerm drv+  writeDrvAterm store sp aterm+  reg <- registrationFor store sp Nothing (drvReferences drv)+  registerPath (stDB store) reg {prContentAddress = textAddress aterm}++-- | The content address of a store object made from a text, as a @.drv@+-- is: the SHA-256 of its bytes under the text method.+textAddress :: BS.ByteString -> Maybe ContentAddress+textAddress = contentAddressFromParts TextMethod sha256Algo . sha256Digest++-- | The algorithm every content address nova-nix makes a path from hashes+-- with.+sha256Algo :: Text+sha256Algo = "sha256"++-- | A @.drv@'s references: its input sources and input @.drv@ paths -+-- the same set upstream records when writing a derivation to the store.+drvReferences :: Derivation -> [StorePath]+drvReferences drv = drvInputSrcs drv ++ Map.keys (drvInputDrvs drv)++-- | Write every recorded @.drv@ ATerm (keyed by its store-path text) to+-- the store and register the whole closure in one batch: rows all land+-- before edges ('registerPaths'), so references between the closure's+-- own @.drv@ files resolve regardless of map order.  Input SOURCES must+-- already be registered - the build driver runs 'materializeEvalSources'+-- first.+--+-- Keys come from evaluation via 'storePathToText' so they always parse;+-- an unparseable key is skipped defensively.  The ATerm bytes were+-- rendered by evaluation, so a re-parse failure is an invariant break+-- and throws rather than registering a recipe with dropped references.+writeDrvClosure :: Store -> Map Text BS.ByteString -> IO ()+writeDrvClosure store closure = do+  regs <- mapM writeOne (Map.toList closure)+  registerPaths (stDB store) (catMaybes regs)+  where+    writeOne (pathText, aterm) =+      case parseStorePath defaultStoreDir pathText of+        Nothing -> pure Nothing+        Just sp -> do+          writeDrvAterm store sp aterm+          case fromATerm aterm of+            Right drv -> (\reg -> Just reg {prContentAddress = textAddress aterm}) <$> registrationFor store sp Nothing (drvReferences drv)+            Left err ->+              throwIO+                ( userError+                    ( "writeDrvClosure: recorded ATerm for "+                        <> T.unpack pathText+                        <> " does not re-parse: "+                        <> T.unpack err+                    )+                )++-- ---------------------------------------------------------------------------+-- Exclusive creation+-- ---------------------------------------------------------------------------++-- Every regular file and directory a tree materializes is created+-- exclusively: a name already taken refuses the write instead of+-- landing on the earlier entry.  'onDiskNameKey' predicts which+-- siblings a folding volume merges, but only the volume knows its own+-- fold table, so the create is what catches a pair the key misses.+-- Upstream's restore creates the same way (@RestoreSink@ in+-- fs-sink.cc at 2.24.9: @O_CREAT | O_EXCL@ for a regular file, a+-- refused @create_directory@ for a directory), and the refusals carry+-- its words ("Nix.Store.Exclusive").  Symlinks need nothing extra:+-- @symlink(2)@ and CreateSymbolicLinkW never replace an existing name,+-- and 'createSymlinkOfKind' words that refusal as upstream does.++-- | Run a create that must find its name free, its refusal becoming the+-- failure the given action describes.  Only the refusal becomes a+-- value: it is a property of the tree being written, where any other+-- I\/O failure (permissions, a full disk) is one of the machine and+-- stays an exception.+refuseTaken :: IO Text -> IO a -> IO (Either Text a)+refuseTaken describe create = do+  attempt <- tryJust (guard . isAlreadyExistsError) create+  either (const (Left <$> describe)) (pure . Right) attempt++-- | Create a regular file of a materialized tree exclusively and write+-- it through the handle, closed on the way out.+withNewTreeFile :: OsPath -> (Handle -> IO a) -> IO (Either Text a)+withNewTreeFile path write =+  bracket (openNewTreeFile path) (traverse_ hClose) (traverse write)++-- | Open a regular file of a materialized tree, created exclusively.+openNewTreeFile :: OsPath -> IO (Either Text Handle)+openNewTreeFile path = refuseTaken (fileTakenMessage <$> OP.decodeFS path) (openNewBinaryFile path)++-- | Create a directory of a materialized tree exclusively.  Its parent+-- is created first if missing, which only the root can need.  A+-- refusal asks what holds the name, as @create_directory@ does before+-- it chooses between returning false and throwing.+createTreeDirectory :: OsPath -> IO (Either Text ())+createTreeDirectory path = do+  OsDir.createDirectoryIfMissing True (OP.takeDirectory path)+  refuseTaken describe (OsDir.createDirectory path)+  where+    describe = do+      occupant <- bool OccupiedByOther OccupiedByDirectory <$> OsDir.doesDirectoryExist path+      directoryTakenMessage occupant <$> OP.decodeFS path++-- ---------------------------------------------------------------------------+-- NAR unpacking+-- ---------------------------------------------------------------------------++-- | Unpack a NarEntry tree to a filesystem destination.  Returns @Left@+-- on an entry name or link target the host cannot hold+-- ("Nix.Store.EntryName"); these can come from untrusted cache data, so+-- a typed failure is used instead of a partial 'error'.+--+-- Names and targets reach the filesystem as the bytes the NAR carries,+-- as upstream's restore writes them on POSIX: the tree is walked in+-- 'OsPath's, a POSIX path being bytes.  Only the destination enters as+-- a 'FilePath', spelled as every 'FilePath' API spells it.+--+-- The sensitivity is the destination volume's ('stCaseSensitivity' for+-- a store path) and decides whether case-variant siblings need the+-- case-hack ('onDiskNameKey').+--+-- Regular files and directories are written in one pass; symlinks are+-- created in a second pass, after their targets are materialized.  Windows+-- symlinks are typed (file vs directory) and the NAR format does not record+-- the target's kind, so the only reliable way to pick the flavor is to look+-- at the target on disk - which may sort after the link within the tree.+unpackNarEntry :: CaseSensitivity -> FilePath -> NAR.NarEntry -> IO (Either Text ())+unpackNarEntry sensitivity path entry = do+  root <- OP.encodeFS path+  walked <- unpackTree sensitivity root entry+  case walked of+    Left err -> pure (Left err)+    Right links -> createSymlinks links++-- | First unpack pass: write regular files and directories, recording+-- symlinks as (link path, target) for the second pass.+unpackTree :: CaseSensitivity -> OsPath -> NAR.NarEntry -> IO (Either Text [(OsPath, OsPath)])+unpackTree sensitivity path entry = case entry of+  NAR.NarRegular isExec contents -> do+    OsDir.createDirectoryIfMissing True (OP.takeDirectory path)+    written <- withNewTreeFile path (`BS.hPut` contents)+    case written of+      Left err -> pure (Left err)+      Right () -> do+        when isExec (ExecBit.markExecutableOsPath path)+        pure (Right [])+  NAR.NarSymlink target -> fmap (\targetPath -> [(path, targetPath)]) <$> linkTargetPath target+  NAR.NarDirectory entries -> do+    created <- createTreeDirectory path+    case created of+      Left err -> pure (Left err)+      Right () -> unpackChildren sensitivity path entries++-- | The on-disk identity a NAR entry name occupies on a volume of the+-- given case sensitivity.  Two sibling entries sharing a key name ONE+-- file on that volume, so the unpack keeps them apart+-- (@unpackNamedChildren@).  A folding volume (the default APFS format,+-- NTFS through Win32) keys a name by its uppercase; a sensitive one+-- (Linux, a case-sensitive APFS volume) keys it byte-for-byte.  The+-- fold is per-character uppercase, which keeps apart the collisions+-- real trees carry (@Makefile@\/@makefile@) but not every pair the+-- volume folds: APFS reads U+00DF and U+1E9E as one name while+-- 'toUpper' leaves U+00DF unchanged, so that pair takes two keys and+-- the exclusive create refuses the second at the write, as+-- upstream's restore does.  The reverse miss (U+0131 uppercases to+-- @I@, which APFS keeps distinct) only spells a name with a suffix it+-- did not need.  A name that is not UTF-8 has no characters to fold+-- and keys as its bytes; no host whose volumes fold admits one+-- ("Nix.Store.EntryName"), and the create would catch what the key+-- missed.  Win32 strips a trailing dot or space on create, which would+-- merge names this key keeps apart, but Windows refuses such names+-- before any is keyed.+--+-- Upstream decides this per process, not per volume: its+-- @use-case-hack@ setting defaults to on for Darwin and off elsewhere+-- (archive.cc at 2.24.9), so a case-sensitive macOS volume still has+-- @makefile@ restored as @makefile~nix~case~hack~1@ (observed from+-- @nix-store --restore@ 2.33.2).  The hack exists to work around+-- folding, and a volume that does not fold needs none, so nova-nix+-- keys by the probed answer and materializes true names there.  The+-- divergence is in on-disk spelling only: either tree re-serialises+-- to the same NAR.+onDiskNameKey :: CaseSensitivity -> BS.ByteString -> BS.ByteString+onDiskNameKey sensitivity name = case sensitivity of+  CaseSensitive -> name+  CaseInsensitive -> either (const name) (TE.encodeUtf8 . T.map toUpper) (TE.decodeUtf8' name)++-- | The first pair of sibling names folding to the same on-disk file,+-- if any: (earlier entry, colliding later entry).+firstNameCollision :: CaseSensitivity -> [BS.ByteString] -> Maybe (BS.ByteString, BS.ByteString)+firstNameCollision sensitivity = go Map.empty+  where+    go !_ [] = Nothing+    go !seen (name : rest) =+      let key = onDiskNameKey sensitivity name+       in case Map.lookup key seen of+            Just earlier -> Just (earlier, name)+            Nothing -> go (Map.insert key name seen) rest++-- | Whether a tree on a volume of the given case sensitivity is read+-- back with the case-hack suffix stripped ('volumeCaseHack').  Where+-- it is, an INCOMING entry name carrying the suffix must be rejected:+-- materialized verbatim it would re-serialise under a different name+-- and fail its own hash recheck.  Upstream's restore accepts such a+-- name and its dump then strips the suffix (archive.cc at 2.24.9), so+-- the tree fails there as well, only later; refusing at the write+-- boundary surfaces the same failure before anything is materialized.+-- A volume that keeps names apart reads every name as spelled, so the+-- name materializes and round-trips there.+volumeStripsCaseHack :: CaseSensitivity -> Bool+volumeStripsCaseHack sensitivity = volumeCaseHack sensitivity == NAR.CaseHackEnabled++-- | Refuse an entry name before any sibling is written: one the host+-- cannot hold ('checkEntryName'), or one carrying the case-hack suffix+-- where the destination volume's serialiser would strip it.+admitEntryName :: CaseSensitivity -> BS.ByteString -> Either Text ()+admitEntryName sensitivity name = do+  checkEntryName hostNameRules name+  when (volumeStripsCaseHack sensitivity && NAR.caseHackSuffix `BS.isInfixOf` name) $+    Left ("NAR entry name contains the case-hack suffix: " <> shownBytes name)++-- | The case-hacked disk name for the given occurrence of a key.+caseHackName :: BS.ByteString -> Int -> BS.ByteString+caseHackName name occurrence = name <> NAR.caseHackSuffix <> BS8.pack (show occurrence)++-- | Disk names for a sibling list on a volume of the given case+-- sensitivity, WITHOUT per-directory case sensitivity: upstream's+-- case-hack where names fold, every name as spelled where they do not.+-- The first occurrence of each key keeps its spelling; every later+-- name with the same key gains the reversible suffix and a per-name+-- counter, which the serialiser strips on the way back out+-- ('volumeCaseHack').  Order is preserved; result pairs are (NAR+-- name, on-disk name).+caseHackDiskNames :: CaseSensitivity -> [BS.ByteString] -> [(BS.ByteString, BS.ByteString)]+caseHackDiskNames sensitivity = reverse . snd . foldl' step (Map.empty, [])+  where+    step (!seen, !acc) name =+      let key = onDiskNameKey sensitivity name+       in case Map.lookup key seen of+            Nothing -> (Map.insert key (0 :: Int) seen, (name, name) : acc)+            Just occurrences ->+              let next = occurrences + 1+               in (Map.insert key next seen, (name, caseHackName name next) : acc)++-- | Unpack directory children.  Entry names arrive as the raw bytes+-- the NAR carries, and every sibling's name is admitted+-- ('admitEntryName') before the first is written, so a name the host+-- cannot hold leaves no partial directory behind it.+unpackChildren :: CaseSensitivity -> OsPath -> [(BS.ByteString, NAR.NarEntry)] -> IO (Either Text [(OsPath, OsPath)])+unpackChildren sensitivity path entries = case traverse_ (admitEntryName sensitivity . fst) entries of+  Left err -> pure (Left err)+  Right () -> unpackNamedChildren sensitivity path entries++-- | Unpack admitted directory children.+--+-- On a volume the probe reports sensitive (Linux, case-sensitive APFS)+-- no two sibling names share an on-disk identity and every entry+-- materializes as spelled.  Sibling names folding to one on-disk name+-- (NTFS, default APFS) take the TRUE-NAME path when the platform+-- provides one: the just-created empty directory gains NTFS+-- per-directory case sensitivity and the tree materializes under its+-- real names.  Where the flag is unavailable (a non-NTFS store volume,+-- a folding APFS volume) the collision falls back to upstream's+-- case-hack renaming, which the volume's serialiser reverses.  Either+-- way a registered path re-serialises to its NAR byte-for-byte - the+-- substituter's on-disk recheck verifies it.  The name spelled on disk+-- is the one the host is asked to hold, suffix included.+unpackNamedChildren :: CaseSensitivity -> OsPath -> [(BS.ByteString, NAR.NarEntry)] -> IO (Either Text [(OsPath, OsPath)])+unpackNamedChildren sensitivity path entries = do+  diskNames <- resolveDiskNames+  walkChildren (zip diskNames (map snd entries))+  where+    names = map fst entries+    resolveDiskNames = case firstNameCollision sensitivity names of+      Nothing -> pure names+      Just _ -> do+        trueNames <- trySetCaseSensitiveDir =<< OP.decodeFS path+        pure+          ( if trueNames+              then names+              else map snd (caseHackDiskNames sensitivity names)+          )+    walkChildren [] = pure (Right [])+    walkChildren ((diskName, child) : rest) = do+      spelled <- entryNamePath diskName+      case spelled of+        Left err -> pure (Left err)+        Right component -> do+          result <- unpackTree sensitivity (path OP.</> component) child+          case result of+            Left err -> pure (Left err)+            Right links -> do+              restResult <- walkChildren rest+              case restResult of+                Left err -> pure (Left err)+                Right moreLinks -> pure (Right (links <> moreLinks))++-- | Second unpack pass: create the recorded symlinks in dependency+-- order - each link is created after every pending link its target+-- resolves at or through - so the Windows link flavor (file vs+-- directory) is read off the real target with one probe per link.+-- Links on a dependency cycle have no knowable kind and default to file+-- links, as dangling links do.+createSymlinks :: [(OsPath, OsPath)] -> IO (Either Text ())+createSymlinks pending = createAll (orderLinks pending)+  where+    createAll [] = pure (Right ())+    createAll (link : rest) = do+      made <- uncurry createSymlink link+      case made of+        Left err -> pure (Left err)+        Right () -> createAll rest++-- | Order pending links so each follows every pending link its target+-- path resolves at or through: the target itself, or a link standing on+-- one of the target's ancestor directories.  Purely textual over the+-- same @takeDirectory linkPath \</\> target@ resolution 'createSymlink'+-- probes - no filesystem access.  Kahn's ordering, deterministic:+-- ready links leave in input order, and cycle members keep input order+-- at the end.  Exported for testing (the ordering property is pure).+orderLinks :: [(OsPath, OsPath)] -> [(OsPath, OsPath)]+orderLinks pending =+  let indexed = zip [0 :: Int ..] pending+      linkByIndex = Map.fromList indexed+      indexByKey =+        Map.fromList [(normalisedComponents linkPath, i) | (i, (linkPath, _)) <- indexed]+      -- The pending links this link's resolved target lands on or+      -- passes through (every nonempty component prefix).+      depsOf (linkPath, target) =+        let resolved = normalisedComponents (OP.takeDirectory linkPath OP.</> target)+         in Set.fromList+              [j | prefix <- drop 1 (inits resolved), Just j <- [Map.lookup prefix indexByKey]]+      dependsOn = Map.fromList [(i, depsOf link) | (i, link) <- indexed]+      dependents =+        Map.fromListWith+          (flip (++))+          [(dep, [i]) | (i, deps) <- Map.toList dependsOn, dep <- Set.toList deps]+      initialCounts = Map.map Set.size dependsOn+      initialReady = [i | (i, count) <- Map.toList initialCounts, count == 0]+      -- Kahn's ordering with a two-list queue (amortized O(1) pops).+      run !emittedRev !counts front back = case front of+        [] -> case back of+          [] -> reverse emittedRev+          _ -> run emittedRev counts (reverse back) []+        (i : rest) ->+          let (updatedCounts, readied) = release counts (Map.findWithDefault [] i dependents)+           in run (i : emittedRev) updatedCounts rest (readied ++ back)+      release !counts deps = case deps of+        [] -> (counts, [])+        (d : more) ->+          let updated = Map.adjust (subtract 1) d counts+              (finalCounts, readied) = release updated more+           in (finalCounts, [d | Map.lookup d updated == Just 0] ++ readied)+      emittedOrder = run [] initialCounts initialReady []+      emittedSet = Set.fromList emittedOrder+      cycleRemainder = [link | (i, link) <- indexed, not (Set.member i emittedSet)]+   in [link | i <- emittedOrder, Just link <- [Map.lookup i linkByIndex]] ++ cycleRemainder++-- | Path components with @.@ dropped and @..@ collapsed textually - the+-- spelling-insensitive key that matches a link target against pending+-- link paths ('OP.splitDirectories' accepts both separator spellings+-- on Windows).  A @..@ with nothing left to pop stays, matching no real+-- path.+normalisedComponents :: OsPath -> [OsPath]+normalisedComponents path = reverse (foldl' step [] (OP.splitDirectories path))+  where+    step stack comp+      | comp == currentDirectory = stack+      | comp == parentDirectory = case stack of+          (top : rest) | top /= parentDirectory -> rest+          _ -> comp : stack+      | otherwise = comp : stack+    currentDirectory = OP.pack [dot]+    parentDirectory = OP.pack [dot, dot]+    dot = OP.unsafeFromChar '.'++-- | Create one unpacked symlink, parents first, with the Windows flavor+-- read off the target ('createSymlinkOfKind').  A creation failure is+-- loud, and failing lets the caller fall back to a local build.+createSymlink :: OsPath -> OsPath -> IO (Either Text ())+createSymlink linkPath target = do+  OsDir.createDirectoryIfMissing True (OP.takeDirectory linkPath)+  createSymlinkOfKind linkPath target++-- ---------------------------------------------------------------------------+-- Streaming NAR unpacking+-- ---------------------------------------------------------------------------++-- | Where a node of an archive lies under the destination it unpacks at.+data UnpackPlace+  = -- | The destination itself.+    UnpackRoot+  | -- | A path below the destination, relative to it.+    BelowRoot !OsPath++-- | A place as a path under a destination.+placedUnder :: OsPath -> UnpackPlace -> OsPath+placedUnder root = \case+  UnpackRoot -> root+  BelowRoot relative -> root OP.</> relative++-- | The place of an entry of the directory at a place.+entryPlace :: UnpackPlace -> OsPath -> UnpackPlace+entryPlace place component = BelowRoot $ case place of+  UnpackRoot -> component+  BelowRoot relative -> relative OP.</> component++-- | One open directory in the streaming unpack: its place and the+-- sibling names materialized so far, keyed by their on-disk identity+-- ('onDiskNameKey') for collision handling.+data UnpackFrame = UnpackFrame+  { ufPlace :: !UnpackPlace,+    ufSeen :: !(Map BS.ByteString Int)+  }++-- | Mutable state behind a t'NarUnpackSink' - the same deliberate IO+-- boundary as the store's other materializers.  'nusTargets' is the+-- stack of places the NEXT node materializes at: the destination at the+-- root, plus one pushed per open directory entry.  A symlink is recorded+-- by its place, so it can be made under the destination or wherever the+-- tree is moved ('moveNarUnpack').+data NarUnpackState = NarUnpackState+  { -- | The destination volume's case sensitivity, keying sibling+    -- names exactly as the strict path does.+    nusCaseSensitivity :: !CaseSensitivity,+    nusRoot :: !OsPath,+    nusFrames :: ![UnpackFrame],+    nusTargets :: ![UnpackPlace],+    nusOpen :: !(Maybe (Handle, OsPath, Bool)),+    nusLinks :: ![(UnpackPlace, OsPath)]+  }++-- | A push sink materializing 'Stream.NarEvent's under a destination+-- path as they arrive, so a substituted NAR unpacks in the same pass+-- that downloads it.  Semantics mirror 'unpackNarEntry' - the same+-- name bytes and host checks, executable bit, and second-pass+-- symlink creation - with one divergence: sibling names colliding on+-- a folding volume always take upstream's case-hack renaming, never+-- the NTFS true-name path, because per-directory case sensitivity can+-- only be enabled on an EMPTY directory and a stream cannot know a+-- directory's siblings before materializing the first.  On a volume+-- the probe reports sensitive nothing collides, as in the strict path.+-- Upstream's own streaming restore behaves identically, and the+-- substituter's on-disk recheck proves the tree re-serialises to its+-- NAR either way.+newtype NarUnpackSink = NarUnpackSink (IORef NarUnpackState)++-- | A sink for one NAR unpack under the given destination path, on a+-- volume of the given case sensitivity.+newNarUnpackSink :: CaseSensitivity -> FilePath -> IO NarUnpackSink+newNarUnpackSink sensitivity destPath = do+  root <- OP.encodeFS destPath+  NarUnpackSink <$> newIORef (NarUnpackState sensitivity root [] [UnpackRoot] Nothing [])++-- | Feed one event.  On 'Left' the partial tree stays for the caller+-- to remove - 'abortNarUnpack' first, so no handle stays open on it.+sinkNarEvent :: NarUnpackSink -> Stream.NarEvent -> IO (Either Text ())+sinkNarEvent (NarUnpackSink ref) event = do+  narState <- readIORef ref+  outcome <- applyNarEvent narState event+  case outcome of+    Left err -> pure (Left err)+    Right updated -> do+      writeIORef ref updated+      pure (Right ())++-- | One event's filesystem effects plus the state that follows it.+-- The stream machine already proved grammar well-formedness, so the+-- mismatch arms guard sink-state desync, not archive syntax.+applyNarEvent :: NarUnpackState -> Stream.NarEvent -> IO (Either Text NarUnpackState)+applyNarEvent narState event = case event of+  Stream.EventRegularBegin isExec _declaredSize -> withNodeTarget narState $ \_ path -> do+    OsDir.createDirectoryIfMissing True (OP.takeDirectory path)+    opened <- openNewTreeFile path+    pure (fmap (\fileHandle -> narState {nusOpen = Just (fileHandle, path, isExec)}) opened)+  Stream.EventRegularChunk slice -> case nusOpen narState of+    Nothing -> pure (Left "NAR stream sink: file contents outside an open file")+    Just (fileHandle, _, _) -> do+      BS.hPut fileHandle slice+      pure (Right narState)+  Stream.EventRegularEnd -> case nusOpen narState of+    Nothing -> pure (Left "NAR stream sink: file close without an open file")+    Just (fileHandle, path, isExec) -> do+      hClose fileHandle+      when isExec (ExecBit.markExecutableOsPath path)+      pure (Right narState {nusOpen = Nothing})+  Stream.EventSymlink targetBytes -> withNodeTarget narState $ \place _ ->+    fmap (\target -> narState {nusLinks = (place, target) : nusLinks narState})+      <$> linkTargetPath targetBytes+  Stream.EventDirectoryBegin -> withNodeTarget narState $ \place path -> do+    created <- createTreeDirectory path+    pure (narState {nusFrames = UnpackFrame place Map.empty : nusFrames narState} <$ created)+  Stream.EventEntryBegin name -> case nusFrames narState of+    [] -> pure (Left "NAR stream sink: entry outside a directory")+    (frame : outer) -> case admitEntryName (nusCaseSensitivity narState) name of+      Left err -> pure (Left err)+      Right () -> do+        -- Sequential case-hack: the disk name of entry N depends only+        -- on the siblings before it, the same sequence+        -- 'caseHackDiskNames' folds over a whole list.+        let key = onDiskNameKey (nusCaseSensitivity narState) name+            (diskName, occurrences) = case Map.lookup key (ufSeen frame) of+              Nothing -> (name, 0)+              Just seen -> (caseHackName name (seen + 1), seen + 1)+            updatedFrame = frame {ufSeen = Map.insert key occurrences (ufSeen frame)}+        spelled <- entryNamePath diskName+        pure $+          fmap+            ( \component ->+                let !place = entryPlace (ufPlace frame) component+                 in narState+                      { nusFrames = updatedFrame : outer,+                        nusTargets = place : nusTargets narState+                      }+            )+            spelled+  Stream.EventEntryEnd -> case nusTargets narState of+    -- The root destination never pops; only entry-pushed paths do.+    (_ : rest@(_ : _)) -> pure (Right narState {nusTargets = rest})+    _ -> pure (Left "NAR stream sink: entry close without an open entry")+  Stream.EventDirectoryEnd -> case nusFrames narState of+    [] -> pure (Left "NAR stream sink: directory close without an open directory")+    (_ : outer) -> pure (Right narState {nusFrames = outer})++-- | Run an action on the place the next node materializes at, and its+-- path under the destination.+withNodeTarget :: NarUnpackState -> (UnpackPlace -> OsPath -> IO (Either Text NarUnpackState)) -> IO (Either Text NarUnpackState)+withNodeTarget narState act = case nusTargets narState of+  (place : _) -> act place (placedUnder (nusRoot narState) place)+  [] -> pure (Left "NAR stream sink: node with no destination")++-- | The symlinks an unpack recorded, in archive order: where each lies+-- under the destination the archive unpacked at, and its target.  A+-- link's Windows flavour is read off what its target reaches from where+-- the link is made, so they are made once the tree lies where it stays+-- ('moveNarUnpack').+newtype NarLinks = NarLinks [(UnpackPlace, OsPath)]++-- | Close an unpack after 'Stream.NarDone': every node must be closed.+-- The symlinks it recorded are answered, not made.+closeNarUnpack :: NarUnpackSink -> IO (Either Text NarLinks)+closeNarUnpack (NarUnpackSink ref) = do+  narState <- readIORef ref+  pure $ case (nusOpen narState, nusFrames narState) of+    (Just _, _) -> Left "NAR stream sink: stream ended inside a file"+    (Nothing, _ : _) -> Left "NAR stream sink: stream ended inside a directory"+    (Nothing, []) -> Right (NarLinks (reverse (nusLinks narState)))++-- | Move a tree an archive unpacked from the destination it unpacked at+-- to the path given ('moveOutput'), and make the symlinks it records+-- there, each where it lies in the tree, in the dependency order and with+-- the flavour probing of the strict path's second pass+-- ('createSymlinks').  An archive that is a symlink leaves nothing at its+-- destination to move, and its link is made at the path.+moveNarUnpack :: FilePath -> FilePath -> NarLinks -> IO (Either Text ())+moveNarUnpack from to links@(NarLinks recorded) = do+  case [target | (UnpackRoot, target) <- recorded] of+    [] -> moveOutput from to+    _ : _ -> pure ()+  OP.encodeFS to >>= \root -> createLinksUnder root links++-- | Make an unpack's symlinks under a destination.+createLinksUnder :: OsPath -> NarLinks -> IO (Either Text ())+createLinksUnder root (NarLinks links) = createSymlinks [(placedUnder root place, target) | (place, target) <- links]++-- | Finish after 'Stream.NarDone' where the archive unpacked: every node+-- must be closed ('closeNarUnpack'), then the recorded symlinks are made+-- at the sink's own destination.+finishNarUnpack :: NarUnpackSink -> IO (Either Text ())+finishNarUnpack sink@(NarUnpackSink ref) = do+  root <- nusRoot <$> readIORef ref+  closeNarUnpack sink >>= either (pure . Left) (createLinksUnder root)++-- | Close any open handle so the caller can remove the partial tree;+-- Windows will not delete a file a handle still holds open.+abortNarUnpack :: NarUnpackSink -> IO ()+abortNarUnpack (NarUnpackSink ref) = do+  narState <- readIORef ref+  case nusOpen narState of+    Nothing -> pure ()+    Just (fileHandle, _, _) ->+      hClose fileHandle `catch` \(_ :: IOException) -> pure ()+  writeIORef ref narState {nusOpen = Nothing}++-- | Why a streamed archive stopped short of its end.+data NarStreamFailure+  = -- | The store refused what the archive holds (a name, a taken+    -- path): a property of the archive, not of how it arrived.+    NarStreamRefused !Text+  | -- | The bytes do not parse as a NAR.  A truncated or torn transfer+    -- reads the same as a malformed archive.+    NarStreamMalformed !Text+  deriving (Eq, Show)++-- | Where a NAR fed to 'sinkNarStream' ends.+data ArchiveEnd+  = -- | At the end of its input: a byte after the root node's close fails+    -- the archive as malformed.+    AtEndOfInput+  | -- | At the root node's close: the input after it is left unread, as+    -- upstream's restore leaves the rest of the source it reads a NAR+    -- from.+    AtRootClose+  deriving (Eq, Show)++-- | An archive being unpacked into a sink as its chunks arrive, ending+-- where an 'ArchiveEnd' says: the parser's state, and the SHA-256 and+-- size of the bytes it has consumed.  The last chunk fed is held back+-- from the digest until the parser asks for another or finishes, since+-- the input after the root node's close is a suffix of that chunk and+-- not the archive's.  The result type is the parser's, which only says+-- what input follows the archive's end.+data NarFeed = forall r. NarFeed !(r -> BS.ByteString) !Hash.HashContext !Int !BS.ByteString !(Stream.NarStep r)++-- | What feeding an archive a chunk comes to.+data NarFed+  = -- | The archive goes on past what has been fed, and is fed next here.+    NarGoesOn !NarFeed+  | -- | The archive ended: its SHA-256, its size, and the bytes of the+    -- last chunk fed that follow its end.+    NarEnded !Hash.NixHash !Int !BS.ByteString++-- | An archive's parser before its first byte, ending where the+-- 'ArchiveEnd' says.+startNarFeed :: ArchiveEnd -> NarFeed+startNarFeed = \case+  AtEndOfInput -> NarFeed (const BS.empty) Hash.hashInit 0 BS.empty Stream.narStream+  AtRootClose -> NarFeed id Hash.hashInit 0 BS.empty Stream.narPrefix++-- | Feed an archive its next chunk, the empty chunk for the end of its+-- input, each event that completes going to the sink.  The recorded+-- symlinks are not created yet ('finishNarUnpack'), so a caller checks+-- the digest before any link exists.  On a failure the sink is already+-- aborted.+feedNar :: NarUnpackSink -> NarFeed -> BS.ByteString -> IO (Either NarStreamFailure NarFed)+feedNar sink (NarFeed unconsumed context count held step) chunk =+  advance (Just chunk) context count held step `onException` abortNarUnpack sink+  where+    -- The chunk given is pending until the parser first asks for input;+    -- once it has it, the parser is run up to its next request.+    advance pending !hashing !consumed kept current = case current of+      Stream.NarAwait continue -> case pending of+        Just next -> advance Nothing (Hash.hashUpdate hashing kept) (consumed + BS.length kept) next (continue next)+        Nothing -> pure (Right (NarGoesOn (NarFeed unconsumed hashing consumed kept current)))+      Stream.NarYield event next -> do+        sunk <- sinkNarEvent sink event+        either (stopWith . NarStreamRefused) (const (advance pending hashing consumed kept next)) sunk+      Stream.NarFail msg -> stopWith (NarStreamMalformed (T.pack msg))+      Stream.NarDone result ->+        let after = unconsumed result+            archived = BS.take (BS.length kept - BS.length after) kept+         in pure (Right (NarEnded (Hash.hashFinalize (Hash.hashUpdate hashing archived)) (consumed + BS.length archived) (after <> fold pending)))+    stopWith failure = Left failure <$ abortNarUnpack sink++-- | Tell an archive its input has ended, and take its SHA-256 and size+-- where it ends there.  A parser that still asks for input is refused as+-- one that does not end does; nova-cache's never asks after the end.  On+-- a failure the sink is already aborted.+endNar :: NarUnpackSink -> NarFeed -> IO (Either NarStreamFailure (Hash.NixHash, Int))+endNar sink feed =+  feedNar sink feed BS.empty >>= \case+    Left failure -> pure (Left failure)+    Right (NarEnded digest size _) -> pure (Right (digest, size))+    Right (NarGoesOn _) -> Left (NarStreamMalformed "the archive goes on past the end of its input") <$ abortNarUnpack sink++-- | Feed a chunk source through the streaming NAR parser into a sink+-- ('feedNar'), hashing and counting exactly the bytes the parser+-- consumes, and return the archive's SHA-256 and size once it ends where+-- the 'ArchiveEnd' says it does.  No chunk is pulled after the archive+-- ends.  On a failure the sink is already aborted.+sinkNarStream :: ArchiveEnd -> NarUnpackSink -> IO BS.ByteString -> IO (Either NarStreamFailure (Hash.NixHash, Int))+sinkNarStream end sink source = pull (startNarFeed end) `onException` abortNarUnpack sink+  where+    pull feed =+      source >>= feedNar sink feed >>= \case+        Left failure -> pure (Left failure)+        Right (NarGoesOn next) -> pull next+        Right (NarEnded digest size _) -> pure (Right (digest, size))++-- | Hold an archive's hash and size, as read, to what its path's info+-- claims: the hash first, then the size, as upstream's import of a NAR+-- checks them, each refused in upstream's words ('narHashMismatch',+-- 'narSizeMismatch') naming the path as given.+checkNarClaim :: Text -> Hash.NixHash -> Integer -> Hash.NixHash -> Integer -> Either Text ()+checkNarClaim path claimedHash claimedSize gotHash gotSize+  | gotHash /= claimedHash = Left (narHashMismatch path claimedHash gotHash)+  | gotSize /= claimedSize = Left (narSizeMismatch path claimedSize gotSize)+  | otherwise = Right ()++-- | Upstream's refusal of an archive whose hash is not the one its+-- path's info claims, both in SRI form.+narHashMismatch :: Text -> Hash.NixHash -> Hash.NixHash -> Text+narHashMismatch path (Hash.NixHash specified) (Hash.NixHash got) =+  importMismatch "hash" path (sri specified) (sri got)+  where+    sri digest = narHashAlgorithm <> "-" <> B64.encode digest++-- | Upstream's refusal of an archive whose size is not the one its+-- path's info claims.+narSizeMismatch :: Text -> Integer -> Integer -> Text+narSizeMismatch path specified got = importMismatch "size" path (T.pack (show specified)) (T.pack (show got))++-- | The shape upstream gives both refusals: what mismatched, the path,+-- and what was specified above what was got.+importMismatch :: Text -> Text -> Text -> Text -> Text+importMismatch what path specified got =+  what <> " mismatch importing path '" <> path <> "';\n  specified: " <> specified <> "\n  got:       " <> got++-- | The algorithm a NAR hash is taken with, as SRI names it.+narHashAlgorithm :: Text+narHashAlgorithm = "sha256"++-- ---------------------------------------------------------------------------+-- Paths copied in+-- ---------------------------------------------------------------------------++-- | Whether a path copied into the store must be signed, as upstream's+-- store asks under @require-sigs@.+data SignatureRequirement+  = -- | One of these keys must have signed the path's info, unless its+    -- content address makes its path ('addressMakesPath').+    RequireSignature ![Signing.PublicKey]+  | -- | It is taken unsigned: @require-sigs@ is off, or the path comes+    -- from a client the daemon trusts that asks it not to check.+    SignaturesNotRequired++-- | What a content address and the references it is stated with make of+-- the path they are stated for ('addressMakesPath').+data AddressedPath+  = -- | Exactly the path.+    MakesItsPath+  | -- | Another path.+    MakesAnotherPath+  | -- | No path: a fixed address other than a NAR's SHA-256 with+    -- references, its own path among them or not, refused in upstream's+    -- words as upstream refuses to make a path from it.+    MakesNoPath !Text+  deriving (Eq, Show)++-- | What a content address and the references it is stated with make of+-- a path, as upstream makes a path from a content address: a text by its+-- SHA-256 with its references; a NAR by its SHA-256 as a @source@ path+-- with its references, and @self@ when it references itself; any other+-- fixed address only with no references at all.+addressMakesPath :: StorePath -> [StorePath] -> ContentAddress -> AddressedPath+addressMakesPath sp refs address = case caMethod address of+  TextMethod -> madeIf (caAlgo address == sha256Algo && makeTextPath name digest refs == Right sp)+  FixedMethod NarIngestion+    | caAlgo address == sha256Algo -> madeIf (makeStorePath defaultStoreDir sourceType digest name == Right sp)+  FixedMethod method+    | not (null refs) -> MakesNoPath (fixedReferencesRefusal name)+    | otherwise -> madeIf (makeFixedOutputPath name (caAlgo address) method digest == Right sp)+  where+    madeIf made+      | made = MakesItsPath+      | otherwise = MakesAnotherPath+    name = spName sp+    digest = caDigest address+    self = sp `elem` refs+    others = Set.toAscList (Set.delete sp (Set.fromList refs))+    sourceType = "source" <> T.concat [":" <> storePathToText defaultStoreDir r | r <- others] <> (if self then ":self" else "")++-- | Upstream's refusal to make a path, of the name given, from a fixed+-- content address other than a NAR's SHA-256 that comes with references.+fixedReferencesRefusal :: Text -> Text+fixedReferencesRefusal name =+  "fixed output derivation '"+    <> name+    <> "' is not allowed to refer to other store paths.\nYou may need to use the 'unsafeDiscardReferences' derivation attribute, see the manual for more details."++-- | Upstream's warning of a stated content address that does not make its+-- path.  Upstream prints it, @warning:@ and all, at its error level, each+-- time it tests the address: when it counts a path's signatures, and when+-- it registers the path.+notContentAddressed :: StorePath -> Text+notContentAddressed sp = "warning: path '" <> storePathToText defaultStoreDir sp <> "' claims to be content-addressed but isn't"++-- | Whether a path may be registered with the content address it is stated+-- with, as upstream's store decides as it registers one: an address that+-- makes no path is refused as 'MakesNoPath' says, and one that makes+-- another path is warned of at the error level ('notContentAddressed') and+-- refused as claiming to be what it is not.+addressRegistrable :: Logger -> StorePath -> [StorePath] -> ContentAddress -> IO (Either Text ())+addressRegistrable logger sp refs address = case addressMakesPath sp refs address of+  MakesItsPath -> pure (Right ())+  MakesNoPath refusal -> pure (Left refusal)+  MakesAnotherPath -> do+    logAt logger LevelError (notContentAddressed sp)+    pure (Left ("cannot add path '" <> storePathToText defaultStoreDir sp <> "' to the Nix store because it claims to be content-addressed but isn't"))++-- ---------------------------------------------------------------------------+-- Eval source materialization+-- ---------------------------------------------------------------------------++-- | Restore the copies of eval-coerced paths into the store and register+-- them.  Each entry is a copy's fixed-output store path with the+-- path-value text of the tree evaluation hashed for it, the path with its+-- symlinks resolved (text only: evaluation writes no copy of a coerced+-- path).  Each entry not already valid is adopted when the tree already at+-- its path reproduces its address, and otherwise restored from a dump of+-- that tree ('restoreSource'); its metadata is made canonical+-- ('canonicalizeMetadata'), and it is registered.  A source carries no+-- references.  A store upstream Nix's database may also manage is+-- refused before any entry is looked at, by an+-- 'IOException' carrying the reason ("Nix.Store.Upstream"): a tree on+-- disk with no row here is cleared unless it reproduces its address.+materializeEvalSources :: Store -> Map StorePath Text -> IO ()+materializeEvalSources store sourceCache = do+  refusal <- upstreamManagedRefusal ReplacesUpstreamPaths (stDir store)+  maybe (mapM_ adopt (Map.toList sourceCache)) (throwIO . userError . T.unpack) refusal+  where+    -- Each source registers IMMEDIATELY after its restore (sources carry+    -- no cross-references, so there is nothing to batch).  A tree already+    -- on disk is adopted only after verification: its NAR digest must+    -- reproduce the store path being registered - an interrupted earlier+    -- restore leaves a partial tree, and registering it as-is validates+    -- content that does not match its address.  A verified adoption keeps+    -- the files' bytes (rewriting a read-only tree fails on Windows and+    -- would wedge the store permanently) and has only their metadata made+    -- canonical, since the tree may be one a restore left before it got+    -- that far, or one an evaluation wrote; a failed one clears and+    -- restores.+    -- The whole check-then-act runs under the path's cross-process+    -- lock, validity re-checked once held, so of two processes+    -- materializing the same source the second finds the path valid+    -- rather than clearing the tree the first registered.  Same protocol+    -- as the builder's withOutputLocks.+    adopt (sp, srcText) =+      withPathLock (stLogger store) (stDir store) sp $ \_ -> do+        valid <- isValid store sp+        unless valid $ do+          let dest = storePathToFilePath (stDir store) sp+          onDisk <- doesPathExist dest+          adopted <- if onDisk then adoptedTreeAddress (stCaseSensitivity store) dest sp else pure Nothing+          reg <- case adopted of+            Just address -> do+              canonicalizeMetadata dest+              (\reg -> reg {prContentAddress = Just address}) <$> registrationFor store sp Nothing []+            Nothing -> do+              when onDisk (Dir.removePathForcibly dest)+              restoreSource store srcText sp >>= either (refuse (storePathToText defaultStoreDir sp)) pure+          registerPath (stDB store) reg+    refuse spText reason =+      throwIO (userError (T.unpack ("refusing to register " <> spText <> ": " <> reason)))++-- | Restore a source tree at the store path evaluation named it by,+-- from a dump of the source, as upstream's @addToStoreFromDump@+-- restores the dump it hashed (@restorePath@, local-store.cc at+-- 2.24.9) rather than copying files: the source's NAR streams out of+-- the walk, through the hash and into an unpack sink in one pass, so a+-- sibling pair the store's volume folds takes the case-hack on the way+-- in, and no file's contents are ever held whole.  The source is read+-- as evaluation read it to name the path: the tree its resolved text+-- names, store text in this store's directory ('storeTextToFilePath'),+-- under the case-hack that text calls for ('pathCaseHack'); the restored+-- tree is read as a store path, under its volume's.+--+-- Evaluation hashed the source earlier, so the dump is held to that+-- address before any link is created: a source that changed in between+-- is refused, never registered under a hash its bytes no longer have.+-- The restored tree is then rechecked on disk, as the substituter+-- rechecks an unpacked one, since the volume decides the final+-- spelling of every name.  Any failure removes the tree.+restoreSource :: Store -> Text -> StorePath -> IO (Either Text PathRegistration)+restoreSource store srcText sp = do+  outcome <- restore `onException` Dir.removePathForcibly dest+  either (\reason -> Left reason <$ Dir.removePathForcibly dest) (pure . Right) outcome+  where+    dest = storePathToFilePath (stDir store) sp+    src = storeTextToFilePath (stDir store) srcText+    caseHack = pathCaseHack (stCaseSensitivity store) srcText+    restore = do+      sink <- newNarUnpackSink (stCaseSensitivity store) dest+      streamed <- ExecBit.withNarSource caseHack src (sinkNarStream AtEndOfInput sink)+      case streamed of+        Left (NarStreamRefused reason) -> pure (Left reason)+        Left (NarStreamMalformed reason) -> pure (Left ("the dump of " <> srcText <> " does not parse: " <> reason))+        Right (digest, size) -> case sourceAddress sp digest of+          Nothing -> do+            abortNarUnpack sink+            pure (Left (srcText <> " changed after evaluation hashed it, so it no longer reproduces its store path; re-evaluate"))+          Just address -> do+            finished <- finishNarUnpack sink+            either (pure . Left) (const (sealAndRecheck digest size address)) finished+    sealAndRecheck digest size address = do+      canonicalizeMetadata dest+      onDisk <- ExecBit.narHashOfPath (volumeCaseHack (stCaseSensitivity store)) dest+      pure $+        if onDisk /= digest+          then Left "the restored tree does not reproduce its store path on disk"+          else+            Right+              PathRegistration+                { prPath = sp,+                  prNarHash = Hash.formatNixHash digest,+                  prNarSize = size,+                  prDeriver = Nothing,+                  prReferences = [],+                  prUltimate = NotUltimate,+                  prSignatures = Set.empty,+                  prContentAddress = Just address,+                  prRegistrationTime = RegisteredNow+                }++-- | The content address a recursive NAR digest gives a store path, when+-- the digest and the path's own name derive exactly that path, as a+-- @source@ path's address is derived.+sourceAddress :: StorePath -> Hash.NixHash -> Maybe ContentAddress+sourceAddress sp (Hash.NixHash digest)+  | makeFixedOutputPath (spName sp) sha256Algo NarIngestion digest == Right sp = contentAddressFromParts (FixedMethod NarIngestion) sha256Algo digest+  | otherwise = Nothing++-- | Register the store objects evaluation wrote: makes each one's+-- metadata canonical ('canonicalizeMetadata') and records it in the DB.+-- Batched so a write referring to another resolves.  Covers every+-- eval-time writer, not only @builtins.toFile@:+-- an unregistered write reaches @drvInputSrcs@ and fails the build.+materializeEvalStoreWrites :: Store -> Map Text ([StorePath], StoreWriteMode) -> IO ()+materializeEvalStoreWrites store storeWrites = do+  regs <- catMaybes <$> mapM prepare (Map.toList storeWrites)+  unless (null regs) (registerPaths (stDB store) regs)+  where+    -- Checked and sealed under the path's lock, validity re-checked+    -- once held, so a peer mid-producing the same path is waited out+    -- rather than torn-read (and refused).  The lock releases before+    -- the batched registration: registration is an upsert over content+    -- both holders verified reproduces the same path, so the winner+    -- and loser record the same row.+    prepare (spText, (refs, mode)) =+      case parseStorePath defaultStoreDir spText of+        Nothing -> pure Nothing+        Just sp -> withPathLock (stLogger store) (stDir store) sp $ \_ -> do+          valid <- isValid store sp+          if valid+            then pure Nothing+            else do+              let dest = storePathToFilePath (stDir store) sp+              onDisk <- doesPathExist dest+              -- Absent means removed since eval; nothing to register.+              if not onDisk+                then pure Nothing+                else do+                  -- The writers verified (or rewrote) this content at+                  -- write time; a mismatch here means the tree changed+                  -- between evaluation and registration, and registering+                  -- it would record a hash its bytes do not have, then+                  -- seal the lie.  Refuse loudly instead.+                  address <- writtenAddress (stCaseSensitivity store) dest sp refs mode+                  case address of+                    Nothing ->+                      throwIO+                        ( userError+                            ( "refusing to register "+                                <> T.unpack spText+                                <> ": the on-disk content does not reproduce its store path; "+                                <> "delete the path and re-evaluate"+                            )+                        )+                    Just reproduced -> do+                      canonicalizeMetadata dest+                      (\reg -> Just reg {prContentAddress = Just reproduced}) <$> registrationFor store sp Nothing refs++-- | Add a tree, given as its NAR, as the path the SHA-256 of the NAR, a+-- name and the store paths it references make ('makeSourcePath'), and+-- answer the path: upstream's @addToStore@ of a dump under @NixArchive@+-- and SHA-256 with those references, which @nix profile@ adds each+-- generation by (@ProfileManifest::build@ in profile.cc).  A valid path is+-- passed over.  Otherwise, under the path's lock, what is at the path is+-- cleared, the NAR is unpacked there as a substituted one is+-- ('unpackNarEntry') and its metadata made canonical, and it is registered+-- only once it serialises back to the NAR it came from, since the volume+-- decides the final spelling of every name; a tree that does not is removed+-- and refused.  The references must be valid.  A store upstream Nix's+-- database may also manage is refused before anything is looked at+-- ("Nix.Store.Upstream").+addSourceTree :: Store -> Text -> Set StorePath -> NAR.NarEntry -> IO (Either Text StorePath)+addSourceTree store name refs entry =+  case makeSourcePath name (sha256Digest nar) refs of+    Left bad -> pure (Left (badStorePathText bad))+    Right sp -> do+      refusal <- upstreamManagedRefusal ReplacesUpstreamPaths (stDir store)+      case refusal of+        Just reason -> pure (Left reason)+        Nothing -> withPathLock (stLogger store) (stDir store) sp $ \_ -> do+          valid <- isValid store sp+          if valid then pure (Right sp) else place sp+  where+    nar = NAR.serialise entry+    place sp = do+      let dest = storePathToFilePath (stDir store) sp+      Dir.removePathForcibly dest+      placed <- (unpackNarEntry (stCaseSensitivity store) dest entry >>= traverse (const (sealed sp dest))) `onException` Dir.removePathForcibly dest+      case placed of+        Right (Just reg) -> Right sp <$ registerPath (stDB store) reg+        Right Nothing -> Left (storePathToText defaultStoreDir sp <> ": the unpacked tree does not serialise to the NAR it was unpacked from") <$ Dir.removePathForcibly dest+        Left reason -> Left reason <$ Dir.removePathForcibly dest+    sealed sp dest = do+      canonicalizeMetadata dest+      reg <- registrationFor store sp Nothing (Set.toAscList refs)+      pure (if prNarHash reg == Hash.formatNixHash (Hash.hashBytes nar) then Just reg {prContentAddress = contentAddressFromParts (FixedMethod NarIngestion) sha256Algo (sha256Digest nar)} else Nothing)++-- | The content address under which on-disk content re-derives exactly+-- the store path it is about to be registered under, by the scheme that+-- named the write, or 'Nothing' when it does not.  An unreadable+-- destination counts as a mismatch.+writtenAddress :: CaseSensitivity -> FilePath -> StorePath -> [StorePath] -> StoreWriteMode -> IO (Maybe ContentAddress)+writtenAddress sensitivity dest sp refs mode = case mode of+  WriteRecursive -> adoptedTreeAddress sensitivity dest sp+  WriteFlat -> withFileDigest (\digest -> makeFixedOutputPath (spName sp) sha256Algo FlatIngestion digest == Right sp) (FixedMethod FlatIngestion)+  WriteText -> withFileDigest (\digest -> makeTextPath (spName sp) digest refs == Right sp) TextMethod+  where+    withFileDigest derives method = do+      result <- try (BS.readFile dest) :: IO (Either IOException BS.ByteString)+      pure $ case sha256Digest <$> result of+        Right digest | derives digest -> contentAddressFromParts method sha256Algo digest+        _ -> Nothing++-- | The content address under which an on-disk tree reproduces the source+-- store path it is about to be registered under ('sourceAddress'), or+-- 'Nothing' when its recursive NAR digest and the path's own name do not+-- derive exactly this path.  An unreadable tree counts as a mismatch.+-- The sensitivity is the store volume's, which decides the case-hack mode+-- the tree is read back under.+adoptedTreeAddress :: CaseSensitivity -> FilePath -> StorePath -> IO (Maybe ContentAddress)+adoptedTreeAddress sensitivity dest sp =+  (>>= sourceAddress sp . NAR.narHash)+    <$> ExecBit.serialiseIfReadable (volumeCaseHack sensitivity) dest  -- | Recursively copy a file or directory tree to a destination path. -- A symlink is replicated as a symlink: the store path's name came from a
+ src/Nix/Store/Access.hs view
@@ -0,0 +1,1125 @@+{-# LANGUAGE CPP #-}++-- | Who a directory the store creates is open to, how it is created+-- that way, and when a directory already there may hold a store or lead+-- to one.+--+-- A store's directory and its state directory are readable by every+-- user and changeable only by the user nova-nix runs as and the+-- system's administrators ('StoreAccess', 'StateAccess').  A directory created on the+-- way to a store, @C:\\nix@ when the installer has not made it, is+-- theirs alone on Windows, and on POSIX as open as a store's directory+-- ('ParentAccess'); a build directory is that user's alone ('OwnerAccess').+--+-- == POSIX+--+-- A mode says so: a store's directories and the parents made for them+-- take the default mode narrowed by the umask, as upstream's+-- @createDirs@ makes them (file-system.cc), and a build directory 0700, as+-- upstream's @createTempDir@ makes its build directories.+--+-- == Windows+--+-- A directory created with no security descriptor takes the access+-- control list its parent passes down, and a drive root passes down+-- modify for Authenticated Users, every signed-in user, so a store made+-- that way under the default @C:\\nix\\store@ would let any of them+-- change, replace or delete store paths and the database, and change a+-- build while it runs.  Each directory is created instead with a+-- protected DACL, one that takes nothing from its parent, in the one+-- CreateDirectoryW call that makes it, so it never exists with the list+-- its parent would pass down.  Every grant is inherited by the files and+-- directories made under it (@OICI@), so a store path or a build's tree+-- is covered too.+--+-- A store's directories grant full control to the user nova-nix runs+-- as, SYSTEM and Administrators, and read and execute to Users, naming+-- the user once when it is SYSTEM: the protected DACL install-nova-nix's+-- @install.ps1@ sets on @C:\\nix@, with the same rights, inheritance and+-- principals.  The installer sets it on @C:\\nix@, which the store then+-- inherits; nova-nix sets it on each store directory it creates, since a+-- store can be wherever @--store@ names.  A build directory grants full+-- control to that user alone.  The user is the process token's, as the+-- installer's @WindowsIdentity.GetCurrent().User@ is, and neither sets+-- the owner, which stays the token's default.+--+-- == Build accounts+--+-- Where builds run as build accounts, the local group @nixbld@'s, the+-- account nova-nix runs as is the service that keeps the store, and it+-- plays the part of the user above, as a t'StoreAccounts' value says.+-- The store's directory+-- then grants its entries to itself alone, and the group the right to+-- create files and directories in it and nothing else, so what a build+-- makes there takes its own token's default DACL rather than the store's.+-- Registering a path ('withValidPathAccess') gives each of its nodes the+-- service as owner and a protected DACL that grants the service, SYSTEM+-- and Administrators full control, Users and the group read and execute,+-- and the node's owner read-control alone ('validPathSddl'), so no build+-- changes a valid path, the build account that made it included.  A+-- machine with no such group, a single-user store's, has no build+-- accounts to grant: the store's directory passes its entries down as it+-- always has, and a registered path's DACL grants what it would inherit+-- from it, with the user as its owner.+--+-- A parent created on the way to a store grants full control to the+-- user, SYSTEM and Administrators and nothing to other users, so no+-- other user can rename it and put a store of their own in its place,+-- and nothing it holds is opened to other users unless it says so+-- itself.  The installer accepts such a @C:\\nix@, whose every entry+-- names an account it trusts, and gives it its own DACL, which adds read+-- and execute for Users.+--+-- nova-nix never changes the list of a directory that already exists;+-- the next section says when it uses one.+--+-- == A directory already there+--+-- On Windows a directory already on the way to a store, the store's+-- directory and its state directory among them, is used only when no+-- account but the user nova-nix runs as, SYSTEM and Administrators can+-- change it: one of them owns it, it has a DACL, and no allow entry of+-- any kind grants another account a right that changes it, an+-- inherit-only entry, which grants nothing on the directory itself,+-- included.  That is install-nova-nix's rule for @C:\\nix@ and what it+-- holds.  A drive root lets every signed-in user create a folder in it,+-- so where the installer never ran another user can make @C:\\nix@+-- first, and as its owner give themselves the right to delete what it+-- holds, move the store aside and put a store and database of their own+-- in its place.+--+-- The volume root itself is not checked: its default DACL lets other+-- users create folders in it but not delete or rename one already+-- there, and Windows may own it as TrustedInstaller.  Every directory+-- below it is, wherever @--store@ names the store, so a folder made at a+-- drive root that took the root's DACL, which lets other users change+-- what is made in it, is refused.  A directory is checked before+-- anything is created in it or read from it, since a database another+-- account controls is as dangerous to read as to write.  One nova-nix+-- creates passes by construction.  A link is checked as itself and not+-- followed: one another account made is refused, and where one the user+-- made leads is the user's to choose.+--+-- On POSIX nothing is checked, as upstream checks nothing: there only+-- root can create a directory in @/@.+--+-- == Whether this process can keep a store+--+-- 'probeStoreWriting' says whether a store's state directory can be+-- read and written, as a command that opens the store itself needs.  On+-- POSIX that is the answer @access(2)@ gives.  On Windows the directory+-- must also be granted listing and adding files and directories, which+-- the directory's access control list decides and the read-only attribute+-- does not, and every directory on the way to it must pass the rule+-- above: a store the service that keeps it created is the service's, so+-- no other process may open it directly, an elevated administrator's+-- included, and goes through the service's daemon instead.+module Nix.Store.Access+  ( -- * Who a directory is open to+    DirAccess (..),+    StoreAccounts (..),++    -- * Creating a directory+    createDirectoryWith,+    createStoreDirectory,+    createStateDirectory,+    checkStateDirectory,++    -- * Whether this process can keep a store+    StoreWriting (..),+    probeStoreWriting,++    -- * A directory already there+    storeDirectories,+    stateDirectories,+    DirSecurity (..),+    AclEntry (..),+    Distrust (..),+    parseSecurityDescriptor,+    securityDistrust,+    descriptorDistrust,+    distrustMessage,++    -- * A registered path+    ValidNode (..),+    withValidPathAccess,++    -- * The Windows access control list+    Sid,+    sidFromText,+    sidText,+    accessSddl,+    validPathSddl,++    -- * Well-known accounts+    localSystemSid,+    administratorsSid,+    serviceSid,+    novaNixServiceSid,+  )+where++import Control.Exception (IOException, try)+import Control.Monad (guard)+import qualified Crypto.Hash as CH+import Data.Bits (complement, shiftL, (.&.), (.|.))+import qualified Data.ByteArray as BA+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import Data.Char (isDigit, isHexDigit)+import Data.Foldable (toList)+import Data.Maybe (listToMaybe, mapMaybe)+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import qualified Data.Text.Read as TR+import Data.Word (Word16, Word32, Word8)+import Numeric (showHex)+import qualified System.FilePath.Windows as Windows++#if defined(mingw32_HOST_OS)++import Control.Exception (bracket, finally)+import Control.Monad (unless, void, when)+import Data.Foldable (traverse_)+import Data.Maybe (fromMaybe, isNothing)+import Foreign.C.String (CString, CWString, peekCString, peekCWString, withCWString)+import Foreign.C.Types (CInt, CULong (..))+import Foreign.Marshal.Alloc (alloca)+import Foreign.Marshal.Utils (maybePeek)+import Foreign.Ptr (Ptr, castPtr)+import Foreign.Storable (peek)+import Nix.Store.Win32Path (win32FilePath)+import System.Directory (doesDirectoryExist)+import System.FilePath (takeDirectory)+import System.IO.Error (alreadyExistsErrorType, catchIOError, ioeSetFileName, isAlreadyExistsError, mkIOError, modifyIOError)+import System.Win32.Info (getFullPathName)+import System.Win32.Types (ErrCode, failUnlessSuccess, failWith, localFree)++#else++import System.Directory (createDirectoryIfMissing)+import qualified System.Posix.Directory as Posix+import System.Posix.Files (accessModes, fileAccess, ownerModes)++#endif++-- ---------------------------------------------------------------------------+-- Who a directory is open to+-- ---------------------------------------------------------------------------++-- | Who a directory the store creates is open to.+data DirAccess+  = -- | Readable by every user, changeable by the user nova-nix runs as,+    -- SYSTEM and Administrators, and on Windows a directory in which the+    -- build accounts' group, where the machine has one, may create entries+    -- and do nothing else: a store's directory.+    StoreAccess+  | -- | Readable by every user, changeable by the user nova-nix runs as,+    -- SYSTEM and Administrators, and passing that down to all it holds: a+    -- store's state directory.+    StateAccess+  | -- | On Windows readable and changeable by the user nova-nix runs as,+    -- SYSTEM and Administrators alone, and on POSIX the mode of a store's+    -- directory: a directory created on the way to a store.+    ParentAccess+  | -- | The user nova-nix runs as alone: a build directory.+    OwnerAccess+  deriving (Eq, Show)++-- | The accounts a store's directories and registered paths name on+-- Windows, beside SYSTEM, Administrators and Users.+data StoreAccounts = StoreAccounts+  { -- | The account that keeps the store: the one nova-nix runs as, the+    -- user in a single-user store and the service where builds run as+    -- build accounts.+    saService :: !Sid,+    -- | The build accounts' local group, @nixbld@, where the machine has+    -- one, and 'Nothing' where it does not, as in a single-user store.+    saBuilders :: !(Maybe Sid)+  }+  deriving (Eq, Show)++-- ---------------------------------------------------------------------------+-- Creating a directory+-- ---------------------------------------------------------------------------++-- | Create a directory open to whom the access says, failing with an+-- 'System.IO.Error.isAlreadyExistsError' exception when anything already+-- answers to the name, a symlink included, which is not followed.  Its+-- parent must exist.  On POSIX its mode is 0777 for 'StoreAccess',+-- 'StateAccess' and 'ParentAccess' and 0700 for 'OwnerAccess', each+-- narrowed by the umask; on Windows it is created with the protected DACL+-- 'accessSddl' describes for the t'StoreAccounts' of this machine.+createDirectoryWith :: DirAccess -> FilePath -> IO ()+#if defined(mingw32_HOST_OS)+createDirectoryWith access path =+  modifyIOError (`ioeSetFileName` path) $ do+    accounts <- storeAccounts+    target <- win32FilePath path+    withCWString target $ \cTarget ->+      withCWString (T.unpack (accessSddl accounts access)) $ \cSddl ->+        failUnlessSuccess "CreateDirectory" (c_nn_dir_create_sddl cTarget cSddl)+#else+createDirectoryWith access path = Posix.createDirectory path $ case access of+  StoreAccess -> accessModes+  StateAccess -> accessModes+  ParentAccess -> accessModes+  OwnerAccess -> ownerModes+#endif++-- | Run an action given the step that registering a path takes for each+-- of its nodes on Windows, given the kind of node it is: the node+-- itself, a link not followed, is given the service as its owner and the+-- protected DACL 'validPathSddl' describes for the t'StoreAccounts' of+-- this machine, which no build account may change.  The DACL is each+-- node's own, not one inherited from the path's root, so the walk that+-- sets it is the caller's, which does not follow a link.  On POSIX the+-- step does nothing, and the walk's own ownership change stands for it.+withValidPathAccess :: ((ValidNode -> FilePath -> IO ()) -> IO a) -> IO a+#if defined(mingw32_HOST_OS)+withValidPathAccess use = do+  accounts <- storeAccounts+  withDescriptor (validPathSddl accounts ValidDirectory) $ \directory ->+    withDescriptor (validPathSddl accounts ValidLeaf) $ \leaf ->+      use $ \node -> giveValidPathAccess $ case node of+        ValidDirectory -> directory+        ValidLeaf -> leaf+  where+    withDescriptor sddl inner =+      withCWString (T.unpack sddl) $ \cSddl ->+        alloca $ \descriptorOut -> do+          failUnlessSuccess "ConvertStringSecurityDescriptorToSecurityDescriptorW" (c_nn_descriptor_from_sddl cSddl descriptorOut)+          bracket (peek descriptorOut) (void . localFree) inner+#else+withValidPathAccess use = use (\_ _ -> pure ())+#endif++-- | The kind of node of a registered path, by what its DACL can pass on.+data ValidNode+  = -- | A directory, whose entries pass to what it holds.+    ValidDirectory+  | -- | A file or a link, which holds nothing: Windows keeps no+    -- inheritance flags on such a node's entries, so it is given none.+    ValidLeaf+  deriving (Eq, Show)++-- | Create a store's directory, given its path, where it is missing,+-- with any missing parent of it, as @createDirectoryIfMissing True@+-- does: the directories 'createStateDirectory' creates and checks, less+-- the state directory, for what is written into a store before it is+-- opened.  On POSIX that is all it does.  On Windows the store's+-- directory is open to whom 'StoreAccess' says and each parent to whom+-- 'ParentAccess' says, and one already there is refused as+-- 'createStateDirectory' refuses one.+createStoreDirectory :: FilePath -> IO ()+#if defined(mingw32_HOST_OS)+createStoreDirectory storeDir = do+  accounts <- storeAccounts+  full <- getFullPathName storeDir+  traverse_ (prepareDirectory accounts full) (storeDirectories full)+#else+createStoreDirectory = createDirectoryIfMissing True+#endif++-- | Create a store's state directory, given its path, where it is+-- missing, with the store directory it is in and any missing parent of+-- that, as @createDirectoryIfMissing True@ does.  On POSIX that is all+-- it does: the modes are the default, narrowed by the umask.  On+-- Windows it takes the directories 'stateDirectories' gives, outermost+-- first.  One that is missing is created, open to whom its access says.+-- One already there, or made by another process before this one could+-- make it, is refused unless it can be trusted with a store+-- ('descriptorDistrust'), with a 'userError' naming it and what is+-- wrong ('distrustMessage'), before anything is created in it; then+-- something other than a directory there fails with an+-- 'System.IO.Error.isAlreadyExistsError' exception naming it.+createStateDirectory :: FilePath -> IO ()+#if defined(mingw32_HOST_OS)+createStateDirectory stateDir = do+  accounts <- storeAccounts+  full <- getFullPathName stateDir+  traverse_ (prepareDirectory accounts (takeDirectory full)) (stateDirectories full)+#else+createStateDirectory = createDirectoryIfMissing True+#endif++-- | Refuse a store, given its state directory, before anything is read+-- from it, as 'createStateDirectory' refuses one: on Windows each of the+-- directories it takes that exists must be trusted with a store, and one+-- that does not exist is passed over.  On POSIX it checks nothing.+checkStateDirectory :: FilePath -> IO ()+#if defined(mingw32_HOST_OS)+checkStateDirectory stateDir =+  distrustedStateDirectory stateDir >>= traverse_ (\(dir, store, reason) -> ioError (userError (distrustMessage dir store reason)))+#else+checkStateDirectory _ = pure ()+#endif++-- | Whether the process can keep the store whose state directory is given+-- (the module header says what that asks).  A directory that does not+-- exist, or one that cannot be examined, is not writable.+data StoreWriting+  = -- | The state directory can be read and written, and on Windows every+    -- directory on the way to it can be trusted.+    StoreWritable+  | -- | It cannot.+    StoreNotWritable+  deriving (Eq, Show)++-- | Whether this process can read and write a store's state directory,+-- given its path, so that a command may open the store itself.  On POSIX+-- it is one @access(2)@ call for reading and writing, as upstream makes+-- on its state directory, so root, whom the call lets through whatever+-- the modes say, is writable.  On Windows the answer is+-- 'StoreWritable' only when the directory's access control list grants+-- this process's token listing and adding files and subdirectories and+-- no existing directory on the way to it is distrusted for this+-- machine's accounts, as 'checkStateDirectory' would refuse the store.+-- An I\/O failure on the way is 'StoreNotWritable', never an exception.+probeStoreWriting :: FilePath -> IO StoreWriting+#if defined(mingw32_HOST_OS)+probeStoreWriting stateDir = either (const StoreNotWritable) writingOf <$> (try allowed :: IO (Either IOException Bool))+  where+    allowed = directoryChangeable stateDir >>= changeable+    changeable True = isNothing <$> distrustedStateDirectory stateDir+    changeable False = pure False+#else+probeStoreWriting stateDir = either (const StoreNotWritable) writingOf <$> (try (fileAccess stateDir readable writable searchable) :: IO (Either IOException Bool))+  where+    -- The modes access(2) is asked about: read and write, not search.+    readable = True+    writable = True+    searchable = False+#endif++-- | 'StoreWritable' for a yes.+writingOf :: Bool -> StoreWriting+writingOf True = StoreWritable+writingOf False = StoreNotWritable++#if defined(mingw32_HOST_OS)++foreign import ccall unsafe "nn_winfs.h nn_token_user_sid"+  c_nn_token_user_sid :: Ptr CWString -> Ptr CString -> IO ErrCode++foreign import ccall unsafe "nn_winfs.h nn_dir_create_sddl"+  c_nn_dir_create_sddl :: CWString -> CWString -> IO ErrCode++foreign import ccall unsafe "nn_winfs.h nn_entry_security"+  c_nn_entry_security :: CWString -> Ptr (Ptr ()) -> Ptr CULong -> Ptr CString -> IO ErrCode++foreign import ccall unsafe "nn_winfs.h nn_dir_access"+  c_nn_dir_access :: CWString -> CULong -> Ptr CInt -> Ptr CString -> IO ErrCode++foreign import ccall unsafe "nn_winfs.h nn_local_group_sid"+  c_nn_local_group_sid :: CWString -> Ptr CWString -> Ptr CString -> IO ErrCode++foreign import ccall unsafe "nn_winfs.h nn_descriptor_from_sddl"+  c_nn_descriptor_from_sddl :: CWString -> Ptr (Ptr ()) -> IO ErrCode++foreign import ccall unsafe "nn_winfs.h nn_entry_set_owner_dacl"+  c_nn_entry_set_owner_dacl :: CWString -> Ptr () -> Ptr CString -> IO ErrCode++-- | The accounts this machine's store names: the one this process runs+-- as, and the local group 'buildersGroupName' where there is one.+storeAccounts :: IO StoreAccounts+storeAccounts = StoreAccounts <$> tokenUserSid <*> localGroupSid buildersGroupName++-- | The name of the build accounts' local group, as upstream names its+-- Linux build users' group.+buildersGroupName :: String+buildersGroupName = "nixbld"++-- | The SID of the local group the name names on this machine, or+-- 'Nothing' where it has no local group of that name: none at all, or an+-- account of another kind.  A failure names the call that failed.+localGroupSid :: String -> IO (Maybe Sid)+localGroupSid name =+  withCWString name $ \cName -> alloca $ \sidOut -> alloca $ \failedOut -> do+    code <- c_nn_local_group_sid cName sidOut failedOut+    when (code /= 0) $ do+      call <- maybePeek peekCString =<< peek failedOut+      failWith (fromMaybe "nn_local_group_sid" call) code+    traverse readSid =<< maybePeek pure =<< peek sidOut+  where+    readSid sid = (`finally` localFree sid) $ do+      text <- T.pack <$> peekCWString sid+      maybe (ioError (userError ("the group " <> name <> " has a SID that is not one: " <> show text))) pure (sidFromText text)++-- | Give the node at the path itself, a link not followed, the owner and+-- protected DACL of the security descriptor given.  A failure names the+-- call that failed and the path.+giveValidPathAccess :: Ptr () -> FilePath -> IO ()+giveValidPathAccess descriptor path =+  modifyIOError (`ioeSetFileName` path) $ do+    target <- win32FilePath path+    withCWString target $ \cTarget -> alloca $ \failedOut -> do+      code <- c_nn_entry_set_owner_dacl cTarget descriptor failedOut+      when (code /= 0) $ do+        call <- maybePeek peekCString =<< peek failedOut+        failWith (fromMaybe "nn_entry_set_owner_dacl" call) code++-- | The first directory on the way to a store that exists and cannot be+-- trusted with it, given the store's state directory, the store's+-- directory it is on the way to and why, or 'Nothing' when every+-- directory that exists can ('checkStateDirectory' refuses a store for+-- the first).+distrustedStateDirectory :: FilePath -> IO (Maybe (FilePath, FilePath, Distrust))+distrustedStateDirectory stateDir = do+  accounts <- storeAccounts+  full <- getFullPathName stateDir+  let store = takeDirectory full+      distrusted (dir, access) = do+        descriptor <- entrySecurity dir+        pure ((\reason -> (dir, store, reason)) <$> (descriptor >>= descriptorDistrust accounts access))+  firstJust distrusted (stateDirectories full)++-- | The first answer that is not 'Nothing' of an action over a list's+-- elements in order, which runs no action after it.+firstJust :: (a -> IO (Maybe b)) -> [a] -> IO (Maybe b)+firstJust _ [] = pure Nothing+firstJust step (item : rest) = step item >>= maybe (firstJust step rest) (pure . Just)++-- | Whether the directory's access control list grants this process's+-- token listing it and adding files and subdirectories to it, which is+-- what a store's state directory is used for.  The rights are checked+-- against the list and the directory is not opened for them, since an+-- open made for backup intent passes whatever the list says for a token+-- whose backup or restore privilege is enabled, as an administrator's+-- session started over SSH has, and a write does not.  A directory that+-- does not exist, or whose list cannot be read, is a failure.+directoryChangeable :: FilePath -> IO Bool+directoryChangeable dir = do+  target <- win32FilePath dir+  withCWString target $ \cTarget ->+    alloca $ \grantedOut -> alloca $ \failedOut -> do+      code <- c_nn_dir_access cTarget (fileListDirectory .|. fileAddFile .|. fileAddSubdirectory) grantedOut failedOut+      case code of+        0 -> (/= 0) <$> peek grantedOut+        _ -> do+          call <- maybePeek peekCString =<< peek failedOut+          failWith (fromMaybe "nn_dir_access" call) code++-- | @FILE_LIST_DIRECTORY@, @FILE_ADD_FILE@ and @FILE_ADD_SUBDIRECTORY@+-- (winnt.h), the rights a directory is opened for to list it and to add+-- files and subdirectories to it.+fileListDirectory, fileAddFile, fileAddSubdirectory :: CULong+fileListDirectory = 0x1+fileAddFile = 0x2+fileAddSubdirectory = 0x4++-- | Check a directory on the way to a store, given the machine's+-- accounts and the store's directory, where it exists, and create it+-- with its access where it does not ('createStateDirectory').+prepareDirectory :: StoreAccounts -> FilePath -> (FilePath, DirAccess) -> IO ()+prepareDirectory accounts store (dir, access) =+  entrySecurity dir >>= maybe (createDirectoryWith access dir `catchIOError` raced) keep+  where+    raced err+      | isAlreadyExistsError err = entrySecurity dir >>= maybe (ioError err) keep+      | otherwise = ioError err+    keep descriptor = do+      refuseUntrusted accounts access store dir descriptor+      present <- doesDirectoryExist dir+      unless present (ioError (mkIOError alreadyExistsErrorType "createDirectory" Nothing (Just dir)))++-- | Refuse the store whose directory is given, for the machine's+-- accounts, when the directory on the way to it whose access and+-- security descriptor are given cannot be trusted with it.+refuseUntrusted :: StoreAccounts -> DirAccess -> FilePath -> FilePath -> ByteString -> IO ()+refuseUntrusted accounts access store dir descriptor =+  traverse_ (ioError . userError . distrustMessage dir store) (descriptorDistrust accounts access descriptor)++-- | The security descriptor of the entry at the path itself, a link read+-- as itself and not followed, holding its owner and DACL, or 'Nothing'+-- when nothing has the name.  A failure names the call that failed and+-- the path.+entrySecurity :: FilePath -> IO (Maybe ByteString)+entrySecurity path =+  modifyIOError (`ioeSetFileName` path) $ do+    target <- win32FilePath path+    withCWString target $ \cTarget ->+      alloca $ \descriptorOut -> alloca $ \lengthOut -> alloca $ \failedOut -> do+        code <- c_nn_entry_security cTarget descriptorOut lengthOut failedOut+        case code of+          0 -> bracket (peek descriptorOut) (void . localFree) $ \descriptor -> do+            size <- peek lengthOut+            Just <$> BS.packCStringLen (castPtr descriptor, fromIntegral size)+          _+            | code `elem` [errorFileNotFound, errorPathNotFound] -> pure Nothing+            | otherwise -> do+                call <- maybePeek peekCString =<< peek failedOut+                failWith (fromMaybe "nn_entry_security" call) code++-- | @ERROR_FILE_NOT_FOUND@ and @ERROR_PATH_NOT_FOUND@ (winerror.h), the+-- errors CreateFileW gives when nothing has the name, or a directory on+-- the way to it is missing.+errorFileNotFound, errorPathNotFound :: ErrCode+errorFileNotFound = 2+errorPathNotFound = 3++-- | The user this process runs as, its token's user.  A failure names+-- the call that failed, which the shim reports beside its error.+tokenUserSid :: IO Sid+tokenUserSid =+  alloca $ \sidOut -> alloca $ \failedOut -> do+    code <- c_nn_token_user_sid sidOut failedOut+    when (code /= 0) $ do+      call <- maybePeek peekCString =<< peek failedOut+      failWith (fromMaybe "nn_token_user_sid" call) code+    bracket (peek sidOut) (void . localFree) $ \sid -> do+      text <- T.pack <$> peekCWString sid+      maybe (ioError (userError ("the process token's user SID is not a SID: " <> show text))) pure (sidFromText text)++#endif++-- ---------------------------------------------------------------------------+-- A directory already there+-- ---------------------------------------------------------------------------++-- | The directories down to a store's directory, given its full path on+-- Windows, outermost first, each with the access it is created with+-- where it is missing: the store's directory with 'StoreAccess', and+-- each parent of it with 'ParentAccess'.  The volume root, the drive+-- 'System.FilePath.Windows.splitDrive' gives, is never among them (the+-- module header says why), so a store at a drive root has none.  It+-- follows Windows' path rules on every platform.+storeDirectories :: FilePath -> [(FilePath, DirAccess)]+storeDirectories storeDir = reverse (zip (reverse below) (StoreAccess : repeat ParentAccess))+  where+    (root, rest) = Windows.splitDrive storeDir+    below = map (root Windows.</>) (scanl1 (Windows.</>) (Windows.splitDirectories rest))++-- | The directories 'storeDirectories' gives for the store directory a+-- state directory is in, given the state directory's full path on+-- Windows, then the state directory itself, with 'StateAccess'.+stateDirectories :: FilePath -> [(FilePath, DirAccess)]+stateDirectories stateDir = storeDirectories (Windows.takeDirectory stateDir) <> [(stateDir, StateAccess)]++-- | The owner and DACL of a directory, as its security descriptor holds+-- them.+data DirSecurity = DirSecurity+  { -- | The owner, 'Nothing' when the descriptor names none.+    dsOwner :: !(Maybe Sid),+    -- | The DACL's entries in order, 'Nothing' when there is no DACL or+    -- a null one, either of which lets every account do anything.+    dsDacl :: !(Maybe [AclEntry])+  }+  deriving (Eq, Show)++-- | An entry of a DACL, by what it grants.+data AclEntry+  = -- | An allow entry of any kind and any inheritance, an inherit-only+    -- entry among them: its flags, the inheritance ones among them, the+    -- rights it grants and the account it grants them to.+    AllowEntry !Word8 !Word32 !Sid+  | -- | A deny, audit or alarm entry of any kind, which grants nothing.+    OtherEntry+  | -- | An entry of any other type, given: one winnt.h numbers after the+    -- callback types, such as a mandatory label, which belongs in a+    -- SACL, or one it does not define.+    UnknownEntry !Word8+  deriving (Eq, Show)++-- | Why a directory on the way to a store cannot be trusted with it.+data Distrust+  = -- | Its owner, 'Nothing' for none, is not the user, SYSTEM or+    -- Administrators.+    OwnedBy !(Maybe Sid)+  | -- | It has no DACL, or a null one.+    NoDacl+  | -- | Its DACL holds an 'UnknownEntry'.+    UnreadableEntry+  | -- | An allow entry grants this account, not the user, SYSTEM or+    -- Administrators, a right that changes the directory.+    WritableBy !Sid+  | -- | Its security descriptor does not parse+    -- ('parseSecurityDescriptor').+    UnreadableDescriptor+  deriving (Eq, Show)++-- | Why a directory with the owner and DACL given, of the access given,+-- cannot be trusted with a store for the accounts given, or 'Nothing'+-- when it can: install-nova-nix's rule, which the module header gives,+-- with the service in the user's place.  One grant to another account+-- is trusted, on the store's directory alone: the build accounts'+-- group's, to create entries in it and nothing more, applying to the+-- directory itself and passed to nothing it holds, as 'accessSddl'+-- writes it.  Of the entries that fail the rule, the first is named.+securityDistrust :: StoreAccounts -> DirAccess -> DirSecurity -> Maybe Distrust+securityDistrust accounts access (DirSecurity owner dacl)+  | not (maybe False trusted owner) = Just (OwnedBy owner)+  | otherwise = maybe (Just NoDacl) (listToMaybe . mapMaybe entryDistrust) dacl+  where+    trusted sid = sid `elem` [saService accounts, localSystemSid, administratorsSid]+    entryDistrust entry = case entry of+      AllowEntry flags rights sid+        | rights .&. changeRights == 0 || trusted sid || buildersCreating flags rights sid -> Nothing+        | otherwise -> Just (WritableBy sid)+      OtherEntry -> Nothing+      UnknownEntry _ -> Just UnreadableEntry+    buildersCreating flags rights sid =+      access == StoreAccess+        && Just sid == saBuilders accounts+        && rights .&. complement createOnly == 0+        && flags .&. passingDown == 0++-- | 'securityDistrust' of a security descriptor given as bytes, or+-- 'UnreadableDescriptor' when they are not one.+descriptorDistrust :: StoreAccounts -> DirAccess -> ByteString -> Maybe Distrust+descriptorDistrust accounts access = maybe (Just UnreadableDescriptor) (securityDistrust accounts access) . parseSecurityDescriptor++-- | @OBJECT_INHERIT_ACE@, @CONTAINER_INHERIT_ACE@ and @INHERIT_ONLY_ACE@+-- (winnt.h), the flags of an entry that passes to what a directory holds.+passingDown :: Word8+passingDown = 0x1 .|. 0x2 .|. 0x8++-- | The refusal of a store, given its directory second, for a directory+-- on the way to it, given first, that cannot be trusted with it, in+-- install-nova-nix's words where it has them.+distrustMessage :: FilePath -> FilePath -> Distrust -> String+distrustMessage dir store reason =+  dir <> " " <> why <> ", so the store in " <> store <> " cannot be trusted; move " <> dir <> " aside and let nova-nix or install-nova-nix create it"+  where+    why = case reason of+      OwnedBy owner -> "belongs to " <> maybe "no one" (T.unpack . sidText) owner <> ", not to you, SYSTEM or Administrators"+      NoDacl -> "has no DACL, which lets every account change it"+      UnreadableEntry -> "carries an access entry of a kind nova-nix cannot read"+      WritableBy sid -> "lets " <> T.unpack (sidText sid) <> " change it"+      UnreadableDescriptor -> "has a security descriptor nova-nix cannot read"++-- | The rights that let an account change a directory, install-nova-nix's+-- write rights (winnt.h).  The generic two are among them because an+-- inherit-only entry can hold them in place of the rights they map to+-- once inherited.+changeRights :: Word32+changeRights =+  foldl'+    (.|.)+    0+    [ 0x2, -- FILE_WRITE_DATA: on a directory, adding a file+      0x4, -- FILE_APPEND_DATA: on a directory, adding a subdirectory+      0x10, -- FILE_WRITE_EA+      0x40, -- FILE_DELETE_CHILD+      0x100, -- FILE_WRITE_ATTRIBUTES+      0x10000, -- DELETE+      0x40000, -- WRITE_DAC+      0x80000, -- WRITE_OWNER+      0x10000000, -- GENERIC_ALL+      0x40000000 -- GENERIC_WRITE+    ]++-- | The owner and DACL a self-relative security descriptor holds, the+-- form GetSecurityInfo returns one in, or 'Nothing' when the bytes are+-- not one.  The descriptor starts with its revision, its control flags+-- at byte 2, and the offsets of its owner at 4 and its DACL at 16, an+-- offset of 0 for one it does not hold; the DACL is there only when the+-- flags say so, and a DACL that is there at offset 0 is a null one.+-- Every entry of the DACL is read, as Windows keeps it.+parseSecurityDescriptor :: ByteString -> Maybe DirSecurity+parseSecurityDescriptor bytes = do+  revision <- byteAt 0 bytes+  control <- word16At 2 bytes+  ownerOffset <- word32At 4 bytes+  daclOffset <- word32At 16 bytes+  guard (revision == descriptorRevision && control .&. selfRelative /= 0)+  owner <- partAt ownerOffset sidIn+  dacl <- if control .&. daclPresent == 0 then Just Nothing else partAt daclOffset aclEntriesIn+  pure (DirSecurity owner dacl)+  where+    partAt offset parse+      | offset == 0 = Just Nothing+      | otherwise = Just <$> parse (BS.drop (fromIntegral offset) bytes)++-- | The SID the bytes start with: its revision, 1, the count of its+-- subauthorities, its identifier authority in six bytes, the most+-- significant first, then each subauthority in four, the least+-- significant first.  It is written as ConvertSidToStringSidW writes it,+-- so a SID 'sidFromText' does not accept is no SID here either.+sidIn :: ByteString -> Maybe Sid+sidIn bytes = do+  revision <- byteAt 0 bytes+  count <- byteAt 1 bytes+  guard (revision == sidRevision)+  authority <- foldl' (\value byte -> value * 256 + toInteger byte) 0 <$> traverse (`byteAt` bytes) [2 .. sidHeaderSize - 1]+  subauthorities <- traverse (\index -> word32At (sidHeaderSize + 4 * index) bytes) [0 .. fromIntegral count - 1]+  sidFromText (sidRevisionPrefix <> authorityText authority <> foldMap (("-" <>) . T.pack . show) subauthorities)+  where+    authorityText value+      | value < fieldLimit = T.pack (show value)+      | otherwise = "0x" <> T.justifyRight wideAuthorityDigits '0' (T.pack (showHex value ""))++-- | The entries of the ACL the bytes start with: its header gives its+-- size at byte 2 and its count of entries at 4, and the entries follow+-- it, each led by its type and, at its byte 2, its own size.  An entry+-- that runs past the ACL, or an ACL past the bytes, is not one.+aclEntriesIn :: ByteString -> Maybe [AclEntry]+aclEntriesIn bytes = do+  size <- fromIntegral <$> word16At 2 bytes+  count <- fromIntegral <$> word16At 4 bytes+  guard (size >= aclHeaderSize && BS.length bytes >= size)+  entriesIn count (BS.drop aclHeaderSize (BS.take size bytes))+  where+    entriesIn :: Int -> ByteString -> Maybe [AclEntry]+    entriesIn count rest+      | count <= 0 = Just []+      | otherwise = do+          size <- fromIntegral <$> word16At 2 rest+          guard (size >= aceHeaderSize && BS.length rest >= size)+          entry <- entryIn (BS.take size rest)+          (entry :) <$> entriesIn (count - 1) (BS.drop size rest)++-- | An entry of a DACL, given its bytes: one of a type winnt.h lays out+-- has its access mask after its header and a SID after that, where its+-- layout says.+entryIn :: ByteString -> Maybe AclEntry+entryIn entry = do+  kind <- byteAt 0 entry+  case entryLayout kind of+    Nothing -> Just (UnknownEntry kind)+    Just layout -> do+      flags <- byteAt 1 entry+      rights <- word32At aceHeaderSize entry+      sidStart <- sidOffset layout+      sid <- sidIn (BS.drop sidStart entry)+      Just (if kind `elem` allowTypes then AllowEntry flags rights sid else OtherEntry)+  where+    sidOffset layout = case layout of+      CommonLayout -> Just 8+      CompoundLayout -> Just 12+      -- The flags, after the mask, say which of the two object type+      -- GUIDs come before the SID.+      ObjectLayout -> do+        flags <- word32At 8 entry+        let present flag = flags .&. flag /= 0+        Just (12 + guidSize * length (filter present [aceObjectTypePresent, aceInheritedObjectTypePresent]))++-- | Where an entry's SID starts, by the structure winnt.h lays its type+-- out as.+data EntryLayout+  = -- | @ACCESS_ALLOWED_ACE@: the SID after the mask.+    CommonLayout+  | -- | @ACCESS_ALLOWED_COMPOUND_ACE@: the SID after the mask, the+    -- compound type and a reserved field.+    CompoundLayout+  | -- | @ACCESS_ALLOWED_OBJECT_ACE@: the SID after the mask, the flags+    -- and the object type GUIDs the flags say are there.+    ObjectLayout++-- | The layout of an entry of the type given, for each type winnt.h+-- defines for a DACL; 'Nothing' for any other.+entryLayout :: Word8 -> Maybe EntryLayout+entryLayout kind+  | kind `elem` commonTypes = Just CommonLayout+  | kind == compoundType = Just CompoundLayout+  | kind `elem` objectTypes = Just ObjectLayout+  | otherwise = Nothing++-- | The entry types winnt.h lays out as @ACCESS_ALLOWED_ACE@: allow,+-- deny, audit and alarm (0 to 3), and their callback forms (9, 10, 13+-- and 14).+commonTypes :: [Word8]+commonTypes = [0x0, 0x1, 0x2, 0x3, 0x9, 0xA, 0xD, 0xE]++-- | @ACCESS_ALLOWED_COMPOUND_ACE_TYPE@ (winnt.h).+compoundType :: Word8+compoundType = 0x4++-- | The object entry types (winnt.h): allow, deny, audit and alarm (5 to+-- 8), and their callback forms (11, 12, 15 and 16).+objectTypes :: [Word8]+objectTypes = [0x5, 0x6, 0x7, 0x8, 0xB, 0xC, 0xF, 0x10]++-- | The allow types among them: @ACCESS_ALLOWED_ACE_TYPE@, the compound+-- type, @ACCESS_ALLOWED_OBJECT_ACE_TYPE@ and the callback forms of the+-- first and the last.+allowTypes :: [Word8]+allowTypes = [0x0, compoundType, 0x5, 0x9, 0xB]++-- | @SECURITY_DESCRIPTOR_REVISION@ (winnt.h).+descriptorRevision :: Word8+descriptorRevision = 1++-- | @SE_SELF_RELATIVE@ and @SE_DACL_PRESENT@ (winnt.h), the control flags+-- saying the descriptor holds offsets and that it has a DACL.+selfRelative, daclPresent :: Word16+selfRelative = 0x8000+daclPresent = 0x4++-- | @SID_REVISION@ (winnt.h).+sidRevision :: Word8+sidRevision = 1++-- | The bytes of a SID before its subauthorities: its revision, its+-- count and its identifier authority.+sidHeaderSize :: Int+sidHeaderSize = 8++-- | The size of an ACL's header and of an entry's header (winnt.h's+-- @ACL@ and @ACE_HEADER@).+aclHeaderSize, aceHeaderSize :: Int+aclHeaderSize = 8+aceHeaderSize = 4++-- | The size of a GUID, and @ACE_OBJECT_TYPE_PRESENT@ and+-- @ACE_INHERITED_OBJECT_TYPE_PRESENT@ (winnt.h), the flags saying an+-- object entry holds one for its object type and one for its inherited+-- object type.+guidSize :: Int+guidSize = 16++aceObjectTypePresent, aceInheritedObjectTypePresent :: Word32+aceObjectTypePresent = 0x1+aceInheritedObjectTypePresent = 0x2++-- | The byte, and the 16-bit and 32-bit little-endian words, at an+-- offset into the bytes, or 'Nothing' past their end.+byteAt :: Int -> ByteString -> Maybe Word8+byteAt offset bytes = BS.indexMaybe bytes offset++word16At :: Int -> ByteString -> Maybe Word16+word16At offset bytes = do+  low <- byteAt offset bytes+  high <- byteAt (offset + 1) bytes+  Just (fromIntegral low .|. fromIntegral high `shiftL` 8)++word32At :: Int -> ByteString -> Maybe Word32+word32At offset bytes = do+  low <- word16At offset bytes+  high <- word16At (offset + 2) bytes+  Just (fromIntegral low .|. fromIntegral high `shiftL` 16)++-- ---------------------------------------------------------------------------+-- The Windows access control list+-- ---------------------------------------------------------------------------++-- | A security identifier in the string form ConvertSidToStringSidW+-- writes: @S-1-5-18@ for SYSTEM.  'sidFromText' is the one way to make+-- one, so the text 'accessSddl' writes as an entry's trustee is a SID+-- and nothing more.+newtype Sid = Sid Text+  deriving (Show)++-- | Two SIDs are equal when they name one account.  Only an authority of+-- 2^32 or more has two spellings, its hexadecimal digits in either case,+-- and which case ConvertSidToStringSidW writes them in is undocumented.+instance Eq Sid where+  Sid a == Sid b = T.toLower a == T.toLower b++-- | A SID from its string form, @S-R-I-S...@: @S@, the revision, which is+-- 1, the identifier authority and one to fifteen subauthorities, joined+-- by @-@.  The authority is a decimal below 2^32, or @0x@ and twelve+-- hexadecimal digits for one of 2^32 or more, and each subauthority a+-- decimal below 2^32, as ConvertSidToStringSidW writes them.  A decimal+-- has no leading zero, so a SID whose authority is below 2^32, SYSTEM's+-- among them, has the one spelling 'accessSddl' compares the user's+-- with.  Anything else, any other character included, is 'Nothing'.+sidFromText :: Text -> Maybe Sid+sidFromText text = do+  rest <- T.stripPrefix sidRevisionPrefix text+  case T.splitOn "-" rest of+    authority : subauthorities@(_ : _)+      | validAuthority authority,+        length subauthorities <= maxSubAuthorities,+        all (canonicalDecimalBelow fieldLimit) subauthorities ->+          Just (Sid text)+    _ -> Nothing+  where+    validAuthority authority =+      canonicalDecimalBelow fieldLimit authority || maybe False wideAuthority (T.stripPrefix "0x" authority)+    -- The form ConvertSidToStringSidW takes only for an authority whose+    -- top 16 of 48 bits are not all zero.+    wideAuthority digits =+      T.length digits == wideAuthorityDigits && T.all isHexDigit digits && T.any (/= '0') (T.take wideHighDigits digits)++-- | A SID's string form, as 'sidFromText' took it.+sidText :: Sid -> Text+sidText (Sid text) = text++-- | Whether text is a decimal below the limit, spelled with no sign,+-- space or leading zero.+canonicalDecimalBelow :: Integer -> Text -> Bool+canonicalDecimalBelow limit digits = case T.uncons digits of+  Just ('0', more) -> T.null more+  Just _+    | T.all isDigit digits, Right (value, unread) <- TR.decimal digits -> T.null unread && value < limit+  _ -> False++-- | A SID's string form up to its identifier authority: @S@ and the+-- revision, @SID_REVISION@ (winnt.h).+sidRevisionPrefix :: Text+sidRevisionPrefix = "S-1-"++-- | @SID_MAX_SUB_AUTHORITIES@ (winnt.h).+maxSubAuthorities :: Int+maxSubAuthorities = 15++-- | The bound of a subauthority, a 32-bit value, and of an authority+-- written in decimal.+fieldLimit :: Integer+fieldLimit = 2 ^ (32 :: Int)++-- | The hexadecimal digits of a 48-bit authority, and of its top 16+-- bits.+wideAuthorityDigits, wideHighDigits :: Int+wideAuthorityDigits = 12+wideHighDigits = 4++-- | The security descriptor, in SDDL, that a directory of the given+-- access is created with on Windows, for the given accounts: a protected+-- DACL (@D:P@) of allow entries.  'StateAccess' grants full control to+-- the service, SYSTEM and Administrators and read and execute to Users,+-- in that order, naming the service once when it is SYSTEM itself, each+-- inherited by files and directories below (@OICI@), as install-nova-nix+-- grants them on @C:\\nix@.  'StoreAccess' grants the same where the+-- machine has no build accounts' group, so a single-user store is as it+-- always was.  Where it has one, each of those entries applies to the+-- store's directory alone, so what a build makes there takes its token's+-- own default DACL rather than one passed down, and the group gets the+-- right to create files and directories there and nothing else.+-- 'ParentAccess' grants what 'StateAccess' does less Users' entry, and+-- 'OwnerAccess' grants full control to the service alone.+accessSddl :: StoreAccounts -> DirAccess -> Text+accessSddl accounts access = protectedDacl <> foldMap grantSddl (accessGrants accounts access)++-- | The security descriptor, in SDDL, that a node of a path of the kind+-- given is given when the path is registered, on Windows: the service as+-- its owner, and a protected DACL of allow entries that grants full+-- control to the service, SYSTEM and Administrators, read and execute to+-- Users and the build accounts' group where there is one, and read+-- access to its own DACL alone to its owner (@OWNER RIGHTS@), which+-- takes the place of the rights an owner otherwise has whatever the DACL+-- says.  A directory's entries are inherited below (@OICI@), and a file's+-- or a link's carry no inheritance flags, which Windows would not keep on+-- them.  A build account that made a node, and owns it where the service+-- has not taken it, can then change nothing of it.+validPathSddl :: StoreAccounts -> ValidNode -> Text+validPathSddl accounts node =+  "O:" <> sidText (saService accounts) <> protectedDacl <> foldMap grantSddl grants+  where+    inheritance = case node of+      ValidDirectory -> PassedDown+      ValidLeaf -> ItselfAlone+    grants =+      map (Grant inheritance fileAllAccess) (trustedAccounts accounts)+        <> [Grant inheritance readAndExecute usersSid]+        <> [Grant inheritance readAndExecute builders | builders <- toList (saBuilders accounts)]+        <> [Grant inheritance readControl ownerRightsSid]++-- | One allow entry of a DACL nova-nix writes: whether it is passed to+-- what a directory holds, the rights, and the account it grants them to.+data Grant = Grant !Inheritance !Word32 !Sid++-- | Whether an entry is passed to the files and directories below, as+-- well as applying to the directory itself.+data Inheritance = PassedDown | ItselfAlone++-- | Each entry a directory of the given access is created with.+accessGrants :: StoreAccounts -> DirAccess -> [Grant]+accessGrants accounts access = case access of+  StoreAccess -> case saBuilders accounts of+    Nothing -> stateGrants+    Just builders -> map (Grant ItselfAlone fileAllAccess) trusted <> [Grant ItselfAlone readAndExecute usersSid, Grant ItselfAlone createOnly builders]+  StateAccess -> stateGrants+  ParentAccess -> map (Grant PassedDown fileAllAccess) trusted+  OwnerAccess -> [Grant PassedDown fileAllAccess (saService accounts)]+  where+    trusted = trustedAccounts accounts+    stateGrants = map (Grant PassedDown fileAllAccess) trusted <> [Grant PassedDown readAndExecute usersSid]++-- | The accounts the installer trusts with a store, the service in the+-- user's place: the service, named once when it is SYSTEM itself,+-- SYSTEM and Administrators.+trustedAccounts :: StoreAccounts -> [Sid]+trustedAccounts accounts = [service | service /= localSystemSid] <> [localSystemSid, administratorsSid]+  where+    service = saService accounts++-- | An allow entry (@A@) in SDDL, its flags @OICI@ when it is passed+-- down, the installer's @ContainerInherit, ObjectInherit@ with no+-- propagation flags, and none when it applies to the directory itself+-- alone.  Its object and inherited-object type fields stay empty: they+-- apply to directory-service objects, not to files.+grantSddl :: Grant -> Text+grantSddl (Grant inheritance rights sid) = "(A;" <> flags <> ";0x" <> T.pack (showHex rights "") <> ";;;" <> sidText sid <> ")"+  where+    flags = case inheritance of+      PassedDown -> "OICI"+      ItselfAlone -> ""++-- | SDDL's DACL (@D:@), protected (@P@): it takes no entry from the+-- parent, as the installer's @SetAccessRuleProtection($true, $false)@+-- makes its own.+protectedDacl :: Text+protectedDacl = "D:P"++-- | The rights to create files and directories in a directory and+-- nothing else: @FILE_ADD_FILE@, @FILE_ADD_SUBDIRECTORY@,+-- @FILE_TRAVERSE@, @FILE_READ_ATTRIBUTES@ and @SYNCHRONIZE@ (winnt.h).+createOnly :: Word32+createOnly = 0x2 .|. 0x4 .|. 0x20 .|. 0x80 .|. 0x100000++-- | @READ_CONTROL@ (winnt.h): reading a node's security descriptor.+readControl :: Word32+readControl = 0x20000++-- | @FILE_ALL_ACCESS@ (winnt.h), .NET's @FileSystemRights.FullControl@.+fileAllAccess :: Word32+fileAllAccess = 0x1F01FF++-- | @FILE_GENERIC_READ | FILE_GENERIC_EXECUTE@ (winnt.h): .NET's+-- @FileSystemRights.ReadAndExecute@ with the @Synchronize@ right .NET+-- adds to every allow entry it writes.+readAndExecute :: Word32+readAndExecute = 0x1200A9++-- | SYSTEM, the installer's @LocalSystemSid@.+localSystemSid :: Sid+localSystemSid = Sid "S-1-5-18"++-- | The SID of the virtual account a service of this name runs as,+-- @NT SERVICE\\NAME@.  Windows derives it from the name alone: the name+-- in upper case, as UTF-16, is hashed with SHA-1, and each of the five+-- 4-byte groups of the digest, as a little-endian unsigned integer, is a+-- subauthority of @S-1-5-80@.  It is known before the service is+-- installed, though Windows resolves the name only once it is.  The+-- upper-casing is that of ASCII names, which services have.+serviceSid :: Text -> Sid+serviceSid name = Sid (serviceSidPrefix <> T.intercalate "-" (map (T.pack . show) subauthorities))+  where+    digest = BA.convert (CH.hash (TE.encodeUtf16LE (T.toUpper name)) :: CH.Digest CH.SHA1) :: ByteString+    subauthorities = [littleEndian (BS.take subauthorityBytes (BS.drop (index * subauthorityBytes) digest)) | index <- [0 .. serviceSidSubAuthorities - 1]]++-- | An unsigned integer from its bytes, the least significant first.+littleEndian :: ByteString -> Word32+littleEndian = BS.foldr' (\byte acc -> acc `shiftL` bitsPerByte .|. fromIntegral byte) 0+  where+    bitsPerByte = 8++-- | What a service's SID starts with, and how many subauthorities follow.+serviceSidPrefix :: Text+serviceSidPrefix = "S-1-5-80-"++serviceSidSubAuthorities, subauthorityBytes :: Int+serviceSidSubAuthorities = 5+subauthorityBytes = 4++-- | The virtual account @NT SERVICE\\nova-nix@, which the Windows service+-- the daemon is to run as will run as.+novaNixServiceSid :: Sid+novaNixServiceSid = serviceSid "nova-nix"++-- | The local Administrators group, the installer's+-- @BuiltinAdministratorsSid@.+administratorsSid :: Sid+administratorsSid = Sid "S-1-5-32-544"++-- | The local Users group, the installer's @BuiltinUsersSid@.+usersSid :: Sid+usersSid = Sid "S-1-5-32-545"++-- | @OWNER RIGHTS@, the SID whose entry stands for an object's owner in+-- place of the rights its owner otherwise holds.+ownerRightsSid :: Sid+ownerRightsSid = Sid "S-1-3-4"
src/Nix/Store/CaseSensitive.hs view
@@ -21,9 +21,12 @@     -- * Reading a tree back     volumeCaseHack,     processCaseHack,+    pathCaseHack,   ) where +import Data.Text (Text)+import Nix.Store.Path (isCanonicalStoreText) import qualified NovaCache.NAR as NAR  #if defined(darwin_HOST_OS)@@ -67,6 +70,18 @@ -- where nova-nix's stores fold. processCaseHack :: NAR.CaseHack processCaseHack = NAR.defaultCaseHack++-- | The case-hack mode a read of path-value text runs under, given the+-- sensitivity of the store's volume.  Store text names a tree on that+-- volume, read back as the store reads its own paths+-- ('volumeCaseHack'); any other path is a source ('processCaseHack').+-- Evaluation hashes a path and the build driver restores its copy under+-- this one rule, each from the same resolved text, so the copy+-- reproduces the address evaluation gave it.+pathCaseHack :: CaseSensitivity -> Text -> NAR.CaseHack+pathCaseHack storeVolume path+  | isCanonicalStoreText path = volumeCaseHack storeVolume+  | otherwise = processCaseHack  #if defined(darwin_HOST_OS) 
src/Nix/Store/DB.hs view
@@ -8,8 +8,7 @@ -- * __References__: which other store paths does this path depend on? --   (Needed for garbage collection - can't delete a path that others --   reference.)--- * __Registrant__: who put this path here? (Substituted from cache?---   Built locally?)+-- * __Registration time__: when the path was registered. -- * __Deriver__: which .drv file produced this output? (For @nix-store -q --   --deriver@.) -- * __NAR hash__: SHA-256 of the path's NAR serialization. (For integrity@@ -17,20 +16,55 @@ -- * __NAR size__: byte count of the NAR. (For disk usage reporting.) -- * __Validity__: has this path been verified? (A path can exist on disk --   but be invalid if the build was interrupted.)+-- * __Trust__: whether this store built the path, the signatures it+--   carries, and the content address its name was made from, if it was. -- -- C++ Nix uses SQLite for this.  So do we.  The database lives at -- @\/nix\/store\/.nova-nix\/db.sqlite@ (or @C:\\nix\\store\\.nova-nix\\db.sqlite@).+--+-- == The schema+--+-- The tables and columns are upstream's, under upstream's names, and the+-- trust columns hold what upstream's hold: @ultimate@ 1 for a path this+-- store built and NULL otherwise, @sigs@ the signatures spelled as a+-- narinfo spells them and separated by spaces, or NULL for none, and+-- @ca@ the content address as upstream renders it, or NULL for none.+-- @DerivationOutputs@ lists each valid derivation's outputs, so the+-- derivations that make a path are found without reading a @.drv@.  A+-- database an earlier nova-nix made has neither the trust columns nor+-- that table, and gains both when it is opened for writing+-- ('openStoreDB'), the table filled from the derivations it holds.+-- Unlike upstream's, a row names its path in the platform's spelling of+-- the store directory, the NAR hash is spelled in nix-base32, @narSize@+-- is never NULL, and @Refs@ has neither upstream's delete actions nor its+-- trigger, since this module removes a path's edges itself.+--+-- A row names its path under the directory the store was opened at when+-- the path was registered, so a store opened at a directory with none of+-- its rows under it finds none of them: every lookup misses, and the paths+-- and outputs in it name the old directory besides.  Both opens refuse+-- such a store ('foreignStoreDir').  A store with a row under the+-- directory it is opened at opens, as one that was moved and then built+-- into at its new directory does. module Nix.Store.DB   ( -- * Database handle     StoreDB,      -- * Types     PathRegistration (..),+    RegistrationTime (..),+    statedRegistrationTime,     PathInfo (..),+    Ultimate (..),      -- * Lifecycle     openStoreDB,+    openStoreDBReadOnly,+    storeTablesExist,+    foreignStoreDir,+    storeRowRange,     closeStoreDB,+    createStoreDirectories,      -- * Registration     registerPath,@@ -41,6 +75,9 @@     queryDeriver,     queryPathInfo,     queryAllValidPaths,+    queryReferrers,+    queryValidDerivers,+    queryPathFromHashPart,      -- * Unregistration     UnregisterResult (..),@@ -53,26 +90,40 @@   ) where -import Control.Exception (throwIO)+import Control.Exception (IOException, bracketOnError, throwIO, try)+import Control.Monad (guard, unless, when)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import Data.Foldable (for_, traverse_)+import Data.IORef (newIORef)+import Data.Int (Int64) import Data.List (sortOn)+import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T+import qualified Data.Text.Encoding as TE import Database.SQLite.Simple-  ( Connection,+  ( Connection (..),     Only (..),     Query (..),+    SQLData (..),     close,     execute,     executeMany,     execute_,     open,     query,+    query_,+    withImmediateTransaction,     withTransaction,   )-import Nix.Store.Path (StoreDir (..), StorePath, defaultStoreDir, storePathToFilePath, storePathToText)-import System.Directory (createDirectoryIfMissing)-import System.FilePath ((</>))+import qualified Database.SQLite3 as SQLite3+import Nix.Daemon.Protocol (ContentAddress, Signature, parseContentAddress, parseSignature, renderContentAddress, renderSignature)+import Nix.Derivation (DerivationOutput (..), drvExtension, drvOutputs, fromATerm)+import Nix.Store.Access (checkStateDirectory, createStateDirectory)+import Nix.Store.Path (StoreDir (..), StorePath, defaultStoreDir, spName, storePathHashLen, storePathToFilePath, storePathToText)+import System.FilePath (isAbsolute, takeDirectory, takeFileName, (</>))  -- --------------------------------------------------------------------------- -- Named constants@@ -103,20 +154,58 @@     prNarHash :: !Text,     prNarSize :: !Int,     prDeriver :: !(Maybe Text),-    prReferences :: ![StorePath]+    prReferences :: ![StorePath],+    -- | Whether this store built the path.+    prUltimate :: !Ultimate,+    -- | The signatures the path carries.+    prSignatures :: !(Set Signature),+    -- | The content address the path's name was made from, if it was.+    prContentAddress :: !(Maybe ContentAddress),+    -- | When the path is recorded as registered.+    prRegistrationTime :: !RegistrationTime   }   deriving (Eq, Show) +-- | When a path is recorded as registered, as its row's+-- @registrationTime@ holds it.+data RegistrationTime+  = -- | The time its registration commits.+    RegisteredNow+  | -- | A time its info states, in seconds since the epoch.+    RegisteredAt !Int64+  deriving (Eq, Show)++-- | The time a path's info states it was registered, as upstream's store+-- records it: 0 states no time, and the path is recorded at the time its+-- registration commits.+statedRegistrationTime :: Int64 -> RegistrationTime+statedRegistrationTime 0 = RegisteredNow+statedRegistrationTime seconds = RegisteredAt seconds+ -- | Stored information about a registered path. data PathInfo = PathInfo   { piPath :: !Text,     piNarHash :: !Text,     piNarSize :: !Int,     piDeriver :: !(Maybe Text),-    piRegTime :: !Int+    piRegTime :: !Int,+    -- | Whether this store built the path.+    piUltimate :: !Ultimate,+    -- | The signatures the path carries.+    piSignatures :: !(Set Signature),+    -- | The content address the path's name was made from, if it was.+    piContentAddress :: !(Maybe ContentAddress)   }   deriving (Eq, Show) +-- | Whether a path is ultimately trusted, upstream's @ultimate@: a+-- derivation output this store built is, and a path that reached it any+-- other way is not.+data Ultimate+  = Ultimate+  | NotUltimate+  deriving (Eq, Show)+ -- --------------------------------------------------------------------------- -- SQL statements -- ---------------------------------------------------------------------------@@ -130,9 +219,42 @@   \  hash             TEXT NOT NULL,\   \  registrationTime INTEGER NOT NULL,\   \  deriver          TEXT,\-  \  narSize          INTEGER NOT NULL\+  \  narSize          INTEGER NOT NULL,\+  \  ultimate         INTEGER,\+  \  sigs             TEXT,\+  \  ca               TEXT\   \)" +-- | The trust columns, with their types, which a ValidPaths table an+-- earlier nova-nix made lacks.+trustColumns :: [(Text, Text)]+trustColumns = [("ultimate", "INTEGER"), ("sigs", "TEXT"), ("ca", "TEXT")]++-- | The table of each valid derivation's outputs, upstream's: the+-- derivation's row, the output's name, and its path.  A derivation's+-- outputs go with its row.+derivationOutputsTable :: Text+derivationOutputsTable = "DerivationOutputs"++-- | Create the DerivationOutputs table and the index that finds a path's+-- derivations.+createDerivationOutputsSQL :: [Query]+createDerivationOutputsSQL =+  [ "CREATE TABLE IF NOT EXISTS DerivationOutputs (\+    \  drv  INTEGER NOT NULL,\+    \  id   TEXT NOT NULL,\+    \  path TEXT NOT NULL,\+    \  PRIMARY KEY (drv, id),\+    \  FOREIGN KEY (drv) REFERENCES ValidPaths(id) ON DELETE CASCADE\+    \)",+    "CREATE INDEX IF NOT EXISTS IndexDerivationOutputs ON DerivationOutputs(path)"+  ]++-- | The tables a store's database holds, as 'createValidPathsSQL' and+-- 'createRefsSQL' make them.+storeTables :: Set.Set Text+storeTables = Set.fromList ["ValidPaths", "Refs"]+ -- | Create the Refs table. createRefsSQL :: String createRefsSQL =@@ -142,39 +264,220 @@   \  PRIMARY KEY (referrer, reference)\   \)" +-- | Upstream's index that finds a path's referrers.+createReferenceIndexSQL :: Query+createReferenceIndexSQL = "CREATE INDEX IF NOT EXISTS IndexReference ON Refs(reference)"+ -- --------------------------------------------------------------------------- -- Lifecycle -- ---------------------------------------------------------------------------  -- | Open (or create) the store database.--- Creates the store directory, metadata subdirectory, and database--- tables if they don't exist.  Enables WAL mode for concurrency and--- foreign-key enforcement for referential integrity.+-- Creates the store directory and metadata subdirectory+-- ('createStoreDirectories') and the database tables if they don't+-- exist.  Enables WAL mode for concurrency and foreign-key enforcement+-- for referential integrity.  A statement that fails closes the+-- connection it ran on.  A database that holds rows, none of them under+-- the directory given ('storeRowRange'), is refused with an 'IOError'+-- before anything is written to it. openStoreDB :: StoreDir -> IO StoreDB openStoreDB dir = do-  let storeRoot = unStoreDir dir-      metaDir = storeRoot </> metaDirName-      dbPath = metaDir </> dbFileName-  createDirectoryIfMissing True metaDir-  conn <- open dbPath+  createStoreDirectories dir+  bracketOnError (open dbPath) close (configureDB dir)+  where+    dbPath = unStoreDir dir </> metaDirName </> dbFileName++-- | Create the store directory and its metadata subdirectory where+-- they are missing, with any missing parent of the store directory, as+-- 'createStateDirectory' creates them: on Windows the store directory+-- is open to whom 'Nix.Store.Access.StoreAccess' says, the metadata+-- directory to whom 'Nix.Store.Access.StateAccess' says, and a parent+-- this creates to whom 'Nix.Store.Access.ParentAccess' says.  A directory already+-- there keeps the access it has, and on Windows one another account+-- could change is refused before anything is created in it.+createStoreDirectories :: StoreDir -> IO ()+createStoreDirectories dir = createStateDirectory (unStoreDir dir </> metaDirName)++-- | Set a connection to a store's database up: its pragmas and its+-- tables, bringing a database an earlier nova-nix made up to the schema+-- ('migrateSchema').+configureDB :: StoreDir -> Connection -> IO StoreDB+configureDB dir conn = do   execute_ conn "PRAGMA journal_mode=WAL"-  -- SQLite's default busy timeout is zero, so a second process hitting-  -- a peer's write transaction died on an uncaught ErrorBusy SQLError-  -- instead of waiting its turn.  Upstream waits an hour-  -- (sqlite3_busy_timeout(db, 60 * 60 * 1000), sqlite.cc:78 at-  -- 2.28.7); the pragma reaches the same API.-  execute_ conn "PRAGMA busy_timeout=3600000"+  waitWhileBusy conn   -- SQLite leaves foreign keys OFF per connection; without this the Refs   -- REFERENCES clauses are inert, and deleting a ValidPaths row (path   -- deletion, garbage collection) would leave dangling Refs edges that   -- closure JOINs silently under-report.   execute_ conn "PRAGMA foreign_keys=ON"+  -- Before any table statement and the migration, so that a refused open+  -- writes nothing: the migration lists a derivation's outputs from its+  -- file at the path its row holds, and a store opened away from its files+  -- would be given none, and keep none once used where it was made.+  refuseForeignStore db   execute_ conn (fromString createValidPathsSQL)   execute_ conn (fromString createRefsSQL)-  pure StoreDB {sdbDir = dir, sdbConn = conn}+  execute_ conn createReferenceIndexSQL+  migrateSchema db+  pure db   where+    db = StoreDB {sdbDir = dir, sdbConn = conn}     fromString = Query . T.pack +-- | Add what a database an earlier nova-nix made lacks: the trust columns,+-- NULL in every row it holds, so each path reads back as not ultimate,+-- unsigned and with no content address, and the DerivationOutputs table,+-- filled from each valid derivation's file.  A derivation whose file+-- cannot be read or parsed has no outputs listed, as upstream would not+-- have registered it.  The upgrade runs in a write transaction and looks+-- again inside it, so of two processes opening the database at once one+-- upgrades it and the other finds nothing left to do; a database that+-- needs nothing takes no write lock.+migrateSchema :: StoreDB -> IO ()+migrateSchema db = do+  outdated <- schemaOutdated conn+  when outdated (withImmediateTransaction conn upgrade)+  where+    conn = sdbConn db+    upgrade = do+      columns <- validPathsColumns conn+      for_ trustColumns $ \(column, kind) ->+        unless (Set.member column columns) $+          execute_ conn (Query ("ALTER TABLE ValidPaths ADD COLUMN " <> column <> " " <> kind))+      tables <- databaseTables conn+      unless (Set.member derivationOutputsTable tables) $ do+        traverse_ (execute_ conn) createDerivationOutputsSQL+        derivations <- query_ conn "SELECT path FROM ValidPaths WHERE path LIKE '%.drv'" :: IO [Only Text]+        for_ derivations $ \(Only pathText) -> do+          contents <- try (BS.readFile (T.unpack pathText)) :: IO (Either IOException ByteString)+          case fromATerm <$> contents of+            Right (Right drv) -> insertDerivationOutputs db pathText (drvOutputs drv)+            _ -> pure ()++-- | Whether a database lacks a trust column or the DerivationOutputs+-- table.+schemaOutdated :: Connection -> IO Bool+schemaOutdated conn = do+  columns <- validPathsColumns conn+  tables <- databaseTables conn+  pure (not (all ((`Set.member` columns) . fst) trustColumns && Set.member derivationOutputsTable tables))++-- | The columns of a database's ValidPaths table.+validPathsColumns :: Connection -> IO (Set Text)+validPathsColumns conn = Set.fromList . map fromOnly <$> query_ conn "SELECT name FROM pragma_table_info('ValidPaths')"++-- | The tables a database holds.+databaseTables :: Connection -> IO (Set Text)+databaseTables conn = Set.fromList . map fromOnly <$> query_ conn "SELECT name FROM sqlite_master WHERE type = 'table'"++-- | Have a connection wait up to an hour for a peer's lock, as upstream's+-- does (sqlite3_busy_timeout(db, 60 * 60 * 1000) in the @SQLite@ constructor,+-- sqlite.cc), where SQLite's default timeout of zero fails at once with+-- ErrorBusy.  The pragma reaches the same API, and writes nothing.+waitWhileBusy :: Connection -> IO ()+waitWhileBusy conn = execute_ conn "PRAGMA busy_timeout=3600000"++-- | Open the database of a store that has one, for reading only.  The+-- connection is opened read-only and wrapped in sqlite-simple's+-- t'Connection', whose two fields the cabal file's bound on sqlite-simple+-- pins.  It runs no pragma that writes and no table statement, so the+-- database file is never written and nothing is created around it but+-- what SQLite itself needs.  For a database in WAL+-- mode, which a store's is, that is a wal-index: SQLite creates the+-- @-wal@ and @-shm@ files beside one that has none, and leaves them when+-- the connection closes, since a read-only connection cannot checkpoint;+-- the next connection that writes removes them as it closes.  Only an+-- immutable open creates neither, and it reads with no locks, so a+-- concurrent writer can give it wrong answers or corruption errors;+-- upstream opens immutably only a store it is told is read-only+-- (@LocalStore::openDB@ in local-store.cc).  Before the database is+-- opened, on Windows the directories on the way to it are checked as+-- 'checkStateDirectory' checks them, and a store another account could+-- change is refused.  So is a database that holds rows, none of them under+-- the directory given ('storeRowRange'), with an 'IOError'.+openStoreDBReadOnly :: StoreDir -> IO StoreDB+openStoreDBReadOnly dir = do+  checkStateDirectory (unStoreDir dir </> metaDirName)+  bracketOnError opened close $ \conn -> do+    waitWhileBusy conn+    let db = StoreDB dir conn+    refuseForeignStore db+    pure db+  where+    dbPath = unStoreDir dir </> metaDirName </> dbFileName+    opened = Connection <$> SQLite3.open2 (T.pack dbPath) [SQLite3.SQLOpenReadOnly] SQLite3.SQLVFSDefault <*> newIORef 0++-- | Whether a database holds the store's tables ('storeTables').  One+-- whose first open was cut short, or that another process is opening for+-- the first time, holds none of them yet.+storeTablesExist :: StoreDB -> IO Bool+storeTablesExist db = (storeTables `Set.isSubsetOf`) <$> databaseTables (sdbConn db)++-- | The directory a ValidPaths row was recorded under, when it is not the+-- one given.  A row is under a directory when it is that directory joined+-- to the row's own file name, as 'registerPaths' writes a row and the+-- queries build the text they look one up by, so a row spelled any other+-- way is not, and its directory is the row's own.+foreignStoreDir :: StoreDir -> Text -> Maybe StoreDir+foreignStoreDir dir row+  | T.pack (unStoreDir dir </> takeFileName rowPath) == row = Nothing+  | otherwise = Just (StoreDir (takeDirectory rowPath))+  where+    rowPath = T.unpack row++-- | The range of ValidPaths row text that lies under a store directory: the+-- rows from the first component up to, and excluding, the second.  The+-- first is the directory with the separator that joins it to a name, as+-- the join spells it, so a trailing separator or a drive root is spelled+-- as the lookups spell it, and a sibling directory whose name extends+-- this one's is outside the range.  The second is the first with its last+-- character replaced by the next.  A join ends the first in a separator+-- or a drive's colon, which have a next, so the second is absent only for+-- the empty directory, whose first is empty and whose range is every row.+storeRowRange :: StoreDir -> (Text, Maybe Text)+storeRowRange dir = (prefix, upperBound)+  where+    prefix = T.dropEnd 1 (T.pack (unStoreDir dir </> "x"))+    upperBound = do+      (rest, final) <- T.unsnoc prefix+      guard (final /= maxBound)+      Just (T.snoc rest (succ final))++-- | Refuse, with an 'IOError', a database that holds rows when none of them+-- is under the store's directory ('storeRowRange'): none of its rows would+-- be found, so it would read as empty.  A database with no row, or none of+-- the store's tables yet ('storeTablesExist'), is not refused, and neither+-- is one with a row under the directory, however many lie elsewhere.  The+-- directory the message names is the newest row's ('foreignStoreDir').+--+-- The rows under the directory are found by a range over the @path@+-- column, which its UNIQUE constraint indexes under SQLite's default+-- BINARY collation: it compares the UTF-8 bytes, which order as code+-- points do, so the range holds exactly the text beginning with the+-- prefix.+refuseForeignStore :: StoreDB -> IO ()+refuseForeignStore db = do+  ready <- storeTablesExist db+  when ready $ do+    underDirectory <- rowUnderDirectory+    unless underDirectory $ do+      newest <- query_ conn "SELECT path FROM ValidPaths ORDER BY id DESC LIMIT 1" :: IO [Only Text]+      case newest of+        (Only row : _)+          | Just recorded <- foreignStoreDir dir row -> throwIO (userError (refusal row recorded))+        _ -> pure ()+  where+    conn = sdbConn db+    dir = sdbDir db+    rowUnderDirectory = case storeRowRange dir of+      (from, Just before) -> not . null <$> (query conn "SELECT 1 FROM ValidPaths WHERE path >= ? AND path < ? LIMIT 1" (from, before) :: IO [Only Int])+      (from, Nothing) -> not . null <$> (query conn "SELECT 1 FROM ValidPaths WHERE path >= ? LIMIT 1" (Only from) :: IO [Only Int])+    refusal row recorded+      | isAbsolute (unStoreDir recorded) =+          "store '" <> unStoreDir dir <> "' was made at '" <> unStoreDir recorded <> "', and its paths and the outputs built in it name that directory; use it from there"+      | otherwise =+          "store '" <> unStoreDir dir <> "' records its paths under another directory, as in '" <> T.unpack row <> "', and its outputs name that directory"+ -- | Close the store database. closeStoreDB :: StoreDB -> IO () closeStoreDB db = close (sdbConn db)@@ -191,14 +494,23 @@ -- | Register several store paths as valid in one transaction. -- -- ALL path rows are inserted BEFORE any reference edge, so references among the--- paths in this batch - e.g. intra-derivation cross-output references - are--- never dropped.  (Registering one path at a time loses an edge whenever a--- referrer is registered before its referent.)+-- paths in this batch - e.g. intra-derivation cross-output references -+-- resolve whatever the batch order.  (Registering one path at a time would+-- refuse a referrer registered before its referent.) -- -- Re-registering an existing path refreshes its metadata (NAR hash, size, -- deriver) via @ON CONFLICT DO UPDATE@, so a path first registered with a--- placeholder hash is corrected on a later real registration.+-- placeholder hash is corrected on a later real registration.  A trust+-- field the new registration states replaces the recorded one, and one it+-- leaves absent (not ultimate, no signatures, no content address) keeps+-- what was recorded, so writing a derivation again does not drop the+-- signatures it was substituted with. --+-- A derivation's outputs are listed in DerivationOutputs from its file in+-- the store, as upstream lists them from the file when it registers one,+-- so the file must be in place: one that cannot be read or parsed refuses+-- the batch with upstream's message, @error parsing derivation ...@.+-- -- A reference to a path neither registered nor in the batch refuses the -- whole batch, recording nothing, with an 'IOError' carrying upstream's -- message, @path \'\/nix\/store\/\<hash\>-\<name\>\' is not valid@@@ -215,8 +527,37 @@ registerPaths db regs = withTransaction (sdbConn db) $ do   mapM_ (insertPathRow db) regs   mapM_ (insertPathRefs db) (sortOn prPath regs)+  mapM_ (registerDerivationOutputs db . prPath) (filter (isDerivation . prPath) regs) --- | Insert (or refresh) a single ValidPaths row.+-- | Whether a store path names a derivation, by its name, as upstream+-- tells one.+isDerivation :: StorePath -> Bool+isDerivation sp = drvExtension `T.isSuffixOf` spName sp++-- | List a registered derivation's outputs, read from its file.+registerDerivationOutputs :: StoreDB -> StorePath -> IO ()+registerDerivationOutputs db sp = do+  contents <- BS.readFile file+  case fromATerm contents of+    Left err -> throwIO (userError ("error parsing derivation '" <> T.unpack (storePathToText defaultStoreDir sp) <> "': " <> T.unpack err))+    Right drv -> insertDerivationOutputs db (T.pack file) (drvOutputs drv)+  where+    file = storePathToFilePath (sdbDir db) sp++-- | Record a derivation's outputs against its row, the derivation and its+-- outputs' paths spelled as rows spell them.+insertDerivationOutputs :: StoreDB -> Text -> [DerivationOutput] -> IO ()+insertDerivationOutputs db drvText outputs =+  for_ outputs $ \out ->+    execute+      (sdbConn db)+      "INSERT OR REPLACE INTO DerivationOutputs (drv, id, path) \+      \VALUES ((SELECT id FROM ValidPaths WHERE path = ?), ?, ?)"+      (drvText, doName out, T.pack (storePathToFilePath (sdbDir db) (doPath out)))++-- | Insert (or refresh) a single ValidPaths row.  A path registered+-- again keeps the registration time its row has, as upstream's store+-- keeps it when it updates a valid path's info. insertPathRow :: StoreDB -> PathRegistration -> IO () insertPathRow db reg = do   -- DB rows key store paths in PLATFORM spelling (storePathToFilePath):@@ -228,11 +569,49 @@   let pathText = T.pack (storePathToFilePath (sdbDir db) (prPath reg))   execute     (sdbConn db)-    "INSERT INTO ValidPaths (path, hash, registrationTime, deriver, narSize) \-    \VALUES (?, ?, strftime('%s','now'), ?, ?) \-    \ON CONFLICT(path) DO UPDATE SET hash = excluded.hash, narSize = excluded.narSize, deriver = excluded.deriver"-    (pathText, prNarHash reg, prDeriver reg, prNarSize reg)+    "INSERT INTO ValidPaths (path, hash, registrationTime, deriver, narSize, ultimate, sigs, ca) \+    \VALUES (?, ?, COALESCE(?, strftime('%s','now')), ?, ?, ?, ?, ?) \+    \ON CONFLICT(path) DO UPDATE SET hash = excluded.hash, narSize = excluded.narSize, deriver = excluded.deriver, \+    \ultimate = COALESCE(excluded.ultimate, ultimate), sigs = COALESCE(excluded.sigs, sigs), ca = COALESCE(excluded.ca, ca)"+    ( pathText,+      prNarHash reg,+      registrationTimeField (prRegistrationTime reg),+      prDeriver reg,+      prNarSize reg,+      ultimateField (prUltimate reg),+      signaturesField (prSignatures reg),+      SQLText . renderContentAddress <$> prContentAddress reg+    ) +-- | The time a row is recorded as registered at, or NULL for the time the+-- row is written, which the statement reads from SQLite's clock.+registrationTimeField :: RegistrationTime -> Maybe Int64+registrationTimeField RegisteredNow = Nothing+registrationTimeField (RegisteredAt seconds) = Just seconds++-- | The @ultimate@ column of a row: 1 for an ultimately trusted path and+-- NULL otherwise, as upstream writes it.+ultimateField :: Ultimate -> SQLData+ultimateField Ultimate = SQLInteger 1+ultimateField NotUltimate = SQLNull++-- | A row's @ultimate@ column as upstream reads it: 1 is ultimately+-- trusted, and anything else, NULL included, is not.+ultimateFromField :: Maybe Int -> Ultimate+ultimateFromField (Just 1) = Ultimate+ultimateFromField _ = NotUltimate++-- | The @sigs@ column of a row: the signatures as a narinfo spells them,+-- in order and separated by spaces, or NULL for none, as upstream writes+-- them.  The column is text, and a key name that is not UTF-8, which no+-- key nova-nix reads has, is kept as the bytes it is.+signaturesField :: Set Signature -> SQLData+signaturesField sigs+  | Set.null sigs = SQLNull+  | otherwise = either (const (SQLBlob spelled)) SQLText (TE.decodeUtf8' spelled)+  where+    spelled = BS.intercalate " " (map renderSignature (Set.toAscList sigs))+ -- | Insert the reference edges for a path whose row already exists. -- -- Re-registration REPLACES the edge set: the metadata-refresh contract@@ -299,8 +678,8 @@       IO [Only Text]   pure [p | Only p <- rows] --- | Query every registered valid path, as full path text in registration--- order of the table (sorted for determinism).+-- | Query every registered valid path, as full path text, sorted by that+-- text for determinism. queryAllValidPaths :: StoreDB -> IO [Text] queryAllValidPaths db = do   rows <- query (sdbConn db) "SELECT path FROM ValidPaths ORDER BY path" () :: IO [Only Text]@@ -422,25 +801,102 @@   where     conn = sdbConn db --- | Query full path info for a registered store path.+-- | Query full path info for a registered store path.  A trust column a+-- row holds that does not read back, which only an edit outside nova-nix+-- can leave, fails the query, as upstream's fails on a hash it cannot+-- read, @invalid-path entry for ...@. queryPathInfo :: StoreDB -> StorePath -> IO (Maybe PathInfo) queryPathInfo db sp = do   let pathText = T.pack (storePathToFilePath (sdbDir db) sp)   rows <-     query       (sdbConn db)-      "SELECT path, hash, narSize, deriver, registrationTime FROM ValidPaths WHERE path = ?"+      "SELECT path, hash, narSize, deriver, registrationTime, ultimate, sigs, ca FROM ValidPaths WHERE path = ?"       (Only pathText) ::-      IO [(Text, Text, Int, Maybe Text, Int)]+      IO [(Text, Text, Int, Maybe Text, Int, Maybe Int, SQLData, Maybe Text)]   case rows of-    ((pth, hsh, sz, drv, regTime) : _) ->-      pure $-        Just+    ((pth, hsh, sz, drv, regTime, ultimate, sigs, ca) : _) ->+      either (throwIO . userError . T.unpack . invalidEntry) (pure . Just) $ do+        signatures <- signaturesFromField sigs+        address <- traverse parseContentAddress ca+        pure           PathInfo             { piPath = pth,               piNarHash = hsh,               piNarSize = sz,               piDeriver = drv,-              piRegTime = regTime+              piRegTime = regTime,+              piUltimate = ultimateFromField ultimate,+              piSignatures = signatures,+              piContentAddress = address             }     [] -> pure Nothing+  where+    invalidEntry reason = "invalid-path entry for '" <> storePathToText defaultStoreDir sp <> "': " <> reason++-- | The signatures a @sigs@ column holds, separated by spaces, as+-- upstream reads them: none for NULL, the column's bytes whether SQLite+-- holds it as text or as a blob.+signaturesFromField :: SQLData -> Either Text (Set Signature)+signaturesFromField field = case field of+  SQLNull -> Right Set.empty+  SQLText spelled -> fromBytes (TE.encodeUtf8 spelled)+  SQLBlob spelled -> fromBytes spelled+  _ -> Left "the signatures column holds neither text nor bytes"+  where+    fromBytes = fmap Set.fromList . traverse parseSignature . filter (not . BS.null) . BS.split space+    space = 0x20++-- | The valid paths that reference a path, as full path text, sorted: a+-- path that references itself is among its own referrers, as upstream+-- lists it.+queryReferrers :: StoreDB -> StorePath -> IO [Text]+queryReferrers db sp = do+  let pathText = T.pack (storePathToFilePath (sdbDir db) sp)+  rows <-+    query+      (sdbConn db)+      "SELECT vp.path FROM Refs r \+      \JOIN ValidPaths vp ON r.referrer = vp.id \+      \WHERE r.reference = (SELECT id FROM ValidPaths WHERE path = ?) \+      \ORDER BY vp.path"+      (Only pathText) ::+      IO [Only Text]+  pure [p | Only p <- rows]++-- | The valid derivations with an output at a path, as full path text,+-- sorted: upstream's @queryValidDerivers@, which reads them from+-- DerivationOutputs.  The path need not be valid itself.+queryValidDerivers :: StoreDB -> StorePath -> IO [Text]+queryValidDerivers db sp = do+  let pathText = T.pack (storePathToFilePath (sdbDir db) sp)+  rows <-+    query+      (sdbConn db)+      "SELECT DISTINCT vp.path FROM DerivationOutputs d \+      \JOIN ValidPaths vp ON d.drv = vp.id \+      \WHERE d.path = ? \+      \ORDER BY vp.path"+      (Only pathText) ::+      IO [Only Text]+  pure [p | Only p <- rows]++-- | The valid path whose hash part is the one given, as full path text,+-- or why the hash part is refused: upstream's @queryPathFromHashPart@,+-- which takes the first valid path at or after the store directory and+-- the hash part and answers it when it begins with them.  A hash part+-- that is not a store path hash's length is refused in upstream's words.+queryPathFromHashPart :: StoreDB -> Text -> IO (Either Text (Maybe Text))+queryPathFromHashPart db hashPart+  | T.length hashPart /= storePathHashLen = pure (Left "invalid hash part")+  | otherwise = do+      rows <- query (sdbConn db) "SELECT path FROM ValidPaths WHERE path >= ? ORDER BY path LIMIT 1" (Only prefix) :: IO [Only Text]+      pure+        ( Right+            ( case rows of+                (Only found : _) | prefix `T.isPrefixOf` found -> Just found+                _ -> Nothing+            )+        )+  where+    prefix = T.pack (unStoreDir (sdbDir db) </> T.unpack hashPart)
src/Nix/Store/EntryName.hs view
@@ -4,11 +4,13 @@ -- A NAR carries names and link targets as bytes.  Upstream's restore on -- POSIX appends each name to the destination path as it finds it and -- hands each target to @symlink@ unchanged (@RestoreSink@ in fs-sink.cc--- at 2.24.9), refusing only what the archive grammar refuses: an empty--- name, @.@, @..@, a @/@ or a NUL (@parse@ in archive.cc).  Those--- refusals hold on every host, through the parser's own check.  Every--- other limit belongs to a filesystem, so it is decided per host--- ('NameRules'): a name the host cannot hold is refused before anything+-- at 2.24.9), refusing only what its archive parser refuses: an empty+-- name, @.@, @..@, a @/@ or a NUL in a name, a name over 255 bytes or a+-- target over 4095, an empty target or one holding NUL, and a node 64+-- directories deep (@parse@ in archive.cc at 2.36.0).  Those refusals+-- hold on every host, through nova-cache's parser, which makes the same+-- ones.  Every other limit belongs to a filesystem, so it is decided per+-- host ('NameRules'): a name the host cannot hold is refused before anything -- is written, and a store path holding one does not materialize there, -- whichever way it arrives. --
src/Nix/Store/Exclusive.hs view
@@ -38,8 +38,8 @@  import Control.Exception (bracketOnError) import Data.Bits ((.|.))-import Data.List (isPrefixOf) import GHC.IO.SubSystem (IoSubSystem (..), ioSubSystem)+import Nix.Store.Win32Path (win32FilePath) import System.IO (Handle) import System.IO.Error (ioeSetFileName, modifyIOError) import System.Win32.File@@ -53,7 +53,6 @@     gENERIC_READ,     gENERIC_WRITE,   )-import System.Win32.Info (getFullPathName) import System.Win32.Types (hANDLEToHandle)  #else@@ -111,24 +110,6 @@     attributes = case ioSubSystem of       IoPOSIX -> fILE_ATTRIBUTE_NORMAL       IoNative -> fILE_ATTRIBUTE_NORMAL .|. fILE_FLAG_OVERLAPPED---- | The Win32 file-namespace spelling of a path (@\\\\?\\@), which--- CreateFileW takes past MAX_PATH.  @base@ converts every path it--- opens to this form, under either I\/O manager--- (@__hs_create_device_name@ in GHC's utils\/fs\/fs.c), so a raw--- CreateFileW without it would refuse long paths @base@ accepts.  The--- namespace form is taken literally, so separators, @.@ and @..@ are--- resolved first by GetFullPathNameW, as that conversion does.-win32FilePath :: FilePath -> IO FilePath-win32FilePath path-  | any (`isPrefixOf` path) namespacePrefixes = pure path-  | otherwise = toNamespace <$> getFullPathName path-  where-    namespacePrefixes = [fileNamespace, "\\\\.\\", "\\??\\"]-    toNamespace full = case full of-      '\\' : '\\' : share -> fileNamespace <> "UNC\\" <> share-      _ -> fileNamespace <> full-    fileNamespace = "\\\\?\\"  #else 
src/Nix/Store/ExecBit.hs view
@@ -1,3 +1,5 @@+{-# LANGUAGE ScopedTypeVariables #-}+ -- | The executable bit, on a platform that does not have one. -- -- Windows' 'System.Directory.getPermissions' answers from the file@@ -13,13 +15,14 @@     markExecutableOsPath,     copyExecMark,     serialiseFromPath,+    serialiseIfReadable,     withNarSource,     narHashOfPath,     execStreamName,   ) where -import Control.Exception (bracket_)+import Control.Exception (Handler (..), IOException, bracket_, catches) import Control.Monad (unless, when) import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BS8@@ -48,11 +51,14 @@ execStreamPath path = path ++ ":" ++ execStreamName  -- | Whether a regular file is executable, by whichever representation the--- platform keeps it in.+-- platform keeps it in.  On Unix that is the owner-execute bit of the+-- file's own mode, as upstream's dump reads it, not what this process may+-- do, which root or an access control entry would answer otherwise;+-- the flag lands in NAR bytes, so a divergence moves a hash. isExecutable :: FilePath -> IO Bool isExecutable path   | usesStream = Dir.doesFileExist (execStreamPath path)-  | otherwise = Dir.executable <$> Dir.getPermissions path+  | otherwise = NAR.defaultExecBitResolver path  -- | Mark a regular file executable. --@@ -111,13 +117,26 @@ -- file's permissions.  The walk is nova-cache's own -- name safety, -- case-hack folding and entry ordering are subtle and belong there -- -- and the resolver hook (nova-cache 0.11.1) answers the flag during--- the walk, replacing the post-hoc rewrite this module used to do.+-- the walk, so the archive needs no rewrite after it. -- The case-hack mode is the reader's: a store path's volume decides -- it ('Nix.Store.CaseSensitive.volumeCaseHack'), and the process does -- for a source ('Nix.Store.CaseSensitive.processCaseHack'). serialiseFromPath :: NAR.CaseHack -> FilePath -> IO NAR.NarEntry serialiseFromPath = NAR.serialiseFromPathOpts . serialiseOptions +-- | 'serialiseFromPath', or 'Nothing' when the tree cannot be read into+-- an archive: an access that failed ('NAR.NarWalkError') or an entry the+-- walk refuses, such as one of a type a NAR cannot hold (an+-- 'IOException').  For a caller that treats an unreadable tree as one+-- that is not there; anything else, an asynchronous exception included,+-- passes through.+serialiseIfReadable :: NAR.CaseHack -> FilePath -> IO (Maybe NAR.NarEntry)+serialiseIfReadable mode path =+  (Just <$> serialiseFromPath mode path)+    `catches` [ Handler (\(_ :: NAR.NarWalkError) -> pure Nothing),+                Handler (\(_ :: IOException) -> pure Nothing)+              ]+ -- | 'NovaCache.NAR.withNarSource' through the same exec-bit source of -- truth: the path's NAR as a pull source of chunks, no file's contents -- held whole.@@ -127,8 +146,7 @@ -- | The NAR hash of a path, read through the same exec-bit source of -- truth 'serialiseFromPath' writes.  Streams on every platform: the -- archive is pulled in chunks with the ADS resolver answering the--- flags, and the digest folds over them.  Before the resolver hook,--- Windows had to materialize the tree in memory to rewrite the flags.+-- flags, and the digest folds over them. narHashOfPath :: NAR.CaseHack -> FilePath -> IO Hash.NixHash narHashOfPath mode path =   withNarSource mode path $ \pull ->
src/Nix/Store/GC.hs view
@@ -1,4 +1,7 @@--- | Garbage collection: roots, the reachability walk, and the sweep.+{-# LANGUAGE ScopedTypeVariables #-}++-- | Garbage collection: roots, the reachability walk, the sweep, and the+-- checked delete of named paths. -- -- == Roots --@@ -6,8 +9,11 @@ -- it references transitively.  Roots live under the store's metadata -- directory, @\<store\>\/.nova-nix\/gcroots@.  Upstream keeps them under -- its state directory (@\/nix\/var\/nix\/gcroots@); this store has no--- state directory apart from @.nova-nix@, and roots beside the database--- mean a store copied or moved as one directory keeps them.  Two kinds:+-- state directory apart from @.nova-nix@, so its roots are beside its+-- database.  A store copied or moved as one directory takes them along,+-- but its rows still name each path under the old directory's spelling,+-- so at the new one no path is valid (see the spelling section below).+-- Two kinds: -- -- * __Permanent roots__ are entries anywhere under @gcroots@ except --   @auto@: a symlink whose target lies in the store roots the store@@ -19,28 +25,30 @@ --   since a symlink on Windows needs Developer Mode.  Nothing in --   nova-nix creates a permanent root; they are for the operator. ----- * __Indirect roots__ are what @build --out-link PATH@ registers---   ('addOutLinkRoot', upstream's @addPermRoot@): the out-link---   @PATH -> \<store path\>@ where the user asked for it, plus a record---   @gcroots\/auto\/\<sha256 of PATH\>@ holding PATH's absolute---   spelling.  Upstream's record is a symlink to the out-link; here it---   is a regular file with the same content, because the record must be---   writable on every platform the store runs on.  The out-link itself---   is a native symlink everywhere, with the Developer Mode requirement---   the README states for symlinks.  A record whose out-link no longer---   exists is stale and removed by the next walk, as upstream removes---   its stale @auto@ links; one whose out-link exists but no longer---   points into the store is simply not a root.+-- * __Indirect roots__ are what @build@ registers for the link it makes+--   to its output ('addOutLinkRoot', upstream's @addPermRoot@): the+--   out-link @PATH -> \<store path\>@, @.\/result@ unless @--out-link@+--   names another path, plus a record+--   @gcroots\/auto\/\<sha256 of PATH\>@ holding the bytes of PATH's+--   absolute spelling.  Upstream's record is a symlink to the out-link;+--   here it is a regular file with the same content, because the record+--   must be writable on every platform the store runs on.  The out-link+--   itself is a native symlink everywhere, with the Developer Mode+--   requirement the README states for symlinks.  A record whose out-link+--   no longer exists is stale and removed by the next walk, as upstream+--   removes its stale @auto@ links; one whose out-link exists but no+--   longer points into the store is simply not a root. -- -- Upstream also finds runtime roots (open files and mapped executables -- of running processes, through @\/proc@ on Linux and @lsof@ elsewhere) -- and per-process temporary roots.  Neither exists here: the lock below -- covers builds in flight, and a program running out of an unrooted--- store path is not protected.  Upstream's @keep-derivations@ and--- @keep-outputs@ are not implemented either: the builder registers--- outputs with no deriver, so a @.drv@ is kept only while something--- references it, and an unrooted @.drv@ and the sources only it--- references are collected.+-- store path is not protected.  Upstream's @keep-derivations@, on by+-- default, keeps a @.drv@ while an output that names it as its deriver+-- is live, and @keep-outputs@ keeps a path while a @.drv@ that outputs+-- it is live (gc.cc at 2.24.9).  Neither is implemented here, so a+-- @.drv@ is kept only while something references it, and an unrooted+-- @.drv@ and the sources only it references are collected. -- -- == Reachability and the sweep --@@ -63,7 +71,7 @@ -- -- 'collectGarbage' is the IO boundary: dead rows go in one database -- transaction ('unregisterPathRows'), then trees one by one.  Rows--- before trees for the reason 'Nix.Store.deleteStorePathRaw' gives: a+-- before trees for the reason 'deleteStorePathRaw' gives: a -- tree without a row is inert debris, a row without a tree is a lie -- existence checks believe.  A dead row with no tree is unregistered -- without a line or a count: upstream's sweep walks the directory and@@ -76,31 +84,53 @@ -- registration ("Nix.Store.DB"), and the collector compares that text -- with paths derived from the handle's directory. -- 'Nix.Store.Handle.openStore' canonicalises the spelling, so one--- directory named two ways keys the same rows; a store whose rows were--- registered under another spelling (a symlinked parent, a store moved--- and opened at its new path) would make every row look dead, so the--- collector and the checked delete refuse when any row lies outside the--- opened directory ('validPathsUnder') rather than sweep a rooted--- closure over a text mismatch.+-- directory named two ways keys the same rows, and a store with rows but+-- none under the directory it is opened at is refused at the open+-- ('Nix.Store.DB.storeRowRange').  A database that holds a row under the+-- opened directory and another registered under another spelling (a+-- symlinked parent, or a store used at two directories) would make that+-- row look dead, so the collector and the checked delete refuse when any+-- row lies outside the opened directory ('validPathsUnder') rather than+-- sweep a rooted closure over a text mismatch. --+-- == A store upstream Nix also manages+--+-- Upstream registers its paths in its own database and keeps its roots+-- under its own state directory, so in a directory upstream also uses,+-- no row or root here keeps an upstream path, and the sweep would take+-- every one for an unregistered tree.  The collector and the checked+-- delete refuse such a store before the lock is taken, as+-- "Nix.Store.Upstream" recognises it.+--+-- == Deleting named paths+--+-- Upstream's @nix-store --delete@ is a collection whose action is+-- @gcDeleteSpecific@ (@opDelete@ at 2.24.9), and the checked delete+-- here is one too: it holds the exclusive lock, reads the roots once,+-- and checks every path it is given against that live set+-- ('deleteStorePaths' for a batch in argument order,+-- 'deleteStorePathRaw' for one path).  The live set is made and+-- consumed inside the call, so a delete always checks the roots of its+-- own store as they stand under the lock it holds.+-- -- == The lock -- -- Upstream serialises collection against writers with a store-wide -- @gc.lock@, held exclusively by the collector and shared by every -- writer, plus a socket through which a writer registers roots with a -- running collector.  nova-nix keeps the lock and drops the socket:--- every open t'Store' handle holds the shared lock from 'Nix.Store.Handle.openStore' to--- 'Nix.Store.Handle.closeStore' ("Nix.Store.Handle"), and 'collectGarbage' (and--- 'withLiveSet', which the checked delete runs under) trades the--- handle's shared lease for the exclusive lock for the duration.  A--- collection therefore runs only while no other process has the store--- open, and a process opening the store while one runs waits for it to--- finish.  That is coarser than the per-path locks the builder and--- substituter hold, and deliberately so: a per-path lock covers a path--- while it is being produced, but not the window between a dependency's--- registration and the build that consumes it, nor the writers that--- register without one (the @.drv@ closure, the eval-time store--- writes).  Under the exclusive lock no writer is active, so the+-- every open t'Store' handle holds the shared lock from+-- 'Nix.Store.Handle.openStore' to 'Nix.Store.Handle.closeStore'+-- ("Nix.Store.Handle"), and 'collectGarbage' and the checked delete+-- trade the handle's shared lease for the exclusive lock for the+-- duration.  A collection therefore runs only while no other process has+-- the store open, and a process opening the store while one runs waits+-- for it to finish.  That is coarser than the per-path locks the builder+-- and substituter hold, and deliberately so: a per-path lock covers a+-- path while it is being produced, but not the window between a+-- dependency's registration and the build that consumes it, nor the+-- writers that register without one (the @.drv@ closure, the eval-time+-- store writes).  Under the exclusive lock no writer is active, so the -- collector takes no per-path lock and creates no lock file. -- 'findRoots' alone needs only the handle's shared lease: a listing -- changes nothing another handle reads, and upstream's @--print-roots@@@ -110,6 +140,9 @@     GcRoot (..),     findRoots,     addOutLinkRoot,+    LinkRooting (..),+    makeOutLinkRoot,+    addIndirectRoot,     gcRootsDir,     autoRootsDir,     gcRootsDirName,@@ -119,11 +152,7 @@     -- * Reachability (pure)     referencesMap,     reachableFrom,--    -- * The live set-    LiveSet,-    withLiveSet,-    isLive,+    referrersFirst,      -- * Collection     GcResults (..),@@ -133,15 +162,29 @@     showFreedBytes,     gcSummaryLine, +    -- * Deleting named paths+    StoreEntryName,+    storeEntryName,+    storeEntryNameText,+    DeleteOutcome (..),+    deleteStorePaths,+    deleteStorePathRaw,+    deleteSpecificPaths,+     -- * Messages     findingRootsMessage,     stillAliveMessage,+    specificStillAliveMessage,   ) where  import Control.Exception (IOException, catch, throwIO, try)-import Control.Monad (when)+import Control.Monad (join, unless, when)+import Control.Monad.Except (ExceptT (..), runExceptT, throwError)+import Control.Monad.IO.Class (liftIO)+import Data.ByteString (ByteString) import qualified Data.ByteString as BS+import Data.Foldable (foldlM, traverse_) import Data.List (isPrefixOf, sort) import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map@@ -152,19 +195,22 @@ import qualified Data.Text as T import qualified Data.Text.Encoding as TE import GHC.IO.Exception (IOErrorType (InappropriateType))-import Nix.Eval.CanonPath (canonPath) import Nix.Hash (sha256Digest)-import Nix.Store.DB (UnregisterResult (..), isValidPath, metaDirName, queryAllReferences, queryAllValidPaths, unregisterPathRows)+import Nix.HostPath (absolutePath, hostPathBytes, hostPathFromBytes)+import Nix.Logger (Logger, logMessage)+import Nix.Store.DB (UnregisterResult (..), isValidPath, metaDirName, queryAllReferences, queryAllValidPaths, queryReferences, queryReferrers, unregisterPathRow, unregisterPathRows) import Nix.Store.Handle (Store (..), withCollectorLock)-import Nix.Store.Lock (lockedPathOf)-import Nix.Store.Path (StoreDir (..), StorePath, defaultStoreDir, parseStorePathBaseName, parseStorePathPrefix, platformStoreDir, storePathToFilePath)+import Nix.Store.Lock (lockFileSuffix, lockedPathOf, withLockFile)+import Nix.Store.Path (StoreDir (..), StorePath, defaultStoreDir, parseStorePath, parseStorePathBaseName, parseStorePathPrefix, platformStoreDir, storePathToFilePath, storePathToText) import Nix.Store.Symlink (WalkNode (..), classifyWalkNode, createSymlinkOfKind)+import Nix.Store.Upstream (UpstreamHazard (..), upstreamManagedRefusal, upstreamStateDir) import qualified NovaCache.Base32 as Base32-import System.Directory (createDirectoryIfMissing, getFileSize, getSymbolicLinkTarget, listDirectory, makeAbsolute, removePathForcibly, renamePath)+import System.Directory (createDirectoryIfMissing, doesPathExist, getFileSize, getSymbolicLinkTarget, listDirectory, pathIsSymbolicLink, removePathForcibly, renamePath)+import qualified System.Directory.OsPath as OsDir import System.FilePath (normalise, splitDirectories, takeDirectory, takeFileName, (</>))-import System.IO (hPutStrLn, stderr)+import qualified System.FilePath.Windows as Windows import System.IO.Error (ioeGetErrorType, isDoesNotExistError, isPermissionError)-import System.OsPath (encodeFS)+import System.OsPath (decodeFS, encodeFS) import Text.Printf (printf)  -- ---------------------------------------------------------------------------@@ -187,17 +233,18 @@ autoRootsDir :: StoreDir -> FilePath autoRootsDir dir = gcRootsDir dir </> autoRootsDirName --- | The record name for an out-link: nix-base32 of the SHA-256 of the--- link's absolute spelling, so one out-link has one record however--- often it is re-registered.  Upstream hashes with SHA-1; the digest is--- an internal key and the store has no SHA-1 primitive to spend on it.-indirectRootRecordName :: FilePath -> FilePath-indirectRootRecordName link = T.unpack (Base32.encode (sha256Digest (TE.encodeUtf8 (T.pack link))))+-- | The record name for an out-link, given the bytes of its absolute+-- spelling ('Nix.HostPath.hostPathBytes'): nix-base32 of their SHA-256,+-- so one out-link has one record however often it is re-registered.+-- Upstream hashes with SHA-1; the digest is an internal key and the store+-- has no SHA-1 primitive to spend on it.+indirectRootRecordName :: BS.ByteString -> FilePath+indirectRootRecordName link = T.unpack (Base32.encode (sha256Digest link))  -- | Where a record is written before it is renamed into @auto@: under -- the metadata directory, which the roots walk never enters, so a -- listing under the shared lease sees a record whole or not at all.-recordStagingPath :: StoreDir -> FilePath -> FilePath+recordStagingPath :: StoreDir -> BS.ByteString -> FilePath recordStagingPath dir link = unStoreDir dir </> metaDirName </> indirectRootRecordName link <> stagingSuffix  -- | The suffix of a record still being written.@@ -209,33 +256,35 @@ -- ---------------------------------------------------------------------------  -- | Upstream's first progress line of a collection or a checked delete.-findingRootsMessage :: String+findingRootsMessage :: Text findingRootsMessage = "finding garbage collector roots..."  -- | Upstream's progress line before the sweep.-deletingGarbageMessage :: String+deletingGarbageMessage :: Text deletingGarbageMessage = "deleting garbage..." --- | Upstream's per-path line of the sweep.-deletingPathMessage :: Text -> String-deletingPathMessage path = "deleting '" <> T.unpack path <> "'"+-- | Upstream's per-path line of the sweep, the path in single quotes,+-- since upstream formats this store path as a string, not as a path.+deletingPathMessage :: Text -> Text+deletingPathMessage path = "deleting '" <> path <> "'"  -- | Upstream's line for an indirect-root record whose out-link is gone.-removingStaleLinkMessage :: FilePath -> FilePath -> String+removingStaleLinkMessage :: FilePath -> FilePath -> Text removingStaleLinkMessage record outLink =-  "removing stale link from '" <> record <> "' to '" <> outLink <> "'"+  "removing stale link from " <> quotedPath record <> " to " <> quotedPath outLink  -- | Upstream's line for a symlink root naming a path the database does -- not hold, with the target as the link spells it.-skippingInvalidRootMessage :: FilePath -> FilePath -> String+skippingInvalidRootMessage :: FilePath -> FilePath -> Text skippingInvalidRootMessage link target =-  "skipping invalid root from '" <> link <> "' to '" <> target <> "'"+  "skipping invalid root from " <> quotedPath link <> " to " <> quotedPath target  -- | Upstream's line for a roots-directory entry it cannot read.-unreadableRootMessage :: FilePath -> String-unreadableRootMessage path = "cannot read potential root '" <> path <> "'"+unreadableRootMessage :: FilePath -> Text+unreadableRootMessage path = "cannot read potential root " <> quotedPath path --- | Upstream's refusal to delete a path a root keeps alive.  Upstream's+-- | Upstream's refusal to delete a path a root keeps alive, the path in+-- single quotes, since upstream formats it as a string.  Upstream's -- hint names @nix-store --query --roots@ and @--query --referrers@; -- this tool has @store gc --print-roots@ for the first and lists -- referrers in its own refusal for the second, so the hint names what@@ -246,18 +295,41 @@     <> path     <> "' since it is still alive. To find out why, use: nova-nix store gc --print-roots" +-- | Upstream's refusal, in its own words, of a path a delete of named+-- paths leaves alive ('deleteSpecificPaths'), which a client of+-- upstream's reads.+specificStillAliveMessage :: Text -> Text+specificStillAliveMessage path =+  "Cannot delete path '"+    <> path+    <> "' since it is still alive. To find out why, use: nix-store --query --roots and nix-store --query --referrers"++-- | Upstream's progress line before a delete of named paths.+deletingSpecifiedMessage :: Text+deletingSpecifiedMessage = "deleting specified paths..."+ -- | Upstream's refusal of an out-link inside the store, with this tool's -- command in the parenthetical. rootInsideStoreMessage :: FilePath -> Text rootInsideStoreMessage link =   "creating a garbage collector root ("-    <> T.pack link+    <> quotedPath link     <> ") in the Nix store is forbidden (are you running nova-nix build inside the store?)" +-- | The refusal of a Windows out-link holding an unpaired surrogate,+-- which has no bytes for its record to hold.+unrecordableLinkMessage :: FilePath -> Text+unrecordableLinkMessage link = "cannot register '" <> T.pack link <> "' as a garbage collector root: its name has no UTF-8 form"+ -- | Upstream's refusal to clobber something that is not a store link. alreadyExistsMessage :: FilePath -> Text-alreadyExistsMessage link = "cannot create symlink '" <> T.pack link <> "'; already exists"+alreadyExistsMessage link = "cannot create symlink " <> quotedPath link <> "; already exists" +-- | A path as upstream's messages show one: between double quotes, with+-- nothing inside escaped.+quotedPath :: FilePath -> Text+quotedPath path = "\"" <> T.pack path <> "\""+ -- | The refusal of a collection or a checked delete over a database -- keyed under another spelling of the store directory. storeSpellingMismatchMessage :: FilePath -> Text -> Text@@ -293,7 +365,10 @@   }  -- | Every root the store has, valid paths only, each link once and--- sorted as @--print-roots@ prints them.  A symlink root naming a path+-- sorted as @--print-roots@ prints them: those under the store's own+-- roots directory and, for a store where upstream's local store would+-- keep its own, those under upstream's @gcroots@ and @profiles@ in its+-- state directory ('rootDirectories').  A symlink root naming a path -- the database does not hold is reported and dropped, a regular-file -- root naming one is dropped silently, both as upstream does.  Stale -- indirect-root records are removed on the way, and an entry that@@ -304,7 +379,7 @@ -- lock as the first step of a collection. findRoots :: Store -> IO [GcRoot] findRoots store = do-  candidates <- walkRoots (stDir store) (gcRootsDir (stDir store))+  candidates <- concat <$> mapM (walkRoots (stLogger store) (stDir store)) (rootDirectories (stDir store))   Set.toAscList . Set.fromList . catMaybes <$> mapM validOnly candidates   where     validOnly candidate = do@@ -312,41 +387,58 @@       if valid         then pure (Just (GcRoot (rcLink candidate) (T.pack (storePathToFilePath (stDir store) (rcPath candidate)))))         else do-          mapM_ (hPutStrLn stderr . skippingInvalidRootMessage (rcLink candidate)) (rcInvalidReport candidate)+          mapM_ (logMessage (stLogger store) . skippingInvalidRootMessage (rcLink candidate)) (rcInvalidReport candidate)           pure Nothing +-- | The directories a store's roots are found under: its own roots+-- directory, and for a store in a directory upstream's local store uses+-- ('upstreamStateDir'), upstream's @gcroots@ and @profiles@ beside its+-- database, where upstream's clients keep their roots and profiles, as+-- upstream's collector reads them.  A directory that is not there holds+-- no root.+rootDirectories :: StoreDir -> [FilePath]+rootDirectories dir = gcRootsDir dir : maybe [] (\state -> [state </> gcRootsDirName, state </> upstreamProfilesDirName]) (upstreamStateDir (unStoreDir dir))++-- | Upstream's directory of profiles in its state directory.+upstreamProfilesDirName :: FilePath+upstreamProfilesDirName = "profiles"+ -- | Walk the roots directory.  A directory recurses; a symlink into the -- store is a permanent root, and any other symlink is followed one hop -- as upstream follows it; a regular file is an indirect-root record -- under @auto@ and a basename-named permanent root elsewhere.  An entry -- that cannot be read (permission denied, vanished, not a directory -- after all) is reported with upstream's line and contributes nothing;--- any other failure propagates, as upstream's does.-walkRoots :: StoreDir -> FilePath -> IO [RootCandidate]-walkRoots storeDir path = walk `catch` unreadable+-- any other failure propagates, as upstream's does.  What the walk+-- reports goes to the logger.+walkRoots :: Logger -> StoreDir -> FilePath -> IO [RootCandidate]+walkRoots logger storeDir path = walk `catch` unreadable   where     walk = do       node <- classifyWalkNode path       case node of         WalkDirectory -> do           entries <- listDirectory path-          concat <$> mapM (walkRoots storeDir . (path </>)) (sort entries)+          concat <$> mapM (walkRoots logger storeDir . (path </>)) (sort entries)         WalkSymlink -> do           target <- getSymbolicLinkTarget path           case parseStoreTarget storeDir target of             Just sp -> pure [RootCandidate path sp (Just target)]-            Nothing -> followIndirect storeDir path (takeDirectory path </> target)+            Nothing -> followIndirect logger storeDir path (takeDirectory path </> target)         WalkRegular           | isUnderDir (autoRootsDir storeDir) path -> do               recorded <- BS.readFile path-              followIndirect storeDir path (T.unpack (TE.decodeUtf8Lenient recorded))+              -- A record holding bytes no host path has, which on Windows+              -- only a hand edit leaves, names no out-link.+              outLink <- traverse decodeFS (hostPathFromBytes recorded)+              maybe (pure []) (followIndirect logger storeDir path) outLink           | otherwise ->               pure [RootCandidate path sp Nothing | Just sp <- [parseStorePathBaseName (T.pack (takeFileName path))]]         WalkAbsent -> pure []     unreadable :: IOException -> IO [RootCandidate]     unreadable e       | isPermissionError e || isDoesNotExistError e || ioeGetErrorType e == InappropriateType = do-          hPutStrLn stderr (unreadableRootMessage path)+          logMessage logger (unreadableRootMessage path)           pure []       | otherwise = throwIO e @@ -354,9 +446,9 @@ -- A symlink into the store is the root (reported under the out-link's -- own path, which is what the user created); an absent out-link makes -- a record under @auto@ stale, and it is removed; anything else is not--- a root.-followIndirect :: StoreDir -> FilePath -> FilePath -> IO [RootCandidate]-followIndirect storeDir record outLink = do+-- a root.  The removal is reported to the logger.+followIndirect :: Logger -> StoreDir -> FilePath -> FilePath -> IO [RootCandidate]+followIndirect logger storeDir record outLink = do   node <- classifyWalkNode outLink   case node of     WalkSymlink -> do@@ -364,7 +456,7 @@       pure [RootCandidate outLink sp (Just target) | Just sp <- [parseStoreTarget storeDir target]]     WalkAbsent       | isUnderDir (autoRootsDir storeDir) record -> do-          hPutStrLn stderr (removingStaleLinkMessage record outLink)+          logMessage logger (removingStaleLinkMessage record outLink)           removePathForcibly record           pure []     _ -> pure []@@ -385,56 +477,84 @@ isUnderDir :: FilePath -> FilePath -> Bool isUnderDir dir path = splitDirectories (normalise dir) `isPrefixOf` splitDirectories (normalise path) --- | Register an out-link as an indirect root: upstream's @addPermRoot@.--- The link's spelling is made absolute and collapsed without resolving--- symlinks (upstream's @canonPath@), so a @..@ cannot spell a link into--- the store past the refusal, and the store directory it is compared--- with is the handle's canonical one.  A link inside the store is--- refused, as is clobbering anything that is not already a symlink into--- the store; an existing store link is replaced.  The link's parent--- directories are created, as upstream's @makeSymlink@ creates them.--- The link is created first and the record second, so a failed link--- (Windows without Developer Mode) leaves no record naming it; the--- record is written under the metadata directory and renamed into--- @auto@, so a listing under the shared lease never reads a torn one,--- and a record already holding the link is left alone, since its--- content is a function of its name.  Upstream replaces the link--- atomically through a temporary name and a rename; a rename cannot--- replace a directory symlink on Windows, so the old link is removed--- and the new one created, one code path for every platform, and the--- link is briefly absent rather than briefly two things.+-- | Register an out-link as an indirect root in a local store:+-- 'makeOutLinkRoot' over the handle's canonical store directory.  The+-- store's lease already holds collection off while the link is made, so a+-- path needs no temporary root first.  The record is written under the+-- metadata directory and renamed into @auto@, so a listing under the+-- shared lease never reads a torn one, and a record already holding the+-- link is left alone, since its content is a function of its name. addOutLinkRoot :: Store -> FilePath -> StorePath -> IO (Either Text FilePath)-addOutLinkRoot store rawLink sp = do-  link <- T.unpack . canonPath . T.pack <$> makeAbsolute rawLink-  if isUnderDir (unStoreDir (stDir store)) link-    then pure (Left (rootInsideStoreMessage link))-    else do-      node <- classifyWalkNode link-      replaceable <- case node of+addOutLinkRoot store =+  makeOutLinkRoot (stDir store) (LinkRooting (\_ -> pure (Right ())) (\bytes -> Right () <$ publishRecord (stDir store) bytes))++-- | How a store keeps an out-link's path from collection: while the link+-- is made, and once it is.+data LinkRooting = LinkRooting+  { -- | Keep a path from collection until the link exists.+    lrHold :: !(StorePath -> IO (Either Text ())),+    -- | Record the link as a root, given the bytes of its absolute+    -- spelling.+    lrRecord :: !(ByteString -> IO (Either Text ()))+  }++-- | Make an out-link and root it, over a store directory: upstream's+-- @addPermRoot@.  The link's spelling is made absolute and collapsed+-- without resolving symlinks ('absolutePath', upstream's @canonPath@), so+-- a @..@ cannot spell a link into the store past the refusal.  The+-- spelling is the link's own bytes throughout, so a link no text can spell+-- is created, recorded and found again under the name it was given; on+-- Windows one holding an unpaired surrogate, which has no bytes to record,+-- is refused.  A link inside the store is refused, as is clobbering+-- anything that is not already a symlink into the store; an existing store+-- link is replaced.  The link's parent directories are created, as+-- upstream's @makeSymlink@ creates them.+--+-- The path is held ('lrHold') after those refusals and before the link is+-- looked at, and the record is made ('lrRecord') once the link exists, so+-- a failed link (Windows without Developer Mode) leaves no record naming+-- it.  Whichever of the two fails is the answer.  Upstream replaces the+-- link atomically through a temporary name and a rename; a rename cannot+-- replace a directory symlink on Windows, so the old link is removed and+-- the new one created, one code path for every platform, and the link is+-- briefly absent rather than briefly two things.+makeOutLinkRoot :: StoreDir -> LinkRooting -> FilePath -> StorePath -> IO (Either Text FilePath)+makeOutLinkRoot dir rooting rawLink sp = do+  cwd <- OsDir.getCurrentDirectory+  spelled <- absolutePath cwd <$> encodeFS rawLink+  link <- decodeFS spelled+  runExceptT $ do+    when (isUnderDir (unStoreDir dir) link) (throwError (rootInsideStoreMessage link))+    linkBytes <- maybe (throwError (unrecordableLinkMessage link)) pure (hostPathBytes spelled)+    ExceptT (lrHold rooting sp)+    node <- liftIO (classifyWalkNode link)+    replaceable <- liftIO $ case node of       WalkAbsent -> pure True-        WalkSymlink -> isJust . parseStoreTarget (stDir store) <$> getSymbolicLinkTarget link+      WalkSymlink -> isJust . parseStoreTarget dir <$> getSymbolicLinkTarget link       _ -> pure False-      if not replaceable-        then pure (Left (alreadyExistsMessage link))-        else do+    unless replaceable (throwError (alreadyExistsMessage link))+    liftIO $ do       when (node == WalkSymlink) (removePathForcibly link)       createDirectoryIfMissing True (takeDirectory link)-          linkPath <- encodeFS link-          target <- encodeFS (storePathToFilePath (stDir store) sp)-          created <- createSymlinkOfKind linkPath target-          case created of-            Left err -> pure (Left err)-            Right () -> do-              publishRecord (stDir store) link-              pure (Right link)+    target <- liftIO (encodeFS (storePathToFilePath dir sp))+    ExceptT (createSymlinkOfKind spelled target)+    ExceptT (lrRecord rooting linkBytes)+    pure link --- | Write an out-link's record into @auto@ by rename, unless a record--- with that content is already there.-publishRecord :: StoreDir -> FilePath -> IO ()-publishRecord dir link = do-  let record = autoRootsDir dir </> indirectRootRecordName link-      staging = recordStagingPath dir link-      content = TE.encodeUtf8 (T.pack link)+-- | Record a link someone else made as a root, by the bytes of its+-- absolute spelling, as upstream records an indirect root: what+-- the link names is kept for as long as it names a store path, and a+-- record whose link has gone is removed as roots are found.+addIndirectRoot :: Store -> BS.ByteString -> IO ()+addIndirectRoot store = publishRecord (stDir store)++-- | Write an out-link's record into @auto@ by rename, given the bytes of+-- the link's spelling, unless a record with that content is already+-- there.+publishRecord :: StoreDir -> BS.ByteString -> IO ()+publishRecord dir content = do+  let record = autoRootsDir dir </> indirectRootRecordName content+      staging = recordStagingPath dir content   createDirectoryIfMissing True (autoRootsDir dir)   existing <- try (BS.readFile record) :: IO (Either IOException BS.ByteString)   when (existing /= Right content) $ do@@ -461,41 +581,74 @@       | Set.member path seen = go seen pending       | otherwise = go (Set.insert path seen) (Map.findWithDefault [] path refs ++ pending) +-- | Paths ordered so that each comes before every one of them it+-- references, as upstream orders the paths it deletes:+-- a depth-first walk over the references from each path in order, each+-- path placed after what it references, the whole reversed.  A reference+-- outside the paths, or from a path to itself, is not followed, and a+-- cycle among them is cut where the walk meets a path it entered.+referrersFirst :: Map Text [Text] -> Set Text -> [Text]+referrersFirst references paths = snd (foldl' visit (Set.empty, []) (Set.toAscList paths))+  where+    visit (seen, placed) path+      | Set.member path seen = (seen, placed)+      | otherwise =+          let followed = [r | r <- sort (Map.findWithDefault [] path references), r /= path, Set.member r paths]+              (seenAfter, placedAfter) = foldl' visit (Set.insert path seen, placed) followed+           in (seenAfter, path : placedAfter)+ -- --------------------------------------------------------------------------- -- The live set -- ---------------------------------------------------------------------------  -- | The live set at one moment under the exclusive collector lock: the -- roots' closure over the references map.  Only 'withLiveSet' makes--- one, so a checked delete holding it holds the lock and a set the--- delete can act on.+-- one, and no export takes or returns one, so a checked delete holding+-- it holds the lock it was made under and the roots of its own store. newtype LiveSet = LiveSet (Set Text)  -- | Whether the live set holds a path, spelled as the database spells it. isLive :: LiveSet -> Text -> Bool isLive (LiveSet live) path = Set.member path live --- | Run a checked operation under the exclusive collector lock with the--- live set as it stands, after upstream's roots line.  Refused, with--- the action not run, when the database holds a path outside the opened--- directory ('validPathsUnder').-withLiveSet :: Store -> (LiveSet -> IO a) -> IO (Either Text a)-withLiveSet store act = withCollectorLock store $ do+-- | Run a checked delete under the exclusive collector lock with the+-- live set as it stands, the extra roots given among its roots, after+-- upstream's roots line.  Refused, with the action not run, for a store+-- upstream Nix's database may also manage, before the lock is taken,+-- and when the database holds a path outside the opened directory.+-- Every caller consumes the set inside the action and returns no part+-- of it.+withLiveSet :: Store -> Set StorePath -> (LiveSet -> IO a) -> IO (Either Text a)+withLiveSet store extraRoots act = unlessUpstreamManaged store $ withCollectorLock store $ do   checked <- validPathsUnder store   case checked of     Left err -> pure (Left err)     Right _ -> do-      hPutStrLn stderr findingRootsMessage-      live <- liveSetOf store+      logMessage (stLogger store) findingRootsMessage+      live <- liveSetOf store extraRoots       Right <$> act live --- | The roots' closure as it stands; the caller holds the collector lock.-liveSetOf :: Store -> IO LiveSet-liveSetOf store = do+-- | The closure of the roots as they stand and the extra roots given,+-- which a caller keeps alive for the paths it is working with, as+-- upstream's temporary roots are; the caller holds the collector lock.+liveSetOf :: Store -> Set StorePath -> IO LiveSet+liveSetOf store extraRoots = do   roots <- findRoots store   refs <- referencesMap <$> queryAllReferences (stDB store)-  pure (LiveSet (reachableFrom refs (map grPath roots)))+  let extra = [T.pack (storePathToFilePath (stDir store) sp) | sp <- Set.toList extraRoots]+  pure (LiveSet (reachableFrom refs (map grPath roots <> extra))) +-- | Run a collection or a checked delete unless upstream Nix's database+-- may also manage the store, as the handle spells its directory or as+-- its links resolve ("Nix.Store.Upstream").  The paths upstream+-- registers have no row here and the roots it keeps are not read, so+-- every one would be deleted as an unregistered tree.  The look reads+-- nothing of this store's, so it runs before the collector lock and a+-- refusal does not wait behind an open handle.+unlessUpstreamManaged :: Store -> IO (Either Text a) -> IO (Either Text a)+unlessUpstreamManaged store act =+  upstreamManagedRefusal DeletesUpstreamPaths (stDir store) >>= maybe act (pure . Left)+ -- | Every valid path as the database spells it, refused when one lies -- outside the opened directory: the collector and the checked delete -- compare row text with paths derived from the handle's directory, and@@ -541,7 +694,7 @@  -- | The sweep plan over the valid set, the live set and the store -- directory's entries.  The lock-file test is the one--- 'Nix.Store.deleteStorePathRaw' makes: a lock-shaped name with no row+-- 'deleteStorePathRaw' makes: a lock-shaped name with no row -- is a lock file, since only the rows can tell one from a store object -- that happens to be called @flake.lock@, so a dead row's tree goes -- whatever its name, and an unregistered lock-shaped entry stays only@@ -560,25 +713,27 @@         && (Set.member (fullPath entry) valid || not (guardsLivePath entry))     guardsLivePath entry = maybe False (\guarded -> Set.member (fullPath guarded) live) (lockedPathOf entry) --- | Collect garbage: find the roots, walk the references, remove every--- dead row in one transaction, then every dead or unregistered tree.--- Holds the collector lock throughout, and is refused over a database--- keyed under another spelling of the directory ('validPathsUnder').--- The progress lines are upstream's, on stderr; the summary is the--- caller's to print ('gcSummaryLine').-collectGarbage :: Store -> IO (Either Text GcResults)-collectGarbage store = withCollectorLock store $ do+-- | Collect garbage: find the roots, the extra roots given among them,+-- walk the references, remove every dead row in one transaction, then+-- every dead or unregistered tree.  Holds the collector lock throughout.+-- Refused for a store upstream Nix's database may also manage, before+-- the lock is taken, and over a database keyed under another spelling of+-- the directory.  The progress lines are upstream's, told to the+-- handle's logger; the summary is the caller's to print+-- ('gcSummaryLine').+collectGarbage :: Store -> Set StorePath -> IO (Either Text GcResults)+collectGarbage store extraRoots = unlessUpstreamManaged store $ withCollectorLock store $ do   checked <- validPathsUnder store   case checked of     Left err -> pure (Left err)     Right valid -> Right <$> sweep valid   where     sweep valid = do-      hPutStrLn stderr findingRootsMessage-      LiveSet live <- liveSetOf store+      logMessage (stLogger store) findingRootsMessage+      LiveSet live <- liveSetOf store extraRoots       entries <- map T.pack <$> listDirectory (unStoreDir (stDir store))       let plan = sweepPlan (stDir store) valid live entries-      hPutStrLn stderr deletingGarbageMessage+      logMessage (stLogger store) deletingGarbageMessage       unregistered <- unregisterPathRows (stDB store) (spDeadRows plan)       case unregistered of         RowReferenced referrers ->@@ -586,10 +741,14 @@           -- dead set would have made its reference live.  Loud, not silent.           throwIO (userError ("collectGarbage: live paths reference dead ones: " <> show referrers))         _ -> pure ()-      freed <- foldlIO 0 (spTrees plan) deleteTree+      freed <- foldlIO 0 (spTrees plan) (deleteTree store)       pure GcResults {gcrDeleted = spTrees plan, gcrBytesFreed = freed}-    deleteTree !acc path = do-      hPutStrLn stderr (deletingPathMessage path)++-- | Remove a store directory entry's tree, given the bytes freed so far,+-- with upstream's line for it, and answer the bytes freed with it.+deleteTree :: Store -> Integer -> Text -> IO Integer+deleteTree store !acc path = do+  logMessage (stLogger store) (deletingPathMessage path)   let target = T.unpack path   node <- classifyWalkNode target   case node of@@ -635,3 +794,221 @@     <> " store paths deleted, "     <> showFreedBytes (gcrBytesFreed results)     <> " freed"++-- ---------------------------------------------------------------------------+-- Deleting named paths+-- ---------------------------------------------------------------------------++-- | What deleting one entry removed.+data DeleteOutcome = DeleteOutcome+  { -- | A ValidPaths row (with its outgoing reference edges) was removed.+    doRowRemoved :: !Bool,+    -- | An on-disk tree was removed.+    doTreeRemoved :: !Bool+  }+  deriving (Eq, Show)++-- | The name of one entry of a store directory, which is how a delete+-- names its target.  Joined to the directory, it names an entry directly+-- inside it, never the directory itself, a path above it or a path+-- elsewhere.  'storeEntryName' is the only way to make one.+newtype StoreEntryName = StoreEntryName Text+  deriving (Eq, Show)++-- | The store entry a name spells, or why it spells none.  Refused: the+-- empty name, which joins to the directory itself; a @\/@ or a @\\@,+-- the separators of either host, refused on both so a name means the+-- same on every host; a dot-leading name, which covers @.@, @..@ and the+-- store's own metadata directory and is never a store path, since a+-- store path's name starts with its hash; a @:@, which on Windows makes+-- @C:x@ a path on drive C and @name:x@ a stream of the file @name@; and+-- a NUL, which no file name holds.  The name is not checked as a store+-- path name: the entries a delete exists to remove are the ones current+-- name rules reject.+storeEntryName :: Text -> Either Text StoreEntryName+storeEntryName name+  | T.null name = Left "empty store path name"+  | T.any Windows.isPathSeparator name =+      Left (name <> ": a path separator is not valid in a store path name")+  | T.isPrefixOf "." name = Left (name <> ": dot-leading names are not store paths")+  | T.any (== ':') name = Left (name <> ": ':' is not valid in a store path name")+  | T.any (== '\NUL') name = Left (name <> ": NUL is not valid in a store path name")+  | otherwise = Right (StoreEntryName name)++-- | The name as text.+storeEntryNameText :: StoreEntryName -> Text+storeEntryNameText (StoreEntryName name) = name++-- | Delete store entries by name in the order given, each as+-- 'deleteStorePathRaw' deletes one, under one collector lock and one+-- live set, after upstream's roots line, printed once for the call.+-- The action reports each deletion as it completes, before the next+-- begins, and runs under the collector lock.  The first entry whose+-- delete returns 'Left' ends the call with that reason: the entries+-- before it are deleted and reported, and those after it are untouched.+-- The order is what deletes a reference chain leaf-first in one call: a+-- referrer named earlier is unregistered before the path it references+-- is checked.  Refused, with nothing deleted or reported, for a store+-- upstream Nix's database may also manage and over a database keyed+-- under another spelling of the directory.+deleteStorePaths :: Store -> [StoreEntryName] -> (StoreEntryName -> DeleteOutcome -> IO ()) -> IO (Either Text ())+deleteStorePaths store names report =+  join <$> withLiveSet store Set.empty (\live -> runExceptT (traverse_ (deleteAndReport live) names))+  where+    deleteAndReport live name = do+      removed <- ExceptT (deleteStorePathChecked store live name)+      liftIO (report name removed)++-- | Delete one store entry by name: its registration row and its+-- on-disk tree, under the collector lock with the live set as it+-- stands, after upstream's roots line.  Row first, tree second: an+-- orphan tree left by a failed removal is inert debris, while a+-- still-registered row whose tree is gone would be adopted as valid by+-- existence checks.  A row without a tree and a tree without a row both+-- delete (the repair cases); only a target with neither is an error.+-- An unregistered lock file of a store path is refused, since lock+-- files coordinate concurrent store access.+--+-- Liveness is upstream's rule for a specific delete: a path reachable+-- from a root is refused with its words.  The referrer refusal that+-- follows is this tool's own in wording and in shape.  Upstream refuses+-- a path with an unrooted referrer with the same still-alive line+-- unless that referrer is named in the same invocation (its+-- @pathsToDelete@ set in 2.24.9's @deleteReferrersClosure@), in which+-- case the named set deletes referrer-first; this delete removes+-- exactly the path named and lists the referrers that stand in the way,+-- so a chain deletes leaf-first in argument order through+-- 'deleteStorePaths', which shares one lock and one live set among the+-- entries it is given.  Refused, with nothing deleted, for a store+-- upstream Nix's database may also manage and over a database keyed+-- under another spelling of the directory.+deleteStorePathRaw :: Store -> StoreEntryName -> IO (Either Text DeleteOutcome)+deleteStorePathRaw store name =+  join <$> withLiveSet store Set.empty (\live -> deleteStorePathChecked store live name)++-- | Delete store paths as upstream's collector deletes the paths it is+-- named, with the extra roots given kept alive as upstream's temporary+-- roots are: each path in path order together with the paths that+-- reference it, which must all be among those named, the referrers+-- first ('referrersFirst'), each with upstream's line.  A path that is+-- live, or that a path not named references, is left, and the delete+-- stops there with upstream's refusal ('specificStillAliveMessage'), the+-- paths before it deleted.  So a path and the paths that reference it+-- delete together in whatever order they are named.  A path the+-- database does not hold has no referrers, and its tree is deleted.+-- Naming no path deletes nothing and takes no lock, as upstream returns+-- at once; otherwise it is refused, with nothing deleted, as+-- 'collectGarbage' refuses.+deleteSpecificPaths :: Store -> Set StorePath -> Set StorePath -> IO (Either Text GcResults)+deleteSpecificPaths store extraRoots targets+  | Set.null targets = pure (Right (GcResults [] 0))+  | otherwise = join <$> withLiveSet store extraRoots deleteNamed+  where+    pathText = T.pack . storePathToFilePath (stDir store)+    named = Set.map pathText targets+    deleteNamed live = do+      logMessage (stLogger store) deletingSpecifiedMessage+      outcome <- runExceptT (foldlM (deleteWithReferrers live) (GcResults [] 0, Set.empty) (Set.toAscList targets))+      pure (fst <$> outcome)+    deleteWithReferrers :: LiveSet -> (GcResults, Set Text) -> StorePath -> ExceptT Text IO (GcResults, Set Text)+    deleteWithReferrers live (results, dead) sp = do+      closure <- liftIO (referrerClosure live dead (pathText sp))+      (deleted, deadAfter) <- case closure of+        Nothing -> pure (results, dead)+        Just visited -> do+          references <- liftIO (Map.fromList <$> traverse (\path -> (,) path <$> referencesOf path) (Set.toList visited))+          let order = referrersFirst references visited+          unregistered <- liftIO (unregisterPathRows (stDB store) order)+          case unregistered of+            -- Unreachable: the closure holds every path that references+            -- one of its paths.  Loud, since the trees would go next.+            RowReferenced referrers -> throwError ("paths outside the delete reference it: " <> T.intercalate ", " referrers)+            _ -> pure ()+          freed <- liftIO (foldlIO (gcrBytesFreed results) order (deleteTree store))+          pure (GcResults (gcrDeleted results <> order) freed, Set.union dead visited)+      if Set.member (pathText sp) deadAfter+        then pure (deleted, deadAfter)+        else throwError (specificStillAliveMessage (storePathToText defaultStoreDir sp))+    -- The path with every path that references it, transitively, when+    -- none is live and all are named; paths already deleted are passed.+    referrerClosure :: LiveSet -> Set Text -> Text -> IO (Maybe (Set Text))+    referrerClosure live dead start = go Set.empty [start]+      where+        go visited pending = case pending of+          [] -> pure (Just visited)+          path : rest+            | Set.member path visited || Set.member path dead -> go visited rest+            | isLive live path || not (Set.member path named) -> pure Nothing+            | otherwise -> do+                referrers <- referrersOf path+                go (Set.insert path visited) (rest <> referrers)+    referrersOf, referencesOf :: Text -> IO [Text]+    referrersOf path = maybe (pure []) (queryReferrers (stDB store)) (parseStorePath (stDir store) path)+    referencesOf path = maybe (pure []) (queryReferences (stDB store)) (parseStorePath (stDir store) path)++-- | The delete of one entry given the live set, which stands for the+-- collector lock being held.  Inside the collector lock the sequence+-- also holds the target's per-path lock - the same file a substituter+-- of the path locks, as upstream's deletePath does - so a holder that+-- is not a store handle (nothing in this tool, but nothing forbids one)+-- still cannot have its delete-materialize-register torn apart by this+-- delete.+deleteStorePathChecked :: Store -> LiveSet -> StoreEntryName -> IO (Either Text DeleteOutcome)+deleteStorePathChecked store live (StoreEntryName basename)+  | isLive live (T.pack target) = pure (Left (stillAliveMessage (T.pack target)))+  | otherwise = deleteUnderPathLock+  where+    target = unStoreDir (stDir store) </> T.unpack basename+    deleteUnderPathLock = withLockFile (stLogger store) (target <> lockFileSuffix) $ \_ -> do+      -- A holder never deletes a lock file (the 'Nix.Store.Lock'+      -- header), and neither does this delete.  A target is one when+      -- stripping the suffix leaves a well-formed store basename AND no+      -- registration row bears the full name: names like @flake.lock@+      -- are legal store-path names, so a registered object of this+      -- exact name deletes normally, and only the rows can tell the two+      -- apart.  The check precedes the row removal below, which is+      -- destructive.+      registered <- case parseStorePathBaseName basename of+        Just sp -> isValidPath (stDB store) sp+        Nothing -> pure False+      case (registered, lockedPathOf basename) of+        (False, Just guardedPath) ->+          pure+            ( Left+                ( basename+                    <> ": names the lock file of "+                    <> guardedPath+                    <> "; lock files coordinate concurrent store access"+                    <> " and are never deleted here (store gc removes it,"+                    <> " and any unregistered store object of this exact"+                    <> " name, once "+                    <> guardedPath+                    <> " is not live)"+                )+            )+        _ -> deleteRowAndTree+    deleteRowAndTree = do+      rowResult <- unregisterPathRow (stDB store) (T.pack target)+      case rowResult of+        RowReferenced referrers ->+          pure+            ( Left+                ( basename+                    <> " is referenced by:"+                    <> T.concat ["\n  " <> r | r <- referrers]+                )+            )+        _ -> do+          -- 'doesPathExist' follows links, so a dangling top-level symlink+          -- would read as absent; links are leaves here (as in store walks),+          -- and leftover link debris must still be removable.+          treeExisted <- do+            onDisk <- doesPathExist target+            if onDisk+              then pure True+              else pathIsSymbolicLink target `catch` \(_ :: IOException) -> pure False+          when treeExisted (removePathForcibly target)+          let rowRemoved = rowResult == RowUnregistered+          if rowRemoved || treeExisted+            then pure (Right DeleteOutcome {doRowRemoved = rowRemoved, doTreeRemoved = treeExisted})+            else pure (Left (basename <> ": not in this store (no registration row, no tree on disk)"))
src/Nix/Store/Handle.hs view
@@ -41,20 +41,23 @@ where  import Control.Concurrent.MVar (MVar, newMVar, putMVar, takeMVar, withMVar)-import Control.Exception (SomeException, mask, onException, throwIO, try)+import Control.Exception (SomeException, bracketOnError, mask, onException, throwIO, try)+import Data.Text (Text) import qualified Data.Text as T import Nix.Eval.CanonPath (canonPath)+import Nix.Logger (Logger) import Nix.Store.CaseSensitive (CaseSensitivity, probeCaseSensitivity)-import Nix.Store.DB (StoreDB, closeStoreDB, metaDirName, openStoreDB)+import Nix.Store.DB (StoreDB, closeStoreDB, createStoreDirectories, metaDirName, openStoreDB) import Nix.Store.Lock (LockMode (..), PathLock, acquireLockFileWith, releasePathLock, withLockFileWith) import Nix.Store.Path (StoreDir (..))-import System.Directory (createDirectoryIfMissing, makeAbsolute)+import System.Directory (makeAbsolute) import System.FilePath ((</>))  -- | An open store with database and configuration.  'stDir' is the -- canonical spelling ('canonicalStoreDir'); 'stGcLease' is the handle's--- shared hold on the collector lock, swapped, never released early, by--- 'withCollectorLock'.+-- shared hold on the collector lock, which 'withCollectorLock' swaps for+-- the exclusive lock and back; after a failed renewal the handle holds+-- none until it is closed. data Store = Store   { stDir :: !StoreDir,     stDB :: !StoreDB,@@ -62,7 +65,11 @@     -- | How the volume holding the store compares sibling names, probed     -- at open ('probeCaseSensitivity') and consulted by every NAR     -- materialization into the store.-    stCaseSensitivity :: !CaseSensitivity+    stCaseSensitivity :: !CaseSensitivity,+    -- | Where an operation through the handle reports what it is doing:+    -- a wait on a lock, a collection's progress, a substitution's+    -- messages, a build's messages and the lines its builder writes.+    stLogger :: !Logger   }  -- | Upstream's name for the store-wide garbage-collector lock file.@@ -83,25 +90,31 @@  -- | Open a Nix store at the given directory, keyed by its canonical -- spelling.  Creates the store directory and database if they don't--- exist.  The shared lease is taken before the database is touched, so--- an opener arriving during a collection reads nothing until the--- collection is over.  It waits with the collector's own line: upstream's--- opener never waits here (it hands its roots to the running collector--- through a socket instead), so there is no upstream line for the wait,--- and the collector's names what is being waited for.-openStore :: StoreDir -> IO Store-openStore rawDir = do+-- exist, the directories as 'createStoreDirectories' does.  The shared+-- lease is taken before the database is touched, so an opener arriving+-- during a collection reads nothing until the collection is over.  It+-- waits with the collector's own line: upstream's opener never waits+-- here (it hands its roots to the running collector through a socket+-- instead), so there is no upstream line for the wait, and the+-- collector's names what is being waited for.  A step that fails+-- once the lease is held releases what was taken before it, the database+-- and the lease, so a failed open holds nothing that a later collection+-- would wait on.  The line goes to the logger given, which the handle+-- keeps for its operations ('stLogger').  On Windows a store another+-- account could change is refused before the lease is taken, by+-- 'createStoreDirectories'.+openStore :: Logger -> StoreDir -> IO Store+openStore logger rawDir = do   dir <- canonicalStoreDir rawDir-  let metaDir = unStoreDir dir </> metaDirName-      lockPath = gcLockFilePath dir-  createDirectoryIfMissing True metaDir-  lease <- acquireLockFileWith LockShared bigGcLockMessage lockPath-  db <- openStoreDB dir+  let lockPath = gcLockFilePath dir+  createStoreDirectories dir+  bracketOnError (acquireLockFileWith logger LockShared bigGcLockMessage lockPath) releasePathLock $ \lease ->+    bracketOnError (openStoreDB dir) closeStoreDB $ \db -> do       -- After the directory exists: the probe answers for a path on disk,       -- and a fresh store's directory sits on the volume it will live on.       sensitivity <- probeCaseSensitivity (unStoreDir dir)       leaseVar <- newMVar lease-  pure Store {stDir = dir, stDB = db, stGcLease = leaseVar, stCaseSensitivity = sensitivity}+      pure Store {stDir = dir, stDB = db, stGcLease = leaseVar, stCaseSensitivity = sensitivity, stLogger = logger}  -- | Close the store: the database first, then the lease, so the lock -- outlives every write this handle made.  Waits for an in-progress@@ -112,7 +125,7 @@   withMVar (stGcLease store) releasePathLock  -- | Upstream's announcement when the collector lock is busy.-bigGcLockMessage :: String+bigGcLockMessage :: Text bigGcLockMessage = "waiting for the big garbage collector lock..."  -- | Run an action holding the collector lock exclusively.  The handle's@@ -126,12 +139,13 @@ -- opened again), the surrendered lease goes back instead, so the handle -- stays closable: 'closeStore' releases it as a no-op, and the failure -- reaches the caller, whose handle holds no lease until it is closed.+-- The message goes to the handle's logger. withCollectorLock :: Store -> IO a -> IO a withCollectorLock store act = mask $ \restore -> do   lease <- takeMVar (stGcLease store)   releasePathLock lease-  outcome <- try (restore (withLockFileWith LockExclusive bigGcLockMessage lockPath (const act)))-  renewed <- acquireLockFileWith LockShared bigGcLockMessage lockPath `onException` putMVar (stGcLease store) lease+  outcome <- try (restore (withLockFileWith (stLogger store) LockExclusive bigGcLockMessage lockPath (const act)))+  renewed <- acquireLockFileWith (stLogger store) LockShared bigGcLockMessage lockPath `onException` putMVar (stGcLease store) lease   putMVar (stGcLease store) renewed   either (\e -> throwIO (e :: SomeException)) pure outcome   where
+ src/Nix/Store/Import.hs view
@@ -0,0 +1,692 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TupleSections #-}++-- | Paths a store takes from elsewhere: a NAR with what its path claims of+-- itself ('importNar'), a dump made into the path its content address+-- makes ('beginDumpAdd'), or a text with the references it names+-- ('addTextToStore'), each held to upstream's checks before it becomes+-- valid, and refused in upstream's words.+--+-- A NAR is taken when one of the caller's keys signed its path's info, or+-- when its content address and references make exactly its path, which+-- its bytes then have to reproduce.  Its hash and size are held to the+-- bytes that arrive.  A derivation, by any route, is taken only when each+-- of its outputs is the path its inputs make ('checkDerivationOutputs').+--+-- A NAR and a dump arrive a chunk at a time, each step taking the next+-- chunk, so a daemon can feed them as its client sends them.  What they+-- write goes to a staging directory in the store until it has been+-- checked, and is moved to its path under the path's lock, so giving+-- one up never touches a store path.+module Nix.Store.Import+  ( -- * Importing a NAR+    AdmittedNar,+    admitNar,+    NarImportStart (..),+    NarImport,+    beginNarImport,+    NarImportStep (..),+    feedNarImport,+    endNarImport,+    abandonNarImport,+    importNar,++    -- * Adding a dump+    DumpAdd,+    beginDumpAdd,+    feedDumpAdd,+    EndedDump,+    endDumpAdd,+    endedDumpPath,+    placeDump,+    abandonDumpAdd,++    -- * Adding a text+    addTextToStore,++    -- * The checks+    checkDerivationOutputs,++    -- * Writing a path (exposed for testing)+    replacePath,+  )+where++import Control.Exception (IOException, catch, displayException, finally, mask, onException, try, tryJust)+import Control.Monad (guard, unless, when)+import Control.Monad.Except (ExceptT (..), liftEither, runExceptT, throwError, withExceptT)+import Control.Monad.IO.Class (liftIO)+import Control.Monad.State.Strict (StateT, evalStateT, gets, modify')+import Data.Bifunctor (first)+import qualified Data.ByteString as BS+import Data.Foldable (for_, traverse_)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe)+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Word (Word64)+import Database.SQLite.Simple (SQLError)+import Nix.Daemon.Protocol (ContentAddress, ContentAddressMethod (..), contentAddressFromParts, renderSignature)+import Nix.Derivation (Derivation (..), DerivationOutput (..), drvExtension, drvFileDerivation, fixedOutput, fixedOutputModulo, fromATerm, inputAddressed, inputAddressedModulo)+import Nix.Hash (FileIngestionMethod (..), IncrementalHash, bytesToHexText, hashFinalizeBytes, hashInitWithAlgo, hashUpdateChunk, hexToBytes, makeFixedOutputPath, makeSourcePath, makeTextPath, sha256Digest, unknownHashAlgo)+import Nix.Logger (Level (..), Logger (..))+import Nix.Store (AddressedPath (..), ArchiveEnd (..), NarFed (..), NarFeed, NarLinks, NarStreamFailure (..), NarUnpackSink, PathRegistration (..), RegistrationTime (..), SignatureRequirement (..), Store (..), Ultimate (..), UpstreamHazard (..), abortNarUnpack, addressMakesPath, addressRegistrable, canonicalizeMetadata, checkNarClaim, closeNarUnpack, endNar, feedNar, fixedReferencesRefusal, isValid, moveNarUnpack, moveOutput, newNarUnpackSink, notContentAddressed, registerPath, registrationFor, startNarFeed, upstreamManagedRefusal, volumeCaseHack, withPathLock)+import Nix.Store.Access (DirAccess (OwnerAccess), createDirectoryWith)+import Nix.Store.Exclusive (openNewBinaryFile)+import qualified Nix.Store.ExecBit as ExecBit+import Nix.Store.Path (BadStorePath, StoreDir (..), StorePath (spName), badStorePathText, defaultStoreDir, storePathBasename, storePathToFilePath, storePathToText)+import Nix.Substituter (checkContentAddress)+import qualified NovaCache.Hash as Hash+import qualified NovaCache.NAR as NAR+import qualified NovaCache.NarInfo as NarInfo+import qualified NovaCache.Signing as Signing+import Numeric (showHex)+import qualified System.Directory as Dir+import System.FilePath ((</>))+import System.IO (Handle, hClose)+import System.IO.Error (ioeGetErrorString, isAlreadyExistsError, isUserError)+import qualified System.OsPath as OP+import System.Random (randomIO)++-- ---------------------------------------------------------------------------+-- Importing a NAR+-- ---------------------------------------------------------------------------++-- | A path admitted to be imported from its NAR: the store, what the path+-- claims of itself, and the NAR hash it claims.+data AdmittedNar = AdmittedNar !Store !PathRegistration !Hash.NixHash++-- | Admit a path to be imported from its NAR, given what it claims of+-- itself as a registration: its NAR hash and size, its references and+-- deriver, its content address, its signatures and whether it is+-- ultimately trusted.  Nothing is read yet.  Where signatures are+-- required, the path's signatures are counted as upstream's store counts+-- them for one it is handed a NAR for: a path whose stated address makes+-- it needs none; an address that makes another path is warned of, as+-- upstream warns each time it tests one ('notContentAddressed'), and the+-- path needs a signature; an address that makes no path is refused+-- ('MakesNoPath'); and a path neither content-addressed nor signed by one+-- of the keys is refused.  A store+-- upstream Nix's database may also manage is refused+-- ("Nix.Store.Upstream").+admitNar :: Store -> SignatureRequirement -> PathRegistration -> IO (Either Text AdmittedNar)+admitNar store requirement claim = runExceptT $ do+  narHash <- liftEither (claimedNarHash claim)+  case requirement of+    SignaturesNotRequired -> pure ()+    RequireSignature keys -> case addressMakesPath sp (prReferences claim) <$> prContentAddress claim of+      Just MakesItsPath -> pure ()+      Just (MakesNoPath refusal) -> throwError refusal+      Just MakesAnotherPath -> liftIO (logAt (stLogger store) LevelError (notContentAddressed sp)) >> signedOrRefused keys narHash+      Nothing -> signedOrRefused keys narHash+  refusal <- liftIO (upstreamManagedRefusal ReplacesUpstreamPaths (stDir store))+  traverse_ throwError refusal+  pure (AdmittedNar store claim narHash)+  where+    sp = prPath claim+    signedOrRefused :: [Signing.PublicKey] -> Hash.NixHash -> ExceptT Text IO ()+    signedOrRefused keys narHash =+      unless (signedByOneOf keys claim narHash) $+        throwError ("cannot add path '" <> storePathToText defaultStoreDir sp <> "' because it lacks a signature by a trusted key")++-- | How an import begins.+data NarImportStart+  = -- | The path is valid already, so its NAR is not read.+    NarAlreadyValid+  | -- | Its NAR is to be read.+    NarImportBegun !NarImport++-- | A NAR being imported: the path admitted, the staging directory its+-- tree is unpacked in, and the archive read so far.+data NarImport = NarImport !AdmittedNar !Staging !NarUnpackSink !NarFeed++-- | Begin importing an admitted path.  One already valid is left as it is.+-- For another, a staging directory is made in the store, where the NAR is+-- unpacked as it arrives ('feedNarImport'), so nothing is written at the+-- path until the archive has been held to the claim.  The import begun+-- holds that directory until it ends or is given up+-- ('abandonNarImport'), so a caller begins it with asynchronous+-- exceptions masked, as 'importNar' does.+beginNarImport :: AdmittedNar -> IO NarImportStart+beginNarImport admitted@(AdmittedNar store claim _) = do+  valid <- isValid store (prPath claim)+  if valid+    then pure NarAlreadyValid+    else do+      staging <- createStaging (stDir store)+      sink <- newNarUnpackSink (stCaseSensitivity store) (stagedTree staging) `onException` removeStaging staging+      pure (NarImportBegun (NarImport admitted staging sink (startNarFeed AtRootClose)))++-- | What feeding an import a chunk comes to.+data NarImportStep+  = -- | Its archive goes on, and is fed next here.+    NarImportGoesOn !NarImport+  | -- | The path is valid: registered from the archive, or by another+    -- writer while the archive was read.+    NarImported++-- | Feed an import the next chunk of its NAR.  The archive is unpacked up+-- to its root node's close, and the bytes of the chunk past that close+-- are not the archive's: upstream's daemon reads an imported NAR the same+-- way and leaves what follows it to the stream it came on, which drains+-- the rest of a frame or skips to the claimed size.  Once the archive+-- ends ('settleNar'), or is refused, the staging directory is gone; an+-- exception removes it too.+feedNarImport :: NarImport -> BS.ByteString -> IO (Either Text NarImportStep)+feedNarImport begun@(NarImport admitted staging sink feed) chunk =+  stepped `onException` abandonNarImport begun+  where+    stepped =+      feedNar sink feed chunk >>= \case+        Left failure -> Left (streamFailure failure) <$ removeStaging staging+        Right (NarGoesOn next) -> pure (Right (NarImportGoesOn (NarImport admitted staging sink next)))+        Right (NarEnded digest size _) -> (NarImported <$) <$> (settleNar admitted staging sink digest size `finally` removeStaging staging)++-- | Tell an import that its NAR's bytes ended: an archive that had not+-- ended by then is refused as the truncated archive it is.  The staging+-- directory is gone after, however it ends.+endNarImport :: NarImport -> IO (Either Text ())+endNarImport begun@(NarImport admitted staging sink feed) =+  ended `onException` abandonNarImport begun+  where+    ended =+      endNar sink feed >>= \case+        Left failure -> Left (streamFailure failure) <$ removeStaging staging+        Right (digest, size) -> settleNar admitted staging sink digest size `finally` removeStaging staging++-- | Give up an import, removing what it unpacked.  It releases what the+-- import held from its beginning, the same at every step, and never+-- touches the path itself, so it may be called on the import as it began,+-- and after the import has ended.+abandonNarImport :: NarImport -> IO ()+abandonNarImport (NarImport _ staging sink _) = abortNarUnpack sink >> removeStaging staging++-- | Make a path valid from its archive, read and unpacked in a staging+-- directory: the archive's hash and size, over the bytes read to its root+-- node's close, are held to the claim, and then, under the path's lock+-- and with the path still not valid, the tree is moved to the path, the+-- links it records made there, its metadata made canonical, and the tree+-- as it lies there held to the hash, the tree to the address it states,+-- the address to the path, and a derivation to its outputs.  A refusal+-- removes the tree.  What passes is registered as the claim states it.+settleNar :: AdmittedNar -> Staging -> NarUnpackSink -> Hash.NixHash -> Int -> IO (Either Text ())+settleNar (AdmittedNar store claim narHash) staging sink digest size = runExceptT $ do+  liftEither (heldToClaim digest)+  links <- ExceptT (closeNarUnpack sink)+  ExceptT $ placeStaged store sp staging (Just links) $ \dest -> do+    liftIO (canonicalizeMetadata dest)+    onDisk <- liftIO (ExecBit.narHashOfPath caseHack dest)+    liftEither (heldToClaim onDisk)+    for_ (prContentAddress claim) (ExceptT . checkContentAddress caseHack defaultStoreDir sp dest)+    ExceptT (registrable store claim)+    ExceptT (registered store claim)+  where+    sp = prPath claim+    caseHack = volumeCaseHack (stCaseSensitivity store)+    heldToClaim got = checkNarClaim (storePathToText defaultStoreDir sp) narHash (toInteger (prNarSize claim)) got (toInteger size)++-- | Import a path from its NAR, pulled from a chunk source, as upstream's+-- local store adds a path it is handed a NAR for: the path is admitted+-- ('admitNar'), a path already valid is left as it is with the source not+-- read, and otherwise the NAR is read up to its root node's close+-- ('feedNarImport') and the path made valid from it ('settleNar').  No+-- chunk is pulled after that close, so a caller that needs the bytes of+-- the last chunk past it gives a source that ends where they begin.  The+-- import is given up on an exception from its beginning on.+importNar :: Store -> SignatureRequirement -> PathRegistration -> IO BS.ByteString -> IO (Either Text ())+importNar store requirement claim source = runExceptT $ do+  admitted <- ExceptT (admitNar store requirement claim)+  ExceptT $ mask $ \restore ->+    beginNarImport admitted >>= \case+      NarAlreadyValid -> pure (Right ())+      NarImportBegun begun -> restore (pumped begun) `onException` abandonNarImport begun+  where+    pumped begun =+      source >>= feedNarImport begun >>= \case+        Left reason -> pure (Left reason)+        Right (NarImportGoesOn next) -> pumped next+        Right NarImported -> pure (Right ())++-- | What a refused archive is refused with.+streamFailure :: NarStreamFailure -> Text+streamFailure failure = case failure of+  NarStreamRefused reason -> reason+  NarStreamMalformed reason -> reason++-- ---------------------------------------------------------------------------+-- Adding a dump+-- ---------------------------------------------------------------------------++-- | A dump being added as the path its content address makes: what the+-- path is made from, the staging directory its contents are written in,+-- how its bytes are being taken, and their hash so far under the+-- address's algorithm.+data DumpAdd = DumpAdd+  { daStore :: !Store,+    daName :: !Text,+    daMethod :: !ContentAddressMethod,+    daAlgo :: !Text,+    daReferences :: !(Set StorePath),+    daStaging :: !Staging,+    daReading :: !DumpReading,+    daHash :: !IncrementalHash+  }++-- | How a dump's bytes are being taken.+data DumpReading+  = -- | A NAR, unpacked as it arrives.+    ReadingArchive !NarUnpackSink !NarFeed+  | -- | A NAR whose root node has closed, with its SHA-256; no byte may+    -- follow.+    ArchiveRead !NarUnpackSink !Hash.NixHash+  | -- | A file's contents, written as they arrive.+    ReadingFile !Handle++-- | Begin adding a dump, given the name, the method and the algorithm of+-- the content address its path is made from, and the paths it refers to,+-- as upstream's store adds a dump a client sends: a NAR for the+-- recursive method, and a file's contents for the flat and text methods.+-- What the address cannot make is refused before anything is read+-- ('addressAdmits').  A store upstream Nix's database may also manage is+-- refused too ("Nix.Store.Upstream").  Otherwise a staging directory is+-- made in the store, where the dump is written as it arrives+-- ('feedDumpAdd').  The add begun holds that directory until it ends or+-- is given up ('abandonDumpAdd'), so a caller begins it with asynchronous+-- exceptions masked.+beginDumpAdd :: Store -> Text -> ContentAddressMethod -> Text -> Set StorePath -> IO (Either Text DumpAdd)+beginDumpAdd store name method algo refs = runExceptT $ do+  hashing <- maybe (throwError (unknownHashAlgo algo)) pure (hashInitWithAlgo algo)+  liftEither (addressAdmits name method algo refs)+  refusal <- liftIO (upstreamManagedRefusal ReplacesUpstreamPaths (stDir store))+  traverse_ throwError refusal+  liftIO $ do+    staging <- createStaging (stDir store)+    reading <- startReading staging `onException` removeStaging staging+    pure (DumpAdd store name method algo refs staging reading hashing)+  where+    startReading staging = case method of+      FixedMethod NarIngestion -> (\sink -> ReadingArchive sink (startNarFeed AtRootClose)) <$> newNarUnpackSink (stCaseSensitivity store) (stagedTree staging)+      FixedMethod FlatIngestion -> ReadingFile <$> (OP.encodeFS (stagedTree staging) >>= openNewBinaryFile)+      TextMethod -> ReadingFile <$> (OP.encodeFS (stagedTree staging) >>= openNewBinaryFile)++-- | Whether a content address can make a path with these references, or+-- why not.  Only a NAR's SHA-256 address may come with references, as+-- upstream makes a path from an address, and the others are refused in+-- its words.  A text's path is made from its SHA-256 alone, and upstream+-- has no words for another algorithm: its store stops on an assertion.+addressAdmits :: Text -> ContentAddressMethod -> Text -> Set StorePath -> Either Text ()+addressAdmits name method algo refs = case method of+  TextMethod+    | algo /= sha256Algo -> Left ("cannot add '" <> name <> "' as a text hashed with " <> algo <> ": a text's content address is its " <> sha256Algo <> " hash")+  FixedMethod ingestion+    | not (Set.null refs) && not (ingestion == NarIngestion && algo == sha256Algo) ->+        Left (fixedReferencesRefusal name)+  _ -> Right ()++-- | Write the next chunk of a dump, an empty chunk writing nothing: the+-- dump's end is 'endDumpAdd'.  A NAR is unpacked up to its root node's+-- close, and a byte after that close is refused, as a dump is all+-- archive.  Once a chunk is refused the staging directory is gone; an+-- exception removes it too.+feedDumpAdd :: DumpAdd -> BS.ByteString -> IO (Either Text DumpAdd)+feedDumpAdd add chunk+  | BS.null chunk = pure (Right add)+  | otherwise = (fmap (\reading -> add {daReading = reading, daHash = hashUpdateChunk (daHash add) chunk}) <$> taken) `onException` abandonDumpAdd add+  where+    taken = case daReading add of+      ReadingArchive sink feed ->+        feedNar sink feed chunk >>= \case+          Left failure -> Left (streamFailure failure) <$ removeStaging (daStaging add)+          Right (NarGoesOn next) -> pure (Right (ReadingArchive sink next))+          Right (NarEnded digest _ after)+            | BS.null after -> pure (Right (ArchiveRead sink digest))+            | otherwise -> trailing+      ArchiveRead {} -> trailing+      ReadingFile handle -> Right (ReadingFile handle) <$ BS.hPut handle chunk+    trailing = Left trailingBytesRefusal <$ abandonDumpAdd add++-- | The refusal of a dump that goes on past its archive's end, in the+-- words nova-cache's parser refuses an archive's trailing bytes with.+trailingBytesRefusal :: Text+trailingBytesRefusal = "trailing bytes after NAR root node"++-- | A dump read to its end: the add, the path its address makes, the+-- address, and for a NAR what was read of it.+data EndedDump = EndedDump !DumpAdd !StorePath !ContentAddress !(Maybe ReadArchive)++-- | A dump's archive as it was read: its SHA-256, and the links it+-- records, which are made once its tree lies at its path.+data ReadArchive = ReadArchive !Hash.NixHash !NarLinks++-- | The path an ended dump's address makes.+endedDumpPath :: EndedDump -> StorePath+endedDumpPath (EndedDump _ sp _ _) = sp++-- | End a dump: a NAR must have ended with its bytes, every node of it+-- closed, and a file is closed.  The path its address makes is worked+-- out from its hash, a name the store cannot hold refused in upstream's+-- words.  A refusal or an exception removes the staging directory.+endDumpAdd :: DumpAdd -> IO (Either Text EndedDump)+endDumpAdd add = (runExceptT ending >>= either (\reason -> Left reason <$ abandonDumpAdd add) (pure . Right)) `onException` abandonDumpAdd add+  where+    ending = do+      archive <- case daReading add of+        ReadingArchive sink feed -> do+          (digest, _) <- withExceptT streamFailure (ExceptT (endNar sink feed))+          Just . ReadArchive digest <$> ExceptT (closeNarUnpack sink)+        ArchiveRead sink digest -> Just . ReadArchive digest <$> ExceptT (closeNarUnpack sink)+        ReadingFile handle -> Nothing <$ liftIO (hClose handle)+      let digest = hashFinalizeBytes (daHash add)+      sp <- liftEither (first badStorePathText (dumpPath add digest))+      address <- maybe (throwError (unknownHashAlgo (daAlgo add))) pure (contentAddressFromParts (daMethod add) (daAlgo add) digest)+      pure (EndedDump add sp address archive)++-- | The path a dump's address makes, given the dump's hash.+dumpPath :: DumpAdd -> BS.ByteString -> Either BadStorePath StorePath+dumpPath add digest = case daMethod add of+  TextMethod -> makeTextPath name digest (Set.toAscList (daReferences add))+  FixedMethod NarIngestion+    | daAlgo add == sha256Algo -> makeSourcePath name digest (daReferences add)+  FixedMethod ingestion -> makeFixedOutputPath name (daAlgo add) ingestion digest+  where+    name = daName add++-- | Make an ended dump's path valid, under the path's lock, unless it is+-- valid by then: the contents are moved to the path, the links a NAR+-- records made there, their metadata made canonical, and the path+-- registered with its NAR hash and size, the references given and its+-- content address, as upstream registers a dump it adds.  A NAR is held+-- to the hash it was read with once it lies at the path, since the+-- volume decides the final spelling of every name, and a derivation to+-- its outputs; a refusal removes it.  The staging directory is gone+-- after, however it ends.+placeDump :: EndedDump -> IO (Either Text ())+placeDump (EndedDump add sp address archive) =+  placeStaged store sp (daStaging add) ((\(ReadArchive _ links) -> links) <$> archive) settle `finally` removeStaging (daStaging add)+  where+    store = daStore add+    settle dest = do+      liftIO (canonicalizeMetadata dest)+      (narHash, narSize) <- liftIO (narOfPath (volumeCaseHack (stCaseSensitivity store)) dest)+      for_ archive $ \(ReadArchive digest _) ->+        unless (narHash == digest) $+          throwError (storePathToText defaultStoreDir sp <> ": the unpacked tree does not serialise to the NAR it was unpacked from")+      let registration = PathRegistration sp (Hash.formatNixHash narHash) narSize Nothing (Set.toAscList (daReferences add)) NotUltimate Set.empty (Just address) RegisteredNow+      ExceptT (registrable store registration)+      ExceptT (registered store registration)++-- | Give up adding a dump, removing what was written of it.  It releases+-- what the add held from its beginning, the same at every step, so it may+-- be called on the add as it began, and after the add has ended.+abandonDumpAdd :: DumpAdd -> IO ()+abandonDumpAdd add = closeReading (daReading add) >> removeStaging (daStaging add)+  where+    closeReading = \case+      ReadingArchive sink _ -> abortNarUnpack sink+      ArchiveRead sink _ -> abortNarUnpack sink+      -- The file is about to be removed, so a failure to flush what was+      -- written to it is no failure of the add; closing is what lets+      -- Windows remove it.+      ReadingFile handle -> hClose handle `catch` \(_ :: IOException) -> pure ()++-- | The SHA-256 and size of a path's NAR, read as it streams.+narOfPath :: NAR.CaseHack -> FilePath -> IO (Hash.NixHash, Int)+narOfPath caseHack path = ExecBit.withNarSource caseHack path (absorb Hash.hashInit 0)+  where+    absorb !hashing !size pull = do+      chunk <- pull+      if BS.null chunk+        then pure (Hash.hashFinalize hashing, size)+        else absorb (Hash.hashUpdate hashing chunk) (size + BS.length chunk) pull++-- ---------------------------------------------------------------------------+-- Staging+-- ---------------------------------------------------------------------------++-- | A directory in the store that a path's contents are written in before+-- they are moved to the path ('stagedTree'), so a path is never seen+-- half written and what a refusal leaves is not at a store path.  Its+-- name, upstream's prefix for its own and a random number, is no store+-- path's, so a collection sweeps one a stopped process left.+newtype Staging = Staging FilePath++-- | The prefix of a staging directory's name: upstream's for the+-- directories its store stages a path in.+stagingPrefix :: FilePath+stagingPrefix = "tmp-"++-- | Make a staging directory in the store, open to the user nova-nix+-- runs as alone, under a name nothing else has.+createStaging :: StoreDir -> IO Staging+createStaging dir = do+  number <- randomIO :: IO Word64+  let path = unStoreDir dir </> stagingPrefix <> showHex number ""+  created <- tryJust (guard . isAlreadyExistsError) (createDirectoryWith OwnerAccess path)+  either (const (createStaging dir)) (const (pure (Staging path))) created++-- | Where in a staging directory the contents are written.+stagedTree :: Staging -> FilePath+stagedTree (Staging dir) = dir </> "x"++-- | Remove a staging directory and what is left in it.+removeStaging :: Staging -> IO ()+removeStaging (Staging dir) = Dir.removePathForcibly dir++-- | Move staged contents to their path and register them there, under the+-- path's lock: a path valid by then is left as it is, and otherwise the+-- contents are moved to the path, with the links an archive they were+-- unpacked from records made there ('moveNarUnpack'), and the path given+-- to the registration ('replacePath').+placeStaged :: Store -> StorePath -> Staging -> Maybe NarLinks -> (FilePath -> ExceptT Text IO ()) -> IO (Either Text ())+placeStaged store sp staging archived register =+  withPathLock (stLogger store) (stDir store) sp $ \_ -> do+    valid <- isValid store sp+    if valid then pure (Right ()) else replacePath store sp (moved >> register dest)+  where+    dest = storePathToFilePath (stDir store) sp+    moved = case archived of+      Nothing -> liftIO (moveOutput (stagedTree staging) dest)+      Just links -> ExceptT (moveNarUnpack (stagedTree staging) dest links)++-- | Run a write of a path that registers it, the caller holding the+-- path's lock, leaving what it wrote only where the path ends valid: what+-- was at the path is cleared first, and cleared again on a refusal, or on+-- an exception unless the path is valid by then.  An asynchronous+-- exception that arrives while the registration commits is raised once it+-- has committed, as the database's transaction masks its commit, so the+-- path is valid and its tree stays.  Where its validity cannot be read+-- the tree stays too: a tree at a path that is not valid is garbage a+-- collection removes, and one removed from a valid path is a store that+-- no longer holds what its database says.+replacePath :: Store -> StorePath -> ExceptT Text IO () -> IO (Either Text ())+replacePath store sp write = do+  Dir.removePathForcibly dest+  outcome <- runExceptT write `onException` clearUnlessValid+  either (\reason -> Left reason <$ Dir.removePathForcibly dest) (pure . Right) outcome+  where+    dest = storePathToFilePath (stDir store) sp+    clearUnlessValid =+      try (isValid store sp) >>= \case+        Right False -> Dir.removePathForcibly dest+        Right True -> pure ()+        Left (_ :: SQLError) -> pure ()++-- | Register a path, refused in upstream's words where the database+-- refuses it: a reference that is not valid, or a derivation that does+-- not parse, which it raises as a user error.+registered :: Store -> PathRegistration -> IO (Either Text ())+registered store registration = tryJust refusal (registerPath (stDB store) registration)+  where+    refusal err+      | isUserError err = Just (T.pack (ioeGetErrorString err))+      | otherwise = Nothing++-- | The NAR hash a claim states, which must be a SHA-256 hash in the+-- store's spelling.+claimedNarHash :: PathRegistration -> Either Text Hash.NixHash+claimedNarHash claim =+  either (const (Left ("cannot add path '" <> storePathToText defaultStoreDir (prPath claim) <> "': its NAR hash '" <> prNarHash claim <> "' is not a SHA-256 hash in nix-base32"))) Right (Hash.parseNixHash (prNarHash claim))++-- | Whether one of the keys given verifies one of a claim's signatures+-- over its fingerprint, given the NAR hash it claims.+signedByOneOf :: [Signing.PublicKey] -> PathRegistration -> Hash.NixHash -> Bool+signedByOneOf keys claim narHash =+  any (\sig -> any (\key -> either (const False) (Signing.verify key fingerprinted) (TE.decodeUtf8' (renderSignature sig))) keys) (Set.toList (prSignatures claim))+  where+    -- The fields a path's fingerprint is made of, which is what its+    -- signatures sign; a narinfo's transport fields, which no signature+    -- covers, are empty.+    fingerprinted =+      NarInfo.NarInfo+        { NarInfo.niStorePath = storePathToText defaultStoreDir (prPath claim),+          NarInfo.niUrl = "",+          NarInfo.niCompression = "",+          NarInfo.niFileHash = Nothing,+          NarInfo.niFileSize = Nothing,+          NarInfo.niNarHash = Hash.formatNixHash narHash,+          NarInfo.niNarSize = toInteger (prNarSize claim),+          NarInfo.niReferences = map storePathBasename (prReferences claim),+          NarInfo.niDeriver = Nothing,+          NarInfo.niSigs = [],+          NarInfo.niCA = Nothing+        }++-- | Whether a claim may be registered as it lies on disk: its content+-- address, if it states one, makes its path ('addressRegistrable'), and a+-- derivation's outputs are the paths its inputs make.+registrable :: Store -> PathRegistration -> IO (Either Text ())+registrable store claim = do+  addressed <- maybe (pure (Right ())) (addressRegistrable (stLogger store) sp (prReferences claim)) (prContentAddress claim)+  case addressed of+    Left refusal -> pure (Left refusal)+    Right ()+      | isDerivation sp -> either (pure . Left) (checkDerivationOutputs (stDir store) sp) =<< readDerivationAt (stDir store) sp+      | otherwise -> pure (Right ())+  where+    sp = prPath claim++-- ---------------------------------------------------------------------------+-- Adding a text+-- ---------------------------------------------------------------------------++-- | Add a text, with the store paths it references, as the path its+-- SHA-256 and its name make, and answer the path, as upstream adds a+-- text, which is how a client writes a @.drv@.  A valid path is+-- passed over.  Otherwise, under the path's lock, the text is written at+-- the path, its metadata made canonical, a derivation held to its outputs+-- ('checkDerivationOutputs'), and it is registered with its text address; a+-- refusal removes it.  The references must be valid.  A store upstream+-- Nix's database may also manage is refused before anything is written+-- ("Nix.Store.Upstream").+addTextToStore :: Store -> Text -> BS.ByteString -> [StorePath] -> IO (Either Text StorePath)+addTextToStore store name contents refs = runExceptT $ do+  sp <- liftEither (either (Left . badStorePathText) Right (makeTextPath name digest refs))+  refusal <- liftIO (upstreamManagedRefusal ReplacesUpstreamPaths (stDir store))+  traverse_ throwError refusal+  let dest = storePathToFilePath (stDir store) sp+  ExceptT $ withPathLock (stLogger store) (stDir store) sp $ \_ -> do+    valid <- isValid store sp+    if valid+      then pure (Right ())+      else replacePath store sp $ do+        liftIO (BS.writeFile dest contents)+        liftIO (canonicalizeMetadata dest)+        when (isDerivation sp) $ do+          drv <- liftEither (parsedDerivation sp contents)+          ExceptT (checkDerivationOutputs (stDir store) sp drv)+        reg <- liftIO (registrationFor store sp Nothing refs)+        liftIO (registerPath (stDB store) reg {prContentAddress = contentAddressFromParts TextMethod sha256Algo digest})+  pure sp+  where+    digest = sha256Digest contents++-- ---------------------------------------------------------------------------+-- Derivations+-- ---------------------------------------------------------------------------++-- | Whether a derivation's outputs are the paths its inputs make, as+-- upstream checks a derivation it registers: a fixed output's path is the+-- one its hash makes, each output of any other the one the derivation's+-- masked modulo hash makes, its inputs' modulo hashes read from their+-- @.drv@ files in the store, and each output's environment variable+-- names its path.  The refusals are upstream's.  A derivation with+-- outputs that are neither, a floating content address or more than one+-- fixed output, is refused: nova-nix builds neither.+checkDerivationOutputs :: StoreDir -> StorePath -> Derivation -> IO (Either Text ())+checkDerivationOutputs dir sp drv = runExceptT $ do+  expected <- case fixedOutput drv of+    Just out -> liftEither (fixedOutputPaths out)+    Nothing+      | not (all (T.null . doHashAlgo) (drvOutputs drv)) ->+          throwError ("derivation '" <> storePathToText defaultStoreDir sp <> "' has outputs with content addresses nova-nix does not check")+      | otherwise -> do+          inputs <- evalStateT (inputModuloHashes dir drv) Map.empty+          made <- liftEither (either (Left . badStorePathText) Right (inputAddressed drvName inputs drv))+          pure (Map.fromList [(doName out, doPath out) | out <- drvOutputs (drvFileDerivation made)])+  for_ (drvOutputs drv) $ \out -> do+    let stated = doPath out+    for_ (Map.lookup (doName out) expected) $ \path ->+      unless (path == stated) $+        throwError ("derivation has incorrect output '" <> storePathToText defaultStoreDir stated <> "', should be '" <> storePathToText defaultStoreDir path <> "'")+    let pathText = storePathToText defaultStoreDir stated+    case Map.lookup (doName out) (drvEnv drv) of+      Nothing -> throwError ("derivation has missing environment variable '" <> doName out <> "', should be '" <> pathText <> "' but is not present")+      Just value+        | value /= TE.encodeUtf8 pathText ->+            throwError ("derivation has incorrect environment variable '" <> doName out <> "', should be '" <> pathText <> "' but is actually '" <> TE.decodeUtf8Lenient value <> "'")+        | otherwise -> pure ()+  where+    drvName = fromMaybe (spName sp) (T.stripSuffix drvExtension (spName sp))+    fixedOutputPaths out = case hexToBytes (doHash out) of+      Nothing -> Left ("derivation '" <> storePathToText defaultStoreDir sp <> "' has a malformed hash for output '" <> doName out <> "'")+      Just digest ->+        let (method, algo) = case T.stripPrefix "r:" (doHashAlgo out) of+              Just rest -> (NarIngestion, rest)+              Nothing -> (FlatIngestion, doHashAlgo out)+         in either (Left . badStorePathText) (Right . Map.singleton (doName out)) (makeFixedOutputPath drvName algo method digest)++-- | The modulo hash (hex) of each input derivation with the outputs taken+-- from it, in path order, as 'Nix.Derivation.inputAddressed' takes them,+-- each read from its @.drv@ file in the store, and each derivation hashed+-- once however many paths reach it.+inputModuloHashes :: StoreDir -> Derivation -> StateT (Map StorePath Text) (ExceptT Text IO) [(Text, [Text])]+inputModuloHashes dir drv = traverse (\(input, outs) -> (,outs) <$> moduloHashOf input) (Map.toList (drvInputDrvs drv))+  where+    moduloHashOf input = do+      known <- gets (Map.lookup input)+      case known of+        Just hex -> pure hex+        Nothing -> do+          inputDrv <- liftEither =<< liftIO (readDerivationAt dir input)+          hex <- case fixedOutputModulo inputDrv of+            Just modulo -> pure (bytesToHexText modulo)+            Nothing -> bytesToHexText . (`inputAddressedModulo` inputDrv) <$> inputModuloHashes dir inputDrv+          modify' (Map.insert input hex)+          pure hex++-- | The derivation a @.drv@ file in the store holds, or why it cannot be+-- read.+readDerivationAt :: StoreDir -> StorePath -> IO (Either Text Derivation)+readDerivationAt dir sp = do+  contents <- try (BS.readFile (storePathToFilePath dir sp))+  pure $ case contents of+    Left (failure :: IOException) -> Left ("cannot read derivation '" <> storePathToText defaultStoreDir sp <> "': " <> T.pack (displayException failure))+    Right bytes -> parsedDerivation sp bytes++-- | A derivation parsed from its file, or upstream's refusal.+parsedDerivation :: StorePath -> BS.ByteString -> Either Text Derivation+parsedDerivation sp bytes = either (\err -> Left ("error parsing derivation '" <> storePathToText defaultStoreDir sp <> "': " <> err)) Right (fromATerm bytes)++-- | Whether a store path names a derivation, by its name, as upstream+-- tells one.+isDerivation :: StorePath -> Bool+isDerivation sp = drvExtension `T.isSuffixOf` spName sp++-- | The algorithm a text address and a @source@ path hash with.+sha256Algo :: Text+sha256Algo = "sha256"
src/Nix/Store/Lock.hs view
@@ -44,7 +44,7 @@ -- anyway - needs no separate path.  The cost is one empty -- @\<store-path\>.lock@ per substituted or built path left beside it in -- the store directory; the files are inert debris, invisible to path--- queries (only exact store-path basenames resolve).  The one deleter+-- queries (no registration row names one).  The one deleter -- is the collector ("Nix.Store.GC"), which removes a lock file once the -- path it guards is no longer live, and may: it runs under the -- exclusive store-wide lock, when no process has the store open, and@@ -77,12 +77,13 @@ import Control.Exception (bracket) import Data.Text (Text) import qualified Data.Text as T+import Nix.Logger (Logger, logMessage) import Nix.Store.Path (StoreDir, StorePath, parseStorePathBaseName, storePathToFilePath) import System.FileLock (FileLock, SharedExclusive (..), lockFile, tryLockFile, unlockFile)-import System.IO (hPutStrLn, stderr) --- | An exclusive lock held on one store path: the lock file's path and--- the descriptor whose OS lock is the exclusion.  The descriptor sits+-- | A lock held on one lock file, exclusive on a store path's, or in its+-- 'LockMode' on one named directly: the lock file's path and the+-- descriptor whose OS lock it is.  The descriptor sits -- behind an 'MVar' so release is idempotent and thread-safe: a bracket -- and an explicit release can both fire on one lock without a -- double-close.@@ -116,21 +117,21 @@   pure stripped  -- | Take the exclusive lock on a store path, blocking until granted.--- Blocking is upstream's behavior on a busy path lock, announced the--- same way ('waitingForLockMessage') so a stalled substitution names--- what it is waiting for.  The non-blocking probe runs first, so the--- contended case announces itself before the wait begins; the lock--- file is created if absent, atomically at the open.-acquirePathLock :: StoreDir -> StorePath -> IO PathLock-acquirePathLock dir sp = acquireLockFile (pathLockFilePath dir sp)+-- Blocking is upstream's behavior on a busy path lock, announced to the+-- logger the same way ('waitingForLockMessage') so a stalled+-- substitution names what it is waiting for.  The non-blocking probe+-- runs first, so the contended case announces itself before the wait+-- begins; the lock file is created if absent, atomically at the open.+acquirePathLock :: Logger -> StoreDir -> StorePath -> IO PathLock+acquirePathLock logger dir sp = acquireLockFile logger (pathLockFilePath dir sp)  -- | Take the exclusive lock on a lock file named directly, blocking -- until granted.  The raw form exists for the delete path: deletion -- accepts basenames the current store-path name rules reject, so their -- lock files cannot be named through 'StorePath' - yet they must be the -- very files substituters of the same path contend on.-acquireLockFile :: FilePath -> IO PathLock-acquireLockFile lockPath = acquireLockFileWith LockExclusive (waitingForLockMessage lockPath) lockPath+acquireLockFile :: Logger -> FilePath -> IO PathLock+acquireLockFile logger lockPath = acquireLockFileWith logger LockExclusive (waitingForLockMessage lockPath) lockPath  -- | How a lock file is held.  Every per-path lock is exclusive; the -- store-wide garbage-collector lock is the one shared holder, taken@@ -140,17 +141,16 @@   deriving (Eq, Show)  -- | Take a directly named lock file in the given mode, blocking until--- granted.  The message is printed once, to stderr, when the lock is--- busy and the wait begins: the collector announces itself in--- upstream's words and a path lock in its own, so the caller supplies--- the line.-acquireLockFileWith :: LockMode -> String -> FilePath -> IO PathLock-acquireLockFileWith mode busyMessage lockPath = do+-- granted.  The message goes to the logger once, when the lock is busy+-- and the wait begins: the collector announces itself in upstream's+-- words and a path lock in its own, so the caller supplies the line.+acquireLockFileWith :: Logger -> LockMode -> Text -> FilePath -> IO PathLock+acquireLockFileWith logger mode busyMessage lockPath = do   probe <- tryLockFile lockPath (toSharedExclusive mode)   held <- case probe of     Just granted -> pure granted     Nothing -> do-      hPutStrLn stderr busyMessage+      logMessage logger busyMessage       lockFile lockPath (toSharedExclusive mode)   heldRef <- newMVar (Just held)   pure (PathLock lockPath heldRef)@@ -161,8 +161,8 @@ toSharedExclusive LockExclusive = Exclusive  -- | Upstream's log line for a busy path lock.-waitingForLockMessage :: FilePath -> String-waitingForLockMessage lockPath = "waiting for lock on '" <> lockPath <> "'..."+waitingForLockMessage :: FilePath -> Text+waitingForLockMessage lockPath = "waiting for lock on '" <> T.pack lockPath <> "'..."  -- | Take the exclusive lock only if it is free: 'Nothing' when another -- holder - this process's or another's - already has it.@@ -189,15 +189,15 @@       pure Nothing  -- | Run an action holding a path's lock, released on every exit.-withPathLock :: StoreDir -> StorePath -> (PathLock -> IO a) -> IO a-withPathLock dir sp = bracket (acquirePathLock dir sp) releasePathLock+withPathLock :: Logger -> StoreDir -> StorePath -> (PathLock -> IO a) -> IO a+withPathLock logger dir sp = bracket (acquirePathLock logger dir sp) releasePathLock  -- | Run an action holding a directly named lock file's lock, released -- on every exit.  See 'acquireLockFile' for why the raw form exists.-withLockFile :: FilePath -> (PathLock -> IO a) -> IO a-withLockFile lockPath = bracket (acquireLockFile lockPath) releasePathLock+withLockFile :: Logger -> FilePath -> (PathLock -> IO a) -> IO a+withLockFile logger lockPath = bracket (acquireLockFile logger lockPath) releasePathLock  -- | 'withLockFile' in a chosen mode with a chosen busy message.-withLockFileWith :: LockMode -> String -> FilePath -> (PathLock -> IO a) -> IO a-withLockFileWith mode busyMessage lockPath =-  bracket (acquireLockFileWith mode busyMessage lockPath) releasePathLock+withLockFileWith :: Logger -> LockMode -> Text -> FilePath -> (PathLock -> IO a) -> IO a+withLockFileWith logger mode busyMessage lockPath =+  bracket (acquireLockFileWith logger mode busyMessage lockPath) releasePathLock
+ src/Nix/Store/Metadata.hs view
@@ -0,0 +1,542 @@+{-# LANGUAGE CPP #-}++-- | A store path's metadata, made canonical when the path is added to the+-- store.+--+-- Upstream gives every file of a path it adds one form+-- (@canonicalisePathMetaData@ in posix-fs-canonicalise.cc and+-- @setWriteTime@ in file-system.cc, at 2.24.9): a file or directory whose+-- mode is anything but @0444@ or @0555@ is set to @0444@, or @0555@ when+-- its owner may execute it, which drops the write, setuid, setgid and+-- sticky bits; every node's modification time is set to 1, a second past+-- the epoch, a symlink's own included, through @lutimes@, while its access+-- time keeps its whole seconds; and a node another user owns is given to+-- the process's effective user and group.  A symlink's mode is never+-- changed, and a node that is not a regular file, a directory or a symlink+-- fails the path.  A builder reading the path, and every user on the+-- machine, then sees the same tree whatever wrote it.  The executable flag+-- a NAR records is the owner's execute bit, which the canonical mode+-- keeps, so a path's NAR hash is the same before and after.+--+-- On Linux a node's extended attributes, its ACLs among them, are removed+-- first, as upstream removes them (@canonicalisePathMetaData_@ in+-- posix-fs-canonicalise.cc), but for those upstream's @ignored-acls@ names by+-- default, @security.selinux@, @system.nfs4_acl@ and @security.csm@, which+-- nova-nix does not read as a setting: a default ACL would otherwise leave+-- what is made beneath a directory writable by others whatever its mode says.+-- Upstream also clears a node's file flags on macOS (@lchflags@), which+-- nova-nix does not.  A build's output is checked before it is made+-- canonical: every node of it must belong to the user who wrote it, a build+-- user or the user nova-nix runs as ('foreignOwnedNode').+--+-- On Windows, where upstream sets no times and has no modes, every file+-- and directory is given the read-only attribute and the same+-- modification time.  A symlink keeps its attributes, and its own time+-- is set as on POSIX.  The attribute keeps a file from being written; on+-- a directory it does not stop an entry being added or removed, which+-- only an access control list can.  So every node, a symlink included,+-- is also given the store's service as its owner, as upstream gives a+-- node to the store's user, and a valid path's protected DACL+-- ('Nix.Store.Access.validPathSddl'), which lets no build account change+-- it.  An access control list is no part of a NAR, so a path's NAR hash+-- is the same before and after.+--+-- 'metadataChanges' decides what one node needs from what it reads of+-- it, without touching the filesystem, and 'canonicalizeMetadata' walks+-- a tree and makes the changes.  'isPlainFile' reads the form upstream+-- requires of an output with a flat hash.+module Nix.Store.Metadata+  ( -- * Canonicalizing a tree+    canonicalizeMetadata,++    -- * Reading a node+    isPlainFile,+    writableByOthers,+    OutputOwner (..),+    foreignOwnedNode,+    ownedByAnother,+    nodeModificationTime,++    -- * The canonical form+    NodeKind (..),+    Ownership (..),+    NodeMetadata (..),+    MetadataChange (..),+    metadataChanges,+    canonicalPermissions,+    readOnlyPermissions,+    executablePermissions,+    storeModificationTime,+  )+where++import Data.Int (Int64)+import Data.Word (Word32)++#if defined(mingw32_HOST_OS)++import Control.Exception (bracket, tryJust)+import Control.Monad (guard)+import Data.Bits (testBit, (.&.), (.|.))+import Data.Foldable (traverse_)+import Nix.Store.Access (ValidNode (..), withValidPathAccess)+import qualified Nix.Store.ExecBit as ExecBit+import Nix.Store.Symlink (WalkNode (..), classifyWalkNode)+import Nix.Store.Win32Path (win32FilePath)+import qualified System.Directory as Dir+import System.FilePath ((</>))+import System.IO.Error (doesNotExistErrorType, ioeSetFileName, isDoesNotExistError, mkIOError, modifyIOError)+import System.Win32.File+  ( FileAttributeOrFlag,+    closeHandle,+    createFile,+    fILE_FLAG_BACKUP_SEMANTICS,+    fILE_SHARE_DELETE,+    fILE_SHARE_READ,+    fILE_SHARE_WRITE,+    fILE_ATTRIBUTE_DIRECTORY,+    fILE_WRITE_ATTRIBUTES,+    getFileAttributes,+    gENERIC_READ,+    oPEN_EXISTING,+  )+import System.Win32.Time (FILETIME (..), getFileTime, setFileTime)++#else++import Control.Monad (when)+import Data.Bits (complement, testBit, (.&.), (.|.))+import Data.Foldable (traverse_)+import Foreign.C.Types (CTime (..))+#if defined(linux_HOST_OS)+import Control.Monad (unless)+import qualified Data.ByteString as BS+import Data.Foldable (for_)+import Foreign.C.Error (eNODATA, eNOTSUP, getErrno, throwErrnoPath, throwErrnoPathIfMinus1, throwErrnoPathIfMinus1_)+import Foreign.C.String (CString)+import Foreign.C.Types (CInt (..), CSize (..))+import Foreign.Marshal.Alloc (allocaBytes)+import Foreign.Ptr (nullPtr)+import qualified GHC.Foreign as GHC+import GHC.IO.Encoding (getFileSystemEncoding)+import System.Posix.Types (CSsize (..))+#endif+import System.Directory (listDirectory)+import System.FilePath ((</>))+import System.Posix.Files+  ( FileStatus,+    accessTime,+    fileMode,+    fileOwner,+    fileTypeModes,+    getSymbolicLinkStatus,+    groupWriteMode,+    otherWriteMode,+    isDirectory,+    isRegularFile,+    isSymbolicLink,+    modificationTime,+    ownerExecuteMode,+    ownerReadMode,+    setFileMode,+    setSymbolicLinkOwnerAndGroup,+    setSymbolicLinkTimesHiRes,+  )+import System.Posix.Types (GroupID, UserID)+import System.Posix.User (getEffectiveGroupID, getEffectiveUserID)++#endif++-- ---------------------------------------------------------------------------+-- The canonical form+-- ---------------------------------------------------------------------------++-- | What a node of a tree is, read without following a symlink.+data NodeKind = RegularNode | DirectoryNode | SymlinkNode+  deriving (Eq, Show)++-- | Whether a node belongs to the process's effective user.+data Ownership = OwnedByProcess | OwnedByOther+  deriving (Eq, Show)++-- | What canonicalization reads of one node.+data NodeMetadata = NodeMetadata+  { -- | The node's kind.+    nmKind :: !NodeKind,+    -- | Its mode below the file type: the permission, setuid, setgid+    -- and sticky bits.+    nmPermissions :: !Word32,+    -- | Its modification time, in whole seconds since the epoch.+    nmModificationTime :: !Int64,+    -- | Who owns it.+    nmOwnership :: !Ownership+  }+  deriving (Eq, Show)++-- | One change canonicalization makes to a node, in the order upstream+-- makes them.+data MetadataChange+  = -- | Set the node's mode to these bits.+    SetPermissions !Word32+  | -- | Set the node's modification time to 'storeModificationTime',+    -- keeping its access time's whole seconds.+    SetModificationTime+  | -- | Give the node to the process's effective user and group.+    TakeOwnership+  deriving (Eq, Show)++-- | The changes that make one node canonical, none for a node that+-- already is (@canonicalisePathMetaData_@ and+-- @canonicaliseTimestampAndPermissions@ in posix-fs-canonicalise.cc).+metadataChanges :: NodeMetadata -> [MetadataChange]+metadataChanges node = permissions <> time <> ownership+  where+    permissions = case nmKind node of+      SymlinkNode -> []+      _+        | nmPermissions node `elem` [readOnlyPermissions, executablePermissions] -> []+        | otherwise -> [SetPermissions (canonicalPermissions (nmPermissions node))]+    time = [SetModificationTime | nmModificationTime node /= storeModificationTime]+    ownership = case nmOwnership node of+      OwnedByProcess -> []+      OwnedByOther -> [TakeOwnership]++-- | The canonical mode for a node's current one: 'executablePermissions'+-- when its owner may execute it, 'readOnlyPermissions' otherwise.+canonicalPermissions :: Word32 -> Word32+canonicalPermissions perms+  | testBit perms ownerExecuteBit = executablePermissions+  | otherwise = readOnlyPermissions++-- | A canonical node its owner may not execute: @0444@.+readOnlyPermissions :: Word32+readOnlyPermissions = 0o444++-- | A canonical node its owner may execute: @0555@.+executablePermissions :: Word32+executablePermissions = 0o555++-- | The bit of a mode that lets its owner execute the node (@S_IXUSR@).+ownerExecuteBit :: Int+ownerExecuteBit = 6++-- | Every store node's modification time, in seconds since the epoch:+-- upstream's @mtimeStore@ in posix-fs-canonicalise.cc.+storeModificationTime :: Int64+storeModificationTime = 1++-- ---------------------------------------------------------------------------+-- Canonicalizing a tree+-- ---------------------------------------------------------------------------++-- | Make every node of a tree canonical, the root included, without+-- following a symlink.  On POSIX a node that cannot be read or changed+-- fails with the 'Control.Exception.IOException' the system call raised,+-- and one of a type a store path cannot hold fails too; on Windows a node+-- the walk finds absent is passed over, and one whose attributes it+-- cannot read fails, naming it.+canonicalizeMetadata :: FilePath -> IO ()++-- | Whether a node is a regular file its owner may not execute, read+-- without following a symlink: what upstream requires of an output with+-- a flat hash, a node whose @lstat@ has @S_ISREG@ and no @S_IXUSR@+-- (@registerOutputs@ in local-derivation-goal.cc at 2.24.9,+-- derivation-builder-impl.cc at 2.36.0).  On Windows, which has no mode, the+-- owner may execute a file that carries the exec stream+-- ("Nix.Store.ExecBit").  A node that is not there fails with the+-- 'Control.Exception.IOException' raised.+isPlainFile :: FilePath -> IO Bool++-- | Whether a node lets its group or anyone else write it, read without+-- following a symlink, which is never writable: upstream's test of a+-- build's output before it makes the output canonical, since such a node+-- may have been changed by someone other than the build+-- (@registerOutputs@ in local-derivation-goal.cc at 2.24.9,+-- derivation-builder-impl.cc at 2.36.0).  Windows has no such mode, and no+-- node there is.+writableByOthers :: FilePath -> IO Bool++-- | Whom a build's output belongs to while its builder writes it.+data OutputOwner+  = -- | The user nova-nix runs as, as whom the builder ran.+    OwnedByInvoker+  | -- | The build user, by uid, as whom the builder ran.+    OwnedByBuildUser !Word32+  deriving (Eq, Show)++-- | The first node of a tree that does not belong to the output's owner,+-- read without following a symlink, the root first and a directory before+-- its entries, or nothing when the owner owns them all.  Upstream refuses+-- such a node in a build's output, @invalid ownership on file@, where it+-- builds as a build user: it may be a hard link to a file the output has+-- no business changing, which making the output canonical would change.+-- Where the owner is the user nova-nix runs as, a directory is given read+-- and search for its owner before it is listed, so one a builder closed is+-- read rather than refused.  That is a divergence: upstream makes such a+-- directory canonical first, at 0444 for one its owner may not search, and+-- a single-user build of it, not run as root, then fails to read beneath+-- it; here it ends at 0555, since a process that is not root can read a+-- directory only with search on it.  A build user's output is read by+-- root, who needs no mode to list a directory.  Windows has no owner to+-- compare, and finds none.+foreignOwnedNode :: OutputOwner -> FilePath -> IO (Maybe FilePath)++-- | Whether a node, read without following a symlink, belongs to a user+-- other than the build user who wrote it, upstream's other reason to+-- refuse an output as of suspicious ownership.  An output the user nova-nix+-- runs as wrote is never refused for its owner, as upstream checks the+-- owner only of a build user's.  Windows has no owner to compare.+ownedByAnother :: OutputOwner -> FilePath -> IO Bool++-- | A node's own modification time, in whole seconds since the epoch: a+-- symlink's own rather than its target's, as @lstat@ reads it.  A node+-- that is not there fails with the 'Control.Exception.IOException'+-- raised.+nodeModificationTime :: FilePath -> IO Int64++#if defined(mingw32_HOST_OS)++writableByOthers _ = pure False++foreignOwnedNode _ _ = pure Nothing++ownedByAnother _ _ = pure False++isPlainFile path = do+  node <- classifyWalkNode path+  case node of+    WalkRegular -> not <$> ExecBit.isExecutable path+    WalkDirectory -> pure False+    WalkSymlink -> pure False+    WalkAbsent -> ioError (mkIOError doesNotExistErrorType "isPlainFile" Nothing (Just path))++canonicalizeMetadata path = withValidPathAccess (`canonicalizeNode` path)++-- | Make a node canonical, given the step that gives one node of a kind+-- a valid path's owner and DACL.  A directory is done after its entries,+-- so nothing done to them comes after its own time is set, and its DACL,+-- protected, is set after theirs, so none of it is passed to them.+canonicalizeNode :: (ValidNode -> FilePath -> IO ()) -> FilePath -> IO ()+canonicalizeNode giveAccess path = do+  node <- registeredNode path+  case node of+    WalkSymlink -> setStoreTime path *> giveAccess ValidLeaf path+    WalkDirectory -> do+      Dir.listDirectory path >>= traverse_ (canonicalizeNode giveAccess . (path </>))+      sealNode (giveAccess ValidDirectory) path+    WalkRegular -> sealNode (giveAccess ValidLeaf) path+    WalkAbsent -> pure ()++-- | The kind of a node the walk registers, read from its own attributes,+-- a link not followed: any reparse point is a leaf, never descended into.+-- It is 'WalkAbsent' only where nothing has the name.  Any other failure+-- to read them, a refusal among them, fails naming the node, since a node+-- the walk passed over would keep whatever access its build gave it.+registeredNode :: FilePath -> IO WalkNode+registeredNode path =+  modifyIOError (`ioeSetFileName` path) $ do+    target <- win32FilePath path+    found <- tryJust (guard . isDoesNotExistError) (getFileAttributes target)+    pure $ case found of+      Left () -> WalkAbsent+      Right attributes+        | attributes .&. fileAttributeReparsePoint /= 0 -> WalkSymlink+        | attributes .&. fILE_ATTRIBUTE_DIRECTORY /= 0 -> WalkDirectory+        | otherwise -> WalkRegular++-- | @FILE_ATTRIBUTE_REPARSE_POINT@ (winnt.h): a link, or another reparse+-- point.+fileAttributeReparsePoint :: FileAttributeOrFlag+fileAttributeReparsePoint = 0x400++-- | Set a file's or directory's time, give it the read-only attribute,+-- then a valid path's owner and DACL.+sealNode :: (FilePath -> IO ()) -> FilePath -> IO ()+sealNode giveAccess path = do+  setStoreTime path+  perms <- Dir.getPermissions path+  Dir.setPermissions path (Dir.setOwnerWritable False perms)+  giveAccess path++-- | Set a node's own modification time to 'storeModificationTime'.  The+-- node is opened for its attributes alone, which its read-only attribute+-- and another process's open handle both allow, as a symlink itself+-- rather than its target, and with the flag a directory needs.+setStoreTime :: FilePath -> IO ()+setStoreTime path = do+  target <- win32FilePath path+  bracket (open target) closeHandle $ \handle ->+    setFileTime handle Nothing Nothing (Just storeFileTime)+  where+    open target =+      createFile+        target+        fILE_WRITE_ATTRIBUTES+        (fILE_SHARE_READ .|. fILE_SHARE_WRITE .|. fILE_SHARE_DELETE)+        Nothing+        oPEN_EXISTING+        (fILE_FLAG_BACKUP_SEMANTICS .|. fileFlagOpenReparsePoint)+        Nothing++-- | 'storeModificationTime' as a Windows file time.+storeFileTime :: FILETIME+storeFileTime = FILETIME (fromIntegral (unixEpochTicks + storeModificationTime * ticksPerSecond))++-- The node is opened as 'setStoreTime' opens it, as a symlink itself+-- rather than its target and with the flag a directory needs, for the+-- read access GetFileTime asks of a handle.  A time before the epoch+-- rounds down to its second, as a negative @st_mtime@ does.+nodeModificationTime path = do+  target <- win32FilePath path+  bracket (open target) closeHandle $ \handle -> do+    (_, _, FILETIME ticks) <- getFileTime handle+    pure ((fromIntegral ticks - unixEpochTicks) `div` ticksPerSecond)+  where+    open target =+      createFile+        target+        gENERIC_READ+        (fILE_SHARE_READ .|. fILE_SHARE_WRITE .|. fILE_SHARE_DELETE)+        Nothing+        oPEN_EXISTING+        (fILE_FLAG_BACKUP_SEMANTICS .|. fileFlagOpenReparsePoint)+        Nothing++-- | The Unix epoch as a Windows file time, which counts 100-nanosecond+-- ticks from 1601, and the ticks in a second.+unixEpochTicks, ticksPerSecond :: Int64+unixEpochTicks = 116444736000000000+ticksPerSecond = 10000000++-- | @FILE_FLAG_OPEN_REPARSE_POINT@ (winbase.h), which "System.Win32.File"+-- does not export: open a symlink rather than what it points to.+fileFlagOpenReparsePoint :: FileAttributeOrFlag+fileFlagOpenReparsePoint = 0x00200000++#else++isPlainFile path = do+  status <- getSymbolicLinkStatus path+  pure (isRegularFile status && not (testBit (fileMode status) ownerExecuteBit))++writableByOthers path = do+  status <- getSymbolicLinkStatus path+  pure (not (isSymbolicLink status) && fileMode status .&. (groupWriteMode .|. otherWriteMode) /= 0)++nodeModificationTime path = do+  status <- getSymbolicLinkStatus path+  let CTime seconds = modificationTime status+  pure seconds++foreignOwnedNode owner root = do+  user <- ownerID owner+  let walk path = getSymbolicLinkStatus path >>= visit path+      visit path status+        | fileOwner status /= user = pure (Just path)+        | isDirectory status = do+            when (owner == OwnedByInvoker) (openForOwner path status)+            listDirectory path >>= firstFound . map (walk . (path </>))+        | otherwise = pure Nothing+  walk root+  where+    firstFound [] = pure Nothing+    firstFound (look : rest) = look >>= maybe (firstFound rest) (pure . Just)+    openForOwner path status = do+      let mode = fileMode status+          openable = mode .|. ownerReadMode .|. ownerExecuteMode+      when (openable /= mode) (setFileMode path openable)++ownedByAnother owner path = case owner of+  OwnedByInvoker -> pure False+  OwnedByBuildUser uid -> (/= fromIntegral uid) . fileOwner <$> getSymbolicLinkStatus path++-- | The uid an output's owner has.+ownerID :: OutputOwner -> IO UserID+ownerID owner = case owner of+  OwnedByInvoker -> getEffectiveUserID+  OwnedByBuildUser uid -> pure (fromIntegral uid)++-- | Remove a node's extended attributes, read without following a link,+-- but for those upstream ignores by default, as+-- upstream removes them (@canonicalisePathMetaData_@ in+-- posix-fs-canonicalise.cc).  A filesystem that keeps none is no error.+-- Linux only, as upstream's is.+removeExtendedAttributes :: FilePath -> IO ()+#if defined(linux_HOST_OS)+removeExtendedAttributes path = do+  encoding <- getFileSystemEncoding+  GHC.withCString encoding path $ \cpath -> do+    size <- c_llistxattr cpath nullPtr 0+    if size < 0+      then do+        errno <- getErrno+        unless (errno == eNOTSUP || errno == eNODATA) (throwErrnoPath "querying extended attributes" path)+      else when (size > 0) $+        allocaBytes (fromIntegral size) $ \buffer -> do+          listed <- throwErrnoPathIfMinus1 "querying extended attributes" path (c_llistxattr cpath buffer (fromIntegral size))+          names <- BS.split 0 <$> BS.packCStringLen (buffer, fromIntegral listed)+          for_ [name | name <- names, not (BS.null name), name `notElem` keptAttributes] $ \name ->+            BS.useAsCString name $ \cname ->+              throwErrnoPathIfMinus1_ "removing extended attribute" path (c_lremovexattr cpath cname)++-- | The attributes upstream's @ignored-acls@ keeps by default, which even+-- root may be unable to remove (@ignoredAcls@ in globals.hh at 2.24.9,+-- local-settings.hh from 2.34.9).+keptAttributes :: [BS.ByteString]+keptAttributes = ["security.selinux", "system.nfs4_acl", "security.csm"]++foreign import ccall unsafe "sys/xattr.h llistxattr"+  c_llistxattr :: CString -> CString -> CSize -> IO CSsize++foreign import ccall unsafe "sys/xattr.h lremovexattr"+  c_lremovexattr :: CString -> CString -> IO CInt+#else+removeExtendedAttributes _ = pure ()+#endif++-- A directory is changed before its entries are read, as upstream+-- changes it, so one its owner may execute but not read becomes+-- readable first.+canonicalizeMetadata root = do+  user <- getEffectiveUserID+  group <- getEffectiveGroupID+  canonicalizeNode user group root++-- | Make one node canonical, then each entry of a directory.+canonicalizeNode :: UserID -> GroupID -> FilePath -> IO ()+canonicalizeNode user group path = do+  status <- getSymbolicLinkStatus path+  kind <- maybe (ioError (userError ("file '" <> path <> "' has an unsupported type"))) pure (statusKind status)+  removeExtendedAttributes path+  traverse_ (applyChange status) (metadataChanges (statusMetadata user kind status))+  case kind of+    DirectoryNode -> listDirectory path >>= traverse_ (canonicalizeNode user group . (path </>))+    RegularNode -> pure ()+    SymlinkNode -> pure ()+  where+    applyChange _ (SetPermissions perms) = setFileMode path (fromIntegral perms)+    applyChange status SetModificationTime =+      setSymbolicLinkTimesHiRes path (realToFrac (accessTime status)) (fromIntegral storeModificationTime)+    applyChange _ TakeOwnership = setSymbolicLinkOwnerAndGroup path user group++-- | A node's kind from its @lstat@, if it is one a store path may hold.+statusKind :: FileStatus -> Maybe NodeKind+statusKind status+  | isRegularFile status = Just RegularNode+  | isDirectory status = Just DirectoryNode+  | isSymbolicLink status = Just SymlinkNode+  | otherwise = Nothing++-- | What canonicalization reads of a node from its @lstat@.+statusMetadata :: UserID -> NodeKind -> FileStatus -> NodeMetadata+statusMetadata user kind status =+  NodeMetadata+    { nmKind = kind,+      nmPermissions = fromIntegral (fileMode status .&. complement fileTypeModes),+      nmModificationTime = seconds,+      nmOwnership = if fileOwner status == user then OwnedByProcess else OwnedByOther+    }+  where+    CTime seconds = modificationTime status++#endif
+ src/Nix/Store/Ops.hs view
@@ -0,0 +1,335 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE RankNTypes #-}++-- | The store a command works against, as a record of its operations:+-- what it holds, adding what an evaluation wrote, adding a tree by its+-- content, building, checking, and rooting an out-link, and whether+-- evaluation writes its trees in the store's directory or hands each to+-- the store ('EvalWrites').  A command runs over the record rather than+-- an open t'Nix.Store.Handle.Store', so it runs as well over a store+-- reached some other way ("Nix.Daemon.ClientStore" reaches one through a+-- daemon), and over a fake one in tests, in the pattern of+-- "Nix.Realise"'s 'Nix.Realise.RealiseEffects'.+--+-- 'withLocalStore' gives the operations of the store in a directory,+-- which it opens when an operation first needs it and closes once, when+-- the command is done with it.  'localQueries' answers what that store+-- holds for a session that only reads: it makes no store and writes no+-- row, though SQLite can make its wal-index files beside the database+-- ('Nix.Store.DB.openStoreDBReadOnly').+--+-- In a store upstream Nix's database also manages, nova-nix holds no+-- rows, so the queries count a path there as valid when its tree exists+-- and know no references for it ("Nix.Store.Upstream").  That holds until+-- validity there comes from the store's owner, through a client of+-- upstream's daemon.+module Nix.Store.Ops+  ( -- * The operations+    StoreQueries (..),+    StoreOps (..),+    EvalObjects (..),+    nothingToAdd,+    EvalWrites (..),+    MadeOps (..),+    EvalWrite (..),+    evalWriteContents,+    madeAnotherPath,+    BuildStop (..),+    stopReported,++    -- * The local store+    withLocalStore,+    localQueries,++    -- * Opening on first use+    withOpenedOnFirstUse,+  )+where++import Control.Concurrent.MVar (modifyMVarMasked, newMVar, swapMVar)+import Control.Exception (bracket, catch, displayException)+import Control.Monad (filterM)+import Data.ByteString (ByteString)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (isJust)+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import Nix.Builder (BuildConfig (..), BuildStop (..), SubstitutionAccess (..), buildRequests, checkStored, realiseWithoutWriting, stopReported)+import Nix.Logger (Logger)+import Nix.Store (Store (..), StoreDB, UpstreamHazard (..), addOutLinkRoot, addSourceTree, canonicalStoreDir, closeStore, closeStoreDB, dbFileName, isValidPath, materializeEvalSources, materializeEvalStoreWrites, metaDirName, openStore, openStoreDBReadOnly, queryReferences, storeTablesExist, upstreamManagedRefusal, writeDrvClosure)+import Nix.Store.Access (checkStateDirectory)+import Nix.Store.Path (StoreDir (..), StorePath, StoreWriteMode, defaultStoreDir, parseStorePath, storePathToFilePath, storePathToText)+import Nix.Store.Symlink (WalkNode (..), classifyWalkNode)+import qualified NovaCache.NAR as NAR+import System.Directory (doesFileExist)+import System.FilePath ((</>))+import System.IO.Error (illegalOperationErrorType, ioeSetErrorString, mkIOError)++-- ---------------------------------------------------------------------------+-- The operations+-- ---------------------------------------------------------------------------++-- | What a store answers about what it holds.+data StoreQueries m = StoreQueries+  { -- | Which of these paths are valid.+    sqValidPaths :: !(Set StorePath -> m (Set StorePath)),+    -- | The references the store records for a path, none for one it does+    -- not hold, failing on a recorded reference that names no store path.+    sqReferences :: !(StorePath -> m (Either Text (Set StorePath)))+  }++-- | What a command reads from, writes to and builds in a store.+data StoreOps m = StoreOps+  { -- | What the store holds, asked through the same handle as the+    -- operations below, so a store that is not there yet is made by the+    -- first question.+    soQueries :: !(StoreQueries m),+    -- | Add what an evaluation wrote or named, references first.  An add+    -- of nothing asks nothing of the store and so refuses nothing.+    --+    -- The local store ('withLocalStore') adds the sources, then the trees+    -- evaluation wrote, each passed over when it is valid, then every+    -- derivation, written unless its file already holds those bytes and+    -- registered again whether or not it was valid.  It says why it+    -- refuses before anything is written.  A source whose tree cannot be+    -- read is answered with the words of the access that failed, and what+    -- was added before it stays added.+    --+    -- A store reached through a daemon ("Nix.Daemon.ClientStore") has the+    -- trees evaluation wrote already, having taken each as it was made+    -- ('AddedAsMade'), and passes over 'eoStoreWrites'.  It sends each+    -- source it does not hold, then each derivation it does not hold,+    -- after every derivation and source it refers to, and stops at the+    -- first the daemon refuses or whose tree cannot be read, so what was+    -- sent before stays added.  A derivation the daemon holds is not sent+    -- again.+    soAddEvalObjects :: !(EvalObjects -> m (Either Text ())),+    -- | Add a tree, given as its NAR, as the path the NAR's SHA-256, a+    -- name and the store paths it references make, answering the path,+    -- or why it was refused ('Nix.Store.addSourceTree').+    soAddSourceTree :: !(Text -> Set StorePath -> NAR.NarEntry -> m (Either Text StorePath)),+    -- | Realise each derivation for the outputs a request names, with the+    -- message and status of a build that stops.+    soBuild :: !([(StorePath, Set Text)] -> m (Either BuildStop ())),+    -- | Check one derivation, every output of it, as @nova-nix build+    -- --check@ does, with the message and status of a check that stops.+    soCheck :: !(StorePath -> m (Either BuildStop ())),+    -- | Link a path to a store path and register the link as a root,+    -- answering the link as the root records it, or why it was refused.+    soAddOutLinkRoot :: !(FilePath -> StorePath -> m (Either Text FilePath)),+    -- | How the trees an evaluation writes reach this store.+    soEvalWrites :: !(EvalWrites m)+  }++-- | What an evaluation named or wrote in the store without registering+-- it, as its session records them ("Nix.Eval.IO"'s @EvalState@).+data EvalObjects = EvalObjects+  { -- | Each copy of a path value evaluation coerced, by its store path,+    -- with the path-value text of the tree evaluation read for it+    -- ('Nix.Store.materializeEvalSources').+    eoSources :: !(Map StorePath Text),+    -- | Each tree evaluation wrote, by its store path, with its+    -- references and the way its path was named+    -- ('Nix.Store.materializeEvalStoreWrites').  Evaluation records the+    -- ones an 'AddedAsMade' store took as they were made too, so they may+    -- be here, and such a store passes over them.+    eoStoreWrites :: !(Map Text ([StorePath], StoreWriteMode)),+    -- | Each derivation's ATerm, by its store path+    -- ('Nix.Store.writeDrvClosure').+    eoDerivations :: !(Map Text ByteString)+  }++-- | How the trees an evaluation writes reach a store.+data EvalWrites m+  = -- | Evaluation writes each tree into the store's directory as it makes+    -- it, and 'soAddEvalObjects' registers it later.+    WrittenInDirectory+  | -- | Evaluation hands each tree to the store as it makes it, for a+    -- store whose directory evaluation cannot write, and writes nothing+    -- itself.  Such a store passes over 'eoStoreWrites' in+    -- 'soAddEvalObjects', having taken each already.+    AddedAsMade !(MadeOps m)++-- | What a store that takes each tree as it is made gives evaluation.+data MadeOps m = MadeOps+  { -- | Add a tree and answer the path it made, which must be the one+    -- evaluation computed for it, or why the store refused.+    moAdd :: !(EvalWrite -> m (Either Text StorePath)),+    -- | Keep a path from collection, or say why it cannot.  Evaluation+    -- holds a path before it asks whether the store has it and relies on+    -- the answer without adding the path itself.  A store reached through+    -- a daemon holds it for the connection that took the request, so a+    -- connection that breaks and is replaced no longer holds it.+    moHold :: !(StorePath -> m (Either Text ()))+  }++-- | A tree evaluation made, as a store adds it.  Only a text refers to+-- other paths.+data EvalWrite+  = -- | A text, by name, with the paths it refers to and its bytes:+    -- 'Nix.Store.Path.WriteText'.+    TextWrite !Text !(Set StorePath) !ByteString+  | -- | A file, by name and bytes: 'Nix.Store.Path.WriteFlat'.+    FlatWrite !Text !ByteString+  | -- | A tree, by name and NAR: 'Nix.Store.Path.WriteRecursive'.+    NarWrite !Text !ByteString+  deriving (Eq, Show)++-- | The bytes a tree is made from: a text's or a file's, or the NAR.+evalWriteContents :: EvalWrite -> ByteString+evalWriteContents = \case+  TextWrite _ _ contents -> contents+  FlatWrite _ contents -> contents+  NarWrite _ contents -> contents++-- | What is said of a store that makes another path than the one computed+-- for an object, given the one made and the one computed.+madeAnotherPath :: StorePath -> StorePath -> Text+madeAnotherPath made computed = "the store added '" <> storePathToText defaultStoreDir made <> "' where '" <> storePathToText defaultStoreDir computed <> "' was computed"++-- ---------------------------------------------------------------------------+-- The local store+-- ---------------------------------------------------------------------------++-- | Run an action with the operations of the store in 'bcStoreDir'.  The+-- store is opened when an operation first needs it and closed once, when+-- the action ends, by returning or by an exception, so an action that+-- asks nothing of the store never opens it, and one handle serves every+-- operation ("Nix.Store.Handle" says why a process keeps one).  A build+-- and a check run under the configuration ('buildRequests',+-- 'checkStored'), whatever its 'bcMode' says.  The operations report+-- through the logger given.+--+-- An add, a build or a check in a store upstream Nix's database may also+-- manage is refused before the store is opened, since opening it would+-- make this store's database there ("Nix.Store.Upstream").  Under+-- 'RefuseSubstitution' a build there opens nothing and refuses only what+-- it would build ('realiseWithoutWriting'), so a substitution is refused+-- in upstream's read-only words first.  An add answers a source whose+-- tree cannot be read with the words of the access that failed, and its+-- other failures are those of 'Nix.Store.materializeEvalSources',+-- 'Nix.Store.materializeEvalStoreWrites' and 'Nix.Store.writeDrvClosure',+-- which throw.+withLocalStore :: Logger -> BuildConfig -> (StoreOps IO -> IO a) -> IO a+withLocalStore logger config action = withOpenedOnFirstUse (openStore logger dir) closeStore (action . localOps)+  where+    dir = bcStoreDir config+    refusing = upstreamManagedRefusal ReplacesUpstreamPaths dir+    localOps useStore =+      StoreOps+        { soQueries = queriesOf dir (\_ _ query -> useStore >>= query . stDB),+          soAddEvalObjects = \objects ->+            if nothingToAdd objects+              then pure (Right ())+              else refusing >>= maybe (unreadableRefused (useStore >>= (`addEvalObjects` objects))) (pure . Left),+          soAddSourceTree = \name refs entry -> refusing >>= maybe (useStore >>= \store -> addSourceTree store name refs entry) (pure . Left),+          soBuild = \requests ->+            refusing >>= \case+              Nothing -> useStore >>= \store -> buildRequests config store requests+              Just reason -> case bcSubstitution config of+                SubstituteFromCaches -> pure (Left (BuildStop reason 1))+                RefuseSubstitution -> realiseWithoutWriting logger config (heldIn (localQueries dir)) reason requests,+          soCheck = \drvPath -> building (\store -> checkStored config store drvPath),+          soAddOutLinkRoot = \link path -> useStore >>= \store -> addOutLinkRoot store link path,+          soEvalWrites = WrittenInDirectory+        }+      where+        building run = refusing >>= maybe (useStore >>= run) (pure . Left . (`BuildStop` 1))+        heldIn queries path = Set.member path <$> sqValidPaths queries (Set.singleton path)++-- | The queries of the store in a directory for a session that only+-- reads: each opens the store's database read-only for itself and closes+-- it ('openStoreDBReadOnly', which says what SQLite still creates beside+-- it).  A store with no database, or one whose database does not hold the+-- store's tables yet ('storeTablesExist'), answers that it holds nothing,+-- as upstream's read-only evaluation answers once it has made the tables+-- of a store that has none (the @LocalStore@ constructor in local-store.cc at+-- 2.24.9); neither the directory, its metadata, its database nor its+-- collector lock is ever made.  No lease is taken, so a collection may remove+-- a path a query answered for, which a later read then finds missing.+localQueries :: StoreDir -> StoreQueries IO+localQueries rawDir = queriesOf rawDir inDatabase+  where+    inDatabase dir none query = do+      present <- doesFileExist (unStoreDir dir </> metaDirName </> dbFileName)+      if present then bracket (openStoreDBReadOnly dir) closeStoreDB (\db -> storeTablesExist db >>= \ready -> if ready then query db else pure none) else pure none++-- | The queries of the store in a directory, each run against its+-- database through the given action, given the directory's canonical+-- spelling, which answers the value it is given when there is no database+-- to ask.  In a store upstream Nix's database also manages the database+-- is never opened (the module header says why), and the store's tree+-- answers instead, once the directories on the way to it pass the check+-- a database's open makes first ('checkStateDirectory').+queriesOf :: StoreDir -> (forall a. StoreDir -> a -> (StoreDB -> IO a) -> IO a) -> StoreQueries IO+queriesOf rawDir withDatabase =+  StoreQueries+    { sqValidPaths = \paths ->+        asked $ \dir upstreamManaged ->+          if upstreamManaged+            then do+              checkStateDirectory (unStoreDir dir </> metaDirName)+              Set.fromList <$> filterM (onDisk dir) (Set.toList paths)+            else withDatabase dir Set.empty (\db -> Set.fromList <$> filterM (isValidPath db) (Set.toList paths)),+      sqReferences = \path ->+        asked $ \dir upstreamManaged ->+          if upstreamManaged+            then pure (Right Set.empty)+            else withDatabase dir (Right Set.empty) (\db -> fmap Set.fromList . traverse (named dir) <$> queryReferences db path)+    }+  where+    asked query = do+      dir <- canonicalStoreDir rawDir+      upstreamManaged <- isJust <$> upstreamManagedRefusal ReplacesUpstreamPaths dir+      query dir upstreamManaged+    onDisk dir path = (/= WalkAbsent) <$> classifyWalkNode (storePathToFilePath dir path)+    named dir text = maybe (Left ("unparseable reference in store DB: " <> text)) Right (parseStorePath dir text)++-- | Whether an evaluation made nothing to add: no source, tree or+-- derivation.+nothingToAdd :: EvalObjects -> Bool+nothingToAdd objects = Map.null (eoSources objects) && Map.null (eoStoreWrites objects) && Map.null (eoDerivations objects)++-- | An add of objects answered, a source whose tree cannot be read+-- ('NAR.NarWalkError') being the failed access's words rather than an+-- exception, as a store reached through a daemon answers it.  What was+-- added before it stays added.  Any other failure of the add still+-- throws.+unreadableRefused :: IO () -> IO (Either Text ())+unreadableRefused add = (Right <$> add) `catch` (\err -> pure (Left (T.pack (displayException (err :: NAR.NarWalkError)))))++-- | Add an evaluation's objects to an open store, references first.+addEvalObjects :: Store -> EvalObjects -> IO ()+addEvalObjects store objects = do+  materializeEvalSources store (eoSources objects)+  materializeEvalStoreWrites store (eoStoreWrites objects)+  writeDrvClosure store (eoDerivations objects)++-- ---------------------------------------------------------------------------+-- Opening on first use+-- ---------------------------------------------------------------------------++-- | Where a resource opened on first use stands.+data Opening r = Unopened | Opened !r | Closed++-- | Run an action with a resource opened on first use.  The action is+-- given an action that opens the resource the first time it runs and+-- answers the same one after.  When the action ends, by returning or by+-- an exception, the resource is closed once if it was opened, and a use+-- after that fails with an illegal-operation 'IOError', as a closed+-- handle's does.  The opening runs with asynchronous exceptions masked,+-- as 'bracket' runs its acquisition, so a resource that opens is closed.+withOpenedOnFirstUse :: IO r -> (r -> IO ()) -> (IO r -> IO a) -> IO a+withOpenedOnFirstUse open close action = bracket (newMVar Unopened) release (action . use)+  where+    use opening = modifyMVarMasked opening $ \case+      Unopened -> (\resource -> (Opened resource, resource)) <$> open+      Opened resource -> pure (Opened resource, resource)+      Closed -> ioError (ioeSetErrorString (mkIOError illegalOperationErrorType "withOpenedOnFirstUse" Nothing Nothing) "used after it was closed")+    release opening =+      swapMVar opening Closed >>= \case+        Opened resource -> close resource+        _ -> pure ()
src/Nix/Store/Path.hs view
@@ -12,8 +12,10 @@ -- @C:\\nix\\store\\\<hash\>-\<name\>@ -- -- The store is IMMUTABLE.  Once a path is registered, it never changes.--- This is enforced by making the store directory read-only after builds.--- This immutability is what enables:+-- Each path's files and directories are made read-only as the path is+-- added ("Nix.Store.Metadata"); the store directory itself stays+-- writable, so paths can be added and removed.  This immutability is+-- what enables: -- -- * Atomic upgrades (install new version, switch symlink, done) -- * Rollbacks (old version still in store, just switch symlink back)@@ -42,9 +44,12 @@     StoreWriteMode (..),     storePathToFilePath,     storePathToText,+    storePathBasename,     isCanonicalStoreText,+    isInStoreText,     storeTextToFilePath,     qualifyPathText,+    storeDirDrive,     parseStorePath,     parseStorePathPrefix,     parseStorePathBaseName,@@ -107,15 +112,24 @@ -- | Convert a t'StorePath' to a full filesystem path under a t'StoreDir'. storePathToFilePath :: StoreDir -> StorePath -> FilePath storePathToFilePath (StoreDir dir) sp =-  dir </> T.unpack (spHash sp <> "-" <> spName sp)+  dir </> T.unpack (storePathBasename sp) --- | Convert a t'StorePath' to canonical 'Text' with forward slashes.--- Unlike 'storePathToFilePath', this always uses @\/@ as the separator,--- making it safe for ATerm serialization and cross-platform round-trips.+-- | Convert a t'StorePath' to 'Text' under a store directory, joined by+-- @\/@ whatever the platform; the directory keeps its own spelling.+-- Unlike 'storePathToFilePath', the result under 'defaultStoreDir' is the+-- canonical text, safe for ATerm serialization and cross-platform+-- round-trips. storePathToText :: StoreDir -> StorePath -> Text storePathToText (StoreDir dir) sp =-  T.pack dir <> "/" <> spHash sp <> "-" <> spName sp+  T.pack dir <> "/" <> storePathBasename sp +-- | A t'StorePath' with no store directory, @\<hash\>-\<name\>@: what+-- upstream's @StorePath::to_string@ gives, the form a narinfo's+-- @References@ and @Deriver@ fields hold, and how upstream's messages name+-- a derivation where they do not print the whole path.+storePathBasename :: StorePath -> Text+storePathBasename sp = spHash sp <> "-" <> spName sp+ -- | Whether path text lies under the canonical store dir: exactly -- @\/nix\/store@, or @\/nix\/store@ followed by a separator of either -- spelling.  This is the spelling writers put into eval-visible values.@@ -126,6 +140,15 @@     Just (c, _) -> c == '/' || c == '\\'   Nothing -> False +-- | Whether path text names something in the canonical store dir, as+-- upstream's @isInStore@ asks: the store dir followed by a separator and+-- at least one more character, so not the store dir itself+-- (@isInDir@ in file-system.cc).+isInStoreText :: Text -> Bool+isInStoreText txt = case T.stripPrefix defaultStoreDirText txt >>= T.uncons of+  Just (separator, rest) -> (separator == '/' || separator == '\\') && not (T.null rest)+  Nothing -> False+ -- | Resolve path-value text to the filesystem location it names: text -- under the canonical store dir resolves into the given store dir, and -- every other path is 'qualifyPathText' of it.  Writers emit the@@ -135,9 +158,8 @@ -- otherwise resolve against the working drive. -- -- The store dir is a parameter rather than 'platformStoreDir' because a--- caller may have been given one: resolving reads against the platform--- default while writes went elsewhere is how @--store@ came to write to--- one directory and read from another.+-- caller may have been given one (@--store@): reads resolve against the+-- directory the writes go to, not the platform default. storeTextToFilePath :: StoreDir -> Text -> FilePath storeTextToFilePath storeDir txt   | isCanonicalStoreText txt =
src/Nix/Store/Symlink.hs view
@@ -56,8 +56,8 @@ -- kind: the target is resolved relative to the link's directory (an -- absolute target resolves to itself) and probed once.  A creation -- failure is loud rather than approximated: writing the target text as a--- regular file once registered a tree whose NAR hash differed from the--- signed narinfo's, silent store corruption that a later push refused to+-- regular file would register a tree whose NAR hash differs from the+-- signed narinfo's, silent store corruption that a later push refuses to -- publish.  A name already taken is refused in upstream's words, as a -- folded sibling or a raced root meets it. -- The parent directory is not created here; a caller that wants that
+ src/Nix/Store/Upstream.hs view
@@ -0,0 +1,156 @@+-- | A store directory upstream Nix also manages.+--+-- Upstream registers its paths in its own database and keeps its roots+-- under its own state directory, so in a directory upstream also uses,+-- a path upstream registered has no row in this store's database.  Every+-- operation that takes a tree with no row for its own debris would take+-- such a path for one: the collector and the checked delete would delete+-- it ("Nix.Store.GC"), and a build, a substitution, the restore of+-- evaluation's sources and an evaluation's own store write would clear+-- it and write their own tree in its place.  An evaluation's write+-- clears only a tree that does not reproduce its address, but which+-- tree that is depends on how the names on disk are read, and upstream+-- may be writing the path at that moment.  Each of these operations+-- refuses, before it touches anything, a store whose+-- directory, as spelled or as its links resolve, has upstream's database+-- where upstream's local store keeps it ('upstreamDatabasePath'):+-- @\/nix\/var\/nix\/db\/db.sqlite@ for @\/nix\/store@.  They refuse, too,+-- when that path cannot be examined.  An upstream whose state directory+-- is moved (@NIX_STATE_DIR@, or a build configured with another one) and+-- a store reached through a bind mount are not recognised.+--+-- The look runs as each such operation starts, not when the store is+-- opened or an evaluation begins: a handle on such a store still lists+-- its roots and pushes its paths, and an evaluation that writes nothing+-- still evaluates, none of which changes a path in it.+module Nix.Store.Upstream+  ( UpstreamHazard (..),+    upstreamManagedRefusal,+    upstreamDatabasePath,+    upstreamStateDir,+  )+where++import Control.Exception (IOException, displayException, try)+import Data.List (isSuffixOf)+import Data.Maybe (catMaybes, listToMaybe, mapMaybe)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import Nix.Store.Path (StoreDir (..))+import System.Directory (canonicalizePath, getPermissions)+import System.FilePath (dropTrailingPathSeparator, splitDirectories, takeDirectory, (</>))+import System.IO.Error (isDoesNotExistError)++-- ---------------------------------------------------------------------------+-- Layout+-- ---------------------------------------------------------------------------++-- | The state directory upstream Nix would keep for a store in this+-- directory, when the directory is one upstream's local store uses:+-- @\/nix\/var\/nix@ for @\/nix\/store@, unless @NIX_STATE_DIR@ or the+-- build moves it, and for a store opened with a root,+-- @\<root\>\/nix\/store@, @\<root\>\/nix\/var\/nix@.+upstreamStateDir :: FilePath -> Maybe FilePath+upstreamStateDir dir+  | upstreamStoreDirTail `isSuffixOf` splitDirectories trimmed = Just (takeDirectory trimmed </> upstreamStateRelPath)+  | otherwise = Nothing+  where+    trimmed = dropTrailingPathSeparator dir++-- | The database upstream Nix would keep for a store in this directory:+-- @db\/db.sqlite@ in its state directory ('upstreamStateDir').+upstreamDatabasePath :: FilePath -> Maybe FilePath+upstreamDatabasePath dir = (</> upstreamDatabaseRelPath) <$> upstreamStateDir dir++-- | The last two components of every directory upstream's local store+-- keeps a store in.+upstreamStoreDirTail :: [FilePath]+upstreamStoreDirTail = ["nix", "store"]++-- | Upstream's state directory, relative to the directory that holds its+-- store.+upstreamStateRelPath :: FilePath+upstreamStateRelPath = "var" </> "nix"++-- | Upstream's database, relative to its state directory.+upstreamDatabaseRelPath :: FilePath+upstreamDatabaseRelPath = "db" </> "db.sqlite"++-- ---------------------------------------------------------------------------+-- The refusal+-- ---------------------------------------------------------------------------++-- | What a refused operation would do to the paths upstream registers,+-- which its refusal names.+data UpstreamHazard+  = -- | Delete them as unregistered trees: a collection or a checked+    -- delete, which read this store's roots and not upstream's.+    DeletesUpstreamPaths+  | -- | Clear them as unregistered leftovers and write its own trees in+    -- their place: a build, a substitution, the restore of evaluation's+    -- sources or an evaluation's own store write.+    ReplacesUpstreamPaths+  deriving (Eq, Show)++-- | Why an operation on this store directory is refused, or 'Nothing'+-- when it may go ahead: upstream's database exists for the directory as+-- spelled or as its links resolve ('upstreamDatabasePath'), or such a+-- path cannot be examined.  The look reads nothing of the store itself,+-- so a caller runs it before taking any lock.+upstreamManagedRefusal :: UpstreamHazard -> StoreDir -> IO (Maybe Text)+upstreamManagedRefusal hazard (StoreDir dir) = do+  resolved <- canonicalizePath dir+  found <- traverse probe (Set.toList (Set.fromList (mapMaybe upstreamDatabasePath [dir, resolved])))+  pure (listToMaybe (catMaybes found))+  where+    -- On POSIX getPermissions stats the path, and on Windows it opens it+    -- with no access rights, so a database this user cannot read refuses+    -- the store, as present or as unexaminable.+    probe db = do+      probed <- try (getPermissions db)+      pure $ case probed of+        Left err+          | isDoesNotExistError err -> Nothing+          | otherwise -> Just (upstreamUnknownMessage hazard dir db err)+        Right _ -> Just (upstreamManagedMessage hazard dir db)++-- ---------------------------------------------------------------------------+-- Messages+-- ---------------------------------------------------------------------------++-- | The refusal of a store upstream Nix's database also manages.+upstreamManagedMessage :: UpstreamHazard -> FilePath -> FilePath -> Text+upstreamManagedMessage hazard dir db =+  "upstream Nix's database '"+    <> T.pack db+    <> "' also manages the store '"+    <> T.pack dir+    <> "': the paths it registers have no row in this store's database"+    <> unreadRoots hazard+    <> ", so nova-nix would "+    <> hazardVerb hazard+    <> " those paths as unregistered"+  where+    unreadRoots DeletesUpstreamPaths = " and the roots it keeps are not read"+    unreadRoots ReplacesUpstreamPaths = ""++-- | The refusal of a store when upstream Nix's database cannot be looked+-- for.+upstreamUnknownMessage :: UpstreamHazard -> FilePath -> FilePath -> IOException -> Text+upstreamUnknownMessage hazard dir db err =+  "cannot tell whether upstream Nix's database '"+    <> T.pack db+    <> "' manages the store '"+    <> T.pack dir+    <> "' ("+    <> T.pack (displayException err)+    <> "): if it does, nova-nix would "+    <> hazardVerb hazard+    <> " the paths it registers as unregistered"++-- | What the refused operation would do to upstream's paths, as the+-- refusal words it.+hazardVerb :: UpstreamHazard -> Text+hazardVerb DeletesUpstreamPaths = "delete"+hazardVerb ReplacesUpstreamPaths = "replace"
+ src/Nix/Store/Win32Path.hs view
@@ -0,0 +1,28 @@+-- | A path as the store's direct Win32 calls hand it to CreateFileW.+-- Built on Windows only: the POSIX store opens through @unix@, which+-- takes a path as it is.+module Nix.Store.Win32Path+  ( win32FilePath,+  )+where++import Data.List (isPrefixOf)+import System.Win32.Info (getFullPathName)++-- | The Win32 file-namespace spelling of a path (@\\\\?\\@), which+-- CreateFileW takes past MAX_PATH.  @base@ converts every path it+-- opens to this form, under either I\/O manager+-- (@__hs_create_device_name@ in GHC's utils\/fs\/fs.c), so a raw+-- CreateFileW without it would refuse long paths @base@ accepts.  The+-- namespace form is taken literally, so separators, @.@ and @..@ are+-- resolved first by GetFullPathNameW, as that conversion does.+win32FilePath :: FilePath -> IO FilePath+win32FilePath path+  | any (`isPrefixOf` path) namespacePrefixes = pure path+  | otherwise = toNamespace <$> getFullPathName path+  where+    namespacePrefixes = [fileNamespace, "\\\\.\\", "\\??\\"]+    toNamespace full = case full of+      '\\' : '\\' : share -> fileNamespace <> "UNC\\" <> share+      _ -> fileNamespace <> full+    fileNamespace = "\\\\?\\"
src/Nix/Substituter.hs view
@@ -9,1151 +9,1553 @@ -- 2. @GET https:\/\/cache.example.com\/\<hash\>.narinfo@ -- 3. If 200: parse the narinfo (NAR hash, size, references, signature) -- 4. Validate the narinfo's fields, then verify the signature against a---    trusted public key--- 5. @GET https:\/\/cache.example.com\/nar\/\<narhash\>.nar.xz@ and, in---    one bounded streaming pass, decompress, hash, parse, and unpack---    into the store path--- 6. Verify the declared NAR hash and size against the streamed bytes,---    then re-verify the materialized tree from disk--- 7. Register in the store DB with references from narinfo------ A cache that lacks the path (404, or another status upstream reads as--- the file not being there) is passed over, and what no cache holds--- builds locally.  A cache that fails is told apart from one that lacks--- the path, as upstream tells them apart: a failed narinfo query and a--- substitute that fails to arrive stop the build, unless--- 'Nix.Realise.BuildFromSource' (upstream's @fallback@) says to build--- instead ("Nix.Realise").------ The whole sequence runs under an exclusive per-path lock--- ("Nix.Store.Lock"), upstream's pathlocks protocol: taken before any--- deletion or download, validity re-checked under it (another process's--- finished path is adopted without touching disk), and held until the--- caller's registration transaction commits.------ == Cache priority------ Multiple caches can be configured, checked in priority order:------ @--- substituters = https:\/\/cache.novavero.ai https:\/\/cache.nixos.org--- trusted-public-keys = cache.novavero.ai-1:... cache.nixos.org-1:...--- @------ Our nova-cache server implements this protocol.  The narinfo format,--- NAR serialization, signature verification - all handled by the--- @nova-cache@ library.  This module orchestrates the HTTP requests--- and store registration.-module Nix.Substituter-  ( -- * Substitution-    SubstResult (..),-    trySubstitute,-    trySubstituteWith,-    queryReferencesWith,--    -- * Cache configuration-    CacheConfig (..),-    defaultCacheConfig,--    -- * Failure classification-    AttemptFailure (..),-    attemptFailureMessage,-    catchSync,-    compressedBodyCeiling,-    downloadCapFor,--    -- * Verified NAR bytes-    VerifiedNar,-    verifyNar,-    verifiedNarBytes,-    verifiedNarDigest,--    -- * Pure helpers (exported for testing)-    maxNarInfoBody,-    readBodyCapped,-    sortCaches,-    tryCachesWith,-    validateNarInfoFields,-    NarInfoAnswer (..),-    judgeNarInfo,-    verifySigs,-    verifyNarHash,-    verifyNarSize,-    narInfoMatchesPath,-    decompressorFor,-    decompressNar,-    streamingDecompressionSupported,-    withDecompressedSource,-    cappedBodySource,-    materializeNarFromSource,-    consumeNarStream,-    unpackAndVerify,-    clearStaleDestination,-    parseReferences,-    parseDeriver,-  )-where--import Control.Applicative ((<|>))-import Control.Exception (Exception, Handler (..), SomeException, catch, catches, onException, throwIO)-import Control.Monad (void)-import qualified Data.ByteString as BS-import Data.IORef (newIORef, readIORef, writeIORef)-import Data.List (sortBy)-import Data.Ord (comparing)-import Data.Text (Text)-import qualified Data.Text as T-import qualified Data.Text.Encoding as TE-import qualified Data.Text.IO as TIO-import Data.Word (Word64)-import qualified Network.HTTP.Client as HTTP-import qualified Network.HTTP.Client.TLS as HTTPS-import qualified Network.HTTP.Types.Status as HTTP-import Nix.Compression (NarCompression (..), parseNarCompression)-import Nix.Http (AttemptFailure (..), FetchRetryPolicy, RetryEffects, TransferError (..), attemptFailureMessage, catchSync, defaultFetchRetryPolicy, fetchStatusFailure, ioRetryEffects, retryTransient, statusError, transferFailureHandlers, withTransfer, withUserAgent)-import Nix.Realise (Fallback (..), Offer (..))-import Nix.Store (CaseSensitivity, NarStreamFailure (..), PathLock, Store (..), abortNarUnpack, acquirePathLock, finishNarUnpack, isValid, newNarUnpackSink, releasePathLock, setReadOnly, sinkNarStream, unpackNarEntry, volumeCaseHack)-import Nix.Store.DB (PathRegistration (..))-import qualified Nix.Store.ExecBit as ExecBit-import Nix.Store.Path (StoreDir, StorePath (spHash, spName), parseStorePathBaseName, storePathHashLen, storePathToFilePath)-import qualified NovaCache.Bzip2 as Bzip2-import qualified NovaCache.Hash as Hash-import qualified NovaCache.NAR as NAR-import qualified NovaCache.NarInfo as NarInfo-import qualified NovaCache.Signing as Signing-import qualified NovaCache.Validate as Validate-import qualified NovaCache.Xz as Xz-import qualified NovaCache.Zstd as Zstd-import qualified System.Directory as Dir-import System.IO (stderr)---- ------------------------------------------------------------------------------ Types--- ------------------------------------------------------------------------------- | Configuration for a binary cache.-data CacheConfig = CacheConfig-  { -- | Base URL of the cache (e.g. @https:\/\/cache.novavero.ai@).-    ccUrl :: !Text,-    -- | Trusted public keys (@name:base64key@).  A narinfo is accepted-    -- when ANY of them verifies a signature, matching upstream's flat-    -- @trusted-public-keys@ set: the keys are not bound to a particular-    -- substituter, and one signed by any trusted key is enough.-    ccPublicKeys :: ![Text],-    -- | Priority (lower = checked first). cache.nixos.org is 40.-    ccPriority :: !Int-  }-  deriving (Eq, Show)---- | Default cache configuration for cache.nixos.org.-defaultCacheConfig :: CacheConfig-defaultCacheConfig =-  CacheConfig-    { ccUrl = "https://cache.nixos.org",-      ccPublicKeys = ["cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY="],-      ccPriority = 40-    }---- | Result of a substitution attempt.-data SubstResult-  = -- | Verified and unpacked on disk, NOT yet registered: the carried-    -- registration is recorded by the caller, which batches every output-    -- of a derivation into one 'Nix.Store.DB.registerPaths' transaction so-    -- cross-output reference edges are never dropped.  The path's lock-    -- rides along STILL HELD, because the exclusion must survive until-    -- that transaction commits - released earlier, another process could-    -- meet the unpacked-but-unregistered window and delete the tree the-    -- row is about to describe.  The caller releases it after-    -- registration, on every exit path ("Nix.Builder").-    SubstSuccess !PathRegistration !PathLock-  | -- | The path was already valid under its lock - another process-    -- registered it while this one waited - so its work is adopted:-    -- nothing was downloaded, nothing touched disk, and no registration-    -- is needed.  The caller treats this as success.  No lock rides-    -- along; it was released before returning.-    SubstAlreadyValid-  | -- | No cache supplied the path, and none failed to.  A cache without-    -- its narinfo counts, as do one whose narinfo names another path or-    -- carries no trusted signature, and one whose NAR is gone: upstream-    -- passes over all of them without failing the substitution.-    SubstNotFound-  | -- | A cache failed to deliver the path and no cache supplied it, with-    -- the first failure: the narinfo query, the download, or its-    -- verification.  Upstream's failed substitution.-    SubstError !Text-  deriving (Eq, Show)---- ------------------------------------------------------------------------------ Main substitution logic--- ------------------------------------------------------------------------------- | Try to substitute a store path from configured caches.------ Upstream's per-path substitution protocol: take the path's exclusive--- lock FIRST, before any deletion or download, and re-check validity--- under it - another process may have registered the path while this--- one waited, and its finished work must be adopted--- ('SubstAlreadyValid') rather than deleted and redone.  The lock then--- holds across the delete, the download, materialization, and the--- on-disk recheck; a successful result carries it still held (see--- 'SubstSuccess'), and every other exit releases it here.------ Caches are checked in priority order; the first success stops the--- scan and a failing cache falls through to the remaining ones.  On--- success the path is unpacked and read-only on disk but NOT--- registered - the caller records the returned t'PathRegistration'.--- Every narinfo and NAR request runs under upstream's retry policy,--- 'defaultFetchRetryPolicy'.-trySubstitute :: Store -> [CacheConfig] -> StorePath -> IO SubstResult-trySubstitute = trySubstituteWith defaultFetchRetryPolicy ioRetryEffects---- | 'trySubstitute' under a given retry policy and effects: a build--- passes the policy its @builtin:fetchurl@ downloads run under--- ("Nix.Builder"), and a test passes effects that record rather than--- sleep.-trySubstituteWith :: FetchRetryPolicy -> RetryEffects IO -> Store -> [CacheConfig] -> StorePath -> IO SubstResult-trySubstituteWith _ _ _ [] _ = pure SubstNotFound-trySubstituteWith policy effects store caches sp = do-  -- Reuse the process-global TLS manager (connection pooling / keep-alive)-  -- rather than creating a fresh one per call and per output.-  manager <- HTTPS.getGlobalManager-  lock <- acquirePathLock (stDir store) sp-  substituteLocked manager lock `onException` releasePathLock lock-  where-    substituteLocked manager lock = do-      valid <- isValid store sp-      if valid-        then do-          releasePathLock lock-          pure SubstAlreadyValid-        else do-          result <- tryCachesWith (\cache -> tryOneCache (Retrying policy effects) manager store cache sp lock) (sortCaches caches)-          case result of-            SubstSuccess _ _ -> pure result-            other -> do-              releasePathLock lock-              pure other---- | What the caches say about a path's references, from the first cache--- whose narinfo may be used.  References arrive before the path that names--- them ("Nix.Realise"), so this runs ahead of any download, and a narinfo--- passes the same checks as a substitution before its references are--- believed.------ The caches are asked in priority order, as upstream's substitution goal--- asks them (@PathSubstitutionGoal::init@ at 2.24.9).  One without the--- path is passed over.  So is one whose narinfo names another path or no--- trusted key signed, and the scan says why.  A query that fails, once its--- retries are spent or on a narinfo that does not validate, ends the scan--- with 'QueryFailed' under 'NoFallback', as upstream rethrows it.  Under--- 'BuildFromSource' it is reported and passed over, as upstream logs it--- and asks the next cache.-queryReferencesWith :: FetchRetryPolicy -> RetryEffects IO -> Fallback -> [CacheConfig] -> StorePath -> IO Offer-queryReferencesWith _ _ _ [] _ = pure NotOffered-queryReferencesWith policy effects fallback caches sp = do-  manager <- HTTPS.getGlobalManager-  firstAnswer manager (sortCaches caches)-  where-    firstAnswer _ [] = pure NotOffered-    firstAnswer manager (cache : rest) = do-      answer <--        queryNarInfo (Retrying policy effects) manager cache sp-          `catchSync` \err -> pure (NarInfoFailed ("query exception: " <> T.pack (show err)))-      let next = firstAnswer manager rest-          failed failure = case fallback of-            NoFallback -> pure (QueryFailed (ccUrl cache <> ": " <> spName sp <> ": " <> failure))-            BuildFromSource -> reportCache cache sp failure >> next-      case answer of-        NarInfoUsable narInfo -> either failed (pure . Offered) (parseReferences (NarInfo.niReferences narInfo))-        NarInfoAbsent -> next-        NarInfoPassedOver reason -> reportCache cache sp reason >> next-        NarInfoFailed failure -> failed failure---- | Say on stderr what one cache did with a path.-reportCache :: CacheConfig -> StorePath -> Text -> IO ()-reportCache cache sp message =-  TIO.hPutStrLn stderr ("  [subst] " <> ccUrl cache <> ": " <> spName sp <> ": " <> message)---- | Fold per-cache attempts in priority order.  The first success wins and--- stops the scan.  An erroring cache falls through to the remaining ones ---- a transient failure (DNS, TLS, HTTP 500, unsupported compression) from a--- higher-priority cache must not mask a hit in the next - and the first--- error, tagged with its cache URL, is reported only when no cache has the--- path, as upstream's goal fails only once every substituter has been--- tried.-tryCachesWith :: (Monad m) => (CacheConfig -> m SubstResult) -> [CacheConfig] -> m SubstResult-tryCachesWith attempt = go Nothing-  where-    go firstErr [] = pure (maybe SubstNotFound SubstError firstErr)-    go firstErr (cache : rest) = do-      result <- attempt cache-      case result of-        SubstSuccess reg lock -> pure (SubstSuccess reg lock)-        -- A path found valid mid-scan is terminal like a success:-        -- there is nothing left to fetch from any cache.-        SubstAlreadyValid -> pure SubstAlreadyValid-        SubstNotFound -> go firstErr rest-        SubstError err -> go (firstErr <|> Just (ccUrl cache <> ": " <> err)) rest---- | The retry policy and its effects, carried to every request one--- substitution makes.-data Retrying = Retrying !FetchRetryPolicy !(RetryEffects IO)---- | Run one request's attempt under the carried policy.-retrying :: Retrying -> IO (Either AttemptFailure a) -> IO (Either AttemptFailure a)-retrying (Retrying policy effects) = retryTransient policy effects---- | Attempt substitution from a single cache.  Synchronous exceptions--- become 'SubstError', so the scan falls through to the remaining--- caches; asynchronous exceptions propagate ('catchSync') - an--- interrupt mid-download must abort the scan, never continue to the--- next cache and from there to a local build.-tryOneCache :: Retrying -> HTTP.Manager -> Store -> CacheConfig -> StorePath -> PathLock -> IO SubstResult-tryOneCache retry mgr store cache sp lock =-  substituteFromCache retry mgr store cache sp lock-    `catchSync` \err -> pure (SubstError ("substitution exception: " <> T.pack (show err)))---- | Substitution pipeline for a single cache: the narinfo, judged--- ('queryNarInfo'), then the NAR, streamed ('streamWithRetry').  A narinfo--- this build passes over is a miss here without a word, because the--- reference query asks every path first and has said why--- ('queryReferencesWith').-substituteFromCache :: Retrying -> HTTP.Manager -> Store -> CacheConfig -> StorePath -> PathLock -> IO SubstResult-substituteFromCache retry mgr store cache sp lock = do-  answer <- queryNarInfo retry mgr cache sp-  case answer of-    -- Unsupported compression rejects before the download: the value is-    -- known from the narinfo, and a multi-hundred-MB download that can-    -- only fail in decompression is pure waste.  It is still a failed-    -- substitute, as upstream's decompressor fails one.  The strict-    -- 'decompressorFor' encodes the same support set; the suite pins-    -- their agreement.-    NarInfoUsable narInfo -> case streamingDecompressionSupported (NarInfo.niCompression narInfo) of-      Left err -> pure (SubstError err)-      Right () -> streamWithRetry retry mgr store cache sp narInfo lock-    NarInfoAbsent -> pure SubstNotFound-    NarInfoPassedOver _ -> pure SubstNotFound-    NarInfoFailed failure -> pure (SubstError failure)---- | One cache's narinfo for a path, judged before anything is downloaded.-data NarInfoAnswer-  = -- | A narinfo for the path that validates and that a trusted key-    -- signed.-    NarInfoUsable !NarInfo.NarInfo-  | -- | The cache does not hold the path.-    NarInfoAbsent-  | -- | A narinfo this build passes over, and why: one naming another-    -- path, which upstream reads as the path not being in that cache, or-    -- one no trusted key signed, which it warns about and skips.-    NarInfoPassedOver !Text-  | -- | The query failed: the transfer once its retries are spent, a body-    -- that does not parse or validate, or a trusted key that does not-    -- parse.-    NarInfoFailed !Text-  deriving (Eq, Show)---- | Fetch a narinfo from a cache under the substitution's retry policy--- ('trySubstituteWith') and judge it ('judgeNarInfo').-queryNarInfo :: Retrying -> HTTP.Manager -> CacheConfig -> StorePath -> IO NarInfoAnswer-queryNarInfo retry mgr cache sp = do-  fetched <- retrying retry (fetchNarInfoOnce mgr url)-  pure $ case fetched of-    Left failure -> NarInfoFailed (attemptFailureMessage failure)-    Right Nothing -> NarInfoAbsent-    Right (Just narInfo) -> judgeNarInfo cache sp narInfo-  where-    url = ccUrl cache <> "/" <> spHash sp <> ".narinfo"---- | Whether a served narinfo may be used, decided from the narinfo alone, in--- upstream's order.  The fields validate first, standing in for upstream's--- narinfo parser, and above all before 'verifySigs' builds the signed--- fingerprint from them.  The narinfo must then describe the requested path--- (@goodStorePath@ in @Store::queryPathInfo@ at 2.24.9): a misconfigured or--- hostile cache could return a validly signed narinfo for a different path--- under this hash's URL.  Last come the trusted keys, which upstream parses--- when it checks the signature, and a signature one of them verifies--- (@PathSubstitutionGoal::init@).-judgeNarInfo :: CacheConfig -> StorePath -> NarInfo.NarInfo -> NarInfoAnswer-judgeNarInfo cache sp narInfo-  | Left err <- validateNarInfoFields narInfo = NarInfoFailed err-  | not (narInfoMatchesPath sp narInfo) = NarInfoPassedOver ("narinfo names " <> NarInfo.niStorePath narInfo)-  | Left err <- trustedKeys cache = NarInfoFailed err-  | otherwise = either NarInfoPassedOver (const (NarInfoUsable narInfo)) (verifySigs cache narInfo)---- | Validate narinfo field syntax before anything consumes the fields ---- above all before 'verifySigs' builds the signed fingerprint from them.--- The fingerprint is delimited text (semicolons between fields, commas--- between references), so each field must have parsed as well-formed--- before it is spliced in; a malformed narinfo fails here as a plain--- parse error instead of flowing onward.  The checks are nova-cache's--- 'Validate.validateNarInfo': store path, references, hash spellings,--- sizes, and the no-@.drv@ rule.-validateNarInfoFields :: NarInfo.NarInfo -> Either Text ()-validateNarInfoFields narInfo = case Validate.validateNarInfo narInfo of-  Right _ -> Right ()-  Left errs ->-    Left ("invalid narinfo: " <> T.intercalate "; " (map renderValidationError errs))---- | One 'Validate.ValidationError' in the register the other--- substitution errors use.-renderValidationError :: Validate.ValidationError -> Text-renderValidationError verr = case verr of-  Validate.NegativeFileSize n -> "negative FileSize " <> T.pack (show n)-  Validate.NegativeNarSize n -> "negative NarSize " <> T.pack (show n)-  Validate.InvalidStorePath raw parseErr -> fieldError "StorePath" raw parseErr-  Validate.InvalidFileHash raw parseErr -> fieldError "FileHash" raw parseErr-  Validate.InvalidNarHash raw parseErr -> fieldError "NarHash" raw parseErr-  Validate.InvalidReference raw parseErr -> fieldError "Reference" raw parseErr-  Validate.NarHashMismatch expected actual ->-    "NarHash mismatch: declared " <> expected <> ", computed " <> actual-  Validate.FileHashMismatch expected actual ->-    "FileHash mismatch: declared " <> expected <> ", computed " <> actual-  Validate.SignatureInvalid sig -> "signature failed verification: " <> sig-  Validate.NoSignatures -> "narinfo has no signatures"-  Validate.DerivationStorePath path -> "StorePath names a derivation: " <> path-  where-    fieldError field raw parseErr =-      field <> " '" <> raw <> "' does not parse: " <> T.pack parseErr---- | NAR bytes that passed 'verifyNar': they hash to the narinfo's--- signed NarHash and count its signed NarSize.  The constructor is not--- exported, so 'verifyNar' is the only way to obtain one and--- 'unpackVerifiedNar', the strict pipeline's unpack sink, cannot be--- reached with bytes that skipped the check: verify-then-unpack is a--- type, not a statement order.  The decoded digest rides along because--- registration records its canonical spelling and the on-disk recheck--- compares against it, so neither re-parses the narinfo's NarHash.--- Only the strict pipeline can carry this: the streaming pipeline--- writes to disk before the hash can be known (upstream's ordering)--- and relies on its cleanup contract instead--- ('materializeNarFromSource').-data VerifiedNar = VerifiedNar !BS.ByteString !Hash.NixHash-  deriving (Eq, Show)---- | The verified bytes.-verifiedNarBytes :: VerifiedNar -> BS.ByteString-verifiedNarBytes (VerifiedNar bytes _) = bytes---- | The digest the verified bytes hash to, decoded from the narinfo's--- NarHash.-verifiedNarDigest :: VerifiedNar -> Hash.NixHash-verifiedNarDigest (VerifiedNar _ digest) = digest---- | The only constructor of a t'VerifiedNar': the hash check, then the--- size check, with the decoded declared digest carried out.  The NAR--- hash is the content-addressed integrity contract; the signature only--- attests to the narinfo, not the body, so network corruption or a--- compromised cache is caught here, before the bytes are trusted.-verifyNar :: NarInfo.NarInfo -> BS.ByteString -> Either Text VerifiedNar-verifyNar narInfo rawNar = do-  declared <- verifyNarHash narInfo rawNar-  verifyNarSize narInfo rawNar-  pure (VerifiedNar rawNar declared)---- | Verify the NAR hash and size, deserialize, unpack to the store, and--- set permissions: 'verifyNar', then 'unpackVerifiedNar'.  Returns the--- path's registration for the caller to record; no database write--- happens here (see 'SubstSuccess').  The strict counterpart of the--- streaming pipeline, kept as its differential oracle: the suite--- materializes the same NAR through both and requires identical trees.-unpackAndVerify :: Store -> StorePath -> NarInfo.NarInfo -> BS.ByteString -> IO SubstResult-unpackAndVerify store sp narInfo rawNar =-  -- Narinfo metadata is parsed before any disk write: a malformed-  -- narinfo must not leave an unpacked-but-unregistered path behind.-  case verifiedInputs of-    Left err -> pure (SubstError err)-    Right (verified, refs, deriver) -> unpackVerifiedNar store sp verified refs deriver-  where-    verifiedInputs = do-      verified <- verifyNar narInfo rawNar-      refs <- parseReferences (NarInfo.niReferences narInfo)-      deriver <- parseDeriver (stDir store) (NarInfo.niDeriver narInfo)-      pure (verified, refs, deriver)---- | The strict pipeline's unpack sink: deserialize a t'VerifiedNar',--- materialize it at the store path, seal it read-only, and recheck the--- tree on disk against the carried digest before building its--- registration from the references and deriver.  Follows the same--- per-path lock protocol as the live pipeline: the lock is taken--- before the stale destination is cleared, validity re-checks under--- it, and a success carries the lock still held.-unpackVerifiedNar :: Store -> StorePath -> VerifiedNar -> [StorePath] -> Maybe Text -> IO SubstResult-unpackVerifiedNar store sp verified refs deriver =-  case NAR.deserialise (verifiedNarBytes verified) of-    Left err -> pure (SubstError ("NAR deserialisation failed: " <> T.pack err))-    Right narEntry -> do-      lock <- acquirePathLock (stDir store) sp-      result <- unpackLocked narEntry lock `onException` releasePathLock lock-      case result of-        SubstSuccess _ _ -> pure result-        other -> do-          releasePathLock lock-          pure other-  where-    digest = verifiedNarDigest verified-    destPath = storePathToFilePath (stDir store) sp-    unpackLocked narEntry lock = do-      alreadyValid <- isValid store sp-      if alreadyValid-        then pure SubstAlreadyValid-        else do-          unpackResult <--            fmap-              Right-              ( do-                  clearStaleDestination destPath-                  unpackNarEntry (stCaseSensitivity store) destPath narEntry-              )-              `catchSync` (pure . Left)-          case (unpackResult :: Either SomeException (Either Text ())) of-            Left err -> pure (SubstError ("unpack failed: " <> T.pack (show err)))-            Right (Left err) -> pure (SubstError ("unpack failed: " <> err))-            Right (Right ()) -> do-              setReadOnly destPath-              -- A path registered valid must match its recorded hash ON-              -- DISK, not merely in the verified bytes: any divergence-              -- the filesystem introduced between the NAR and the-              -- materialized tree (name folding, link replication) must-              -- surface here, before the row exists.  A mismatching tree-              -- is removed - left in place it would be adopted by-              -- existence checks at this path.-              onDisk <- ExecBit.serialiseFromPath (volumeCaseHack (stCaseSensitivity store)) destPath-              if Hash.hashBytes (NAR.serialise onDisk) /= digest-                then do-                  Dir.removePathForcibly destPath-                  pure-                    ( SubstError-                        ( "unpacked tree does not reproduce the declared NAR hash at "-                            <> T.pack destPath-                        )-                    )-                else-                  pure $-                    SubstSuccess-                      PathRegistration-                        { prPath = sp,-                          -- The canonical spelling of the verified digest,-                          -- so the DB converges on one hash spelling-                          -- regardless of the cache's.-                          prNarHash = Hash.formatNixHash digest,-                          -- The verified actual byte count (equal to the-                          -- declared NarSize per 'verifyNarSize') - no-                          -- Integer conversion that could wrap.-                          prNarSize = BS.length (verifiedNarBytes verified),-                          prDeriver = deriver,-                          prReferences = refs-                        }-                      lock---- | Verify that the downloaded NAR bytes hash to the narinfo's declared--- NarHash, returning the decoded digest on success so registration can--- record its canonical spelling.  Compares decoded hash bytes, so any--- valid encoding of the digest validates.-verifyNarHash :: NarInfo.NarInfo -> BS.ByteString -> Either Text Hash.NixHash-verifyNarHash narInfo rawNar =-  case Hash.parseNixHash (NarInfo.niNarHash narInfo) of-    Left err -> Left ("invalid narinfo NarHash: " <> T.pack err)-    Right declared-      | declared == actual -> Right declared-      | otherwise ->-          Left-            ( "NAR hash mismatch: narinfo declares "-                <> NarInfo.niNarHash narInfo-                <> " but downloaded bytes hash to "-                <> Hash.formatNixHash actual-            )-  where-    actual = Hash.hashBytes rawNar---- | Verify that the downloaded NAR's byte count equals the narinfo's--- declared NarSize.  The hash check pins the content, but the size is a--- separate signed claim that flows into the store DB (and from there--- into re-pushed narinfos), so a wrong declaration must be rejected--- rather than recorded.-verifyNarSize :: NarInfo.NarInfo -> BS.ByteString -> Either Text ()-verifyNarSize narInfo rawNar-  | toInteger (BS.length rawNar) == NarInfo.niNarSize narInfo = Right ()-  | otherwise =-      Left-        ( "NAR size mismatch: narinfo declares "-            <> T.pack (show (NarInfo.niNarSize narInfo))-            <> " bytes but downloaded "-            <> T.pack (show (BS.length rawNar))-        )---- | Whether a served narinfo describes the requested path: the hash component--- of its declared StorePath must equal the requested path's hash.  Only the--- hash is compared, since the cache may use a different store directory.-narInfoMatchesPath :: StorePath -> NarInfo.NarInfo -> Bool-narInfoMatchesPath sp narInfo =-  storePathHashOf (NarInfo.niStorePath narInfo) == Just (spHash sp)---- | Extract the leading hash from a full store path's basename, if well-formed--- (@\<hash\>-\<name\>@ with a hash of the expected length).-storePathHashOf :: Text -> Maybe Text-storePathHashOf path =-  let base = T.takeWhileEnd (\c -> c /= '/' && c /= '\\') path-      (hashPart, rest) = T.splitAt storePathHashLen base-   in if T.length hashPart == storePathHashLen && T.isPrefixOf "-" rest-        then Just hashPart-        else Nothing---- ------------------------------------------------------------------------------ HTTP fetching--- ------------------------------------------------------------------------------- | Cap on a narinfo response body, mirroring nova-cache's server-side--- @maxNarInfoBodySize@ - the server bounds what it reads, and the--- client bounds what any cache in its list can make it buffer.--- Narinfo is small key-value text; 4 MB is far beyond any real one.-maxNarInfoBody :: Int-maxNarInfoBody = 4 * 1024 * 1024---- | Read an HTTP response body in bounded chunks up to a byte cap ---- 'Nothing' once the cap is exceeded, so an over-large body aborts--- mid-stream instead of buffering without limit.  The client-side--- mirror of nova-cache's @readBodyLimited@.-readBodyCapped :: Int -> HTTP.BodyReader -> IO (Maybe BS.ByteString)-readBodyCapped cap reader = go [] 0-  where-    go chunks !total = do-      chunk <- HTTP.brRead reader-      if BS.null chunk-        then pure (Just (BS.concat (reverse chunks)))-        else-          let newTotal = total + BS.length chunk-           in if newTotal > cap-                then pure Nothing-                else go (chunk : chunks) newTotal---- | One narinfo request: @Right Nothing@ when the cache does not hold--- it.  A 'NotFound' or 'Forbidden' answer (404, 410, 401, 403, 407) is--- the cache saying so, not a failure to retry: upstream's transfer layer--- retries neither, and its binary cache store reads both as a missing--- narinfo, so the path is not valid there (@HttpBinaryCacheStore::getFile@--- at 2.24.9).  A narinfo that arrived whole and does not parse, or--- overruns 'maxNarInfoBody', is the cache's bytes and fails at once.-fetchNarInfoOnce :: HTTP.Manager -> Text -> IO (Either AttemptFailure (Maybe NarInfo.NarInfo))-fetchNarInfoOnce mgr url = fetch `catches` transferFailureHandlers url-  where-    fetch = do-      request <- withUserAgent <$> HTTP.parseRequest (T.unpack url)-      withTransfer request mgr $ \response ->-        answer (HTTP.responseStatus response) (HTTP.responseBody response)-    answer status body-      | status /= HTTP.status200 = pure $ case statusError status of-          NotFound -> Right Nothing-          Forbidden -> Right Nothing-          Misc -> Left (fetchStatusFailure url status)-          Transient -> Left (fetchStatusFailure url status)-      | otherwise = do-          capped <- readBodyCapped maxNarInfoBody body-          pure $ case capped of-            Nothing ->-              Left (FatalFailure ("narinfo body exceeds " <> T.pack (show maxNarInfoBody) <> " bytes"))-            -- Lenient decode: the body is cache-controlled bytes, and a-            -- stray invalid UTF-8 sequence must surface as a narinfo parse-            -- error, not an impure UnicodeException (the push side decodes-            -- the same way).-            Just bytes -> case NarInfo.parseNarInfo (TE.decodeUtf8Lenient bytes) of-              Left err -> Left (FatalFailure ("narinfo parse error: " <> T.pack err))-              Right narInfo -> Right (Just narInfo)---- | Stream one substitution end to end, each attempt under the--- substitution's retry policy ('trySubstituteWith').------ By the time this runs the narinfo has already been fetched and--- signature-verified, so the cache claims to hold this path.  Failures--- carry their own retry class: a 'TransientFailure' - transport--- errors, torn or truncated transfers, a status upstream retries,--- anything a fresh attempt could plausibly complete - consumes retry--- budget with upstream's backoff, while a 'FatalFailure' - a completed--- transfer that verifies wrong, a body past its signed ceiling, a--- status upstream never retries, a write the disk refused - ends the--- attempt at once: retrying a deterministic failure only delays the--- outcome.  Every attempt starts from a clean slate--- ('streamNarIntoStore' clears the destination first, and every--- failure path, exceptions included, removes what it wrote), so a retry--- restarts the NAR from its first byte, where upstream resumes from the--- written offset when the server accepts ranges and otherwise retries--- only a transfer that wrote nothing yet.  A NAR the narinfo named and--- the cache answers 'NotFound' or 'Forbidden' for is gone: one request,--- as upstream's @SubstituteGone@ (@BinaryCacheStore::narFromPath@ at--- 2.24.9), reported and then a miss the cache scan passes over, because--- upstream's substitution goal treats a gone substitute like one that--- never existed rather than as a failure.  A narinfo the cache does not--- hold is a miss handled earlier in 'queryNarInfo' and never reaches--- here.-streamWithRetry :: Retrying -> HTTP.Manager -> Store -> CacheConfig -> StorePath -> NarInfo.NarInfo -> PathLock -> IO SubstResult-streamWithRetry retry mgr store cache sp narInfo lock = do-  outcome <- retrying retry (streamNarIntoStore mgr cache store sp narInfo)-  case outcome of-    Right (Just registration) -> pure (SubstSuccess registration lock)-    Right Nothing -> do-      reportCache cache sp ("file '" <> NarInfo.niUrl narInfo <> "' does not exist in the binary cache")-      pure SubstNotFound-    Left failure -> pure (SubstError (attemptFailureMessage failure))---- | Thrown inside the streaming pipeline where a chunk convention has--- no error channel (the capped body source); converted back to the--- pipeline's 'Left' at the attempt boundary in 'streamNarIntoStore'.-newtype StreamAbort = StreamAbort Text-  deriving (Show)--instance Exception StreamAbort---- | Convert what one download attempt throws into the pipeline's--- failure channel, so the retry budget governs it and the caller's--- cleanup contract holds on every exit: the transfer layer's--- classification ('transferFailureHandlers'), and a t'StreamAbort'.--- Nothing else is caught, so an interrupt is never spent as retry--- budget.-tryAttempt :: Text -> IO (Either AttemptFailure a) -> IO (Either AttemptFailure a)-tryAttempt url action =-  action `catches` (Handler streamAborted : transferFailureHandlers url)-  where-    -- A body past its ceiling: the cap derives from the signed NarSize,-    -- so a longer body is the server misdeclaring, not a hiccup.-    streamAborted (StreamAbort msg) = pure (Left (FatalFailure msg))---- | One streaming substitution attempt: download, decompress, hash,--- parse, and materialize in a single bounded pass, then verify.--- Memory is bounded by the decoder's buffers and the parser's--- structural-string cap, never by archive or file size.------ Disk writes begin before the NAR hash can be known - the price of--- never holding the archive, and exactly upstream's ordering - so--- every failure path, exceptions included, removes the tree it wrote--- ('materializeNarFromSource' owns that contract; 'tryAttempt'--- classifies what escapes it).  The narinfo metadata registration--- needs (declared hash, references, deriver) still parses BEFORE the--- first byte downloads: a malformed narinfo must not leave an--- unpacked-but-unregistered path behind.  'Nothing' when the cache no--- longer holds the NAR ('streamWithRetry').-streamNarIntoStore :: HTTP.Manager -> CacheConfig -> Store -> StorePath -> NarInfo.NarInfo -> IO (Either AttemptFailure (Maybe PathRegistration))-streamNarIntoStore mgr cache store sp narInfo = case preflight of-  Left err -> pure (Left (FatalFailure err))-  Right (declaredDigest, refs, deriver, downloadCap) -> do-    let destPath = storePathToFilePath (stDir store) sp-        narUrl = ccUrl cache <> "/" <> NarInfo.niUrl narInfo-    clearStaleDestination destPath-    tryAttempt narUrl $ do-      request <- withUserAgent <$> HTTP.parseRequest (T.unpack narUrl)-      withTransfer request mgr $ \response -> do-        let status = HTTP.responseStatus response-        if status /= HTTP.status200-          then pure (unservedNar narUrl status)-          else do-            source <- cappedBodySource downloadCap (HTTP.responseBody response)-            fmap Just <$> materializeNarFromSource store sp narInfo declaredDigest refs deriver source-  where-    preflight = do-      declaredDigest <- case Hash.parseNixHash (NarInfo.niNarHash narInfo) of-        Left err -> Left ("invalid narinfo NarHash: " <> T.pack err)-        Right digest -> Right digest-      refs <- parseReferences (NarInfo.niReferences narInfo)-      deriver <- parseDeriver (stDir store) (NarInfo.niDeriver narInfo)-      downloadCap <- downloadCapFor narInfo-      pure (declaredDigest, refs, deriver, downloadCap)---- | A NAR response that is not a success.  'NotFound' and 'Forbidden' mean--- the cache no longer holds the NAR, as upstream's binary cache store--- reads both (@HttpBinaryCacheStore::getFile@ at 2.24.9); any other status--- is a failure, retried when upstream retries it.-unservedNar :: Text -> HTTP.Status -> Either AttemptFailure (Maybe PathRegistration)-unservedNar narUrl status = case statusError status of-  NotFound -> Right Nothing-  Forbidden -> Right Nothing-  Misc -> Left (fetchStatusFailure narUrl status)-  Transient -> Left (fetchStatusFailure narUrl status)---- | The byte cap on the compressed NAR body, derived from the SIGNED--- NarSize: the Ed25519 fingerprint covers StorePath, NarHash, NarSize,--- and references - not FileSize - so the unsigned FileSize may only--- LOWER the cap, never raise it.  A rewritten FileSize on an otherwise--- validly-signed narinfo must not buy an unbounded download.-downloadCapFor :: NarInfo.NarInfo -> Either Text Int-downloadCapFor narInfo-  | narSize < 0 || narSize > toInteger (maxBound :: Int) =-      Left ("narinfo declares an unusable NAR size: " <> T.pack (show narSize))-  | otherwise =-      let signedCeiling = compressedBodyCeiling narSize-          capped = maybe signedCeiling (min signedCeiling . max 0) (NarInfo.niFileSize narInfo)-       in Right (fromInteger (min capped (toInteger (maxBound :: Int))))-  where-    narSize = NarInfo.niNarSize narInfo---- | The most a compressed NAR body may legitimately exceed its NarSize--- by: xz and zstd expand incompressible input by well under one--- percent of framing overhead, so a 1/64 (~1.6%) margin plus a fixed--- floor for small NARs is generous for any real codec, while a--- hostile FileSize claiming orders of magnitude more is refused.-compressedBodyCeiling :: Integer -> Integer-compressedBodyCeiling narSize =-  narSize + max compressionOverheadFloorBytes (narSize `div` compressionOverheadDivisor)---- | Fixed overhead floor for small NARs, where framing dominates.-compressionOverheadFloorBytes :: Integer-compressionOverheadFloorBytes = 64 * 1024---- | Proportional overhead margin: 1/64 of the NarSize.-compressionOverheadDivisor :: Integer-compressionOverheadDivisor = 64---- | Materialize a NAR from a compressed chunk source into the store--- path: decompress, hash, parse, and unpack in one pass, then verify--- the tree on disk and build its registration.  The post-download half--- of 'streamNarIntoStore', taking a plain chunk source so the failure--- contract is testable without HTTP.------ The cleanup contract: every failing exit - the pipeline's 'Left',--- a verification mismatch, or an exception (asynchronous included) ---- removes the destination tree, so no partial or unverified tree ever--- survives at the store path.-materializeNarFromSource :: Store -> StorePath -> NarInfo.NarInfo -> Hash.NixHash -> [StorePath] -> Maybe Text -> IO BS.ByteString -> IO (Either AttemptFailure PathRegistration)-materializeNarFromSource store sp narInfo declaredDigest refs deriver source =-  materialize `onException` Dir.removePathForcibly destPath-  where-    destPath = storePathToFilePath (stDir store) sp-    materialize = do-      streamed <--        withDecompressedSource (NarInfo.niNarSize narInfo) (NarInfo.niCompression narInfo) source $-          consumeNarStream (stCaseSensitivity store) destPath narInfo declaredDigest-      case streamed of-        Left err -> do-          Dir.removePathForcibly destPath-          pure (Left err)-        Right narByteCount -> do-          setReadOnly destPath-          -- A path registered valid must match its recorded hash ON-          -- DISK, not merely in the streamed bytes: any divergence the-          -- filesystem introduced between the NAR and the materialized-          -- tree must surface here, before the row exists.  The recheck-          -- streams too, so its memory no longer scales with the path.-          -- Through 'ExecBit', not nova-cache's walk directly: on Windows-          -- the sink writes the exec bit to a stream that walk cannot see,-          -- and a verifier reading the flag back out of the file extension-          -- would reject exactly the paths this representation exists for.-          -- On Unix it is still the streaming hash.-          onDiskDigest <- ExecBit.narHashOfPath (volumeCaseHack (stCaseSensitivity store)) destPath-          if onDiskDigest /= declaredDigest-            then do-              Dir.removePathForcibly destPath-              pure (Left (FatalFailure ("unpacked tree does not reproduce the declared NAR hash at " <> T.pack destPath)))-            else-              pure $-                Right-                  PathRegistration-                    { prPath = sp,-                      -- The canonical spelling of the verified digest,-                      -- so the DB converges on one hash spelling-                      -- regardless of the cache's.-                      prNarHash = Hash.formatNixHash declaredDigest,-                      prNarSize = narByteCount,-                      prDeriver = deriver,-                      prReferences = refs-                    }---- | Drive the decompressed chunk source through incremental hashing,--- the streaming NAR parser, and the store's streaming unpack sink,--- returning the verified NAR byte count.  The hash context folds over--- exactly the bytes the parser consumes, so the digest is of the NAR--- the tree was built from.  The sensitivity is the destination--- volume's, 'stCaseSensitivity' when the destination is a store path.-consumeNarStream :: CaseSensitivity -> FilePath -> NarInfo.NarInfo -> Hash.NixHash -> IO BS.ByteString -> IO (Either AttemptFailure Int)-consumeNarStream sensitivity destPath narInfo declaredDigest narSource = do-  sink <- newNarUnpackSink sensitivity destPath-  streamed <- sinkNarStream sink narSource-  case streamed of-    -- A name or shape the store refuses is a property of the archive,-    -- not of this transfer.-    Left (NarStreamRefused err) -> pure (Left (FatalFailure err))-    -- A truncated body and a torn transfer parse-fail the same way, so-    -- the retry budget applies.-    Left (NarStreamMalformed msg) -> pure (Left (TransientFailure ("NAR stream parse failed: " <> msg)))-    Right (digest, narBytes)-      | toInteger narBytes /= NarInfo.niNarSize narInfo -> do-          abortNarUnpack sink-          -- The grammar completed, so the transfer was whole: a size-          -- that still disagrees is the narinfo misdeclaring.-          pure-            ( Left-                ( FatalFailure-                    ( "NAR size mismatch: narinfo declares "-                        <> T.pack (show (NarInfo.niNarSize narInfo))-                        <> " bytes but the stream carried "-                        <> T.pack (show narBytes)-                    )-                )-            )-      | digest /= declaredDigest -> do-          abortNarUnpack sink-          -- Size matched, so the transfer completed; wrong bytes are-          -- deterministic corruption, not a hiccup.-          pure-            ( Left-                ( FatalFailure-                    ( "NAR hash mismatch: narinfo declares "-                        <> NarInfo.niNarHash narInfo-                        <> " but downloaded bytes hash to "-                        <> Hash.formatNixHash digest-                    )-                )-            )-      | otherwise -> do-          finished <- finishNarUnpack sink-          pure (either (Left . FatalFailure) (const (Right narBytes)) finished)---- | Stream an HTTP body as a chunk source bounded by the download cap--- 'downloadCapFor' derived from the signed NarSize ---- 'readBodyCapped'\'s discipline without the buffering.  Exceeding the--- cap throws t'StreamAbort'; the attempt boundary converts it back to--- the pipeline's error channel.-cappedBodySource :: Int -> HTTP.BodyReader -> IO (IO BS.ByteString)-cappedBodySource cap reader = do-  countRef <- newIORef 0-  pure $ do-    chunk <- HTTP.brRead reader-    consumed <- readIORef countRef-    let total = consumed + BS.length chunk-    if total > cap-      then throwIO (StreamAbort ("NAR body exceeds its download ceiling (" <> T.pack (show cap) <> " bytes)"))-      else do-        writeIORef countRef total-        pure chunk---- | Whether the streaming pipeline can decompress a narinfo--- @Compression@ value, decided from the value alone so unsupported--- compression rejects before any download.  Both this and the strict--- 'decompressorFor' dispatch through 'parseNarCompression', so the--- support set exists exactly once.-streamingDecompressionSupported :: Text -> Either Text ()-streamingDecompressionSupported = void . parseNarCompression---- | Run a consumer over the decompressed view of a chunk source:--- identity for 'CompressionNone', nova-cache's bounded decoders for--- 'CompressionXz', 'CompressionZstd', and 'CompressionBzip2' (output--- capped at the declared NarSize; thrown codec errors convert to the--- pipeline's error channel here, carrying their retry class from--- 'xzFailure', 'zstdFailure', and 'bzip2Failure').-withDecompressedSource :: Integer -> Text -> IO BS.ByteString -> (IO BS.ByteString -> IO (Either AttemptFailure a)) -> IO (Either AttemptFailure a)-withDecompressedSource declaredNarSize compression source consume =-  case parseNarCompression compression of-    Left err -> pure (Left (FatalFailure err))-    Right CompressionNone -> consume source-    Right CompressionXz -> case xzLimitsFor declaredNarSize of-      Left err -> pure (Left (FatalFailure err))-      Right limits ->-        Xz.withXzSource limits source consume-          `catch` \xzErr -> pure (Left (xzFailure xzErr))-    Right CompressionZstd -> case zstdLimitsFor declaredNarSize of-      Left err -> pure (Left (FatalFailure err))-      Right limits ->-        Zstd.withZstdSource limits source consume-          `catch` \zstdErr -> pure (Left (zstdFailure zstdErr))-    Right CompressionBzip2 -> case bzip2LimitsFor declaredNarSize of-      Left err -> pure (Left (FatalFailure err))-      Right limits ->-        Bzip2.withBzip2Source limits source consume-          `catch` \bzip2Err -> pure (Left (bzip2Failure bzip2Err))---- | Classify a decoder failure: a stream error is how truncation and--- torn transfers surface, so it retries; output or memory past the--- declared bounds is the served object misdeclaring - deterministic.-xzFailure :: Xz.XzError -> AttemptFailure-xzFailure xzErr = case xzErr of-  Xz.XzStreamError _ -> TransientFailure rendered-  Xz.XzOutputOverBound _ -> FatalFailure rendered-  Xz.XzMemoryOverBound _ -> FatalFailure rendered-  where-    rendered = renderXzError xzErr---- | 'xzFailure'\'s zstd counterpart, under the same taxonomy.-zstdFailure :: Zstd.ZstdError -> AttemptFailure-zstdFailure zstdErr = case zstdErr of-  Zstd.ZstdStreamError _ -> TransientFailure rendered-  Zstd.ZstdOutputOverBound _ -> FatalFailure rendered-  where-    rendered = renderZstdError zstdErr---- | 'xzFailure'\'s bzip2 counterpart, under the same taxonomy.-bzip2Failure :: Bzip2.Bzip2Error -> AttemptFailure-bzip2Failure bzip2Err = case bzip2Err of-  Bzip2.Bzip2StreamError _ -> TransientFailure rendered-  Bzip2.Bzip2OutputOverBound _ -> FatalFailure rendered-  where-    rendered = renderBzip2Error bzip2Err---- ------------------------------------------------------------------------------ Pure helpers--- ------------------------------------------------------------------------------- | Sort caches by priority (lower = first).-sortCaches :: [CacheConfig] -> [CacheConfig]-sortCaches = sortBy (comparing ccPriority)---- | Verify narinfo signatures against the cache's trusted public keys.--- Accepts when at least one signature verifies under at least one key,--- upstream's any-trusted-key rule.-verifySigs :: CacheConfig -> NarInfo.NarInfo -> Either Text ()-verifySigs cache narInfo =-  case NarInfo.niSigs narInfo of-    [] -> Left "narinfo has no signatures"-    sigs -> do-      keys <- trustedKeys cache-      if any (\key -> any (Signing.verify key narInfo) sigs) keys-        then Right ()-        else Left "no valid signature found"---- | The cache's trusted public keys.  A malformed key is an error rather--- than a silently skipped one: upstream rejects the configuration, so a--- typo cannot quietly narrow the trusted set to the keys that parsed.-trustedKeys :: CacheConfig -> Either Text [Signing.PublicKey]-trustedKeys = traverse parseKey . ccPublicKeys-  where-    parseKey raw = case Signing.parsePublicKey raw of-      Left err -> Left ("invalid public key: " <> T.pack err)-      Right pubKey -> Right pubKey---- | The whole-buffer decompressor for a narinfo @Compression@ value,--- decided from the narinfo's declared values alone so unsupported--- compression rejects before any download.  'CompressionNone' is--- identity; 'CompressionXz' (cache.nixos.org's format),--- 'CompressionZstd' (the modern caches'), and 'CompressionBzip2' (the--- historical caches', and what an absent field means) decompress--- bounded by the declared NarSize, a signed claim the caller validates--- before resolving the decompressor.  The resolved function runs in IO--- because the zstd and bzip2 decoders are IO-native (see--- 'NovaCache.Zstd' and 'NovaCache.Bzip2'); the strict shape follows its--- codecs.  Dispatches through 'parseNarCompression' like the streaming--- path, so the support set exists exactly once.-decompressorFor :: Integer -> Text -> Either Text (BS.ByteString -> IO (Either Text BS.ByteString))-decompressorFor declaredNarSize compression = do-  kind <- parseNarCompression compression-  case kind of-    CompressionNone -> Right (pure . Right)-    CompressionXz -> do-      limits <- xzLimitsFor declaredNarSize-      Right (pure . either (Left . renderXzError) Right . Xz.decompress limits)-    CompressionZstd -> do-      limits <- zstdLimitsFor declaredNarSize-      Right (fmap (either (Left . renderZstdError) Right) . Zstd.decompress limits)-    CompressionBzip2 -> do-      limits <- bzip2LimitsFor declaredNarSize-      Right (fmap (either (Left . renderBzip2Error) Right) . Bzip2.decompress limits)---- | Decompress NAR data based on the compression type from narinfo,--- bounded by the declared NarSize.  Support is decided by--- 'decompressorFor'; this applies the result.-decompressNar :: Integer -> Text -> BS.ByteString -> IO (Either Text BS.ByteString)-decompressNar declaredNarSize compression narData =-  case decompressorFor declaredNarSize compression of-    Left err -> pure (Left err)-    Right decompress -> decompress narData---- | The bounds for one xz decode: output capped at the narinfo's--- declared NarSize, decoder memory at nova-cache's default, so a--- hostile stream can expand to neither more output nor more decoder--- state than the narinfo promised.  Narinfo validation upstream--- already rejected a negative size; the guard keeps the function--- total for direct callers, and a size past Word64 cannot name a--- real NAR.-xzLimitsFor :: Integer -> Either Text Xz.XzLimits-xzLimitsFor declaredNarSize-  | declaredNarSize < 0 || declaredNarSize > toInteger (maxBound :: Word64) =-      Left ("xz decompression bound out of range: " <> T.pack (show declaredNarSize))-  | otherwise =-      Right-        Xz.XzLimits-          { Xz.xzMaxOutputBytes = fromInteger declaredNarSize,-            Xz.xzMaxDecoderMemoryBytes = Xz.defaultXzDecoderMemoryBytes-          }---- | One 'Xz.XzError' in the register the other substitution errors use.-renderXzError :: Xz.XzError -> Text-renderXzError xzErr = case xzErr of-  Xz.XzStreamError msg -> "xz stream error: " <> T.pack msg-  Xz.XzOutputOverBound bound ->-    "xz output exceeds the declared NarSize (" <> T.pack (show bound) <> " bytes)"-  Xz.XzMemoryOverBound bound ->-    "xz decoder memory over its cap (" <> T.pack (show bound) <> " bytes)"---- | The bounds for one zstd decode: output capped at the narinfo's--- declared NarSize; decoder state rides libzstd's built-in window--- limit (see 'NovaCache.Zstd').  The same totality guard as--- 'xzLimitsFor'.-zstdLimitsFor :: Integer -> Either Text Zstd.ZstdLimits-zstdLimitsFor declaredNarSize-  | declaredNarSize < 0 || declaredNarSize > toInteger (maxBound :: Word64) =-      Left ("zstd decompression bound out of range: " <> T.pack (show declaredNarSize))-  | otherwise = Right Zstd.ZstdLimits {Zstd.zstdMaxOutputBytes = fromInteger declaredNarSize}---- | One 'Zstd.ZstdError' in the register the other substitution--- errors use.-renderZstdError :: Zstd.ZstdError -> Text-renderZstdError zstdErr = case zstdErr of-  Zstd.ZstdStreamError msg -> "zstd stream error: " <> T.pack msg-  Zstd.ZstdOutputOverBound bound ->-    "zstd output exceeds the declared NarSize (" <> T.pack (show bound) <> " bytes)"---- | The bounds for one bzip2 decode: output capped at the narinfo's--- declared NarSize.  There is no decoder-memory knob to set - bzip2--- carries no attacker-chosen dictionary size, so decoder state is a--- small constant of the format (see 'NovaCache.Bzip2').  The same--- totality guard as 'xzLimitsFor'.-bzip2LimitsFor :: Integer -> Either Text Bzip2.Bzip2Limits-bzip2LimitsFor declaredNarSize-  | declaredNarSize < 0 || declaredNarSize > toInteger (maxBound :: Word64) =-      Left ("bzip2 decompression bound out of range: " <> T.pack (show declaredNarSize))-  | otherwise = Right Bzip2.Bzip2Limits {Bzip2.bzip2MaxOutputBytes = fromInteger declaredNarSize}---- | One 'Bzip2.Bzip2Error' in the register the other substitution--- errors use.-renderBzip2Error :: Bzip2.Bzip2Error -> Text-renderBzip2Error bzip2Err = case bzip2Err of-  Bzip2.Bzip2StreamError msg -> "bzip2 stream error: " <> T.pack msg-  Bzip2.Bzip2OutputOverBound bound ->-    "bzip2 output exceeds the declared NarSize (" <> T.pack (show bound) <> " bytes)"---- | Parse narinfo references (store path basenames, e.g.--- @abc...-glibc-2.40@) into StorePaths.  A malformed token is an error,--- not filtered: silently dropping a reference registers the path with a--- hole in its closure, which re-push then publishes as a signed narinfo--- missing runtime deps, and GC reads as permission to delete them.-parseReferences :: [Text] -> Either Text [StorePath]-parseReferences = traverse parseRef-  where-    parseRef ref =-      maybe (Left ("malformed narinfo reference: " <> ref)) Right (parseStorePathBaseName ref)---- | The sentinel upstream caches emit for a path whose deriver is unknown.-unknownDeriverSentinel :: Text-unknownDeriverSentinel = "unknown-deriver"---- | Parse a narinfo Deriver - a store path basename on the wire, or the--- @unknown-deriver@ sentinel - into the full path text the store DB--- records (the form "Nix.Push" parses back with 'Nix.Store.Path.parseStorePath').-parseDeriver :: StoreDir -> Maybe Text -> Either Text (Maybe Text)-parseDeriver _ Nothing = Right Nothing-parseDeriver storeDir (Just txt)-  | txt == unknownDeriverSentinel = Right Nothing-  | otherwise = case parseStorePathBaseName txt of-      Just sp -> Right (Just (T.pack (storePathToFilePath storeDir sp)))-      Nothing -> Left ("malformed narinfo deriver: " <> txt)---- ------------------------------------------------------------------------------ NAR unpacking--- ------------------------------------------------------------------------------- | Remove a leftover destination tree before unpacking.  A crash (or a--- failed registration) between 'setReadOnly' here and the caller's--- 'Nix.Store.DB.registerPaths' leaves a read-only, unregistered tree;--- unpacking over it would then fail with permission-denied on every--- retry, permanently wedging substitution of that path.--- 'Dir.removePathForcibly' clears read-only marks and accepts a missing--- path, so the fresh unpack always starts from a clean slate.--- Substitution callers reach this only holding the path's exclusive--- lock ('trySubstitute', 'unpackVerifiedNar'): unlocked, this deletion is+--    trusted public key, unless its content address makes its path or+--    @require-sigs@ is off ('judgeNarInfo')+-- 5. @GET https:\/\/cache.example.com\/\<URL\>@, the file the narinfo's+--    @URL@ field names, and, in one bounded streaming pass, decompress,+--    hash, parse, and unpack into the store path+-- 6. Verify the declared NAR hash and size against the streamed bytes,+--    then re-verify the materialized tree from disk and hold it to the+--    content address the narinfo states, which must make the path+--    ('checkRegistrableAddress')+-- 7. Register in the store DB with references from narinfo+--+-- A build reads a path's narinfo before anything is downloaded, to realise+-- the references it declares first ('queryReferencesWith'), and then+-- fetches the path from the cache that served that narinfo, without asking+-- again ('fetchSubstituteWith').  Each cache that answers is asked about+-- each path once in a run, so a closure costs one narinfo request a path+-- from each cache it asks, and a query that failed is made again.  A path+-- that cache fails to deliver goes to the caches after it, their+-- references first ('queryNextOfferWith').+--+-- A cache that lacks the path (404, or another status upstream reads as+-- the file not being there) is passed over, and what no cache holds+-- builds locally.  A cache that fails is told apart from one that lacks+-- the path, as upstream tells them apart: a failed narinfo query and a+-- substitute that fails to arrive stop the build, unless+-- 'Nix.Realise.BuildFromSource' (upstream's @fallback@) says to build+-- instead ("Nix.Realise").+--+-- The fetch runs under an exclusive per-path lock+-- ("Nix.Store.Lock"), upstream's pathlocks protocol: taken once the+-- narinfo is judged and before any deletion or NAR download, validity+-- re-checked under it (another process's+-- finished path is adopted without touching disk), and held until the+-- caller's registration transaction commits.+--+-- == Caches in a directory+--+-- A @file:\/\/@ URL names a cache in a directory on this machine, as+-- upstream's local binary cache store reads one: the layout a push writes+-- there ("Nix.Push.Directory"), read through the same steps, with each+-- request a file read instead.  A narinfo or NAR file that is not there is+-- the cache lacking it, as a 404 is; any other failure to read one fails+-- as a failed transfer does, though once, since upstream retries only+-- downloads.  A file a narinfo names must lie below the directory+-- ('cacheFilePath').  The first query of a run opens each such cache as+-- upstream opens it ('openCacheDirectory'): one that cannot be opened, or+-- whose @nix-cache-info@ names another store directory, is passed over for+-- the run after a warning, as upstream drops a substituter it cannot+-- open, and one whose @Priority@ does not read fails the query whatever+-- the fallback, as it fails upstream's command.+--+-- == Cache priority+--+-- Multiple caches can be configured, checked in priority order:+--+-- @+-- substituters = https:\/\/cache.novavero.ai file:\/\/\/srv\/cache+-- trusted-public-keys = cache.novavero.ai-1:... cache.example.org-1:...+-- @+--+-- A @file:\/\/@ cache is asked at the priority its @nix-cache-info@+-- states, or at upstream's default of 0 when it states none, as upstream+-- reads that file for a cache's priority; caches of equal priority are+-- asked in the order configured.  An HTTP cache's @nix-cache-info@ is not+-- read: it is asked at the priority its t'CacheConfig' gives, where+-- upstream asks at the one the file states (cache.nixos.org states 40).+-- So among HTTP caches the configured priorities decide alone, and a+-- @file:\/\/@ cache stating a priority between an HTTP cache's stated one+-- and its configured one is asked on the other side of it from where+-- upstream asks it.+--+-- Our nova-cache server implements this protocol.  The narinfo format,+-- NAR serialization, signature verification - all handled by the+-- @nova-cache@ library.  This module orchestrates the requests and+-- builds each path's registration, which "Nix.Builder" records.+module Nix.Substituter+  ( -- * Substituting a closure+    SubstResult (..),+    Substitute,+    substitutePath,+    substituteCache,+    substituteSizes,+    CacheMemo,+    emptyCacheMemo,+    queryReferencesWith,+    queryNextOfferWith,+    fetchSubstituteWith,++    -- * Cache configuration+    CacheConfig (..),+    RequireSigs (..),+    defaultCacheConfig,+    cacheRequirement,++    -- * Failure classification+    AttemptFailure (..),+    attemptFailureMessage,+    narStreamFailure,+    withXzAttempt,+    catchSync,+    compressedBodyCeiling,+    downloadCapFor,++    -- * Verified NAR bytes+    VerifiedNar,+    verifyNar,+    verifiedNarBytes,+    verifiedNarDigest,++    -- * Pure helpers (exported for testing)+    maxNarInfoBody,+    readBodyCapped,+    validateNarInfoFields,+    NarInfoAnswer (..),+    judgeNarInfo,+    verifySigs,+    unsignedWarning,+    verifyNarHash,+    verifyNarSize,+    checkStatedAddress,+    checkContentAddress,+    narInfoMatchesPath,+    decompressorFor,+    decompressNar,+    streamingDecompressionSupported,+    withDecompressedSource,+    cappedBodySource,+    materializeNarFromSource,+    consumeNarStream,+    unpackAndVerify,+    clearStaleDestination,+    parseReferences,+    parseDeriver,+  )+where++import Control.Exception (Exception, IOException, SomeException, bracket, catch, catches, displayException, onException, throwIO, tryJust)+import Control.Monad (guard, void, when)+import Control.Monad.IO.Class (liftIO)+import Control.Monad.State.Strict (StateT, gets, modify')+import Data.Bifunctor (bimap, first)+import qualified Data.ByteString as BS+import Data.Either (isRight)+import Data.Foldable (traverse_)+import Data.IORef (newIORef, readIORef, writeIORef)+import Data.List (sortBy)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (catMaybes, fromMaybe)+import Data.Ord (comparing)+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Word (Word64)+import qualified Network.HTTP.Client as HTTP+import qualified Network.HTTP.Client.TLS as HTTPS+import qualified Network.HTTP.Types.Status as HTTP+import Nix.CacheDirectory (CacheInfo (..), CacheOpenFailure (..), cacheFilePath, fileUrlDirectory, openCacheDirectory)+import Nix.Compression (NarCompression (..), parseNarCompression)+import Nix.Daemon.Protocol (ContentAddress, ContentAddressMethod (..), Signature, caAlgo, caDigest, caMethod, parseContentAddress, parseSignature, renderContentAddress)+import Nix.Hash (FileIngestionMethod (..), ModuloHash, moduloHashFinalize, moduloHashInit, moduloHashUpdate)+import Nix.Http (AttemptFailure (..), FetchRetryPolicy, RetryEffects, TransferError (..), attemptFailureMessage, catchSync, fetchStatusFailure, retryTransient, statusError, transferFailureHandlers, withTransfer, withUserAgent)+import Nix.Key (keyRefusalReason, trustedKeys)+import Nix.Logger (Level (..), Logger (..), logMessage, logWarning)+import Nix.Realise (Fallback (..), Offer (..))+import Nix.Store (AddressedPath (..), ArchiveEnd (..), CaseSensitivity, NarStreamFailure (..), PathLock, SignatureRequirement (..), Store (..), UpstreamHazard (..), abortNarUnpack, acquirePathLock, addressMakesPath, addressRegistrable, canonicalizeMetadata, checkNarClaim, finishNarUnpack, isValid, narHashMismatch, narSizeMismatch, newNarUnpackSink, notContentAddressed, releasePathLock, sinkNarStream, unpackNarEntry, upstreamManagedRefusal, volumeCaseHack)+import Nix.Store.DB (PathRegistration (..), RegistrationTime (..), Ultimate (..))+import qualified Nix.Store.ExecBit as ExecBit+import Nix.Store.Path (StoreDir, StorePath (spHash, spName), defaultStoreDir, parseStorePathBaseName, storePathHashLen, storePathToFilePath, storePathToText)+import qualified NovaCache.Base32 as Nix32+import qualified NovaCache.Bzip2 as Bzip2+import qualified NovaCache.Hash as Hash+import qualified NovaCache.NAR as NAR+import qualified NovaCache.NarInfo as NarInfo+import qualified NovaCache.Signing as Signing+import qualified NovaCache.Validate as Validate+import qualified NovaCache.Xz as Xz+import qualified NovaCache.Zstd as Zstd+import qualified System.Directory as Dir+import System.IO (IOMode (ReadMode), hClose, openBinaryFile, withBinaryFile)+import System.IO.Error (isDoesNotExistError)++-- ---------------------------------------------------------------------------+-- Types+-- ---------------------------------------------------------------------------++-- | Configuration for a binary cache.+data CacheConfig = CacheConfig+  { -- | URL of the cache: the base URL of an HTTP cache (e.g.+    -- @https:\/\/cache.novavero.ai@), whose trailing slashes are dropped+    -- when the cache is opened, as upstream drops them, or the @file:\/\/@+    -- URL of a directory (e.g. @file:\/\/\/srv\/cache@, or+    -- @file:\/\/\/D:\/cache@ on Windows).+    ccUrl :: !Text,+    -- | Trusted public keys (@name:base64key@).  A narinfo is accepted+    -- when ANY of them verifies a signature, matching upstream's flat+    -- @trusted-public-keys@ set: the keys are not bound to a particular+    -- substituter, and one signed by any trusted key is enough.+    ccPublicKeys :: ![Text],+    -- | Files of secret keys whose public keys are trusted beside+    -- 'ccPublicKeys', as bytes, upstream's @secret-key-files@+    -- ('Nix.Key.trustedKeys').+    ccSecretKeyFiles :: ![BS.ByteString],+    -- | Whether a narinfo must be signed by a trusted key, upstream's+    -- @require-sigs@.+    ccRequireSigs :: !RequireSigs,+    -- | Priority (lower = checked first) of an HTTP cache;+    -- 'defaultCacheConfig' gives cache.nixos.org 40.  A @file:\/\/@ cache+    -- is asked at the priority its @nix-cache-info@ states instead.+    ccPriority :: !Int+  }+  deriving (Eq, Show)++-- | Where a cache's files are read.+data CacheTransport+  = -- | Over HTTP, below the cache's URL.+    HttpTransport+  | -- | From the directory the cache's @file:\/\/@ URL names.+    DirectoryTransport !FilePath+  deriving (Eq, Show)++-- | A cache as a run asks it: its configuration, with the priority it is+-- asked at, and where its files are read.  Only opening a cache makes one+-- ('openCache').+data OpenedCache = OpenedCache !CacheConfig !CacheTransport+  deriving (Eq, Show)++-- | The configuration of an opened cache.+openedConfig :: OpenedCache -> CacheConfig+openedConfig (OpenedCache cache _) = cache++-- | Whether a substituted path that is not content-addressed must be+-- signed by a trusted key, as upstream's @require-sigs@ says.+data RequireSigs+  = -- | It must, upstream's default.+    RequireSigs+  | -- | It is taken unsigned.+    AcceptUnsigned+  deriving (Eq, Show)++-- | Default cache configuration for cache.nixos.org.+defaultCacheConfig :: CacheConfig+defaultCacheConfig =+  CacheConfig+    { ccUrl = "https://cache.nixos.org",+      ccPublicKeys = ["cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY="],+      ccSecretKeyFiles = [],+      ccRequireSigs = RequireSigs,+      ccPriority = 40+    }++-- | Result of fetching a path from the cache that offered it+-- ('fetchSubstituteWith').+data SubstResult+  = -- | Verified and unpacked on disk, NOT yet registered: the carried+    -- registration is recorded by the caller, which batches every output+    -- of a derivation into one 'Nix.Store.DB.registerPaths' transaction so+    -- cross-output reference edges are never dropped.  The path's lock+    -- rides along STILL HELD, because the exclusion must survive until+    -- that transaction commits - released earlier, another process could+    -- meet the unpacked-but-unregistered window and delete the tree the+    -- row is about to describe.  The caller releases it after+    -- registration, on every exit path ("Nix.Builder").+    SubstSuccess !PathRegistration !PathLock+  | -- | The path was already valid under its lock - another process+    -- registered it while this one waited - so its work is adopted:+    -- nothing was downloaded, nothing touched disk, and no registration+    -- is needed.  The caller treats this as success.  No lock rides+    -- along; it was released before returning.+    SubstAlreadyValid+  | -- | The cache no longer holds the path's NAR, which upstream passes+    -- over without failing the substitution (@SubstituteGone@).+    SubstNotFound+  | -- | The cache failed to deliver the path: the download or its+    -- verification.  Upstream's failed substitution.  Or the store is one+    -- upstream Nix's database may also manage, refused before the NAR is+    -- asked for ("Nix.Store.Upstream").+    SubstError !Text+  deriving (Eq, Show)++-- ---------------------------------------------------------------------------+-- Main substitution logic+-- ---------------------------------------------------------------------------++-- | A path as one cache offers it: the path, that cache, the narinfo it+-- served for the path, and the caches after it in priority order.  The+-- narinfo validated, describes the path and is trusted ('judgeNarInfo'),+-- and the references realised before the path arrives are the ones it+-- declares.  The constructor is not exported: only the reference queries+-- make one ('queryReferencesWith', 'queryNextOfferWith'), so a fetch+-- is never handed a narinfo that skipped those checks or one checked for+-- another path, and the NAR and the references always come from the same+-- cache, as upstream's substitution goal copies a path from the substituter+-- whose path info it queried.+data Substitute = Substitute !StorePath !OpenedCache !NarInfo.NarInfo ![OpenedCache]+  deriving (Eq, Show)++-- | The path a t'Substitute' fetches.+substitutePath :: Substitute -> StorePath+substitutePath (Substitute sp _ _ _) = sp++-- | How many bytes a t'Substitute' downloads and unpacks, as its narinfo+-- states them: its @FileSize@, none when it states none, and its+-- @NarSize@.+substituteSizes :: Substitute -> (Word64, Word64)+substituteSizes (Substitute _ _ narInfo _) = (maybe 0 fromInteger (NarInfo.niFileSize narInfo), fromInteger (NarInfo.niNarSize narInfo))++-- | The cache a t'Substitute' comes from, with the priority it was asked+-- at.+substituteCache :: Substitute -> CacheConfig+substituteCache (Substitute _ cache _ _) = openedConfig cache++-- | What the caches have said in one run.  Each @file:\/\/@ cache is opened+-- once a run, where upstream opens each substituter once a process, so a+-- command that makes several runs opens it, and warns of one it passes+-- over, in each.  Each cache that answers about a path is asked once: the+-- narinfo it served, which validated, or 'Nothing' when it does not hold+-- the path.  A query that+-- failed is not remembered, so the next one asks again, and neither is a+-- cache whose @Priority@ did not read.  Upstream's per-store path-info cache+-- keeps the same: the info a substituter returned, a path it lacks+-- included, and never a failure, which is thrown before the cache is+-- written.  Its entries expire after @narinfo-cache-positive-ttl@ and+-- @narinfo-cache-negative-ttl@ (a month and an hour) and are also kept on+-- disk across runs; these last one run.+data CacheMemo = CacheMemo+  { -- | What opening each @file:\/\/@ cache found, by its URL.+    memoDirectories :: !(Map Text DirectoryOpening),+    -- | What each cache said about each path, by narinfo URL.+    memoNarInfos :: !(Map Text (Maybe NarInfo.NarInfo))+  }++-- | What opening a @file:\/\/@ cache found.+data DirectoryOpening+  = -- | The cache's directory, and the priority it is asked at.+    DirectoryOpened !FilePath !Int+  | -- | The cache is passed over for the run, as a warning said when it+    -- was opened.+    DirectoryDropped++-- | A run that has asked no cache anything.+emptyCacheMemo :: CacheMemo+emptyCacheMemo = CacheMemo {memoDirectories = Map.empty, memoNarInfos = Map.empty}++-- | Fetch a path from the cache that offered it, as that cache's narinfo+-- describes it, asking no cache anything more: the build's half of a+-- substitution whose reference query already read the narinfo+-- ('queryReferencesWith').  The path is the one the narinfo was checked+-- for, which the t'Substitute' carries, and the caller has made what it+-- references valid first, or the database refuses the registration this+-- returns.+--+-- Upstream's per-path substitution protocol: take the path's exclusive+-- lock FIRST, before any deletion or download, and re-check validity+-- under it - another process may have registered the path while this+-- one waited, and its finished work must be adopted+-- ('SubstAlreadyValid') rather than deleted and redone.  The lock then+-- holds across the delete, the download, materialization, and the+-- on-disk recheck; a successful result carries it still held (see+-- 'SubstSuccess'), and every other exit releases it here.  On success the+-- path is unpacked and read-only on disk but NOT registered - the caller+-- records the returned t'PathRegistration'.  The NAR request runs under+-- the given retry policy.+--+-- A store upstream Nix's database may also manage is refused+-- ('SubstError') before the lock is taken and before the NAR is asked for+-- ("Nix.Store.Upstream"): the destination is cleared before unpacking,+-- and a path upstream registered has no row here.  A NAR the cache no+-- longer holds is 'SubstNotFound', upstream's @SubstituteGone@.  A failure+-- is tagged with the cache's URL, and a synchronous exception is one+-- ('catchSync'), while an asynchronous one propagates: an interrupt+-- mid-download must abort the substitution, never send the path to the+-- next cache and from there to a local build.+fetchSubstituteWith :: FetchRetryPolicy -> RetryEffects IO -> Store -> Substitute -> IO SubstResult+fetchSubstituteWith policy effects store (Substitute sp cache narInfo _) =+  underPathLock store sp $ \lock -> do+    result <-+      streamFromCache (Retrying policy effects) store cache sp narInfo lock+        `catchSync` \err -> pure (SubstError ("substitution exception: " <> T.pack (show err)))+    pure $ case result of+      SubstError err -> SubstError (ccUrl (openedConfig cache) <> ": " <> err)+      other -> other++-- | Run a substitution of a path under its lock: refuse a store upstream+-- Nix's database may also manage before the lock is taken, adopt a path+-- valid under the lock ('SubstAlreadyValid'), and release the lock on+-- every exit but a success, which carries it still held.+underPathLock :: Store -> StorePath -> (PathLock -> IO SubstResult) -> IO SubstResult+underPathLock store sp substituteLocked = do+  refusal <- upstreamManagedRefusal ReplacesUpstreamPaths (stDir store)+  maybe substitute (pure . SubstError) refusal+  where+    substitute = do+      lock <- acquirePathLock (stLogger store) (stDir store) sp+      locked lock `onException` releasePathLock lock+    locked lock = do+      valid <- isValid store sp+      if valid+        then do+          releasePathLock lock+          pure SubstAlreadyValid+        else do+          result <- substituteLocked lock+          case result of+            SubstSuccess _ _ -> pure result+            other -> do+              releasePathLock lock+              pure other++-- | What the caches say about a path's references, from the first cache+-- whose narinfo may be used, with the t'Substitute' that fetches the path+-- from that cache.  References arrive before the path that names them+-- ("Nix.Realise"), so this runs ahead of any download, and a narinfo passes+-- the same checks as a substitution before its references are believed.+--+-- The caches are opened first ('openCaches'), and a cache whose+-- @Priority@ does not read fails the query with 'QueryFailed' whatever the+-- fallback.  They are asked in priority order, as upstream's substitution+-- goal asks them.  One without the path is passed over.  So is one whose+-- narinfo names another path, and the scan says why, and one no trusted+-- key signed, with upstream's warning ('unsignedWarning').  A query that+-- fails, once its retries are spent or on a narinfo that does not+-- validate, ends the scan with 'QueryFailed' under 'NoFallback', as+-- upstream rethrows it.  Under 'BuildFromSource' it is+-- reported and passed over, as upstream logs it and asks the next cache.+-- What the scan says, and the warning for a cache passed over, goes to+-- the logger.+--+-- A cache that answered about the path before in this run answers from+-- the run's t'CacheMemo' instead, so a closure requests each narinfo+-- once and a path no cache holds is looked for once; a query that failed+-- is made again.+queryReferencesWith :: Logger -> FetchRetryPolicy -> RetryEffects IO -> Fallback -> [CacheConfig] -> StorePath -> StateT CacheMemo IO (Offer Substitute)+queryReferencesWith logger policy effects fallback caches sp = do+  opened <- openCaches logger caches+  case opened of+    Left failure -> pure (QueryFailed failure)+    Right usable -> offerFrom logger (Retrying policy effects) fallback (sortCaches usable) sp++-- | 'queryReferencesWith' over the caches after the one a t'Substitute'+-- came from, for a path that substitute did not deliver: upstream's goal+-- moving on to its next substituter.+queryNextOfferWith :: Logger -> FetchRetryPolicy -> RetryEffects IO -> Fallback -> Substitute -> StateT CacheMemo IO (Offer Substitute)+queryNextOfferWith logger policy effects fallback (Substitute sp _ _ later) = offerFrom logger (Retrying policy effects) fallback later sp++-- | The first offer for a path among caches in the order given.+offerFrom :: Logger -> Retrying -> Fallback -> [OpenedCache] -> StorePath -> StateT CacheMemo IO (Offer Substitute)+offerFrom _ _ _ [] _ = pure NotOffered+offerFrom logger retry fallback (opened : rest) sp = do+  (errors, answer) <- askCache retry opened sp+  liftIO (traverse_ (logAt logger LevelError) errors)+  let next = offerFrom logger retry fallback rest sp+      cache = openedConfig opened+      queryFailure failure = QueryFailed (ccUrl cache <> ": " <> spName sp <> ": " <> failure)+      failed failure = case fallback of+        NoFallback -> pure (queryFailure failure)+        BuildFromSource -> liftIO (reportCache logger cache sp failure) >> next+  case answer of+    NarInfoUsable narInfo -> either failed (pure . Offered (Substitute sp opened narInfo rest)) (parseReferences (NarInfo.niReferences narInfo))+    NarInfoAbsent -> next+    NarInfoPassedOver reason -> liftIO (reportCache logger cache sp reason) >> next+    NarInfoUnsigned -> liftIO (logWarning logger (unsignedWarning cache sp)) >> next+    NarInfoFailed failure -> failed failure+    NarInfoTrustFailed failure -> pure (queryFailure failure)++-- | Upstream's warning of a cache's narinfo that no trusted key signed,+-- the path spelled under the logical store directory.+unsignedWarning :: CacheConfig -> StorePath -> Text+unsignedWarning cache sp =+  "ignoring substitute for '" <> storePathToText defaultStoreDir sp <> "' from '" <> ccUrl cache <> "', as it's not signed by any of the keys in 'trusted-public-keys'"++-- | Tell the logger what one cache did with a path.+reportCache :: Logger -> CacheConfig -> StorePath -> Text -> IO ()+reportCache logger cache sp message =+  logMessage logger ("  [subst] " <> ccUrl cache <> ": " <> spName sp <> ": " <> message)++-- ---------------------------------------------------------------------------+-- Opening caches+-- ---------------------------------------------------------------------------++-- | The caches a run asks, each opened once in the run ('openCache'): an+-- HTTP cache as configured, its URL without trailing slashes, and a+-- @file:\/\/@ cache as upstream opens a local binary cache store+-- ('openCacheDirectory'), asked at the priority its @nix-cache-info@+-- states, or at upstream's default when it states none.  One that cannot+-- be opened is left out after a warning to the logger, as upstream drops+-- a substituter it cannot open.  One whose @Priority@ does not read+-- is the 'Left', as it fails upstream's command, and is opened again by+-- the next query.+openCaches :: Logger -> [CacheConfig] -> StateT CacheMemo IO (Either Text [OpenedCache])+openCaches logger caches = fmap catMaybes . sequenceA <$> traverse (openCache logger) caches++-- | One cache, opened for the run ('openCaches'): 'Nothing' when it is+-- passed over.+openCache :: Logger -> CacheConfig -> StateT CacheMemo IO (Either Text (Maybe OpenedCache))+openCache logger cache = case fileUrlDirectory "state its priority in its nix-cache-info" (T.unpack url) of+  Nothing -> pure (Right (Just (OpenedCache cache {ccUrl = T.dropWhileEnd (== '/') url} HttpTransport)))+  Just named -> do+    remembered <- gets (Map.lookup url . memoDirectories)+    fmap usable <$> maybe (openDirectory named) (pure . Right) remembered+  where+    url = ccUrl cache+    usable opening = case opening of+      DirectoryOpened dir priority -> Just (OpenedCache cache {ccPriority = priority} (DirectoryTransport dir))+      DirectoryDropped -> Nothing+    openDirectory named = case named of+      Left refusal -> dropped refusal+      Right dir -> do+        outcome <- liftIO (openCacheDirectory url dir)+        case outcome of+          Left (CachePriorityInvalid message) -> pure (Left message)+          Left (CacheUnopenable message) -> dropped message+          Right info -> remember (DirectoryOpened dir (fromMaybe defaultCachePriority (ciPriority info)))+    dropped message = do+      liftIO (logWarning logger message)+      remember DirectoryDropped+    remember :: DirectoryOpening -> StateT CacheMemo IO (Either Text DirectoryOpening)+    remember opening = do+      modify' (\memo -> memo {memoDirectories = Map.insert url opening (memoDirectories memo)})+      pure (Right opening)++-- | The priority a @file:\/\/@ cache is asked at when its @nix-cache-info@+-- states none: upstream's default for every store's @priority@ setting,+-- which that file's field replaces.+defaultCachePriority :: Int+defaultCachePriority = 0++-- | Sort caches by priority, lower first, and those of one priority in the+-- order given, as upstream sorts its substituters.+sortCaches :: [OpenedCache] -> [OpenedCache]+sortCaches = sortBy (comparing (ccPriority . openedConfig))++-- | The retry policy and its effects, carried to every request one+-- substitution makes.+data Retrying = Retrying !FetchRetryPolicy !(RetryEffects IO)++-- | Run one request's attempt under the carried policy when its cache is+-- served over HTTP.  A directory's file is read once, as upstream retries+-- downloads alone.+attemptOn :: Retrying -> OpenedCache -> IO (Either AttemptFailure a) -> IO (Either AttemptFailure a)+attemptOn (Retrying policy effects) (OpenedCache _ transport) attempt = case transport of+  HttpTransport -> retryTransient policy effects attempt+  DirectoryTransport _ -> attempt++-- | Stream a path's NAR from the cache whose narinfo is given+-- ('streamWithRetry').  Unsupported compression rejects before the+-- download: the value is known from the narinfo, and a multi-hundred-MB+-- download that can only fail in decompression is pure waste.  It is+-- still a failed substitute, as upstream's decompressor fails one.  The+-- strict 'decompressorFor' encodes the same support set; the suite pins+-- their agreement.+streamFromCache :: Retrying -> Store -> OpenedCache -> StorePath -> NarInfo.NarInfo -> PathLock -> IO SubstResult+streamFromCache retry store cache sp narInfo lock =+  case streamingDecompressionSupported (NarInfo.niCompression narInfo) of+    Left err -> pure (SubstError err)+    Right () -> streamWithRetry retry store cache sp narInfo lock++-- | One cache's narinfo for a path, judged before anything is downloaded.+data NarInfoAnswer+  = -- | A narinfo for the path that validates and is trusted: signed by a+    -- trusted key, content-addressed, or under @require-sigs@ off.+    NarInfoUsable !NarInfo.NarInfo+  | -- | The cache does not hold the path.+    NarInfoAbsent+  | -- | A narinfo naming another path, which upstream reads as the path+    -- not being in that cache, passed over, and why.+    NarInfoPassedOver !Text+  | -- | A narinfo no trusted key signed, which upstream warns of and+    -- passes over ('unsignedWarning').+    NarInfoUnsigned+  | -- | The query failed: the transfer once its retries are spent, or a+    -- body that does not parse or validate.+    NarInfoFailed !Text+  | -- | The narinfo's trust cannot be decided: a trusted key or a secret+    -- key file that does not read, or a content address that makes no+    -- path.  Upstream decides trust outside the try that takes a failed+    -- query for the cache's, so this ends the substitution whatever+    -- @fallback@ says.+    NarInfoTrustFailed !Text+  deriving (Eq, Show)++-- | One cache's narinfo for a path, judged ('judgeNarInfo') under what+-- the cache's settings ask of it ('cacheRequirement'), with the lines+-- upstream prints at its error level as it judges one: from the+-- t'CacheMemo' when the run has had it from that cache, and otherwise+-- fetched under the substitution's retry policy and remembered unless the+-- query failed.  A narinfo whose fields do not validate is a failed query,+-- as upstream's parser throws on one.+askCache :: Retrying -> OpenedCache -> StorePath -> StateT CacheMemo IO ([Text], NarInfoAnswer)+askCache retry opened sp = do+  remembered <- gets (Map.lookup url . memoNarInfos)+  case remembered of+    Just held -> liftIO (heldAnswer held)+    Nothing -> do+      fetched <- liftIO (fetchNarInfo retry opened narInfoFile)+      case fetched of+        Left failure -> pure ([], NarInfoFailed failure)+        Right held -> do+          when (isRight (traverse_ validateNarInfoFields held)) $+            modify' (\memo -> memo {memoNarInfos = Map.insert url held (memoNarInfos memo)})+          liftIO (heldAnswer held)+  where+    cache = openedConfig opened+    narInfoFile = spHash sp <> ".narinfo"+    url = ccUrl cache <> "/" <> narInfoFile+    heldAnswer = maybe (pure ([], NarInfoAbsent)) (\narInfo -> (\required -> judgeNarInfo required sp narInfo) <$> cacheRequirement cache)++-- | A narinfo request under the substitution's retry policy: what the cache+-- holds, or why the query failed.+fetchNarInfo :: Retrying -> OpenedCache -> Text -> IO (Either Text (Maybe NarInfo.NarInfo))+fetchNarInfo retry cache file =+  (first attemptFailureMessage <$> attemptOn retry cache (fetchNarInfoOnce cache file))+    `catchSync` \err -> pure (Left ("query exception: " <> T.pack (show err)))++-- | Whether a served narinfo may be used, decided from the narinfo and+-- what the cache's settings ask of it ('cacheRequirement'), in upstream's+-- order, with the lines upstream prints at its error level as it decides.+-- The fields validate first, standing in for upstream's narinfo parser,+-- and above all before 'verifySigs' builds the signed fingerprint from+-- them.  The narinfo must then describe the requested path: a+-- misconfigured or hostile cache could return a validly signed narinfo+-- for a different path under this hash's URL.  Last comes its trust, as+-- upstream's store decides whether a path it copies in is trusted: under+-- @require-sigs@ off every narinfo is; otherwise the trusted keys must+-- read, and then a narinfo whose content address and references make its+-- path is trusted unsigned, its tree held to that address once it is+-- fetched ('checkRegistrableAddress'); an address that makes another path+-- is warned of at the error level ('notContentAddressed') and the narinfo+-- needs a signature, as one with no address does, and is refused once it+-- is fetched however it is trusted; and an address that makes no path, or+-- keys that do not read, fail the trust check in upstream's words+-- ('NarInfoTrustFailed').  A narinfo needing a signature is used when one+-- of the keys verifies one of its signatures.+-- A @CA@ that does not parse is no address here, and fails the path once+-- it is fetched.+judgeNarInfo :: Either Text SignatureRequirement -> StorePath -> NarInfo.NarInfo -> ([Text], NarInfoAnswer)+judgeNarInfo required sp narInfo+  | Left err <- validateNarInfoFields narInfo = ([], NarInfoFailed err)+  | not (narInfoMatchesPath sp narInfo) = ([], NarInfoPassedOver ("narinfo names " <> NarInfo.niStorePath narInfo))+  | otherwise = case required of+      Left err -> ([], NarInfoTrustFailed err)+      Right SignaturesNotRequired -> ([], NarInfoUsable narInfo)+      Right (RequireSignature keys) -> case statedAddress of+        Just MakesItsPath -> ([], NarInfoUsable narInfo)+        Just (MakesNoPath refusal) -> ([], NarInfoTrustFailed refusal)+        Just MakesAnotherPath -> ([notContentAddressed sp], signedBy keys)+        Nothing -> ([], signedBy keys)+  where+    statedAddress = do+      spelled <- NarInfo.niCA narInfo+      address <- either (const Nothing) Just (parseContentAddress spelled)+      refs <- either (const Nothing) Just (parseReferences (NarInfo.niReferences narInfo))+      pure (addressMakesPath sp refs address)+    signedBy keys+      | verifySigs keys narInfo = NarInfoUsable narInfo+      | otherwise = NarInfoUnsigned++-- | What a cache's narinfos are held to, as its settings ask+-- ('judgeNarInfo'): nothing under @require-sigs@ off, and otherwise a+-- signature by one of the keys it trusts ('Nix.Key.trustedKeys'), read+-- each time it is asked, as a key file may change between two+-- substitutions.  A trusted key or a secret key file that does not read+-- is the failure the substitution ends with.+cacheRequirement :: CacheConfig -> IO (Either Text SignatureRequirement)+cacheRequirement cache = case ccRequireSigs cache of+  AcceptUnsigned -> pure (Right SignaturesNotRequired)+  RequireSigs -> case configuredKeys cache of+    Left err -> pure (Left err)+    Right given -> bimap keyRefusalReason RequireSignature <$> trustedKeys given (ccSecretKeyFiles cache)++-- | Validate narinfo field syntax before anything consumes the fields -+-- above all before 'verifySigs' builds the signed fingerprint from them.+-- The fingerprint is delimited text (semicolons between fields, commas+-- between references), so each field must have parsed as well-formed+-- before it is spliced in; a malformed narinfo fails here as a plain+-- parse error instead of flowing onward.  The checks are nova-cache's+-- 'Validate.validateNarInfo': store path, references, hash spellings,+-- sizes, and the no-@.drv@ rule.+validateNarInfoFields :: NarInfo.NarInfo -> Either Text ()+validateNarInfoFields narInfo = case Validate.validateNarInfo narInfo of+  Right _ -> Right ()+  Left errs ->+    Left ("invalid narinfo: " <> T.intercalate "; " (map renderValidationError errs))++-- | One 'Validate.ValidationError' in the register the other+-- substitution errors use.+renderValidationError :: Validate.ValidationError -> Text+renderValidationError verr = case verr of+  Validate.NegativeFileSize n -> "negative FileSize " <> T.pack (show n)+  Validate.NegativeNarSize n -> "negative NarSize " <> T.pack (show n)+  Validate.InvalidStorePath raw parseErr -> fieldError "StorePath" raw parseErr+  Validate.InvalidFileHash raw parseErr -> fieldError "FileHash" raw parseErr+  Validate.InvalidNarHash raw parseErr -> fieldError "NarHash" raw parseErr+  Validate.InvalidReference raw parseErr -> fieldError "Reference" raw parseErr+  Validate.NarHashMismatch expected actual ->+    "NarHash mismatch: declared " <> expected <> ", computed " <> actual+  Validate.FileHashMismatch expected actual ->+    "FileHash mismatch: declared " <> expected <> ", computed " <> actual+  Validate.SignatureInvalid sig -> "signature failed verification: " <> sig+  Validate.NoSignatures -> "narinfo has no signatures"+  Validate.DerivationStorePath path -> "StorePath names a derivation: " <> path+  where+    fieldError field raw parseErr =+      field <> " '" <> raw <> "' does not parse: " <> T.pack parseErr++-- | NAR bytes that passed 'verifyNar': they hash to the narinfo's+-- NarHash and count its NarSize, with the content address the narinfo+-- states, which the unpacked tree is held to ('checkRegistrableAddress').+-- The constructor is not exported, so 'verifyNar' is the only way to+-- obtain one and 'unpackVerifiedNar', the strict pipeline's unpack sink,+-- cannot be reached with bytes that skipped the check:+-- verify-then-unpack is a type, not a statement order.  The decoded+-- digest rides along because registration records its canonical spelling+-- and the on-disk recheck compares against it, so neither re-parses the+-- narinfo's NarHash.+-- Only the strict pipeline can carry this: the streaming pipeline+-- writes to disk before the hash can be known (upstream's ordering)+-- and relies on its cleanup contract instead+-- ('materializeNarFromSource').+data VerifiedNar = VerifiedNar !BS.ByteString !Hash.NixHash !(Maybe Text)+  deriving (Eq, Show)++-- | The verified bytes.+verifiedNarBytes :: VerifiedNar -> BS.ByteString+verifiedNarBytes (VerifiedNar bytes _ _) = bytes++-- | The digest the verified bytes hash to, decoded from the narinfo's+-- NarHash.+verifiedNarDigest :: VerifiedNar -> Hash.NixHash+verifiedNarDigest (VerifiedNar _ digest _) = digest++-- | The content address the narinfo states, if it states one.+verifiedNarAddress :: VerifiedNar -> Maybe Text+verifiedNarAddress (VerifiedNar _ _ address) = address++-- | The only constructor of a t'VerifiedNar': the hash check, then the+-- size check, with the decoded declared digest carried out.  The NAR+-- hash is the content-addressed integrity contract; a signature only+-- attests to the narinfo, not the body, and a narinfo taken unsigned+-- attests to nothing, so network corruption or a compromised cache is+-- caught here, before the bytes are trusted.+verifyNar :: NarInfo.NarInfo -> BS.ByteString -> Either Text VerifiedNar+verifyNar narInfo rawNar = do+  declared <- verifyNarHash narInfo rawNar+  verifyNarSize narInfo rawNar+  pure (VerifiedNar rawNar declared (NarInfo.niCA narInfo))++-- | Verify the NAR hash and size, deserialize, unpack to the store, and+-- set permissions: 'verifyNar', then 'unpackVerifiedNar'.  Returns the+-- path's registration for the caller to record; no database write+-- happens here (see 'SubstSuccess').  The strict counterpart of the+-- streaming pipeline, kept as its differential oracle: the suite+-- materializes the same NAR through both and requires identical trees.+unpackAndVerify :: Store -> StorePath -> NarInfo.NarInfo -> BS.ByteString -> IO SubstResult+unpackAndVerify store sp narInfo rawNar =+  -- Narinfo metadata is parsed before any disk write: a malformed+  -- narinfo must not leave an unpacked-but-unregistered path behind.+  case verifiedInputs of+    Left err -> pure (SubstError err)+    Right (verified, refs, deriver) -> unpackVerifiedNar store sp verified refs deriver (narInfoSignatures narInfo)+  where+    verifiedInputs = do+      verified <- verifyNar narInfo rawNar+      refs <- parseReferences (NarInfo.niReferences narInfo)+      deriver <- parseDeriver (stDir store) (NarInfo.niDeriver narInfo)+      pure (verified, refs, deriver)++-- | The strict pipeline's unpack sink: deserialize a t'VerifiedNar',+-- materialize it at the store path, seal it read-only, and recheck the+-- tree on disk against the carried digest before building its+-- registration from the references, deriver and signatures.  Follows the same+-- per-path lock protocol as the live pipeline: the lock is taken+-- before the stale destination is cleared, validity re-checks under+-- it, and a success carries the lock still held.  A store upstream+-- Nix's database may also manage is refused before the lock, as the+-- live pipeline refuses it.+unpackVerifiedNar :: Store -> StorePath -> VerifiedNar -> [StorePath] -> Maybe Text -> Set Signature -> IO SubstResult+unpackVerifiedNar store sp verified refs deriver sigs =+  case NAR.deserialise (verifiedNarBytes verified) of+    Left err -> pure (SubstError ("NAR deserialisation failed: " <> T.pack err))+    Right narEntry -> do+      refusal <- upstreamManagedRefusal ReplacesUpstreamPaths (stDir store)+      maybe (unpackUnderLock narEntry) (pure . SubstError) refusal+  where+    unpackUnderLock narEntry = do+      lock <- acquirePathLock (stLogger store) (stDir store) sp+      result <- unpackLocked narEntry lock `onException` releasePathLock lock+      case result of+        SubstSuccess _ _ -> pure result+        other -> do+          releasePathLock lock+          pure other+    digest = verifiedNarDigest verified+    destPath = storePathToFilePath (stDir store) sp+    unpackLocked narEntry lock = do+      alreadyValid <- isValid store sp+      if alreadyValid+        then pure SubstAlreadyValid+        else do+          unpackResult <-+            fmap+              Right+              ( do+                  clearStaleDestination destPath+                  unpackNarEntry (stCaseSensitivity store) destPath narEntry+              )+              `catchSync` (pure . Left)+          case (unpackResult :: Either SomeException (Either Text ())) of+            Left err -> pure (SubstError ("unpack failed: " <> T.pack (show err)))+            Right (Left err) -> pure (SubstError ("unpack failed: " <> err))+            Right (Right ()) -> do+              canonicalizeMetadata destPath+              -- A path registered valid must match its recorded hash ON+              -- DISK, not merely in the verified bytes: any divergence+              -- the filesystem introduced between the NAR and the+              -- materialized tree (name folding, link replication) must+              -- surface here, before the row exists.  A mismatching tree+              -- is removed - left in place it would be adopted by+              -- existence checks at this path.+              onDisk <- ExecBit.serialiseFromPath (volumeCaseHack (stCaseSensitivity store)) destPath+              addressed <-+                if Hash.hashBytes (NAR.serialise onDisk) /= digest+                  then pure (Left ("unpacked tree does not reproduce the declared NAR hash at " <> T.pack destPath))+                  else checkRegistrableAddress store sp refs destPath (verifiedNarAddress verified)+              case addressed of+                Left err -> do+                  Dir.removePathForcibly destPath+                  pure (SubstError err)+                Right address ->+                  pure $+                    SubstSuccess+                      PathRegistration+                        { prPath = sp,+                          -- The canonical spelling of the verified digest,+                          -- so the DB converges on one hash spelling+                          -- regardless of the cache's.+                          prNarHash = Hash.formatNixHash digest,+                          -- The verified actual byte count (equal to the+                          -- declared NarSize per 'verifyNarSize') - no+                          -- Integer conversion that could wrap.+                          prNarSize = BS.length (verifiedNarBytes verified),+                          prDeriver = deriver,+                          prReferences = refs,+                          prUltimate = NotUltimate,+                          prSignatures = sigs,+                          prContentAddress = address,+                          prRegistrationTime = RegisteredNow+                        }+                      lock++-- | Hold a substituted tree to the content address its narinfo states, as+-- upstream's store holds a path it adds once the NAR's hash and size are+-- checked: the tree is hashed as the address's method reads it, its NAR,+-- or for a flat or text address the bytes of the regular file it must+-- be, modulo the path's hash part, and refused in upstream's words when+-- that differs.  A narinfo that states no address holds the tree to its+-- NarHash alone, as upstream's does.  The address the tree was held to,+-- if any, is the one its registration records.+checkStatedAddress :: NAR.CaseHack -> StoreDir -> StorePath -> FilePath -> Maybe Text -> IO (Either Text (Maybe ContentAddress))+checkStatedAddress caseHack dir sp destPath stated = case stated of+  Nothing -> pure (Right Nothing)+  Just spelled -> case parseContentAddress spelled of+    Left err -> pure (Left ("narinfo CA '" <> spelled <> "' does not parse: " <> err))+    Right address -> (Just address <$) <$> checkContentAddress caseHack dir sp destPath address++-- | What a substituted tree must pass before its path is registered with+-- the content address its narinfo states: the tree is held to the address+-- ('checkStatedAddress'), and the address, stated with the references+-- given, must make the path, as upstream's store checks as it registers a+-- path ('addressRegistrable').  That holds whether or not a signature+-- vouched for the narinfo, so a narinfo taken unsigned, or signed for an+-- address that makes another path, is refused here and nothing is+-- registered.  The address the registration records, if any.+checkRegistrableAddress :: Store -> StorePath -> [StorePath] -> FilePath -> Maybe Text -> IO (Either Text (Maybe ContentAddress))+checkRegistrableAddress store sp refs destPath stated = do+  held <- checkStatedAddress (volumeCaseHack (stCaseSensitivity store)) (stDir store) sp destPath stated+  case held of+    Right (Just address) -> (Just address <$) <$> addressRegistrable (stLogger store) sp refs address+    other -> pure other++-- | Hold the tree at a path to a content address, as upstream's store+-- holds a path it adds once the NAR's hash and size are checked: the tree+-- is hashed as the address's method reads it, its NAR, or for a flat or+-- text address the bytes of the regular file it must be, modulo the+-- path's hash part, and refused in upstream's words when that differs,+-- the path spelled under the store directory given.+checkContentAddress :: NAR.CaseHack -> StoreDir -> StorePath -> FilePath -> ContentAddress -> IO (Either Text ())+checkContentAddress caseHack dir sp destPath address = case moduloHashInit (caAlgo address) (TE.encodeUtf8 (spHash sp)) of+  Nothing -> pure (Left ("content address '" <> renderContentAddress address <> "' names an algorithm nova-nix cannot hash with"))+  Just start -> (>>= compared) <$> treeDigest caseHack (caMethod address) start destPath+  where+    compared got+      | got == caDigest address = Right ()+      | otherwise =+          Left+            ( "ca hash mismatch importing path '"+                <> storePathToText dir sp+                <> "';\n  specified: "+                <> caAlgo address+                <> ":"+                <> Nix32.encode (caDigest address)+                <> "\n  got:       "+                <> caAlgo address+                <> ":"+                <> Nix32.encode got+            )++-- | A tree's digest modulo a hash part as a content address's method+-- reads the tree: its NAR, or the bytes of the regular file a flat or+-- text address names.+treeDigest :: NAR.CaseHack -> ContentAddressMethod -> ModuloHash -> FilePath -> IO (Either Text BS.ByteString)+treeDigest caseHack method start path = case method of+  FixedMethod NarIngestion -> Right <$> ExecBit.withNarSource caseHack path (absorb start)+  FixedMethod FlatIngestion -> fileDigest+  TextMethod -> fileDigest+  where+    absorb !state pull = do+      chunk <- pull+      if BS.null chunk then pure (moduloHashFinalize state) else absorb (moduloHashUpdate state chunk) pull+    fileDigest = do+      link <- Dir.pathIsSymbolicLink path+      regular <- if link then pure False else Dir.doesFileExist path+      if regular+        then Right <$> withBinaryFile path ReadMode (\handle -> absorb start (BS.hGetSome handle fileReadChunkBytes))+        else pure (Left ("'" <> T.pack path <> "' is not a regular file, which its flat content address names"))++-- | How many bytes of a file 'treeDigest' reads at a time.+fileReadChunkBytes :: Int+fileReadChunkBytes = 64 * 1024++-- | Verify that the downloaded NAR bytes hash to the narinfo's declared+-- NarHash, returning the decoded digest on success so registration can+-- record its canonical spelling.  Compares decoded hash bytes; the+-- declared NarHash parses only as @sha256:@ and nix-base32+-- (@parseNixHash@).+verifyNarHash :: NarInfo.NarInfo -> BS.ByteString -> Either Text Hash.NixHash+verifyNarHash narInfo rawNar =+  case Hash.parseNixHash (NarInfo.niNarHash narInfo) of+    Left err -> Left ("invalid narinfo NarHash: " <> T.pack err)+    Right declared+      | declared == actual -> Right declared+      | otherwise -> Left (narHashMismatch (NarInfo.niStorePath narInfo) declared actual)+  where+    actual = Hash.hashBytes rawNar++-- | Verify that the downloaded NAR's byte count equals the narinfo's+-- declared NarSize.  The hash check pins the content, but the size is a+-- separate claim that flows into the store DB (and from there into+-- re-pushed narinfos), so a wrong declaration must be rejected rather+-- than recorded.+verifyNarSize :: NarInfo.NarInfo -> BS.ByteString -> Either Text ()+verifyNarSize narInfo rawNar+  | toInteger (BS.length rawNar) == NarInfo.niNarSize narInfo = Right ()+  | otherwise = Left (narSizeMismatch (NarInfo.niStorePath narInfo) (NarInfo.niNarSize narInfo) (toInteger (BS.length rawNar)))++-- | Whether a served narinfo describes the requested path: the hash and+-- name components of its declared StorePath must equal the requested+-- path's, as upstream Nix holds one.  Only the base name is compared;+-- 'validateNarInfoFields', which 'judgeNarInfo' runs first, holds the+-- StorePath to the canonical store directory.+narInfoMatchesPath :: StorePath -> NarInfo.NarInfo -> Bool+narInfoMatchesPath sp narInfo =+  storePathBaseOf (NarInfo.niStorePath narInfo) == Just (spHash sp, spName sp)++-- | The hash and the name of a full store path's base name, if well-formed+-- (@\<hash\>-\<name\>@ with a hash of the expected length).+storePathBaseOf :: Text -> Maybe (Text, Text)+storePathBaseOf path =+  let base = T.takeWhileEnd (\c -> c /= '/' && c /= '\\') path+      (hashPart, rest) = T.splitAt storePathHashLen base+   in case T.stripPrefix "-" rest of+        Just name | T.length hashPart == storePathHashLen -> Just (hashPart, name)+        _ -> Nothing++-- ---------------------------------------------------------------------------+-- Reading a cache's files+-- ---------------------------------------------------------------------------++-- | Cap on a narinfo response body, mirroring nova-cache's server-side+-- @maxNarInfoBodySize@ - the server bounds what it reads, and the+-- client bounds what any cache in its list can make it buffer.+-- Narinfo is small key-value text; 4 MB is far beyond any real one.+maxNarInfoBody :: Int+maxNarInfoBody = 4 * 1024 * 1024++-- | Read a chunk source, an HTTP response body or a file, in bounded+-- chunks up to a byte cap - 'Nothing' once the cap is exceeded, so an+-- over-large body aborts mid-stream instead of buffering without limit.+-- The client-side mirror of nova-cache's @readBodyLimited@.+readBodyCapped :: Int -> IO BS.ByteString -> IO (Maybe BS.ByteString)+readBodyCapped cap reader = go [] 0+  where+    go chunks !total = do+      chunk <- reader+      if BS.null chunk+        then pure (Just (BS.concat (reverse chunks)))+        else+          let newTotal = total + BS.length chunk+           in if newTotal > cap+                then pure Nothing+                else go (chunk : chunks) newTotal++-- | Read one file of a cache, named relative to it, the consumer given+-- the file's bytes as a chunk source: @Right Nothing@ when the cache does+-- not hold the file.+--+-- Over HTTP, that is a 'NotFound' or 'Forbidden' answer (404, 410, 401,+-- 403, 407), the cache saying so, not a failure to retry: upstream's+-- transfer layer retries neither, and its binary cache store reads both+-- as the file not being there.  Any other status is a failure, retried+-- when upstream retries it, and the transfer layer classifies what the+-- request throws ('transferFailureHandlers').  The process-global TLS+-- manager serves every request, for its connection pooling and+-- keep-alive.+--+-- From a directory, it is the file not existing, as upstream's local+-- binary cache store reads one.  A name the cache cannot hold+-- ('cacheFilePath'), and any other failure to read the file or to write+-- what it carries, fails, and is never retried ('attemptOn').+readCacheFile :: OpenedCache -> Text -> (IO BS.ByteString -> IO (Either AttemptFailure a)) -> IO (Either AttemptFailure (Maybe a))+readCacheFile (OpenedCache cache transport) file consume = case transport of+  HttpTransport -> overHttp `catches` transferFailureHandlers url+  DirectoryTransport dir -> either (pure . Left . FatalFailure) fromFile (cacheFilePath dir file)+  where+    url = ccUrl cache <> "/" <> file+    overHttp = do+      manager <- HTTPS.getGlobalManager+      request <- withUserAgent <$> HTTP.parseRequest (T.unpack url)+      withTransfer request manager $ \response ->+        let status = HTTP.responseStatus response+         in if status == HTTP.status200+              then fmap Just <$> consume (HTTP.responseBody response)+              else pure (unserved status)+    unserved status = case statusError status of+      NotFound -> Right Nothing+      Forbidden -> Right Nothing+      Misc -> Left (fetchStatusFailure url status)+      Transient -> Left (fetchStatusFailure url status)+    -- Only the open's does-not-exist is the cache lacking the file: one+    -- raised while the consumer writes is a failure like any other.+    fromFile path =+      bracket (tryJust (guard . isDoesNotExistError) (openBinaryFile path ReadMode)) (traverse_ hClose) (readOpened . either (const Nothing) Just)+        `catch` readFailure+    readOpened opened = case opened of+      Nothing -> pure (Right Nothing)+      Just fileHandle -> fmap Just <$> consume (BS.hGetSome fileHandle fileReadChunkBytes)+    readFailure :: IOException -> IO (Either AttemptFailure b)+    readFailure err = pure (Left (FatalFailure (T.pack (displayException err))))++-- | One narinfo request: @Right Nothing@ when the cache does not hold it+-- ('readCacheFile').  A narinfo that arrived whole and does not parse, or+-- overruns 'maxNarInfoBody', is the cache's bytes and fails at once.+fetchNarInfoOnce :: OpenedCache -> Text -> IO (Either AttemptFailure (Maybe NarInfo.NarInfo))+fetchNarInfoOnce cache file = readCacheFile cache file $ \body -> do+  capped <- readBodyCapped maxNarInfoBody body+  pure $ case capped of+    Nothing ->+      Left (FatalFailure ("narinfo body exceeds " <> T.pack (show maxNarInfoBody) <> " bytes"))+    -- Lenient decode: the body is cache-controlled bytes, and a stray+    -- invalid UTF-8 sequence must surface as a narinfo parse error, not+    -- an impure UnicodeException (the push side decodes the same way).+    Just bytes -> first (\err -> FatalFailure ("narinfo parse error: " <> T.pack err)) (NarInfo.parseNarInfo (TE.decodeUtf8Lenient bytes))++-- | Stream one substitution end to end, each attempt under the+-- substitution's retry policy where the cache is served over HTTP+-- ('fetchSubstituteWith', 'attemptOn').+--+-- By the time this runs the narinfo has already been fetched and judged+-- ('judgeNarInfo'), so the cache claims to hold this path.  Failures+-- carry their own retry class: a 'TransientFailure' - transport+-- errors, torn or truncated transfers, a status upstream retries,+-- anything a fresh attempt could plausibly complete - consumes retry+-- budget with upstream's backoff, while a 'FatalFailure' - a completed+-- transfer that verifies wrong, a body past its ceiling, a+-- status upstream never retries, a write the disk refused - ends the+-- attempt at once: retrying a deterministic failure only delays the+-- outcome.  Every attempt starts from a clean slate+-- ('streamNarIntoStore' clears the destination first, and every+-- failure path, exceptions included, removes what it wrote), so a retry+-- restarts the NAR from its first byte, where upstream resumes from the+-- written offset when the server accepts ranges and otherwise retries+-- only a transfer that wrote nothing yet.  A NAR the narinfo named and+-- the cache does not hold ('readCacheFile') is gone: one request, as+-- upstream's @SubstituteGone@, reported and then a miss the cache scan+-- passes over, because upstream's substitution goal treats a gone+-- substitute like one that never existed rather than as a failure.  A+-- narinfo the cache does not hold is a miss handled earlier in 'askCache'+-- and never reaches here.+streamWithRetry :: Retrying -> Store -> OpenedCache -> StorePath -> NarInfo.NarInfo -> PathLock -> IO SubstResult+streamWithRetry retry store cache sp narInfo lock = do+  outcome <- attemptOn retry cache (streamNarIntoStore cache store sp narInfo)+  case outcome of+    Right (Just registration) -> pure (SubstSuccess registration lock)+    Right Nothing -> do+      reportCache (stLogger store) (openedConfig cache) sp ("file '" <> NarInfo.niUrl narInfo <> "' does not exist in the binary cache")+      pure SubstNotFound+    Left failure -> pure (SubstError (attemptFailureMessage failure))++-- | Thrown inside the streaming pipeline where a chunk convention has+-- no error channel (the capped body source); converted back to the+-- pipeline's 'Left' at the attempt boundary in 'streamNarIntoStore'.+newtype StreamAbort = StreamAbort Text+  deriving (Show)++instance Exception StreamAbort++-- | Convert a t'StreamAbort' one attempt throws into the pipeline's+-- failure channel, so the retry budget governs it and the caller's+-- cleanup contract holds on every exit.  A body past its ceiling is the+-- cache misdeclaring, not a hiccup, as the cap derives from the+-- NarSize.  What the transport throws, 'readCacheFile' classifies, and+-- nothing else is caught, so an interrupt is never spent as retry budget.+tryAttempt :: IO (Either AttemptFailure a) -> IO (Either AttemptFailure a)+tryAttempt action = action `catch` \(StreamAbort msg) -> pure (Left (FatalFailure msg))++-- | One streaming substitution attempt: download, decompress, hash,+-- parse, and materialize in a single bounded pass, then verify.+-- Memory is bounded by the decoder's buffers and the parser's+-- structural-string cap, never by archive or file size.+--+-- Disk writes begin before the NAR hash can be known - the price of+-- never holding the archive, and exactly upstream's ordering - so+-- every failure path, exceptions included, removes the tree it wrote+-- ('materializeNarFromSource' owns that contract; 'readCacheFile' and+-- 'tryAttempt' classify what escapes it).  The narinfo metadata+-- registration needs (declared hash, references, deriver) still parses+-- BEFORE the first byte downloads: a malformed narinfo must not leave an+-- unpacked-but-unregistered path behind.  'Nothing' when the cache no+-- longer holds the NAR ('streamWithRetry').+streamNarIntoStore :: OpenedCache -> Store -> StorePath -> NarInfo.NarInfo -> IO (Either AttemptFailure (Maybe PathRegistration))+streamNarIntoStore cache store sp narInfo = case preflight of+  Left err -> pure (Left (FatalFailure err))+  Right (declaredDigest, refs, deriver, downloadCap) -> do+    clearStaleDestination (storePathToFilePath (stDir store) sp)+    tryAttempt $+      readCacheFile cache (NarInfo.niUrl narInfo) $ \body -> do+        source <- cappedBodySource downloadCap body+        materializeNarFromSource store sp narInfo declaredDigest refs deriver source+  where+    preflight = do+      declaredDigest <- case Hash.parseNixHash (NarInfo.niNarHash narInfo) of+        Left err -> Left ("invalid narinfo NarHash: " <> T.pack err)+        Right digest -> Right digest+      refs <- parseReferences (NarInfo.niReferences narInfo)+      deriver <- parseDeriver (stDir store) (NarInfo.niDeriver narInfo)+      downloadCap <- downloadCapFor narInfo+      pure (declaredDigest, refs, deriver, downloadCap)++-- | The byte cap on the compressed NAR body: the 'compressedBodyCeiling'+-- of the narinfo's NarSize.  The Ed25519 fingerprint covers StorePath,+-- NarHash, NarSize and references, so where a signature vouches for the+-- narinfo no field it does not cover moves the cap, and a cache cannot+-- buy a larger download than the signer vouched for.  A narinfo taken+-- unsigned, because its content address makes its path or+-- @require-sigs@ is off, states the size on the cache's word alone, so+-- the cache sets the cap there, and the NAR is held to the size it+-- states ('consumeNarStream').+--+-- FileSize takes no part.  Upstream reads it only for progress and+-- download statistics (@build\/substitution-goal.cc@ and @misc.cc@ at+-- 2.35.4, @build\/substitution-goal.cc@ and @store-api.cc@ at 2.24.9) and+-- checks a substituted NAR against NarHash and NarSize alone, as+-- 'consumeNarStream' does.  A cache that names a NAR by its NarHash, as+-- cache.nixos.org names its zstd NARs, serves one file for every store+-- path with the same NAR, and an upload that compresses that NAR again+-- replaces the file whose FileSize and FileHash an earlier narinfo+-- records.+downloadCapFor :: NarInfo.NarInfo -> Either Text Int+downloadCapFor narInfo+  | narSize < 0 || narSize > toInteger (maxBound :: Int) =+      Left ("narinfo declares an unusable NAR size: " <> T.pack (show narSize))+  | otherwise =+      Right (fromInteger (min (compressedBodyCeiling narSize) (toInteger (maxBound :: Int))))+  where+    narSize = NarInfo.niNarSize narInfo++-- | The most a compressed NAR body may legitimately exceed its NarSize+-- by: xz and zstd expand incompressible input by well under one+-- percent of framing overhead, so a 1/64 (~1.6%) margin plus a fixed+-- floor for small NARs is generous for any real codec, while a body+-- orders of magnitude larger is refused.+compressedBodyCeiling :: Integer -> Integer+compressedBodyCeiling narSize =+  narSize + max compressionOverheadFloorBytes (narSize `div` compressionOverheadDivisor)++-- | Fixed overhead floor for small NARs, where framing dominates.+compressionOverheadFloorBytes :: Integer+compressionOverheadFloorBytes = 64 * 1024++-- | Proportional overhead margin: 1/64 of the NarSize.+compressionOverheadDivisor :: Integer+compressionOverheadDivisor = 64++-- | Materialize a NAR from a compressed chunk source into the store+-- path: decompress, hash, parse, and unpack in one pass, then verify+-- the tree on disk and build its registration.  The post-download half+-- of 'streamNarIntoStore', taking a plain chunk source so the failure+-- contract is testable without HTTP.+--+-- The cleanup contract: every failing exit - the pipeline's 'Left',+-- a verification mismatch, or an exception (asynchronous included) -+-- removes the destination tree, so no partial or unverified tree ever+-- survives at the store path.+materializeNarFromSource :: Store -> StorePath -> NarInfo.NarInfo -> Hash.NixHash -> [StorePath] -> Maybe Text -> IO BS.ByteString -> IO (Either AttemptFailure PathRegistration)+materializeNarFromSource store sp narInfo declaredDigest refs deriver source =+  materialize `onException` Dir.removePathForcibly destPath+  where+    destPath = storePathToFilePath (stDir store) sp+    materialize = do+      streamed <-+        withDecompressedSource (NarInfo.niNarSize narInfo) (NarInfo.niCompression narInfo) source $+          consumeNarStream (stCaseSensitivity store) destPath narInfo declaredDigest+      case streamed of+        Left err -> do+          Dir.removePathForcibly destPath+          pure (Left err)+        Right narByteCount -> do+          canonicalizeMetadata destPath+          -- A path registered valid must match its recorded hash ON+          -- DISK, not merely in the streamed bytes: any divergence the+          -- filesystem introduced between the NAR and the materialized+          -- tree must surface here, before the row exists.  The recheck+          -- streams too, so its memory does not scale with the path.+          -- Through 'ExecBit', not nova-cache's walk directly: on Windows+          -- the sink writes the exec bit to a stream that walk cannot see,+          -- and a verifier reading the flag back out of the file extension+          -- would reject exactly the paths this representation exists for.+          -- On Unix it is still the streaming hash.+          onDiskDigest <- ExecBit.narHashOfPath (volumeCaseHack (stCaseSensitivity store)) destPath+          addressed <-+            if onDiskDigest /= declaredDigest+              then pure (Left ("unpacked tree does not reproduce the declared NAR hash at " <> T.pack destPath))+              else checkRegistrableAddress store sp refs destPath (NarInfo.niCA narInfo)+          case addressed of+            Left err -> do+              Dir.removePathForcibly destPath+              pure (Left (FatalFailure err))+            Right address ->+              pure $+                Right+                  PathRegistration+                    { prPath = sp,+                      -- The canonical spelling of the verified digest,+                      -- so the DB converges on one hash spelling+                      -- regardless of the cache's.+                      prNarHash = Hash.formatNixHash declaredDigest,+                      prNarSize = narByteCount,+                      prDeriver = deriver,+                      prReferences = refs,+                      prUltimate = NotUltimate,+                      prSignatures = narInfoSignatures narInfo,+                      prContentAddress = address,+                      prRegistrationTime = RegisteredNow+                    }++-- | Drive the decompressed chunk source through incremental hashing,+-- the streaming NAR parser, and the store's streaming unpack sink,+-- returning the verified NAR byte count.  The archive ends at its root+-- node's close and the source after it is left unread, as upstream's+-- import of a substituted NAR stops reading there.  The hash context+-- and the count fold over exactly the bytes the parser consumes, so+-- NarHash and NarSize are held to the archive the tree was built from,+-- as upstream holds them.  The sensitivity is the destination volume's,+-- 'stCaseSensitivity' when the destination is a store path.+consumeNarStream :: CaseSensitivity -> FilePath -> NarInfo.NarInfo -> Hash.NixHash -> IO BS.ByteString -> IO (Either AttemptFailure Int)+consumeNarStream sensitivity destPath narInfo declaredDigest narSource = do+  sink <- newNarUnpackSink sensitivity destPath+  streamed <- sinkNarStream AtRootClose sink narSource+  case streamed of+    Left failure -> pure (Left (narStreamFailure failure))+    Right (digest, narBytes) -> case checkNarClaim (NarInfo.niStorePath narInfo) declaredDigest (NarInfo.niNarSize narInfo) digest (toInteger narBytes) of+      -- The archive completed, so it arrived whole: a hash or a size+      -- that still disagrees is the narinfo misdeclaring or the bytes+      -- corrupt, neither of which a retry changes.+      Left refusal -> do+        abortNarUnpack sink+        pure (Left (FatalFailure refusal))+      Right () -> do+        finished <- finishNarUnpack sink+        pure (either (Left . FatalFailure) (const (Right narBytes)) finished)++-- | Why a streamed NAR stopped, as the attempt's failure.  A name or+-- shape the store refuses is a property of the archive, not of this+-- transfer, so no retry can change it.  A truncated body and a torn+-- transfer parse-fail the same way, so a parse failure spends the retry+-- budget.+narStreamFailure :: NarStreamFailure -> AttemptFailure+narStreamFailure failure = case failure of+  NarStreamRefused err -> FatalFailure err+  NarStreamMalformed msg -> TransientFailure ("NAR stream parse failed: " <> msg)++-- | Stream a chunk source, an HTTP response body or a file, bounded by+-- the download cap, which 'downloadCapFor' derives from the NarSize+-- alone - 'readBodyCapped'\'s discipline without the buffering.+-- Exceeding the cap throws t'StreamAbort'; the attempt boundary converts+-- it back to the pipeline's error channel.+cappedBodySource :: Int -> IO BS.ByteString -> IO (IO BS.ByteString)+cappedBodySource cap reader = do+  countRef <- newIORef 0+  pure $ do+    chunk <- reader+    consumed <- readIORef countRef+    let total = consumed + BS.length chunk+    if total > cap+      then throwIO (StreamAbort ("NAR body exceeds its download ceiling (" <> T.pack (show cap) <> " bytes)"))+      else do+        writeIORef countRef total+        pure chunk++-- | Whether the streaming pipeline can decompress a narinfo+-- @Compression@ value, decided from the value alone so unsupported+-- compression rejects before any download.  Both this and the strict+-- 'decompressorFor' dispatch through 'parseNarCompression', so the+-- support set exists exactly once.+streamingDecompressionSupported :: Text -> Either Text ()+streamingDecompressionSupported = void . parseNarCompression++-- | Run a consumer over the decompressed view of a chunk source:+-- identity for 'CompressionNone', nova-cache's bounded decoders for+-- 'CompressionXz', 'CompressionZstd', and 'CompressionBzip2' (output+-- capped at the declared NarSize; thrown codec errors convert to the+-- pipeline's error channel here, carrying their retry class from+-- 'xzFailure', 'zstdFailure', and 'bzip2Failure').+withDecompressedSource :: Integer -> Text -> IO BS.ByteString -> (IO BS.ByteString -> IO (Either AttemptFailure a)) -> IO (Either AttemptFailure a)+withDecompressedSource declaredNarSize compression source consume =+  case parseNarCompression compression of+    Left err -> pure (Left (FatalFailure err))+    Right CompressionNone -> consume source+    Right CompressionXz -> case xzLimitsFor declaredNarSize of+      Left err -> pure (Left (FatalFailure err))+      Right limits -> withXzAttempt limits source consume+    Right CompressionZstd -> case zstdLimitsFor declaredNarSize of+      Left err -> pure (Left (FatalFailure err))+      Right limits ->+        Zstd.withZstdSource limits source consume+          `catch` \zstdErr -> pure (Left (zstdFailure zstdErr))+    Right CompressionBzip2 -> case bzip2LimitsFor declaredNarSize of+      Left err -> pure (Left (FatalFailure err))+      Right limits ->+        Bzip2.withBzip2Source limits source consume+          `catch` \bzip2Err -> pure (Left (bzip2Failure bzip2Err))++-- | Run a consumer over the xz-decompressed view of a chunk source+-- ('Xz.withXzSource'), a decoder failure ending the attempt with its+-- class ('xzFailure') where the decoder throws it.  A failure of the+-- compressed source itself passes through as it was thrown.+withXzAttempt :: Xz.XzLimits -> IO BS.ByteString -> (IO BS.ByteString -> IO (Either AttemptFailure a)) -> IO (Either AttemptFailure a)+withXzAttempt limits source consume =+  Xz.withXzSource limits source consume `catch` (pure . Left . xzFailure)++-- | Classify a decoder failure: a stream error is how truncation and+-- torn transfers surface, so it retries; output or memory past the+-- declared bounds is the served object misdeclaring - deterministic.+xzFailure :: Xz.XzError -> AttemptFailure+xzFailure xzErr = case xzErr of+  Xz.XzStreamError _ -> TransientFailure rendered+  Xz.XzOutputOverBound _ -> FatalFailure rendered+  Xz.XzMemoryOverBound _ -> FatalFailure rendered+  where+    rendered = renderXzError xzErr++-- | 'xzFailure'\'s zstd counterpart, under the same taxonomy.+zstdFailure :: Zstd.ZstdError -> AttemptFailure+zstdFailure zstdErr = case zstdErr of+  Zstd.ZstdStreamError _ -> TransientFailure rendered+  Zstd.ZstdOutputOverBound _ -> FatalFailure rendered+  where+    rendered = renderZstdError zstdErr++-- | 'xzFailure'\'s bzip2 counterpart, under the same taxonomy.+bzip2Failure :: Bzip2.Bzip2Error -> AttemptFailure+bzip2Failure bzip2Err = case bzip2Err of+  Bzip2.Bzip2StreamError _ -> TransientFailure rendered+  Bzip2.Bzip2OutputOverBound _ -> FatalFailure rendered+  where+    rendered = renderBzip2Error bzip2Err++-- ---------------------------------------------------------------------------+-- Pure helpers+-- ---------------------------------------------------------------------------++-- | The signatures a narinfo carries, which a substituted path is+-- registered with, as upstream registers the path info it copied.  A+-- @Sig@ line that does not parse, which upstream would refuse the narinfo+-- for, is left out, so the registration carries only signatures that+-- read.+narInfoSignatures :: NarInfo.NarInfo -> Set Signature+narInfoSignatures = Set.fromList . concatMap (either (const []) pure . parseSignature . TE.encodeUtf8) . NarInfo.niSigs++-- | Whether one of the keys given verifies one of a narinfo's+-- signatures, as upstream checks a signature with the trusted key its+-- name names.+verifySigs :: [Signing.PublicKey] -> NarInfo.NarInfo -> Bool+verifySigs keys narInfo = any (\key -> any (Signing.verify key narInfo) (NarInfo.niSigs narInfo)) keys++-- | The cache's trusted public keys, from @trusted-public-keys@.  A+-- malformed key is an error rather than a silently skipped one: upstream+-- rejects the configuration, so a typo cannot quietly narrow the trusted+-- set to the keys that parsed.+configuredKeys :: CacheConfig -> Either Text [Signing.PublicKey]+configuredKeys = traverse parseKey . ccPublicKeys+  where+    parseKey raw = case Signing.parsePublicKey raw of+      Left err -> Left ("invalid public key: " <> T.pack err)+      Right pubKey -> Right pubKey++-- | The whole-buffer decompressor for a narinfo @Compression@ value,+-- decided from the narinfo's declared values alone so unsupported+-- compression rejects before any download.  'CompressionNone' is+-- identity; 'CompressionXz' (cache.nixos.org's format),+-- 'CompressionZstd' (the modern caches'), and 'CompressionBzip2' (the+-- historical caches', and what an absent field means) decompress+-- bounded by the declared NarSize, a claim the caller validates before+-- resolving the decompressor.  The resolved function runs in IO+-- because the zstd and bzip2 decoders are IO-native (see+-- 'NovaCache.Zstd' and 'NovaCache.Bzip2'); the strict shape follows its+-- codecs.  Dispatches through 'parseNarCompression' like the streaming+-- path, so the support set exists exactly once.+decompressorFor :: Integer -> Text -> Either Text (BS.ByteString -> IO (Either Text BS.ByteString))+decompressorFor declaredNarSize compression = do+  kind <- parseNarCompression compression+  case kind of+    CompressionNone -> Right (pure . Right)+    CompressionXz -> do+      limits <- xzLimitsFor declaredNarSize+      Right (pure . either (Left . renderXzError) Right . Xz.decompress limits)+    CompressionZstd -> do+      limits <- zstdLimitsFor declaredNarSize+      Right (fmap (either (Left . renderZstdError) Right) . Zstd.decompress limits)+    CompressionBzip2 -> do+      limits <- bzip2LimitsFor declaredNarSize+      Right (fmap (either (Left . renderBzip2Error) Right) . Bzip2.decompress limits)++-- | Decompress NAR data based on the compression type from narinfo,+-- bounded by the declared NarSize.  Support is decided by+-- 'decompressorFor'; this applies the result.+decompressNar :: Integer -> Text -> BS.ByteString -> IO (Either Text BS.ByteString)+decompressNar declaredNarSize compression narData =+  case decompressorFor declaredNarSize compression of+    Left err -> pure (Left err)+    Right decompress -> decompress narData++-- | The bounds for one xz decode: output capped at the narinfo's+-- declared NarSize, decoder memory at nova-cache's default, so a+-- hostile stream can expand to neither more output nor more decoder+-- state than the narinfo promised.  Narinfo validation upstream+-- already rejected a negative size; the guard keeps the function+-- total for direct callers, and a size past Word64 cannot name a+-- real NAR.+xzLimitsFor :: Integer -> Either Text Xz.XzLimits+xzLimitsFor declaredNarSize+  | declaredNarSize < 0 || declaredNarSize > toInteger (maxBound :: Word64) =+      Left ("xz decompression bound out of range: " <> T.pack (show declaredNarSize))+  | otherwise =+      Right+        Xz.XzLimits+          { Xz.xzMaxOutputBytes = fromInteger declaredNarSize,+            Xz.xzMaxDecoderMemoryBytes = Xz.defaultXzDecoderMemoryBytes+          }++-- | One 'Xz.XzError' in the register the other substitution errors use.+renderXzError :: Xz.XzError -> Text+renderXzError xzErr = case xzErr of+  Xz.XzStreamError msg -> "xz stream error: " <> T.pack msg+  Xz.XzOutputOverBound bound ->+    "xz output exceeds the declared NarSize (" <> T.pack (show bound) <> " bytes)"+  Xz.XzMemoryOverBound bound ->+    "xz decoder memory over its cap (" <> T.pack (show bound) <> " bytes)"++-- | The bounds for one zstd decode: output capped at the narinfo's+-- declared NarSize; decoder state rides libzstd's built-in window+-- limit (see 'NovaCache.Zstd').  The same totality guard as+-- 'xzLimitsFor'.+zstdLimitsFor :: Integer -> Either Text Zstd.ZstdLimits+zstdLimitsFor declaredNarSize+  | declaredNarSize < 0 || declaredNarSize > toInteger (maxBound :: Word64) =+      Left ("zstd decompression bound out of range: " <> T.pack (show declaredNarSize))+  | otherwise = Right Zstd.ZstdLimits {Zstd.zstdMaxOutputBytes = fromInteger declaredNarSize}++-- | One 'Zstd.ZstdError' in the register the other substitution+-- errors use.+renderZstdError :: Zstd.ZstdError -> Text+renderZstdError zstdErr = case zstdErr of+  Zstd.ZstdStreamError msg -> "zstd stream error: " <> T.pack msg+  Zstd.ZstdOutputOverBound bound ->+    "zstd output exceeds the declared NarSize (" <> T.pack (show bound) <> " bytes)"++-- | The bounds for one bzip2 decode: output capped at the narinfo's+-- declared NarSize.  There is no decoder-memory knob to set - bzip2+-- carries no attacker-chosen dictionary size, so decoder state is a+-- small constant of the format (see 'NovaCache.Bzip2').  The same+-- totality guard as 'xzLimitsFor'.+bzip2LimitsFor :: Integer -> Either Text Bzip2.Bzip2Limits+bzip2LimitsFor declaredNarSize+  | declaredNarSize < 0 || declaredNarSize > toInteger (maxBound :: Word64) =+      Left ("bzip2 decompression bound out of range: " <> T.pack (show declaredNarSize))+  | otherwise = Right Bzip2.Bzip2Limits {Bzip2.bzip2MaxOutputBytes = fromInteger declaredNarSize}++-- | One 'Bzip2.Bzip2Error' in the register the other substitution+-- errors use.+renderBzip2Error :: Bzip2.Bzip2Error -> Text+renderBzip2Error bzip2Err = case bzip2Err of+  Bzip2.Bzip2StreamError msg -> "bzip2 stream error: " <> T.pack msg+  Bzip2.Bzip2OutputOverBound bound ->+    "bzip2 output exceeds the declared NarSize (" <> T.pack (show bound) <> " bytes)"++-- | Parse narinfo references (store path basenames, e.g.+-- @abc...-glibc-2.40@) into StorePaths.  A malformed token is an error,+-- not filtered: silently dropping a reference registers the path with a+-- hole in its closure, which re-push then publishes as a signed narinfo+-- missing runtime deps, and GC reads as permission to delete them.+parseReferences :: [Text] -> Either Text [StorePath]+parseReferences = traverse parseRef+  where+    parseRef ref =+      maybe (Left ("malformed narinfo reference: " <> ref)) Right (parseStorePathBaseName ref)++-- | The sentinel upstream caches emit for a path whose deriver is unknown.+unknownDeriverSentinel :: Text+unknownDeriverSentinel = "unknown-deriver"++-- | Parse a narinfo Deriver - a store path basename on the wire, or the+-- @unknown-deriver@ sentinel - into the full path text the store DB+-- records (the form "Nix.Push" parses back with 'Nix.Store.Path.parseStorePath').+parseDeriver :: StoreDir -> Maybe Text -> Either Text (Maybe Text)+parseDeriver _ Nothing = Right Nothing+parseDeriver storeDir (Just txt)+  | txt == unknownDeriverSentinel = Right Nothing+  | otherwise = case parseStorePathBaseName txt of+      Just sp -> Right (Just (T.pack (storePathToFilePath storeDir sp)))+      Nothing -> Left ("malformed narinfo deriver: " <> txt)++-- ---------------------------------------------------------------------------+-- NAR unpacking+-- ---------------------------------------------------------------------------++-- | Remove a leftover destination tree before unpacking.  A crash (or a+-- failed registration) between 'canonicalizeMetadata' here and the+-- caller's 'Nix.Store.DB.registerPaths' leaves a read-only, unregistered+-- tree; unpacking over it would then fail with permission-denied on every+-- retry, permanently wedging substitution of that path.+-- 'Dir.removePathForcibly' clears read-only marks and accepts a missing+-- path, so the fresh unpack always starts from a clean slate.+-- Substitution callers reach this only holding the path's exclusive+-- lock ('underPathLock', 'unpackVerifiedNar'): unlocked, this deletion is -- exactly the race that lets one process remove a tree another just -- registered. clearStaleDestination :: FilePath -> IO ()
+ src/Nix/Trust.hs view
@@ -0,0 +1,838 @@+{-# LANGUAGE TupleSections #-}++-- | What a derivation's closure relies on: its fixed-output derivations,+-- which of them its builds run as builders and which hold prebuilt code,+-- and the builders and sources it takes from outside itself.+--+-- A fixed-output derivation's output is named by the hash its recipe+-- states, whatever makes it.  A download or a build is checked against+-- that hash before it is registered ("Nix.Builder"); a substitute is+-- checked against the NarHash its cache's narinfo declares, and+-- against the content address the narinfo states when it states one+-- ("Nix.Substituter"), not the recipe's hash.  Every one in the closure is+-- an input the closure relies on ('fixedOutputInputs'), whether a builtin+-- fetches it or the closure builds it, and each says which ('Provenance').+--+-- Each fixed-output input is classified by two kinds of fact.  One is in+-- the graph: a derivation whose builder is inside the input's output runs+-- it as a builder, and so does one whose builder is inside the output of+-- a builtin derivation (@builtin:unpack@, say) made from it, where the+-- input is part of the tree the builder runs from; which of the+-- builtin's inputs holds the builder itself is not in the graph.  A+-- builtin runs nothing from the closure, so neither case needs the bytes.+-- The other fact is in the bytes: an input whose files hold prebuilt code+-- ('prebuiltKind'), an executable image, an object file or a static+-- library, holds what no step of the closure built from source.  The+-- content facts are an argument, keyed by output path, so classification+-- runs over a pure graph and pure facts; "Nix.Trust.Scan" gathers them+-- from the store.+--+-- The rest is read from the graph alone: builders the closure does not+-- contain, such as a program on the host; builders in its input sources;+-- the builtins nova-nix runs itself; and the input sources.  Nothing here+-- says whether any of it is safe.+--+-- A file of prebuilt code whose bytes are those of a fixed-output input+-- the closure runs as a builder, a copy of a seed in a source archive+-- say, is named as that input: it is code the closure already relies on,+-- not more of it.  The report is lines ('renderTrustReport') or one JSON+-- document of the same facts ('trustReportJson').+module Nix.Trust+  ( -- * Prebuilt code+    CodeKind (..),+    prebuiltKind,+    codeKindName,++    -- * Content facts+    CodePlace (..),+    FoundCode (..),+    UnreadFile (..),+    ContentFacts (..),++    -- * The closure+    fixedOutputPath,+    fixedOutputInputs,+    fetchedByBuiltin,++    -- * The report+    Scan (..),+    Provenance (..),+    FixedInput (..),+    InputClass (..),+    inputClass,+    TrustReport (..),+    trustReport,+    renderTrustReport,+    trustReportJson,+    trustReportJsonVersion,+  )+where++import Data.Bits (shiftL, (.|.))+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Lazy as BL+import Data.Int (Int64)+import Data.List (sortOn)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe)+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Text.Encoding.Error (lenientDecode)+import Data.Word (Word32, Word8)+import Nix.DependencyGraph (DepGraph (..), DepNode (..), transitiveDeps)+import Nix.Derivation (Derivation (..), DerivationOutput (..), fixedOutput)+import Nix.Json (Json (..))+import Nix.Store.Path (StorePath (spName), defaultStoreDir, defaultStoreDirText, parseStorePathBaseName, storePathToText)++-- ---------------------------------------------------------------------------+-- Prebuilt code+-- ---------------------------------------------------------------------------++-- | The kinds of prebuilt code the scan recognises, each by its header.+data CodeKind+  = -- | A Portable Executable, Windows' format: an @MZ@ header whose+    -- @e_lfanew@ field points at a @PE\\0\\0@ signature.+    PeImage+  | -- | An ELF executable or shared object.+    ElfImage+  | -- | An ELF relocatable object.+    ElfObject+  | -- | Another ELF file, such as a core dump, or one whose header ends+    -- before its type.+    ElfOther+  | -- | A Mach-O file for one architecture, of either width and byte+    -- order.+    MachO+  | -- | A Mach-O universal file, holding code for several architectures.+    MachOUniversal+  | -- | A COFF object, in the plain form or the bigobj one.+    CoffObject+  | -- | An ar archive: a static library or an import library, whose+    -- members are not read.+    ArArchive+  deriving (Eq, Ord, Show, Enum, Bounded)++-- | How the report names a kind.+codeKindName :: CodeKind -> Text+codeKindName kind = case kind of+  PeImage -> "PE image"+  ElfImage -> "ELF image"+  ElfObject -> "ELF object"+  ElfOther -> "ELF"+  MachO -> "Mach-O"+  MachOUniversal -> "Mach-O universal"+  CoffObject -> "COFF object"+  ArArchive -> "ar archive"++-- | The prebuilt code these bytes are, read from their header, or+-- 'Nothing'.  A script, whatever its @#!@ line names, is not prebuilt+-- code, and neither is an @MZ@ header without a PE signature where its+-- @e_lfanew@ points, nor a COFF header whose tables do not fit in the+-- bytes.  Lazy bytes are read only as far as the header needs: the first+-- few bytes, for an @MZ@ header the bytes up to the signature its+-- @e_lfanew@ names, and for a COFF header the bytes up to the end of its+-- tables.+prebuiltKind :: BL.ByteString -> Maybe CodeKind+prebuiltKind bytes+  | elfMagic `BL.isPrefixOf` bytes = Just (elfKind bytes)+  | any (`BL.isPrefixOf` bytes) machOMagics = Just MachO+  | any (`BL.isPrefixOf` bytes) universalMagics,+    Just count <- fieldAt 4 BigEndian universalCountOffset bytes,+    count > 0,+    count < javaClassFirstMajor =+      Just MachOUniversal+  | arMagic `BL.isPrefixOf` bytes = Just ArArchive+  | dosMagic `BL.isPrefixOf` bytes,+    Just offset <- fieldAt 4 LittleEndian peOffsetField bytes,+    peSignature `BL.isPrefixOf` BL.drop (fromIntegral offset) bytes =+      Just PeImage+  | isCoffObject bytes || isBigObj bytes = Just CoffObject+  | otherwise = Nothing++-- | The order of a multi-byte field's bytes.+data ByteOrder = BigEndian | LittleEndian++-- | The field of this many bytes at an offset, or 'Nothing' past the end.+fieldAt :: Int64 -> ByteOrder -> Int64 -> BL.ByteString -> Maybe Word32+fieldAt width order offset bytes+  | BL.length field == width = Just (BL.foldl' (\acc byte -> acc `shiftL` 8 .|. fromIntegral byte) 0 (mostSignificantFirst field))+  | otherwise = Nothing+  where+    field = BL.take width (BL.drop offset bytes)+    mostSignificantFirst = case order of+      BigEndian -> id+      LittleEndian -> BL.reverse++-- | Whether the bytes run to at least this length, read only that far.+reaches :: BL.ByteString -> Int64 -> Bool+reaches bytes size = BL.length (BL.take size bytes) == size++-- | ELF's identification bytes.+elfMagic :: BL.ByteString+elfMagic = BL.pack [0x7F, 0x45, 0x4C, 0x46]++-- | An ELF file's kind, from its type field, read in the byte order its+-- identification names.+elfKind :: BL.ByteString -> CodeKind+elfKind bytes = case BL.indexMaybe bytes elfDataOffset >>= orderOf >>= \order -> fieldAt 2 order elfTypeOffset bytes of+  Just elfType+    | elfType == elfRelocatable -> ElfObject+    | elfType == elfExecutable || elfType == elfShared -> ElfImage+  _ -> ElfOther+  where+    orderOf :: Word8 -> Maybe ByteOrder+    orderOf encoding+      | encoding == elfLittleEndian = Just LittleEndian+      | encoding == elfBigEndian = Just BigEndian+      | otherwise = Nothing++-- | Where ELF's identification names the byte order, and the two values+-- it takes there.+elfDataOffset :: Int64+elfDataOffset = 5++elfLittleEndian, elfBigEndian :: Word8+elfLittleEndian = 1+elfBigEndian = 2++-- | Where an ELF header holds its type, and the types of a relocatable,+-- an executable and a shared object.+elfTypeOffset :: Int64+elfTypeOffset = 16++elfRelocatable, elfExecutable, elfShared :: Word32+elfRelocatable = 1+elfExecutable = 2+elfShared = 3++-- | Mach-O's magic numbers as a file starts with them: 32-bit and 64-bit,+-- each in big-endian and little-endian order.+machOMagics :: [BL.ByteString]+machOMagics =+  map+    BL.pack+    [ [0xFE, 0xED, 0xFA, 0xCE],+      [0xCE, 0xFA, 0xED, 0xFE],+      [0xFE, 0xED, 0xFA, 0xCF],+      [0xCF, 0xFA, 0xED, 0xFE]+    ]++-- | The universal header's magic numbers, 32-bit and 64-bit, which the+-- format writes big-endian.+universalMagics :: [BL.ByteString]+universalMagics = map BL.pack [[0xCA, 0xFE, 0xBA, 0xBE], [0xCA, 0xFE, 0xBA, 0xBF]]++-- | Where the universal header holds its count of architectures.+universalCountOffset :: Int64+universalCountOffset = 4++-- | A Java class file starts with the universal header's 32-bit magic,+-- and where that header counts its architectures holds its minor and+-- major version, two bytes each, so the word is at least the first major+-- version, 45, where no universal file has that many architectures.+javaClassFirstMajor :: Word32+javaClassFirstMajor = 45++-- | An ar archive's global header.+arMagic :: BL.ByteString+arMagic = "!<arch>\n"++-- | The DOS header's magic, which every Portable Executable starts with.+dosMagic :: BL.ByteString+dosMagic = "MZ"++-- | Where the DOS header holds @e_lfanew@, the offset of the PE+-- signature.+peOffsetField :: Int64+peOffsetField = 0x3C++-- | The signature a Portable Executable's NT headers start with.+peSignature :: BL.ByteString+peSignature = BL.pack [0x50, 0x45, 0x00, 0x00]++-- | The machines a COFF object is written for here: i386, x86-64, ARM64+-- and ARM Thumb-2, as the machine field spells them.+coffMachines :: [Word32]+coffMachines = [0x014C, 0x8664, 0xAA64, 0x01C4]++-- | The size of a COFF file header, of a section header, and of a symbol+-- table entry in the plain form and in the bigobj one.+coffHeaderSize, coffSectionSize, coffSymbolSize, bigObjHeaderSize, bigObjSymbolSize :: Int64+coffHeaderSize = 20+coffSectionSize = 40+coffSymbolSize = 18+bigObjHeaderSize = 56+bigObjSymbolSize = 20++-- | Whether bytes start a COFF object in the plain form: a machine field+-- this scan knows, at least one section, no optional header, which only+-- an image has, and a section table and symbol table that end within+-- the bytes.  Without a symbol table its pointer is zero.+isCoffObject :: BL.ByteString -> Bool+isCoffObject bytes = fromMaybe False $ do+  machine <- fieldAt 2 LittleEndian 0 bytes+  sections <- fieldAt 2 LittleEndian 2 bytes+  symbolTable <- fieldAt 4 LittleEndian 8 bytes+  symbols <- fieldAt 4 LittleEndian 12 bytes+  optionalHeader <- fieldAt 2 LittleEndian 16 bytes+  pure+    ( machine `elem` coffMachines+        && optionalHeader == 0+        && tablesFit bytes coffHeaderSize sections coffSymbolSize symbolTable symbols+    )++-- | The first two words of a bigobj header, which no plain header has:+-- an unknown machine, then all bits set.+bigObjSignature :: BL.ByteString+bigObjSignature = BL.pack [0x00, 0x00, 0xFF, 0xFF]++-- | The bigobj form's first version, and its class identifier, which+-- follows the machine and the time stamp.+bigObjVersion :: Word32+bigObjVersion = 2++bigObjClassId :: BL.ByteString+bigObjClassId = BL.pack [0xC7, 0xA1, 0xBA, 0xD1, 0xEE, 0xBA, 0xA9, 0x4B, 0xAF, 0x20, 0xFA, 0xF6, 0x6A, 0xA4, 0xDC, 0xB8]++-- | Where the bigobj header holds its class identifier.+bigObjClassIdOffset :: Int64+bigObjClassIdOffset = 12++-- | Whether bytes start a COFF object in the bigobj form: its signature,+-- a version from the first bigobj one on, a machine this scan knows, its+-- class identifier, at least one section, and a section table and+-- symbol table that end within the bytes.+isBigObj :: BL.ByteString -> Bool+isBigObj bytes = fromMaybe False $ do+  version <- fieldAt 2 LittleEndian 4 bytes+  machine <- fieldAt 2 LittleEndian 6 bytes+  sections <- fieldAt 4 LittleEndian 44 bytes+  symbolTable <- fieldAt 4 LittleEndian 48 bytes+  symbols <- fieldAt 4 LittleEndian 52 bytes+  pure+    ( bigObjSignature `BL.isPrefixOf` bytes+        && version >= bigObjVersion+        && machine `elem` coffMachines+        && bigObjClassId `BL.isPrefixOf` BL.drop bigObjClassIdOffset bytes+        && tablesFit bytes bigObjHeaderSize sections bigObjSymbolSize symbolTable symbols+    )++-- | Whether a COFF object's section table, at least one section long+-- after its header, and its symbol table end within the bytes.+tablesFit :: BL.ByteString -> Int64 -> Word32 -> Int64 -> Word32 -> Word32 -> Bool+tablesFit bytes headerSize sections symbolSize symbolTable symbols =+  sections > 0+    && reaches bytes (headerSize + coffSectionSize * fromIntegral sections)+    && symbolsFit+  where+    symbolsFit+      | symbolTable == 0 = symbols == 0+      | otherwise = reaches bytes (fromIntegral symbolTable + symbolSize * fromIntegral symbols)++-- ---------------------------------------------------------------------------+-- Content facts+-- ---------------------------------------------------------------------------++-- | Where in a fetched output a file of prebuilt code is.  Paths are text+-- for the report to show.+data CodePlace+  = -- | The output is one file, and it is the code.+    FetchedFile+  | -- | A file of a fetched tree, by its path in the tree.+    TreeFile !Text+  | -- | A member of the fetched file, an archive, by its path in it.+    ArchiveMember !Text+  | -- | A member of an archive in a fetched tree: the archive's path in+    -- the tree, then the member's path in the archive.+    TreeArchiveMember !Text !Text+  deriving (Eq, Ord, Show)++-- | A file of prebuilt code a scan found.+data FoundCode = FoundCode+  { fcKind :: !CodeKind,+    fcPlace :: !CodePlace,+    -- | The SHA-256 of the file's bytes, in lowercase base-16: the hash a+    -- fixed-output derivation of the same bytes states, hashed flat.+    fcSha256 :: !Text+  }+  deriving (Eq, Ord, Show)++-- | A file a scan did not read in full, and why: one that could not be+-- opened, a compressed stream that does not decode, a tar archive that+-- stops reading, or an archive in a format the scan does not open.+data UnreadFile = UnreadFile+  { -- | Its path in a fetched tree, or 'Nothing' for a fetched file.+    ufFile :: !(Maybe Text),+    ufReason :: !Text+  }+  deriving (Eq, Show)++-- | What a scan of a fetched output found in its bytes: the files of+-- prebuilt code, and the files it did not read in full.  Both empty+-- means every file the scan reached was read and none is prebuilt code; a+-- member of a tar archive is read by its header alone, so an archive or+-- compressed stream inside one is neither opened nor reported as not read.+data ContentFacts = ContentFacts+  { cfCode :: ![FoundCode],+    cfUnread :: ![UnreadFile]+  }+  deriving (Eq, Show)++-- ---------------------------------------------------------------------------+-- The closure+-- ---------------------------------------------------------------------------++-- | The store path of a fixed-output derivation's output ('fixedOutput').+fixedOutputPath :: Derivation -> Maybe StorePath+fixedOutputPath = fmap doPath . fixedOutput++-- | The derivations of the root's closure, keyed by @.drv@ path, and+-- among them the fixed-output ones, each with its fixed output.+data Walk = Walk+  { walkNodes :: !(Map StorePath DepNode),+    walkFixed :: !(Map StorePath (DepNode, DerivationOutput))+  }++-- | The derivations of the root's closure: the root and every derivation+-- it depends on, directly or not, that the graph holds.+walkClosure :: DepGraph -> StorePath -> Walk+walkClosure graph root = Walk nodes (Map.mapMaybe (\node -> (node,) <$> fixedOutput (dnDerivation node)) nodes)+  where+    nodes = Map.restrictKeys (unDepGraph graph) (Set.insert root (transitiveDeps graph root))++-- | The fixed-output derivations of the root's closure, each with its+-- output, in @.drv@ path order.+fixedOutputInputs :: DepGraph -> StorePath -> [(DepNode, StorePath)]+fixedOutputInputs graph root = [(node, doPath out) | (node, out) <- Map.elems (walkFixed (walkClosure graph root))]++-- | What every builder of a builtin derivation starts with: upstream's+-- marker for a builder the Nix process runs itself.+builtinBuilderPrefix :: ByteString+builtinBuilderPrefix = "builtin:"++-- | Whether a derivation's builder is one nova-nix runs itself.+isBuiltin :: Derivation -> Bool+isBuiltin drv = builtinBuilderPrefix `BS.isPrefixOf` drvBuilder drv++-- | Whether realising a derivation runs nothing but nova-nix: its builder+-- is a builtin, and it takes no input derivation or source, so nothing+-- from the closure is built or read first.+fetchedByBuiltin :: Derivation -> Bool+fetchedByBuiltin drv = isBuiltin drv && Map.null (drvInputDrvs drv) && null (drvInputSrcs drv)++-- | The separator after the store directory in a canonical store path.+pathSeparator :: Word8+pathSeparator = 0x2F++-- | The store path a builder is inside: its first component under the+-- canonical store directory.  A store path's own component is ASCII, so+-- only it is decoded, and a builder whose path within the store path is+-- not UTF-8 still names the store path it is in.+builderStorePath :: ByteString -> Maybe StorePath+builderStorePath builder = do+  rest <- BS.stripPrefix (TE.encodeUtf8 defaultStoreDirText <> BS.singleton pathSeparator) builder+  either (const Nothing) parseStorePathBaseName (TE.decodeUtf8' (BS.takeWhile (/= pathSeparator) rest))++-- | Where a derivation's builder comes from.+data BuilderUse+  = -- | It is one of nova-nix's builtins.+    BuiltinUse+  | -- | It is inside the output of a derivation of the closure, whose+    -- @.drv@ path is given.+    OutputUse !StorePath+  | -- | It is inside one of the closure's input sources.+    SourceUse+  | -- | It is not in the closure: a path outside the store, or a store+    -- path nothing in the closure provides.+    OutsideUse++-- | Where a derivation's builder comes from, given which @.drv@ makes+-- each output of the closure, and the closure's input sources.+builderUse :: Map StorePath StorePath -> Set StorePath -> Derivation -> BuilderUse+builderUse owners sources drv+  | isBuiltin drv = BuiltinUse+  | Just path <- builderStorePath (drvBuilder drv) =+      case Map.lookup path owners of+        Just owner -> OutputUse owner+        Nothing+          | Set.member path sources -> SourceUse+          | otherwise -> OutsideUse+  | otherwise = OutsideUse++-- | How a builder reaches a fixed-output input it runs.+data Reach+  = -- | The builder is inside the input's own output.+    Inside+  | -- | The builder is inside a builtin derivation's output made from the+    -- input, with any others.+    InTree+  deriving (Eq, Ord, Show)++-- | The fixed-output derivations whose bytes the output of this @.drv@+-- holds as their hash pins them, each with how: itself when it is one,+-- and for a builtin derivation each fixed-output input of it and of the+-- builtin derivations beneath it.  Any other derivation runs a program to+-- make an output no hash fixes, and the chain stops there.+heldAsPinned :: Walk -> StorePath -> [(StorePath, Reach)]+heldAsPinned walk start+  | Map.member start (walkFixed walk) = [(start, Inside)]+  | otherwise = map (,InTree) (Set.toList (go Set.empty Set.empty [start]))+  where+    go !found !_ [] = found+    go found seen (path : rest)+      | Set.member path seen = go found seen rest+      | Map.member path (walkFixed walk) = go (Set.insert path found) (Set.insert path seen) rest+      | Just node <- Map.lookup path (walkNodes walk),+        isBuiltin (dnDerivation node) =+          go found (Set.insert path seen) (Map.keys (dnDeps node) ++ rest)+      | otherwise = go found (Set.insert path seen) rest++-- ---------------------------------------------------------------------------+-- The report+-- ---------------------------------------------------------------------------++-- | What is known of a fixed-output input's bytes.+data Scan+  = -- | The store does not hold its output, so its bytes were not read.+    NotInStore+  | -- | Its output was scanned, and this is what the scan found.+    Scanned !ContentFacts+  deriving (Eq, Show)++-- | How a fixed-output input's bytes come to be, each case with its+-- builder.  Either way the recipe's hash pins them when nova-nix fetches+-- or builds them; bytes a cache supplies are held to its signed NarHash+-- and to the content address its narinfo states.+data Provenance+  = -- | A builtin fetches them, such as @builtin:fetchurl@.+    FetchedBy !ByteString+  | -- | The closure builds them, running this builder.+    BuiltBy !ByteString+  deriving (Eq, Show)++-- | A fixed-output derivation of the closure.+data FixedInput = FixedInput+  { -- | Its @.drv@ path.+    inputDrvPath :: !StorePath,+    -- | Its one output, which the hash fixes.+    inputOutput :: !StorePath,+    inputProvenance :: !Provenance,+    -- | The outputs of the closure's other fixed-output derivations whose+    -- hash, algorithm and mode included, is this one's, so whose bytes+    -- are the same, by output name.+    inputSameHash :: ![StorePath],+    -- | The builders inside its output, each with how many of the+    -- closure's derivations it builds.+    inputBuilders :: !(Map ByteString Int),+    -- | The builders inside a builtin derivation's output made from it,+    -- the tree they run from, each with how many derivations it builds.+    inputTreeBuilders :: !(Map ByteString Int),+    inputScan :: !Scan+  }+  deriving (Eq, Show)++-- | The class a fixed-output input falls in, most opaque first.+data InputClass+  = -- | A build runs it as its builder, or as part of its builder's tree+    -- ('inputBuilders', 'inputTreeBuilders'), whatever its bytes.+    RunAsBuilder+  | -- | It holds prebuilt code.+    HoldsPrebuiltCode+  | -- | Its bytes were not read, or not all of them, and no prebuilt+    -- code was found in what was.+    NotFullyRead+  | -- | Every file the scan reached was read, and none is prebuilt code+    -- (an archive inside a tar archive is not opened, "Nix.Trust.Scan").+    HoldsNoPrebuiltCode+  deriving (Eq, Ord, Show, Enum, Bounded)++-- | The class a fixed-output input falls in: the structural fact first,+-- since it needs no bytes, then what its bytes hold.+inputClass :: FixedInput -> InputClass+inputClass input+  | not (Map.null (inputBuilders input) && Map.null (inputTreeBuilders input)) = RunAsBuilder+  | otherwise = case inputScan input of+      NotInStore -> NotFullyRead+      Scanned facts -> case (cfCode facts, cfUnread facts) of+        (_ : _, _) -> HoldsPrebuiltCode+        ([], _ : _) -> NotFullyRead+        ([], []) -> HoldsNoPrebuiltCode++-- | What a closure relies on.+data TrustReport = TrustReport+  { -- | The fixed-output inputs, by output name.+    trInputs :: ![FixedInput],+    -- | The builders the closure does not contain, each with how many of+    -- its derivations it builds.+    trOutsideBuilders :: !(Map ByteString Int),+    -- | The builders inside input sources, each with how many derivations+    -- it builds.+    trSourceBuilders :: !(Map ByteString Int),+    -- | The builtin builders, each with how many derivations it builds.+    trBuiltinBuilders :: !(Map ByteString Int),+    -- | The input sources: store paths the closure's derivations take+    -- that none of them builds, such as files evaluation copies from the+    -- expression's tree.+    trSources :: !(Set StorePath),+    -- | The outputs of the fixed-output inputs run as builders that are+    -- one file hashed flat with SHA-256, by that hash: a file of prebuilt+    -- code with the same SHA-256 is one of them, by its bytes.+    trBuilderBytes :: !(Map Text [StorePath])+  }+  deriving (Eq, Show)++-- | What the closure of the root relies on, given what scans found in the+-- outputs of its fixed-output inputs, keyed by output path.  An input+-- whose output the facts do not hold is not in the store.  Every+-- derivation of the closure counts, a fixed-output one included: a fixed+-- output built by running a fetched seed shows the seed run as its+-- builder.+trustReport :: Map StorePath ContentFacts -> DepGraph -> StorePath -> TrustReport+trustReport facts graph root =+  TrustReport+    { trInputs = inputs,+      trOutsideBuilders = tally [drvBuilder drv | (drv, OutsideUse) <- uses],+      trSourceBuilders = tally [drvBuilder drv | (drv, SourceUse) <- uses],+      trBuiltinBuilders = tally [drvBuilder drv | (drv, BuiltinUse) <- uses],+      trSources = sources,+      trBuilderBytes =+        Map.fromListWith+          (flip (++))+          [ (doHash out, [doPath out])+          | input <- inputs,+            inputClass input == RunAsBuilder,+            Just (_, out) <- [Map.lookup (inputDrvPath input) (walkFixed walk)],+            doHashAlgo out == flatSha256+          ]+    }+  where+    inputs = sortOn (\input -> (spName (inputOutput input), inputOutput input)) (map inputFor (Map.toList (walkFixed walk)))+    walk = walkClosure graph root+    closureDrvs = map dnDerivation (Map.elems (walkNodes walk))+    sources = Set.fromList (concatMap drvInputSrcs closureDrvs)+    owners = Map.fromList [(doPath out, path) | (path, node) <- Map.toList (walkNodes walk), out <- drvOutputs (dnDerivation node)]+    uses = [(drv, builderUse owners sources drv) | drv <- closureDrvs]+    runs =+      Map.fromListWith+        (Map.unionWith (+))+        [((input, reach), Map.singleton (drvBuilder drv) 1) | (drv, OutputUse owner) <- uses, (input, reach) <- heldAsPinned walk owner]+    runsBy reach path = Map.findWithDefault Map.empty (path, reach) runs+    pinnedBy out = (doHashAlgo out, doHash out)+    byHash = Map.fromListWith (++) [(pinnedBy out, [doPath out]) | (_, out) <- Map.elems (walkFixed walk)]+    inputFor (path, (node, out)) =+      FixedInput+        { inputDrvPath = path,+          inputOutput = doPath out,+          inputProvenance = provenanceOf (dnDerivation node),+          inputSameHash = sortOn (\other -> (spName other, other)) (filter (/= doPath out) (Map.findWithDefault [] (pinnedBy out) byHash)),+          inputBuilders = runsBy Inside path,+          inputTreeBuilders = runsBy InTree path,+          inputScan = maybe NotInStore Scanned (Map.lookup (doPath out) facts)+        }+    provenanceOf drv+      | isBuiltin drv = FetchedBy (drvBuilder drv)+      | otherwise = BuiltBy (drvBuilder drv)+    tally = Map.fromListWith (+) . map (,1)++-- | The report as lines: the fixed-output inputs run as builders, those+-- holding prebuilt code and those not fully read, each with how its bytes+-- come to be, the other inputs pinned to the same hash, the builders+-- inside it or its tree, the prebuilt code found and what was not read;+-- the count of those holding no prebuilt code; the builders from outside+-- the closure, from its input sources and the builtins, each with how+-- many derivations it builds; the count of input sources; and what the+-- report does not say.+renderTrustReport :: TrustReport -> [Text]+renderTrustReport report =+  concat+    [ inputSection "Fixed-output inputs run as builders" RunAsBuilder,+      inputSection "Fixed-output inputs holding prebuilt code" HoldsPrebuiltCode,+      inputSection "Fixed-output inputs not fully read" NotFullyRead,+      [counted "Fixed-output inputs holding no prebuilt code" (length (inClass HoldsNoPrebuiltCode))],+      builderSection "Builders outside the closure" (trOutsideBuilders report),+      builderSection "Builders in input sources" (trSourceBuilders report),+      builderSection "Builtin builders" (trBuiltinBuilders report),+      [counted "Input sources" (Set.size (trSources report))],+      [reliedOnNotSafe]+    ]+  where+    inClass wanted = filter ((== wanted) . inputClass) (trInputs report)+    inputSection label wanted =+      let members = inClass wanted+       in counted label (length members) : concatMap describedInput members+    builderSection label builders =+      counted label (Map.size builders)+        : [indented (displayBytes builder <> ", for " <> derivations count) | (builder, count) <- Map.toList builders]+    counted label count = label <> ": " <> T.pack (show count)+    describedInput input =+      indented (storePathToText defaultStoreDir (inputOutput input))+        : map+          (indented . indented)+          ( provenanceLine (inputProvenance input)+              : map (("same hash as " <>) . storePathToText defaultStoreDir) (inputSameHash input)+              ++ runLines "builder of " (inputBuilders input)+              ++ runLines "in the tree of the builder of " (inputTreeBuilders input)+              ++ scanLines (inputScan input)+          )+    provenanceLine (FetchedBy builder) = "fetched by " <> displayBytes builder+    provenanceLine (BuiltBy builder) = "built in the closure by " <> displayBytes builder <> ", its bytes pinned by its hash"+    runLines lead builders = [lead <> derivations count <> ": " <> displayBytes builder | (builder, count) <- Map.toList builders]+    scanLines NotInStore = ["not read: the store does not hold it"]+    scanLines (Scanned facts) = map codeLine (cfCode facts) ++ map unreadLine (cfUnread facts)+    codeLine code = codeKindName (fcKind code) <> ": " <> placeText (fcPlace code) <> copyText code+    copyText code = case copiesOf report code of+      [] -> ""+      copies -> ", the bytes of " <> T.intercalate " and " (map (storePathToText defaultStoreDir) copies)+    unreadLine unread = "not read: " <> maybe "" (<> ": ") (ufFile unread) <> ufReason unread+    indented = ("  " <>)++-- | The hash algorithm field of a fixed output that is one file hashed+-- with SHA-256: flat, with no method before the algorithm.+flatSha256 :: Text+flatSha256 = "sha256"++-- | The outputs of the fixed-output inputs run as builders whose bytes a+-- file of prebuilt code is, by its SHA-256.  A fetched file is its own+-- input, whose hash the report already gives with the others it equals,+-- so only a file inside a fetched output is named a copy.+copiesOf :: TrustReport -> FoundCode -> [StorePath]+copiesOf report code = case fcPlace code of+  FetchedFile -> []+  _ -> Map.findWithDefault [] (fcSha256 code) (trBuilderBytes report)++-- ---------------------------------------------------------------------------+-- The report as JSON+-- ---------------------------------------------------------------------------++-- | The version of the JSON form, which a change to its fields that a+-- reader of an earlier one would misread raises.+trustReportJsonVersion :: Integer+trustReportJsonVersion = 1++-- | The report as one JSON document, the facts the lines give and the+-- input sources themselves where the lines count them.  Store paths are+-- full paths, keys are camelCase as upstream's JSON output spells its own,+-- and each collection of inputs or builders is an object keyed by its+-- path, members in name order:+--+-- > { "version": 1,+-- >   "fixedOutputInputs": { OUTPUT: INPUT, ... },+-- >   "buildersOutsideClosure": { BUILDER: COUNT, ... },+-- >   "buildersInInputSources": { BUILDER: COUNT, ... },+-- >   "builtinBuilders": { BUILDER: COUNT, ... },+-- >   "inputSources": [ PATH, ... ] }+--+-- An INPUT is its @drvPath@, its @class@ (@runAsBuilder@,+-- @holdsPrebuiltCode@, @notFullyRead@ or @holdsNoPrebuiltCode@), the+-- builtin that fetches it as @fetchedBy@ or the builder that makes it as+-- @builtBy@, @sameHash@, @builderOf@ and @inTreeOfBuilderOf@ (each builder+-- with how many derivations it builds), @inStore@, @prebuiltCode@ and+-- @notRead@.  A @prebuiltCode@ entry is its @kind@, its @file@ in a fetched+-- tree or null for the fetched file, its @member@ in an archive or null,+-- its @sha256@, and @sameBytesAs@, the outputs of the inputs run as+-- builders it is a copy of.  A @notRead@ entry is its @file@ and its+-- @reason@.  A builder that is not UTF-8 is shown with replacement+-- characters, as the lines show it.+trustReportJson :: TrustReport -> Json+trustReportJson report =+  object+    [ ("version", JsonInt trustReportJsonVersion),+      ("fixedOutputInputs", JsonObject (Map.fromList [(pathText (inputOutput input), inputJson input) | input <- trInputs report])),+      ("buildersOutsideClosure", builderCounts (trOutsideBuilders report)),+      ("buildersInInputSources", builderCounts (trSourceBuilders report)),+      ("builtinBuilders", builderCounts (trBuiltinBuilders report)),+      ("inputSources", JsonArray (map (JsonString . pathText) (Set.toList (trSources report))))+    ]+  where+    object = JsonObject . Map.fromList+    pathText = storePathToText defaultStoreDir+    paths = JsonArray . map (JsonString . pathText)+    builderCounts builders = JsonObject (Map.fromList [(displayBytes builder, JsonInt (toInteger count)) | (builder, count) <- Map.toList builders])+    nullable = maybe JsonNull JsonString+    inputJson input =+      object+        ( [ ("drvPath", JsonString (pathText (inputDrvPath input))),+            ("class", JsonString (classKey (inputClass input))),+            provenance (inputProvenance input),+            ("sameHash", paths (inputSameHash input)),+            ("builderOf", builderCounts (inputBuilders input)),+            ("inTreeOfBuilderOf", builderCounts (inputTreeBuilders input))+          ]+            ++ scanned (inputScan input)+        )+    provenance (FetchedBy builder) = ("fetchedBy", JsonString (displayBytes builder))+    provenance (BuiltBy builder) = ("builtBy", JsonString (displayBytes builder))+    scanned NotInStore = [("inStore", JsonBool False), ("prebuiltCode", JsonArray []), ("notRead", JsonArray [])]+    scanned (Scanned facts) =+      [ ("inStore", JsonBool True),+        ("prebuiltCode", JsonArray (map codeJson (cfCode facts))),+        ("notRead", JsonArray (map unreadJson (cfUnread facts)))+      ]+    codeJson code =+      let (file, member) = placeFields (fcPlace code)+       in object+            [ ("kind", JsonString (codeKindKey (fcKind code))),+              ("file", nullable file),+              ("member", nullable member),+              ("sha256", JsonString (fcSha256 code)),+              ("sameBytesAs", paths (copiesOf report code))+            ]+    unreadJson unread = object [("file", nullable (ufFile unread)), ("reason", JsonString (ufReason unread))]++-- | Where a file of prebuilt code is as JSON gives it: its path in a+-- fetched tree, or none for the fetched file, and its path in an archive,+-- or none for a file that is not in one.+placeFields :: CodePlace -> (Maybe Text, Maybe Text)+placeFields place = case place of+  FetchedFile -> (Nothing, Nothing)+  TreeFile path -> (Just path, Nothing)+  ArchiveMember member -> (Nothing, Just member)+  TreeArchiveMember archive member -> (Just archive, Just member)++-- | How JSON names a class.+classKey :: InputClass -> Text+classKey inputClassValue = case inputClassValue of+  RunAsBuilder -> "runAsBuilder"+  HoldsPrebuiltCode -> "holdsPrebuiltCode"+  NotFullyRead -> "notFullyRead"+  HoldsNoPrebuiltCode -> "holdsNoPrebuiltCode"++-- | How JSON names a kind of prebuilt code.+codeKindKey :: CodeKind -> Text+codeKindKey kind = case kind of+  PeImage -> "peImage"+  ElfImage -> "elfImage"+  ElfObject -> "elfObject"+  ElfOther -> "elf"+  MachO -> "machO"+  MachOUniversal -> "machOUniversal"+  CoffObject -> "coffObject"+  ArArchive -> "arArchive"++-- | Where a file of prebuilt code is, as the report says it.+placeText :: CodePlace -> Text+placeText place = case place of+  FetchedFile -> "the fetched file"+  TreeFile path -> path+  ArchiveMember member -> member+  TreeArchiveMember archive member -> member <> " in " <> archive++-- | A count of derivations in words.+derivations :: Int -> Text+derivations 1 = "1 derivation"+derivations count = T.pack (show count) <> " derivations"++-- | A builder's bytes for the report to show.  Display only: a builder+-- that is not UTF-8 is shown with replacement characters, and the bytes+-- are never used as a path.+displayBytes :: ByteString -> Text+displayBytes = TE.decodeUtf8With lenientDecode++-- | The report's last line.+reliedOnNotSafe :: Text+reliedOnNotSafe = "This reports what the closure relies on, not whether any of it is safe."
+ src/Nix/Trust/Fetch.hs view
@@ -0,0 +1,85 @@+-- | Making a closure's fixed-output inputs valid without running anything+-- from the closure, then reading those the store holds, for+-- "Nix.Trust"'s report.+--+-- The store is an argument, a t'FixedOutputStore', so the order the inputs+-- are made valid and read in, and the failure each step stops with, are+-- pure logic that runs in tests over a monad that records the calls.  A+-- store opened directly and a store reached through a daemon+-- ("Nix.Daemon.ClientStore") each give the four operations.+module Nix.Trust.Fetch+  ( FixedOutputStore (..),+    fetchAndScan,+  )+where++import Control.Monad.Except (ExceptT (..), liftEither, runExceptT)+import Control.Monad.Trans (lift)+import Data.Bool (bool)+import Data.Foldable (traverse_)+import Data.List (partition)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (catMaybes)+import Data.Text (Text)+import Nix.DependencyGraph (DepNode (..))+import Nix.Realise (ClosureOutcome (..))+import Nix.Store.Path (StorePath, defaultStoreDir, storePathToText)+import Nix.Trust (ContentFacts, fetchedByBuiltin)++-- | What making the inputs valid and reading them asks of a store.  An+-- operation that cannot be carried out, as opposed to one that ends in+-- an outcome, is a 'Left' with the reason.+data FixedOutputStore m = FixedOutputStore+  { -- | Realise an input 'fetchedByBuiltin' selects, which fetches it or+    -- substitutes it.  'Left' is why it failed.+    fosFetch :: !(DepNode -> m (Either Text ())),+    -- | Substitute an input's output with what it references.  'Left' is+    -- why the store could not be asked.+    fosSubstitute :: !(StorePath -> m (Either Text ClosureOutcome)),+    -- | Whether the store holds a path as valid.+    fosHeld :: !(StorePath -> m (Either Text Bool)),+    -- | The facts of a held path's files.+    fosScan :: !(StorePath -> m ContentFacts)+  }++-- | Make each fixed-output input's output valid in a way that runs+-- nothing from the closure, then scan every one the store holds.  An+-- input that nova-nix's builtins fetch with no input of their own is+-- realised, which substitutes or fetches it; any other is only+-- substituted, with what it references, since making it would run its+-- builder.  That substitution leaves the derivation's @allowSubstitutes@+-- unread: the attribute chooses between building and substituting, and+-- there is no build here to choose.+--+-- Every fetch is made first, then every substitution, then each input is+-- read in order: asked whether the store holds it, and scanned if so.+-- The first fetch that fails stops the run, as a build stops, and so+-- does the first substitution that fails, as upstream's goal for+-- substituting a path fails when a substituter fails, whatever+-- @fallback@ says: @--fallback@ passes over only a cache that cannot be+-- asked, there and here.  An input no cache offers, or whose references+-- no cache offers, does not stop the run: it is not held, so it is not+-- read, and the report names it as not read.  A failure is the reason+-- alone, for the caller to word.+fetchAndScan :: (Monad m) => FixedOutputStore m -> [(DepNode, StorePath)] -> m (Either Text (Map StorePath ContentFacts))+fetchAndScan store inputs = runExceptT $ do+  traverse_ (ExceptT . fosFetch store . fst) fetched+  traverse_ (substitute . snd) others+  Map.fromList . catMaybes <$> traverse scan inputs+  where+    (fetched, others) = partition (fetchedByBuiltin . dnDerivation . fst) inputs+    substitute output = ExceptT (fosSubstitute store output) >>= liftEither . substitutionStop output+    scan (_, output) = do+      held <- ExceptT (fosHeld store output)+      bool (pure Nothing) (Just . (,) output <$> lift (fosScan store output)) held++-- | Whether a substitution's outcome stops the run, and with what words.+-- An input no cache offers, or whose references no cache offers, does+-- not: it is left unread.+substitutionStop :: StorePath -> ClosureOutcome -> Either Text ()+substitutionStop _ ClosureComplete = Right ()+substitutionStop _ ClosureUnavailable = Right ()+substitutionStop _ ClosureIncomplete = Right ()+substitutionStop output ClosureFailed = Left ("a substitute for '" <> storePathToText defaultStoreDir output <> "' or a path it references failed")+substitutionStop _ (ClosureQueryFailed failure) = Left failure
+ src/Nix/Trust/Scan.hs view
@@ -0,0 +1,220 @@+{-# LANGUAGE ScopedTypeVariables #-}++-- | Reading what a fetched output's bytes hold, for "Nix.Trust".+--+-- A fetched output is one file or a tree of them.  Each file is read for+-- prebuilt code by its header ('prebuiltKind'): an executable image, an+-- object file, or an ar archive, whose members are not read.  A file that+-- is a tar archive, plain or compressed with gzip, bzip2, xz or zstd, is+-- opened instead, and each regular file in it is read the same way; an+-- archive inside it is not opened, nor reported as not read.  A file of+-- the output in another archive format the scan knows is reported as not+-- read, never as holding no prebuilt code.+-- The bytes say which a file is, never its name: a source archive and a+-- prebuilt package share their suffixes.  A symbolic link is not+-- followed: a target inside the tree is read where it is, and one outside+-- it is not part of the output.+--+-- A file that cannot be read is reported as not read, with why, and the+-- scan goes on with the rest.  A fetched file is read whole; what it+-- decompresses to is read as it streams, and of each member only as far+-- as its header needs, except that xz and bzip2 decode a stream whole,+-- within 'decompressedBudget'.  A file of prebuilt code is read whole,+-- for the SHA-256 that names it as a fixed-output input of the same bytes+-- ("Nix.Trust").+module Nix.Trust.Scan+  ( scanFetched,+  )+where++import qualified Codec.Archive.Tar as Tar+import qualified Codec.Archive.Tar.Entry as TarEntry+import qualified Codec.Compression.GZip as GZip+import qualified Codec.Compression.Zstd.Lazy as Zstd+import Control.Exception (ErrorCall, Handler (..), IOException, catches, displayException, evaluate, try)+import Data.Bifunctor (bimap)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Lazy as BL+import Data.List (find, sort)+import Data.Text (Text)+import qualified Data.Text as T+import Data.Word (Word64)+import Nix.Builder.Unpack (UnpackLimits (..), defaultUnpackLimits)+import Nix.Compression.Stream (Compression (..), bzip2Reason, compressionOf, xzReason)+import Nix.Hash (sha256LazyHex)+import Nix.Trust (CodePlace (..), ContentFacts (..), FoundCode (..), UnreadFile (..), prebuiltKind)+import qualified NovaCache.Bzip2 as Bzip2+import qualified NovaCache.Xz as Xz+import System.Directory (doesDirectoryExist, listDirectory, pathIsSymbolicLink)+import System.FilePath ((</>))++-- ---------------------------------------------------------------------------+-- Formats+-- ---------------------------------------------------------------------------++-- | How a failure names a stream.+codecName :: Compression -> Text+codecName codec = case codec of+  Gzip -> "gzip"+  Zstd -> "zstd"+  Xz -> "xz"+  Bzip2 -> "bzip2"+  Uncompressed -> "file"++-- | Archive and compression formats the scan recognises and does not+-- open, each as the report names a file of it and by the bytes such a+-- file starts with.+unopenedFormats :: [(Text, BS.ByteString)]+unopenedFormats =+  [ ("a zip archive", "PK\x03\x04"),+    ("a zip archive", "PK\x05\x06"),+    ("a zip archive", "PK\x07\x08"),+    ("a 7z archive", BS.pack [0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C]),+    ("a rar archive", BS.pack [0x52, 0x61, 0x72, 0x21, 0x1A, 0x07]),+    ("a cabinet archive", "MSCF"),+    ("an rpm package", BS.pack [0xED, 0xAB, 0xEE, 0xDB]),+    ("an lzip stream", "LZIP"),+    ("an lz4 stream", BS.pack [0x04, 0x22, 0x4D, 0x18]),+    ("a compress stream", BS.pack [0x1F, 0x9D]),+    ("an OLE compound file, such as an MSI installer", BS.pack [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1])+  ]++-- | Where a POSIX or GNU tar header holds its magic.+tarMagicOffset :: Int+tarMagicOffset = 257++-- | The magic of POSIX's ustar format, which GNU tar's own begins with+-- too.+tarMagic :: BL.ByteString+tarMagic = "ustar"++-- | How much an xz or bzip2 stream may decompress to: the budget+-- @builtin:unpack@ extracts within.  Those decoders return the whole+-- output at once, where gzip and zstd stream theirs.+decompressedBudget :: Word64+decompressedBudget = fromIntegral (ulMaxBytes defaultUnpackLimits)++-- | The separator of a path inside a store path, as a NAR and a tar+-- archive write it on every platform.+treeSeparator :: Text+treeSeparator = "/"++-- ---------------------------------------------------------------------------+-- Scanning+-- ---------------------------------------------------------------------------++-- | What a scan finds in one file.+data Finding = Found !FoundCode | Unread !UnreadFile++-- | What the fetched output at this path holds.+scanFetched :: FilePath -> IO ContentFacts+scanFetched root = do+  findings <- scanEntry root []+  pure (ContentFacts [code | Found code <- findings] [unread | Unread unread <- findings])++-- | The findings at a path of the output, given by its components in the+-- tree, none for the output itself.  A directory's entries are read in+-- order of name, so a scan reports its findings in the same order on+-- every run.+scanEntry :: FilePath -> [FilePath] -> IO [Finding]+scanEntry root components = do+  probed <- try ((,) <$> pathIsSymbolicLink here <*> doesDirectoryExist here)+  case probed of+    Left (failure :: IOException) -> pure [unread failure]+    Right (True, _) -> pure []+    Right (False, True) -> do+      listed <- try (listDirectory here)+      case listed of+        Left (failure :: IOException) -> pure [unread failure]+        Right names -> concat <$> traverse (\name -> scanEntry root (components ++ [name])) (sort names)+    Right (False, False) -> scanFile here inTree+  where+    here = foldl' (</>) root components+    inTree = case components of+      [] -> Nothing+      _ -> Just (T.intercalate treeSeparator (map T.pack components))+    unread failure = Unread (UnreadFile inTree (T.pack (displayException failure)))++-- | The findings in one file, named by its path in a fetched tree, or+-- 'Nothing' for a fetched file.  The gzip and zstd decoders decode as the+-- walk reads, and report a corrupt stream by throwing:+-- 'GZip.DecompressError' from gzip, and 'ErrorCall' from zstd, whose+-- lazy decoder raises every decoding error with @error@, as nothing else+-- on this path does.  The walk's result is forced inside the handlers,+-- so no decoding happens after them.+scanFile :: FilePath -> Maybe Text -> IO [Finding]+scanFile path inTree = do+  attempt <- try (BS.readFile path)+  case attempt of+    Left (failure :: IOException) -> pure [unreadBecause (T.pack (displayException failure))]+    Right bytes -> do+      let codec = compressionOf bytes+          streamError detail = Left (codecName codec <> " stream error: " <> T.pack detail)+      decoded <- decode codec bytes+      walked <- case decoded of+        Left reason -> pure (Left reason)+        Right contents ->+          (Right <$> evaluate (codeIn inTree contents))+            `catches` [ Handler (\(e :: GZip.DecompressError) -> pure (streamError (show e))),+                        Handler (\(e :: ErrorCall) -> pure (streamError (show e)))+                      ]+      pure $ case walked of+        Left reason -> [unreadBecause reason]+        Right (Walked code stopped) -> map Found code ++ [unreadBecause reason | Just reason <- [stopped]]+  where+    unreadBecause reason = Unread (UnreadFile inTree reason)++-- | A file's bytes as the scan reads them: decompressed as their codec+-- says, otherwise as they are.  Nothing is decoded here for gzip and+-- zstd, which decode as their output is read.+decode :: Compression -> BS.ByteString -> IO (Either Text BL.ByteString)+decode codec bytes = case codec of+  Gzip -> pure (Right (GZip.decompress whole))+  Zstd -> pure (Right (Zstd.decompress whole))+  Xz -> pure (bimap xzReason BL.fromStrict (Xz.decompress xzLimits bytes))+  Bzip2 -> bimap bzip2Reason BL.fromStrict <$> Bzip2.decompress bzip2Limits bytes+  Uncompressed -> pure (Right whole)+  where+    whole = BL.fromStrict bytes+    xzLimits = Xz.XzLimits {Xz.xzMaxOutputBytes = decompressedBudget, Xz.xzMaxDecoderMemoryBytes = Xz.defaultXzDecoderMemoryBytes}+    bzip2Limits = Bzip2.Bzip2Limits {Bzip2.bzip2MaxOutputBytes = decompressedBudget}++-- | What reading a file's decoded bytes found: the prebuilt code, and why+-- the reading stopped short, if it did.  Its constructor is built only+-- once the walk ends, so forcing it runs the whole walk.+data Walked = Walked ![FoundCode] !(Maybe Text)++-- | The prebuilt code in a file's decoded bytes: in each regular member+-- of a tar archive, or in the bytes themselves.  Bytes in an archive+-- format the scan does not open are not read, with that as the reason.+codeIn :: Maybe Text -> BL.ByteString -> Walked+codeIn inTree contents+  | BL.take (BL.length tarMagic) (BL.drop (fromIntegral tarMagicOffset) contents) == tarMagic =+      membersIn inTree (Tar.decodeLongNames (Tar.read contents))+  | Just (format, _) <- find ((`BL.isPrefixOf` contents) . BL.fromStrict . snd) unopenedFormats =+      Walked [] (Just (format <> ", which the scan does not open"))+  | otherwise = case prebuiltKind contents of+      Just kind -> Walked [FoundCode kind (maybe FetchedFile TreeFile inTree) (sha256LazyHex contents)] Nothing+      Nothing -> Walked [] Nothing++-- | The prebuilt code among a tar archive's regular members, in archive+-- order, and why the archive stops reading, if it does before its end.+-- Each member is read only as far as its header needs, or whole when it+-- is prebuilt code, and what it is is forced before the next member is+-- read, so the walk holds no member's bytes past its own.+membersIn ::+  Maybe Text ->+  Tar.GenEntries BL.ByteString FilePath FilePath (Either Tar.FormatError Tar.DecodeLongNamesError) ->+  Walked+membersIn inTree = go []+  where+    go !found entries = case entries of+      Tar.Done -> Walked (reverse found) Nothing+      Tar.Fail failure -> Walked (reverse found) (Just ("tar archive stops reading: " <> T.pack (either show show failure)))+      Tar.Next entry rest -> case memberCode entry of+        Nothing -> go found rest+        Just !code -> go (code : found) rest+    memberCode entry = case TarEntry.entryContent entry of+      Tar.NormalFile content _ -> (\kind -> FoundCode kind (placed (T.pack (TarEntry.entryTarPath entry))) (sha256LazyHex content)) <$> prebuiltKind content+      _ -> Nothing+    placed member = maybe (ArchiveMember member) (`TreeArchiveMember` member) inTree
+ test/CacheFixture.hs view
@@ -0,0 +1,301 @@+-- | A model of nova-cache's write endpoints, its multipart upload among+-- them, behind a proxy that refuses a request body over a limit with 413+-- as Cloudflare does, served on loopback for the push tests.  Answers+-- follow nova-cache's server: a narinfo is accepted only when the NAR it+-- names is stored with its FileSize and FileHash, a part only when the+-- parts before it are held, and a completion only when the declared part+-- count and size match what is held.  Faults injected per request stand+-- in for a lost response or a server that lost an upload's parts.+module CacheFixture+  ( CacheSetup (..),+    Multipart (..),+    Fault (..),+    RequestKind (..),+    Logged (..),+    CacheState,+    cacheSetup,+    withModelCache,+    storedObject,+    requestLog,+  )+where++import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BSC+import Data.IORef (atomicModifyIORef', newIORef, readIORef)+import Data.List (sort)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import HttpFixture (FixtureRequest (..), Reply (..), httpResponse, withRequestServer)+import qualified NovaCache.Hash as Hash+import NovaCache.NarInfo (NarInfo (..), parseNarInfo, renderNarInfo)+import Numeric (showHex)++-- | Whether the cache offers the multipart upload: a nova-cache that does+-- not answers each of its requests with 404, before any key is checked.+data Multipart = WithMultipart | WithoutMultipart++-- | What a request is, as the faults and the log name it.+data RequestKind+  = HashList+  | NarInfoGet+  | NarInfoPut+  | NarPut+  | Begin+  | Part !Int+  | Complete+  | Unrouted+  deriving (Eq, Ord, Show)++-- | A fault in place of the server's usual handling of one request.+data Fault+  = -- | Handle the request, then close the connection with no response.+    DropResponse+  | -- | Answer with this status line, and handle nothing.+    Refuse !BS.ByteString+  | -- | Lose every part the request's upload holds, then handle it.+    LoseParts+  | -- | Forget the request's upload, as a reclaim does, then handle it.+    ForgetUpload++-- | The cache a test pushes to.+data CacheSetup = CacheSetup+  { -- | The proxy's limit: a request body over it is refused with 413.+    csBodyLimit :: !Int,+    csMultipart :: !Multipart,+    -- | The write key every write and the hash list must carry.+    csApiKey :: !BS.ByteString,+    -- | The fault, if any, for a request of this kind that the cache has+    -- seen this many times before.+    csFault :: !(RequestKind -> Int -> Maybe Fault)+  }++-- | A cache with the multipart upload, the given proxy limit and write+-- key, and no faults.+cacheSetup :: Int -> BS.ByteString -> CacheSetup+cacheSetup limit key =+  CacheSetup+    { csBodyLimit = limit,+      csMultipart = WithMultipart,+      csApiKey = key,+      csFault = \_ _ -> Nothing+    }++-- | One request as the cache received it.+data Logged = Logged+  { lgKind :: !RequestKind,+    lgBodyBytes :: !Int+  }+  deriving (Eq, Show)++-- | An upload in progress: its NAR's file name and the parts it holds,+-- which are always parts 1 to their count.+data Upload = Upload+  { upFile :: !BS.ByteString,+    upParts :: !(Map Int BS.ByteString)+  }++-- | What the cache holds and what it was asked.+data CacheState = CacheState+  { -- | Stored files by request path: @nar\/\<file\>@ and+    -- @\<hash\>.narinfo@.+    stObjects :: !(Map BS.ByteString BS.ByteString),+    stUploads :: !(Map BS.ByteString Upload),+    stIssued :: !Int,+    stSeen :: !(Map RequestKind Int),+    -- | Newest first.+    stLog :: ![Logged]+  }++-- | Serve the model on loopback for the action, which gets its base URL;+-- returns the action's result and what the cache ended up holding.+withModelCache :: CacheSetup -> (Text -> IO a) -> IO (a, CacheState)+withModelCache setup action = do+  ref <- newIORef (CacheState Map.empty Map.empty 0 Map.empty [])+  result <- withRequestServer (atomicModifyIORef' ref . step setup) action+  final <- readIORef ref+  pure (result, final)++-- | The file stored at a request path.+storedObject :: BS.ByteString -> CacheState -> Maybe BS.ByteString+storedObject path = Map.lookup path . stObjects++-- | Every request the cache received, in order.+requestLog :: CacheState -> [Logged]+requestLog = reverse . stLog++-- | The request paths the model routes.+data Route+  = HashListRoute+  | NarInfoRoute !BS.ByteString+  | NarRoute !BS.ByteString+  | UploadsRoute !BS.ByteString+  | UploadRoute !BS.ByteString !BS.ByteString+  | PartRoute !BS.ByteString !BS.ByteString !BS.ByteString+  | NoRoute++routeOf :: BS.ByteString -> Route+routeOf target = case BSC.split '/' (BS.drop 1 target) of+  ["narinfo-hashes"] -> HashListRoute+  [name] | Just hash <- BS.stripSuffix narInfoSuffix name -> NarInfoRoute hash+  ["nar", file] -> NarRoute file+  ["nar", file, "uploads"] -> UploadsRoute file+  ["nar", file, "uploads", uploadId] -> UploadRoute file uploadId+  ["nar", file, "uploads", uploadId, number] -> PartRoute file uploadId number+  _ -> NoRoute++kindOf :: BS.ByteString -> Route -> RequestKind+kindOf method route = case (method, route) of+  ("GET", HashListRoute) -> HashList+  ("GET", NarInfoRoute _) -> NarInfoGet+  ("PUT", NarInfoRoute _) -> NarInfoPut+  ("PUT", NarRoute _) -> NarPut+  ("POST", UploadsRoute _) -> Begin+  ("PUT", PartRoute _ _ number) -> maybe Unrouted Part (canonicalInt number)+  ("POST", UploadRoute _ _) -> Complete+  _ -> Unrouted++-- | One request: logged, refused by the proxy when its body is over the+-- limit, otherwise handled as the setup's fault for it says.+step :: CacheSetup -> FixtureRequest -> CacheState -> (CacheState, Reply)+step setup request before+  | BS.length (frBody request) > csBodyLimit setup = (logged, respond "413 Payload Too Large" "request body too large")+  | otherwise = case csFault setup kind seen of+      Nothing -> serve setup request route logged+      Just DropResponse -> (fst (serve setup request route logged), Drop)+      Just (Refuse status) -> (logged, respond status "refused by the fixture")+      Just LoseParts -> serve setup request route (withUpload (\upload -> Just upload {upParts = Map.empty}) logged)+      Just ForgetUpload -> serve setup request route (withUpload (const Nothing) logged)+  where+    route = routeOf (frTarget request)+    kind = kindOf (frMethod request) route+    seen = Map.findWithDefault 0 kind (stSeen before)+    logged =+      before+        { stSeen = Map.insert kind (seen + 1) (stSeen before),+          stLog = Logged kind (BS.length (frBody request)) : stLog before+        }+    withUpload change state = case route of+      PartRoute _ uploadId _ -> state {stUploads = Map.update change uploadId (stUploads state)}+      UploadRoute _ uploadId -> state {stUploads = Map.update change uploadId (stUploads state)}+      _ -> state++-- | Handle a request the proxy let through, as nova-cache does.+serve :: CacheSetup -> FixtureRequest -> Route -> CacheState -> (CacheState, Reply)+serve setup request route state+  | WithoutMultipart <- csMultipart setup, isUploadRoute route = (state, notFound)+  | writes && lookup "authorization" (frHeaders request) /= Just ("Bearer " <> csApiKey setup) =+      (state, respond "401 Unauthorized" "missing or wrong write key")+  | otherwise = case (frMethod request, route) of+      ("GET", HashListRoute) ->+        (state, respond "200 OK" (BSC.unlines (Map.keys (Map.mapMaybeWithKey (\path _ -> BS.stripSuffix narInfoSuffix path) (stObjects state)))))+      ("GET", NarInfoRoute hash) ->+        (state, maybe notFound (respond "200 OK") (Map.lookup (hash <> narInfoSuffix) (stObjects state)))+      ("PUT", NarInfoRoute hash) -> either (\err -> (state, respond "400 Bad Request" err)) (\signed -> (store (hash <> narInfoSuffix) signed, ok)) (checkNarInfo body)+      ("PUT", NarRoute file) -> (store (narPath file) body, ok)+      ("POST", UploadsRoute file) ->+        let uploadId = uploadIdText (stIssued state + 1)+         in ( state {stIssued = stIssued state + 1, stUploads = Map.insert uploadId (Upload file Map.empty) (stUploads state)},+              respond "201 Created" (uploadId <> "\n")+            )+      ("PUT", PartRoute file uploadId number) -> putPart file uploadId number+      ("POST", UploadRoute file uploadId) -> complete file uploadId+      _ -> (state, notFound)+  where+    body = frBody request+    writes = frMethod request /= "GET" || isHashList route+    isHashList HashListRoute = True+    isHashList _ = False+    isUploadRoute (UploadsRoute _) = True+    isUploadRoute (UploadRoute _ _) = True+    isUploadRoute (PartRoute {}) = True+    isUploadRoute _ = False+    notFound = respond "404 Not Found" "not found"+    ok = respond "200 OK" ""+    store path bytes = state {stObjects = Map.insert path bytes (stObjects state)}+    upload file uploadId = case Map.lookup uploadId (stUploads state) of+      Just found | upFile found == file -> Just found+      _ -> Nothing+    unknown file uploadId = (state, respond "404 Not Found" ("no upload " <> uploadId <> " of " <> narPath file))+    putPart file uploadId number = case (upload file uploadId, canonicalInt number) of+      (_, Nothing) -> (state, respond "400 Bad Request" "part number must be a whole number from 1 to 10000")+      (Nothing, _) -> unknown file uploadId+      (Just found, Just n)+        | n < 1 || n > maxParts -> (state, respond "400 Bad Request" "part number must be a whole number from 1 to 10000")+        | n > held + 1 ->+            ( state,+              respond+                "409 Conflict"+                ("upload of " <> narPath file <> " holds " <> countedParts held <> ", so the next is part " <> showBytes (held + 1) <> ", not part " <> number)+            )+        | otherwise -> (state {stUploads = Map.insert uploadId found {upParts = Map.insert n body (upParts found)} (stUploads state)}, ok)+        where+          held = Map.size (upParts found)+    complete file uploadId = case (upload file uploadId, parseTotals body) of+      (Nothing, _) -> unknown file uploadId+      (Just _, Nothing) -> (state, respond "400 Bad Request" "completion body is not Parts and FileSize lines")+      (Just found, Just (count, size))+        | count /= Map.size (upParts found) -> (state, respond "409 Conflict" "Parts is not the parts held")+        | size /= BS.length joined -> (state, respond "409 Conflict" "FileSize is not the size the parts join to")+        | otherwise -> ((store (narPath file) joined) {stUploads = Map.delete uploadId (stUploads state)}, ok)+        where+          joined = BS.concat (Map.elems (upParts found))+    -- The narinfo, signed, when the NAR it names is stored as it declares.+    checkNarInfo bytes = do+      narInfo <- either (const (Left "narinfo is not UTF-8")) Right (TE.decodeUtf8' bytes) >>= either (Left . BSC.pack) Right . parseNarInfo+      file <- maybe (Left "narinfo URL is not under nar/") Right (T.stripPrefix "nar/" (niUrl narInfo))+      let named = narPath (TE.encodeUtf8 file)+      nar <- maybe (Left ("NAR " <> named <> " is not stored; upload it before its narinfo")) Right (Map.lookup named (stObjects state))+      if niFileSize narInfo == Just (fromIntegral (BS.length nar)) && niFileHash narInfo == Just (Hash.formatNixHash (Hash.hashBytes nar))+        then Right (TE.encodeUtf8 (renderNarInfo narInfo {niSigs = [fixtureSignature]}))+        else Left ("NAR " <> named <> " is not the file the narinfo declares")++-- | The body that completes an upload: a @Parts@ and a @FileSize@ line,+-- in either order, each value in canonical decimal.+parseTotals :: BS.ByteString -> Maybe (Int, Int)+parseTotals body = case sort (BSC.lines body) of+  [sizeLine, partsLine] -> (,) <$> field "Parts: " partsLine <*> field "FileSize: " sizeLine+  _ -> Nothing+  where+    field key line = BS.stripPrefix key line >>= canonicalInt++-- | A number in canonical decimal: digits only, no sign, no leading zero.+canonicalInt :: BS.ByteString -> Maybe Int+canonicalInt text = case BSC.readInt text of+  Just (n, rest) | BS.null rest && showBytes n == text -> Just n+  _ -> Nothing++-- | The id of the nth upload the model issues: 32 lowercase hex digits,+-- as nova-cache issues them.+uploadIdText :: Int -> BS.ByteString+uploadIdText n = BSC.pack (replicate (uploadIdDigits - length digits) '0' <> digits)+  where+    digits = showHex n ""++-- | A count of parts with its noun, as nova-cache words it.+countedParts :: Int -> BS.ByteString+countedParts 1 = "1 part"+countedParts n = showBytes n <> " parts"++respond :: BS.ByteString -> BS.ByteString -> Reply+respond status = Send . httpResponse status++narPath :: BS.ByteString -> BS.ByteString+narPath file = "nar/" <> file++showBytes :: Int -> BS.ByteString+showBytes = BSC.pack . show++narInfoSuffix :: BS.ByteString+narInfoSuffix = ".narinfo"++-- | Stands in for the server's signature; push only checks one is there.+fixtureSignature :: Text+fixtureSignature = "fixture-1:c2lnbmVk"++uploadIdDigits, maxParts :: Int+uploadIdDigits = 32+maxParts = 10000
+ test/DaemonLink.hs view
@@ -0,0 +1,154 @@+{-# LANGUAGE CPP #-}++-- | A test's connection to a daemon the suite runs, over the daemon's+-- Unix socket, or on Windows its named pipe ("Nix.Daemon.Pipe"); where+-- such a daemon listens; whom its socket or pipe is open to; and the+-- environment a command the suite runs starts from, which names no daemon+-- of the machine's.+module DaemonLink+  ( DaemonLink (..),+    daemonAddress,+    isolatedStoreEnvironment,+    connectDaemon,+    listenerOpenToUsers,+  )+where++import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BS8+import System.Environment (getEnvironment)+import System.FilePath ((</>))+import Test.Harness (TestResult, assertEqual)++#if defined(mingw32_HOST_OS)+import qualified Data.ByteString.Builder as BB+import Data.IORef (atomicModifyIORef', newIORef)+import qualified Data.Text as T+import DirDacl (Dacl (..), DaclEntry (..), directoryDacl)+import GHC.Clock (getMonotonicTimeNSec)+import Nix.Daemon.Connection (Transport (..))+import qualified Nix.Daemon.Pipe as Pipe+import Nix.Store.Access (sidText)+import qualified System.Process as Proc+#else+import Control.Exception (onException)+import Network.Socket (Family (AF_UNIX), SockAddr (SockAddrUnix), SocketType (Stream), close, connect, defaultProtocol, socket)+import Network.Socket.ByteString (recv, sendAll)+import NodeStatus (NodeStatus (..), nodeStatus)+import Nix.Environment (argumentBytes)+#endif++-- | A connection to a daemon, as a test drives it byte by byte.+data DaemonLink = DaemonLink+  { -- | Send bytes, all of them.+    linkSend :: BS.ByteString -> IO (),+    -- | Up to as many bytes as asked, once some have arrived, or none once+    -- the daemon has closed the connection.+    linkReceive :: Int -> IO BS.ByteString,+    -- | Close the connection.+    linkClose :: IO ()+  }++-- | Where a test's daemon listens, given the directory it keeps its+-- store in, or 'Nothing' where that has no spelling as bytes: a socket in+-- the directory, or on Windows a pipe no other daemon of any run has.+daemonAddress :: FilePath -> IO (Maybe BS.ByteString)++-- | Connect to the daemon listening at an address.  A failure throws.+connectDaemon :: BS.ByteString -> IO DaemonLink++-- | Whether the daemon's socket is open to every user, as upstream's is,+-- or on Windows its pipe has the DACL "Nix.Daemon.Pipe" gives it: full+-- control to SYSTEM and Administrators, the daemon's own account the+-- access to create an instance only where it does not own the pipe as+-- Administrators, and Users the right to read and write but not to create+-- an instance.+listenerOpenToUsers :: BS.ByteString -> IO TestResult++#if defined(mingw32_HOST_OS)++daemonAddress _ = do+  pid <- Proc.getCurrentPid+  now <- getMonotonicTimeNSec+  pure (Just (BS8.pack ("\\\\.\\pipe\\nova-nix-test-" <> show pid <> "-" <> show now)))++connectDaemon address = case Pipe.pipePath address of+  Left reason -> ioError (userError (T.unpack reason))+  Right path ->+    Pipe.connectPipe path >>= \connected -> case connected of+      Left reason -> ioError (userError (T.unpack reason))+      Right conn -> do+        let transport = Pipe.connectionTransport conn+        held <- newIORef BS.empty+        let receive count =+              atomicModifyIORef' held (\kept -> (BS.empty, kept)) >>= \kept ->+                if BS.null kept+                  then maybe (pure BS.empty) (keep count) =<< transportReceive transport+                  else keep count kept+            keep count bytes = do+              let (now, later) = BS.splitAt count bytes+              atomicModifyIORef' held (\kept -> (later <> kept, ()))+              pure now+        pure+          DaemonLink+            { linkSend = transportSend transport . BB.byteString,+              linkReceive = receive,+              linkClose = Pipe.closeConnection conn+            }++-- Reading a pipe's DACL opens it, as a client does.+listenerOpenToUsers address = do+  dacl <- directoryDacl (BS8.unpack address)+  owner <- Pipe.processPipeOwner+  let allowed mask sid = DaclEntry 0 0 mask (Just sid)+      fullControl = 0x1F01FF+      accountEntries = case owner of+        Pipe.OwnedByAdministrators -> []+        Pipe.OwnedByAccount account -> [allowed Pipe.daemonPipeAccess (sidText account)]+  pure $+    assertEqual+      "DACL"+      ( Just+          ( Dacl+              True+              ( [allowed fullControl "S-1-5-18", allowed fullControl "S-1-5-32-544"]+                  <> accountEntries+                  <> [allowed Pipe.clientPipeAccess "S-1-5-32-545"]+              )+          )+      )+      dacl++#else++daemonAddress root = argumentBytes (root </> "socket")++connectDaemon address = do+  sock <- socket AF_UNIX Stream defaultProtocol+  connect sock (SockAddrUnix (BS8.unpack address)) `onException` close sock+  pure DaemonLink {linkSend = sendAll sock, linkReceive = recv sock, linkClose = close sock}++listenerOpenToUsers address = assertEqual "mode" (Just 0o666) . fmap nsPermissions <$> nodeStatus (BS8.unpack address)++#endif++-- | The process's environment for a command a test runs, in which nothing+-- on the machine that runs the suite decides which store the command+-- uses: there is no @NIX_REMOTE@; the system configuration directory+-- (@NIX_CONF_DIR@) is one of the test's own, under its root, which holds+-- nothing, so the machine's nix.conf and the @store@ setting it may hold+-- are not read; and the daemon's address (@NIX_DAEMON_SOCKET_PATH@) is one+-- under that root, or on Windows a pipe name of the run's own, at which+-- nothing listens, so a store command given no @--store@ never reaches a+-- daemon of the machine's.  The directory and the socket are named and+-- not made.  A test that sets any of these itself filters it out of what+-- this returns.+isolatedStoreEnvironment :: FilePath -> IO [(String, String)]+isolatedStoreEnvironment root = do+  ambient <- getEnvironment+  address <- daemonAddress root+  pure+    ( [("NIX_DAEMON_SOCKET_PATH", BS8.unpack bytes) | Just bytes <- [address]]+        ++ [("NIX_CONF_DIR", root </> "empty-system-config")]+        ++ filter ((`notElem` ["NIX_REMOTE", "NIX_DAEMON_SOCKET_PATH", "NIX_CONF_DIR"]) . fst) ambient+    )
+ test/DirDacl.hs view
@@ -0,0 +1,148 @@+{-# LANGUAGE CPP #-}++-- | A directory's DACL as Windows reads it back, for the store access+-- tests: whether it is protected and each of its entries, through+-- GetNamedSecurityInfoW (test/cbits/nn_test_dacl.c), an entry's owner,+-- and the user the process runs as.  A POSIX directory has no DACL, so+-- each answers 'Nothing' there.+module DirDacl+  ( Dacl (..),+    DaclEntry (..),+    directoryDacl,+    entryOwner,+    processUserSid,+  )+where++import Data.Text (Text)+import Data.Word (Word32, Word8)++#if defined(mingw32_HOST_OS)+import Control.Exception (finally)+import Control.Monad (when)+import Data.Maybe (fromMaybe)+import qualified Data.Text as T+import Foreign.C.String (CString, CWString, peekCString, peekCWString, withCWString)+import Foreign.C.Types (CInt (..), CLong (..), CULong (..))+import Foreign.Marshal.Alloc (alloca)+import Foreign.Marshal.Array (allocaArray, peekArray)+import Foreign.Marshal.Utils (maybePeek)+import Foreign.Ptr (Ptr)+import Foreign.Storable (peek)+#endif++-- | One entry of a DACL: its type (0 allows, 1 denies), its flags (the+-- inheritance bits among them), its access mask, and the SID it names,+-- which only an allow or deny entry is read for.+data DaclEntry = DaclEntry+  { deType :: !Word8,+    deFlags :: !Word8,+    deMask :: !Word32,+    deSid :: !(Maybe Text)+  }+  deriving (Eq, Ord, Show)++-- | A directory's DACL: whether it is protected, taking no entry from+-- its parent, and its entries in order.+data Dacl = Dacl+  { daclProtected :: !Bool,+    daclEntries :: ![DaclEntry]+  }+  deriving (Eq, Show)++-- | The DACL of the directory at the path, or 'Nothing' off Windows.  A+-- failure to read it, or a directory with no DACL to read, throws.+directoryDacl :: FilePath -> IO (Maybe Dacl)++-- | The SID of the user this process runs as, as nova-nix reads it for+-- the grants it writes, or 'Nothing' off Windows.+processUserSid :: IO (Maybe Text)++-- | The SID of the owner of the entry at the path, or 'Nothing' off+-- Windows.  A failure to read it throws.+entryOwner :: FilePath -> IO (Maybe Text)++#if defined(mingw32_HOST_OS)++foreign import ccall unsafe "nn_test_dacl_read"+  c_nn_test_dacl_read :: CWString -> Ptr (Ptr ()) -> IO CULong++foreign import ccall unsafe "nn_test_dacl_protected"+  c_nn_test_dacl_protected :: Ptr () -> IO CInt++foreign import ccall unsafe "nn_test_dacl_count"+  c_nn_test_dacl_count :: Ptr () -> IO CLong++foreign import ccall unsafe "nn_test_dacl_entry"+  c_nn_test_dacl_entry :: Ptr () -> CULong -> Ptr CULong -> Ptr CWString -> IO CULong++foreign import ccall unsafe "nn_token_user_sid"+  c_nn_token_user_sid :: Ptr CWString -> Ptr CString -> IO CULong++foreign import ccall unsafe "LocalFree"+  c_LocalFree :: Ptr a -> IO (Ptr a)++foreign import ccall unsafe "nn_test_owner_read"+  c_nn_test_owner_read :: CWString -> Ptr CWString -> IO CULong++directoryDacl path =+  withCWString path $ \cPath -> alloca $ \out -> do+    succeeded "GetNamedSecurityInfoW" =<< c_nn_test_dacl_read cPath out+    descriptor <- peek out+    (Just <$> readDacl descriptor) `finally` c_LocalFree descriptor++entryOwner path =+  withCWString path $ \cPath -> alloca $ \sidOut -> do+    succeeded "GetNamedSecurityInfoW" =<< c_nn_test_owner_read cPath sidOut+    Just <$> (takeWideString =<< peek sidOut)++processUserSid =+  alloca $ \sidOut -> alloca $ \failedOut -> do+    code <- c_nn_token_user_sid sidOut failedOut+    call <- maybePeek peekCString =<< peek failedOut+    succeeded (fromMaybe "nn_token_user_sid" call) code+    Just <$> (takeWideString =<< peek sidOut)++-- | The protection and entries of a security descriptor's DACL.+readDacl :: Ptr () -> IO Dacl+readDacl descriptor = do+  protected <- c_nn_test_dacl_protected descriptor+  count <- c_nn_test_dacl_count descriptor+  when (protected < 0) (ioError (userError "GetSecurityDescriptorControl failed"))+  when (count < 0) (ioError (userError "the directory has no DACL to read"))+  Dacl (protected == 1) <$> traverse (readEntry descriptor . fromIntegral) [0 .. count - 1]++-- | One entry of a security descriptor's DACL.+readEntry :: Ptr () -> CULong -> IO DaclEntry+readEntry descriptor index =+  allocaArray entryFieldCount $ \fields -> alloca $ \sidOut -> do+    succeeded "GetAce" =<< c_nn_test_dacl_entry descriptor index fields sidOut+    values <- peekArray entryFieldCount fields+    sid <- peek sidOut+    named <- maybePeek takeWideString sid+    case values of+      [kind, flags, mask] -> pure (DaclEntry (fromIntegral kind) (fromIntegral flags) (fromIntegral mask) named)+      _ -> ioError (userError "nn_test_dacl_entry wrote the wrong number of fields")++-- | The fields nn_test_dacl_entry writes: type, flags and mask.+entryFieldCount :: Int+entryFieldCount = 3++-- | A string the Win32 API allocated, read and then released.+takeWideString :: CWString -> IO Text+takeWideString str = (T.pack <$> peekCWString str) `finally` c_LocalFree str++-- | Throw unless a Win32 call's error code is 0.+succeeded :: String -> CULong -> IO ()+succeeded call code =+  when (code /= 0) (ioError (userError (call <> " failed with Win32 error " <> show code)))++#else++directoryDacl _ = pure Nothing++entryOwner _ = pure Nothing++processUserSid = pure Nothing++#endif
test/HttpFixture.hs view
@@ -1,26 +1,35 @@ {-# LANGUAGE OverloadedStrings #-}  -- | Scoped loopback HTTP servers for the download tests: the mirrors--- @builtin:fetchurl@ tries, and the binary cache the substituter reads.+-- @builtin:fetchurl@ tries, and the binary cache the substituter reads;+-- and for the push tests, a server that reads each request's body, and+-- one that serves a directory's files, closing each connection or keeping+-- it open for the next request. module HttpFixture   ( Reply (..),+    FixtureRequest (..),     httpResponse,     withHttpServer,     withFetchurlServer,+    withRequestServer,+    withDirectoryServer,+    withKeepAliveDirectoryServer,   ) where  import Control.Concurrent (newEmptyMVar, readMVar, threadDelay, tryPutMVar)-import Control.Concurrent.Async (race, wait, withAsync)+import Control.Concurrent.Async (async, cancel, race, wait, withAsync) import Control.Exception (IOException, bracket, bracketOnError, finally, try) import Control.Monad (forever, void) import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BSC+import Data.Char (toLower) import Data.IORef (atomicModifyIORef', newIORef, readIORef) import Data.Text (Text) import qualified Data.Text as T import qualified Network.Socket as Socket import qualified Network.Socket.ByteString as Socket+import System.FilePath (joinPath, (</>))  -- | How the server answers one request. data Reply@@ -29,39 +38,157 @@   | -- | The headers of a body that outlives the cancellation watchdog,     -- then that body a byte at a time; fixture cleanup stops it.     Trickle+  | -- | No response: the connection closes once the request is read, as+    -- when a response is lost on its way back.+    Drop +-- | A request as 'withRequestServer' read it.+data FixtureRequest = FixtureRequest+  { frMethod :: !BS.ByteString,+    frTarget :: !BS.ByteString,+    -- | Each header's name in lowercase, with its value.+    frHeaders :: ![(BS.ByteString, BS.ByteString)],+    -- | The body, as long as its @Content-Length@ said.+    frBody :: !BS.ByteString+  }+ -- | Loopback HTTP only: no external services, fixed ports, or subprocesses. -- The route answers each request from its target and the number of times -- that target was requested before.  The callback gets the base URL, -- request history, and a first-request signal.  Socket and server-thread -- lifetimes are scoped to the callback. withHttpServer :: (BS.ByteString -> Int -> Reply) -> (Text -> IO [BS.ByteString] -> IO () -> IO a) -> IO a-withHttpServer route action = Socket.withSocketsDo $ do+withHttpServer route action = do   requests <- newIORef []   requested <- newEmptyMVar-  let serve listener = forever $ bracket (fst <$> Socket.accept listener) Socket.close $ \client -> do+  let serve client = do         header <- readHeaders client BS.empty         path <- case BSC.words (BSC.takeWhile (/= '\r') header) of           "GET" : target : _ -> pure target           _ -> fail "unexpected fixture request"         earlier <- atomicModifyIORef' requests (\seen -> (path : seen, length (filter (== path) seen)))-        case route path earlier of-          Trickle -> do-            Socket.sendAll client "HTTP/1.1 200 OK\r\nContent-Length: 1000\r\nConnection: close\r\n\r\npartial"-            void (tryPutMVar requested ())-            sendSlowBody client slowBodyChunks-          Send bytes -> do-            void (tryPutMVar requested ())-            Socket.sendAll client bytes+        answer (void (tryPutMVar requested ())) client (route path earlier)+  withLoopbackServer OneAtATime serve (\base -> action base (reverse <$> readIORef requests) (readMVar requested))++-- | A loopback server for requests that carry a body: each request's+-- method, target, headers and body (read to its @Content-Length@, none+-- without one) go to the handler, which answers it.  Requests are served+-- one at a time, in the order they connect.+withRequestServer :: (FixtureRequest -> IO Reply) -> (Text -> IO a) -> IO a+withRequestServer handler = withLoopbackServer OneAtATime $ \client -> do+  (header, afterHeader) <- BS.breakSubstring headerEnd <$> readHeaders client BS.empty+  request <- case BSC.lines (BSC.filter (/= '\r') header) of+    requestLine : headerLines+      | method : target : _ <- BSC.words requestLine ->+          pure (FixtureRequest method target (map headerField headerLines) BS.empty)+    _ -> fail "unexpected fixture request"+  bodyLength <- case lookup "content-length" (frHeaders request) of+    Nothing -> pure 0+    Just value+      | Just (len, rest) <- BSC.readInt value, BS.null rest, len >= 0 -> pure len+      | otherwise -> fail "fixture request has a bad Content-Length"+  body <- readBody client bodyLength (BS.drop (BS.length headerEnd) afterHeader)+  answer (pure ()) client =<< handler request {frBody = body}+  where+    headerField line =+      let (name, value) = BSC.break (== ':') line+       in (BSC.map toLower name, BSC.dropWhile (== ' ') (BS.drop 1 value))+    readBody client len bytes+      | BS.length bytes >= len = pure (BS.take len bytes)+      | otherwise = do+          chunk <- Socket.recv client headerChunkBytes+          if BS.null chunk then fail "incomplete fixture request body" else readBody client len (bytes <> chunk)++-- | A static file server over a directory, as a web server serving a+-- binary cache's directory is: a GET answers the file under the directory+-- that its target names, and a request for anything else is a 404.  The+-- callback gets the base URL.+withDirectoryServer :: FilePath -> (Text -> IO a) -> IO a+withDirectoryServer root = withRequestServer (fmap (Send . uncurry httpResponse) . directoryAnswer root (,))++-- | 'withDirectoryServer' over connections it keeps open, as a web server+-- speaking HTTP/1.1 keeps them: each response leaves the connection open+-- for the client's next request, so a client may keep it in a pool.  Each+-- client is served on a thread of its own until it closes the+-- connection.+withKeepAliveDirectoryServer :: FilePath -> (Text -> IO a) -> IO a+withKeepAliveDirectoryServer root = withLoopbackServer EachOnItsOwnThread (serveKept BS.empty)+  where+    serveKept pending client = do+      next <- nextRequest client pending+      case next of+        Nothing -> pure ()+        Just (header, rest) -> do+          answered <- case BSC.words (BSC.takeWhile (/= '\r') header) of+            method : target : _ -> directoryAnswer root (,) (FixtureRequest method target [] BS.empty)+            _ -> fail "unexpected fixture request"+          Socket.sendAll client (uncurry keptResponse answered)+          serveKept rest client++-- | The status and body a directory server answers a request with: a GET+-- the file under the directory its target names, anything else a 404.+directoryAnswer :: FilePath -> (BS.ByteString -> BS.ByteString -> a) -> FixtureRequest -> IO a+directoryAnswer root reply request = case (frMethod request, servedFile (frTarget request)) of+  ("GET", Just relative) -> do+    found <- try (BS.readFile (root </> relative)) :: IO (Either IOException BS.ByteString)+    pure (either (const notFound) (reply "200 OK") found)+  _ -> pure notFound+  where+    notFound = reply "404 Not Found" "not found"+    -- A target's path below the directory, never one that leaves it.+    servedFile target = case BSC.split '/' target of+      "" : segments@(_ : _)+        | all (`notElem` ["", ".", ".."]) segments -> Just (joinPath (map BSC.unpack segments))+      _ -> Nothing++-- | The next request's headers on a kept connection, and the bytes that+-- came after them, or 'Nothing' once the client has closed the connection+-- between requests.+nextRequest :: Socket.Socket -> BS.ByteString -> IO (Maybe (BS.ByteString, BS.ByteString))+nextRequest client pending = case BS.breakSubstring headerEnd pending of+  (header, rest)+    | not (BS.null rest) -> pure (Just (header, BS.drop (BS.length headerEnd) rest))+    | BS.length pending > maxHeaderBytes -> fail "fixture request headers too large"+    | otherwise -> do+        chunk <- Socket.recv client headerChunkBytes+        case (BS.null chunk, BS.null pending) of+          (True, True) -> pure Nothing+          (True, False) -> fail "incomplete fixture request"+          _ -> nextRequest client (pending <> chunk)++-- | A whole response that leaves the connection open.+keptResponse :: BS.ByteString -> BS.ByteString -> BS.ByteString+keptResponse status body =+  "HTTP/1.1 " <> status <> "\r\nContent-Length: " <> BSC.pack (show (BS.length body)) <> "\r\n\r\n" <> body++-- | How a loopback server takes the clients it accepts.+data Clients+  = -- | Each served to the end before the next is accepted.+    OneAtATime+  | -- | Each served on a thread of its own, all of them stopped when the+    -- server's scope ends.+    EachOnItsOwnThread++-- | Serve each client the listener accepts with the action, for as long+-- as the callback runs, on a loopback port the callback gets as a base+-- URL.+withLoopbackServer :: Clients -> (Socket.Socket -> IO ()) -> (Text -> IO a) -> IO a+withLoopbackServer clients serve action = Socket.withSocketsDo $   bracket listen Socket.close $ \listener -> do     address <- Socket.getSocketName listener     base <- case address of       Socket.SockAddrInet port _ -> pure ("http://127.0.0.1:" <> T.pack (show port))       _ -> fail "fixture did not bind IPv4"-    withAsync (serve listener) $ \worker -> do+    threads <- newIORef []+    let acceptOne = case clients of+          OneAtATime -> bracket (fst <$> Socket.accept listener) Socket.close serve+          EachOnItsOwnThread -> bracketOnError (fst <$> Socket.accept listener) Socket.close $ \client -> do+            thread <- async (serve client `finally` Socket.close client)+            atomicModifyIORef' threads (\started -> (thread : started, ()))+    withAsync (forever acceptOne) $ \worker -> do       -- WinSock accept is a blocking safe FFI call. Close the listener before       -- withAsync waits for cancellation, or that wait can never finish.-      outcome <- race (wait worker) (action base (reverse <$> readIORef requests) (readMVar requested)) `finally` Socket.close listener+      outcome <- race (wait worker) (action base) `finally` (Socket.close listener >> readIORef threads >>= mapM_ cancel)       case outcome of         Left () -> fail "fixture server stopped unexpectedly"         Right result -> pure result@@ -70,21 +197,43 @@       Socket.bind sock (Socket.SockAddrInet 0 (Socket.tupleToHostAddress (127, 0, 0, 1)))       Socket.listen sock fixtureBacklog       pure sock++-- | The bytes of a request up to and including the blank line that ends+-- its headers, and any of its body that arrived with them.+readHeaders :: Socket.Socket -> BS.ByteString -> IO BS.ByteString readHeaders client bytes-      | "\r\n\r\n" `BS.isInfixOf` bytes = pure bytes+  | headerEnd `BS.isInfixOf` bytes = pure bytes   | BS.length bytes > maxHeaderBytes = fail "fixture request headers too large"   | otherwise = do       chunk <- Socket.recv client headerChunkBytes       if BS.null chunk then fail "incomplete fixture request" else readHeaders client (bytes <> chunk)++-- | Answer a client: send a whole response, trickle one, or send nothing.+-- The signal runs once the client can see the answer begin: before a+-- whole response, after a trickled one's headers.+answer :: IO () -> Socket.Socket -> Reply -> IO ()+answer signal client reply = case reply of+  Send bytes -> signal >> Socket.sendAll client bytes+  Trickle -> do+    Socket.sendAll client "HTTP/1.1 200 OK\r\nContent-Length: 1000\r\nConnection: close\r\n\r\npartial"+    signal+    sendSlowBody slowBodyChunks+  Drop -> signal+  where     -- Keep WinSock's safe recv calls returning while the response remains in     -- flight: cancellation is delivered between chunks. A peer disconnect is     -- expected when the cancellation test closes its HTTP response.-    sendSlowBody _ 0 = pure ()-    sendSlowBody client remaining = do+    sendSlowBody :: Int -> IO ()+    sendSlowBody 0 = pure ()+    sendSlowBody remaining = do       sent <- try (Socket.sendAll client "x") :: IO (Either IOException ())       case sent of         Left _ -> pure ()-        Right () -> threadDelay slowBodyIntervalMicros >> sendSlowBody client (remaining - 1)+        Right () -> threadDelay slowBodyIntervalMicros >> sendSlowBody (remaining - 1)++-- | The blank line that ends a request's headers.+headerEnd :: BS.ByteString+headerEnd = "\r\n\r\n"  -- | The mirrors the fetchurl tests name, answering the same way however -- often they are asked.
test/Main.hs view

19658 lines of diff, too many to show among the others: show this file

+ test/NodeStatus.hs view
@@ -0,0 +1,39 @@+{-# LANGUAGE CPP #-}++-- | A node's mode and modification time as @lstat@ reports them, for the+-- store metadata tests: "System.Directory" reads only the owner's+-- permissions, and follows a symlink for its time.  Windows has no mode,+-- so it answers 'Nothing' there.+module NodeStatus+  ( NodeStatus (..),+    nodeStatus,+  )+where++import Data.Int (Int64)+import Data.Word (Word32)++#if !defined(mingw32_HOST_OS)+import Data.Bits (complement, (.&.))+import Foreign.C.Types (CTime (..))+import System.Posix.Files (fileMode, fileTypeModes, getSymbolicLinkStatus, modificationTime)+#endif++-- | A node's mode below its file type, and its modification time in+-- whole seconds since the epoch.+data NodeStatus = NodeStatus+  { nsPermissions :: !Word32,+    nsModificationTime :: !Int64+  }+  deriving (Eq, Show)++-- | The status of a node, of a symlink itself rather than its target.+nodeStatus :: FilePath -> IO (Maybe NodeStatus)+#if defined(mingw32_HOST_OS)+nodeStatus _ = pure Nothing+#else+nodeStatus path = do+  status <- getSymbolicLinkStatus path+  let CTime seconds = modificationTime status+  pure (Just (NodeStatus (fromIntegral (fileMode status .&. complement fileTypeModes)) seconds))+#endif
+ test/Test/Archive.hs view
@@ -0,0 +1,673 @@+{-# LANGUAGE LambdaCase #-}++-- | Tests of fetched archives: the tar reader, the tar sink's rules, a+-- tree's NAR, and @builtins.fetchTarball@ unpacking in process, each as+-- upstream reads and places an archive's entries.+module Test.Archive+  ( testTarReader,+    testTarSink,+    testArchiveProperties,+    testFetchTarballIO,+  )+where++import qualified Codec.Archive.Tar as Tar+import qualified Codec.Archive.Tar.Entry as TarEntry+import qualified Codec.Compression.GZip as GZip+import Control.Exception (evaluate)+import Control.Monad (void)+import Control.Monad.State.Strict (State, evalState, gets, modify, state)+import Data.Bifunctor (second)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BC+import qualified Data.ByteString.Lazy as BL+import qualified Data.ByteString.Unsafe as BSU+import Data.Char (toLower)+import Data.IORef (atomicModifyIORef', newIORef)+import Data.List (isPrefixOf)+import qualified Data.Map.Strict as Map+import Data.Text (Text)+import qualified Data.Text as T+import Foreign.Ptr (minusPtr)+import Nix.Eval.CanonPath (canonPathValue)+import Nix.Fetch.Archive (ArchiveEntry (..), ArchiveNode (..), FetchFailure (..), drainFile, emptySink, finishSink, readArchive, sinkEntry, unpackArchive)+import Nix.Fetch.Tar (TarFailure (..), TarStep (..), tarReader)+import Nix.Fetch.Tree (Blob (..), NarPiece (..), Tree (..), blobFile, dereferenceSingleton, narPieces)+import Nix.Hash (FileIngestionMethod (..), makeFixedOutputPath, sha256Digest)+import Nix.Store.CaseSensitive (probeCaseSensitivity, volumeCaseHack)+import qualified Nix.Store.ExecBit as ExecBit+import Nix.Store.Path (StoreDir (..), storePathToFilePath)+import qualified NovaCache.Hash as Hash+import qualified NovaCache.NAR as NAR+import qualified NovaCache.Zstd as Zstd+import Numeric (showOct)+import System.Directory (createDirectoryIfMissing, getTemporaryDirectory)+import System.FilePath ((</>))+import System.Timeout (timeout)+import Test.Harness (TestResult (..), allFailures, andThen, assertEqual, evalNixIOStore, fetchedStorePath, forceRemoveIfExists, runTest, runTestM)+import qualified Test.QuickCheck as QC++-- | A QuickCheck property as a test result.+property :: (QC.Testable prop) => prop -> IO TestResult+property prop = do+  result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} prop+  pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))++-- ---------------------------------------------------------------------------+-- Driving the reader over bytes in memory+-- ---------------------------------------------------------------------------++-- | Unpack an archive's bytes, fed in the chunks given, with each file's+-- contents as its blob.+unpackChunks :: [ByteString] -> ([Text], Either FetchFailure (Tree ByteString))+unpackChunks chunks = evalState (readArchive pull store) (chunks, [])+  where+    pull :: State ([ByteString], [ByteString]) (Either Text ByteString)+    pull = state $ \(remaining, held) -> case remaining of+      chunk : rest -> (Right chunk, (rest, held))+      [] -> (Right BS.empty, ([], held))+    store _ _ contents = do+      modify (\(remaining, _) -> (remaining, []))+      after <- drainFile pull (modify . second . (:)) contents+      held <- gets snd+      pure ((,) (BS.concat (reverse held)) <$> after)++-- | Unpack an archive's bytes in one chunk.+unpackBytes :: BL.ByteString -> ([Text], Either FetchFailure (Tree ByteString))+unpackBytes = unpackChunks . BL.toChunks++-- | The tree an archive unpacks to, or why it does not.+treeOf :: BL.ByteString -> Either FetchFailure (Tree ByteString)+treeOf = snd . unpackBytes++-- | An archive the tar package writes, long names and link targets as GNU+-- entries.+archiveOf :: [Tar.GenEntry BL.ByteString FilePath FilePath] -> BL.ByteString+archiveOf = Tar.write . concatMap Tar.encodeLongNames++file :: FilePath -> BL.ByteString -> Tar.GenEntry BL.ByteString FilePath FilePath+file = TarEntry.fileEntry++executable :: FilePath -> BL.ByteString -> Tar.GenEntry BL.ByteString FilePath FilePath+executable path contents = (TarEntry.fileEntry path contents) {TarEntry.entryPermissions = TarEntry.executableFilePermissions}++directory :: FilePath -> Tar.GenEntry BL.ByteString FilePath FilePath+directory = TarEntry.directoryEntry++symlink :: FilePath -> FilePath -> Tar.GenEntry BL.ByteString FilePath FilePath+symlink path target = TarEntry.simpleEntry path (Tar.SymbolicLink target)++hardLink :: FilePath -> FilePath -> Tar.GenEntry BL.ByteString FilePath FilePath+hardLink path target = TarEntry.simpleEntry path (Tar.HardLink target)++-- | An entry of another type, with its body, as a pax or global header is.+special :: Char -> FilePath -> BL.ByteString -> Tar.GenEntry BL.ByteString FilePath FilePath+special flag path body = TarEntry.simpleEntry path (Tar.OtherEntryType flag body (BL.length body))++-- | A pax body of records, each with its length counted as pax counts it:+-- the digits of the length are part of the record.+paxBody :: [(ByteString, ByteString)] -> BL.ByteString+paxBody = BL.fromStrict . BS.concat . map record+  where+    record (key, value) =+      let rest = " " <> key <> "=" <> value <> "\n"+       in BC.pack (show (recordLength (BS.length rest))) <> rest+    recordLength restLength =+      let guess = restLength + digits restLength+       in if digits guess == digits restLength then guess else guess + 1+    digits = length . show++-- | A directory of entries.+dir :: [(ByteString, Tree blob)] -> Tree blob+dir = TreeDirectory . Map.fromList++-- ---------------------------------------------------------------------------+-- Archives written by hand+-- ---------------------------------------------------------------------------++-- | The magic a hand-written header carries: POSIX's, GNU's, POSIX's with+-- a version that is not its own, or none.+data Magic = MagicUstar | MagicGnu | MagicOddVersion | MagicNone++-- | The bytes of a block that a header's size does not fill, to the width.+padTo :: Int -> ByteString -> ByteString+padTo width bytes = BS.take width bytes <> BS.replicate (width - BS.length bytes) 0++-- | A number as the octal field of the width holds one.+octal :: Int -> Int -> ByteString+octal width number = BC.pack (replicate (width - 1 - length digits) '0' <> digits) <> BS.singleton 0+  where+    digits = showOct number ""++-- | A header block with its checksum filled in: its type flag, name, size+-- and link target.+headerBlock :: Magic -> Char -> ByteString -> Int -> ByteString -> ByteString+headerBlock magic flag name size link = withChecksum (padTo 512 unsummed)+  where+    unsummed =+      BS.concat+        [ padTo 100 name,+          "0000644\0",+          "0000000\0",+          "0000000\0",+          octal 12 size,+          octal 12 0,+          BC.replicate 8 ' ',+          BC.singleton flag,+          padTo 100 link,+          stamp+        ]+    stamp = case magic of+      MagicUstar -> "ustar\0" <> "00"+      MagicGnu -> "ustar " <> " \0"+      MagicOddVersion -> "ustar\0" <> "01"+      MagicNone -> BS.replicate 8 0++-- | A header block whose checksum field, spaces until now, holds the sum+-- of the block's bytes.+withChecksum :: ByteString -> ByteString+withChecksum block = BS.take 148 block <> checksum <> BS.drop 156 block+  where+    checksum = BC.pack (replicate (6 - length digits) '0' <> digits) <> "\0 "+    digits = showOct (BS.foldl' (\total byte -> total + fromIntegral byte) (0 :: Int) block) ""++-- | A body padded to whole blocks.+blocks :: ByteString -> ByteString+blocks body = body <> BS.replicate (negate (BS.length body) `mod` 512) 0++-- | A member: its header, with the size of the body, and the body.+member :: Magic -> Char -> ByteString -> ByteString -> ByteString -> ByteString+member magic flag name link body = headerBlock magic flag name (BS.length body) link <> blocks body++-- | A GNU long link header holding a target.+longLink :: ByteString -> ByteString+longLink target = member MagicGnu 'K' "././@LongLink" "" (target <> "\0")++-- | The two blocks that end an archive.+endMark :: ByteString+endMark = BS.replicate 1024 0++-- | A pax body, as strict bytes.+paxBytes :: [(ByteString, ByteString)] -> ByteString+paxBytes = BL.toStrict . paxBody++-- | An archive's bytes unpacked in one chunk.+unpackRaw :: ByteString -> ([Text], Either FetchFailure (Tree ByteString))+unpackRaw bytes = unpackChunks [bytes]++-- | What an archive's bytes refuse with, or the tree.+treeOfRaw :: ByteString -> Either Text (Tree ByteString)+treeOfRaw = either (Left . fetchMessage) Right . snd . unpackRaw++-- | What the reader is doing once chunks are fed: waiting for the next, stopped,+-- or going on with an entry.+data Standing = Waiting | Stopped TarFailure | Moving+  deriving (Eq, Show)++standingAfter :: [ByteString] -> Standing+standingAfter = go tarReader+  where+    go step chunks = case step of+      TarAwait continue -> case chunks of+        [] -> Waiting+        chunk : rest -> go (continue chunk) rest+      TarFail failure -> Stopped failure+      _ -> Moving++-- | Every name and link target a tree holds.+namesIn :: Tree blob -> [ByteString]+namesIn tree = case tree of+  TreeDirectory entries -> concatMap (\(name, sub) -> name : namesIn sub) (Map.toList entries)+  TreeSymlink target -> [target]+  TreeFile _ _ -> []++-- | Whether a name's bytes are a slice of a chunk's memory.+withinChunk :: ByteString -> ByteString -> IO Bool+withinChunk chunk name =+  BSU.unsafeUseAsCStringLen chunk $ \(chunkStart, chunkLength) ->+    BSU.unsafeUseAsCStringLen name $ \(nameStart, _) ->+      let offset = nameStart `minusPtr` chunkStart+       in pure (offset >= 0 && offset < chunkLength)++-- ---------------------------------------------------------------------------+-- The reader+-- ---------------------------------------------------------------------------++-- | The tar formats libarchive reads, and its refusals.+testTarReader :: IO [Bool]+testTarReader = do+  putStrLn "fetch/tar-reader"+  sequence+    [ runTest "a ustar archive's files, directories and links unpack" $+        assertEqual+          "tree"+          (Right (dir [("a", TreeFile False "one"), ("bin", dir [("run", TreeFile True "#!")]), ("empty", dir []), ("link", TreeSymlink "a")]))+          (treeOf (archiveOf [file "top/a" "one", directory "top/bin", executable "top/bin/run" "#!", symlink "top/link" "a", directory "top/empty"])),+      runTest "a long name is a GNU long name, and a long path a ustar prefix" $+        let long = replicate 120 'n'+            deep = replicate 60 'd' <> "/" <> replicate 60 'e' <> "/f"+         in assertEqual+              "tree"+              (Right (dir [(BC.pack long, TreeFile False "long"), (BC.pack (replicate 60 'd'), dir [(BC.pack (replicate 60 'e'), dir [("f", TreeFile False "deep")])]), ("t", TreeSymlink (BC.pack (replicate 150 't')))]))+              (treeOf (archiveOf [file long "long", file deep "deep", symlink "t" (replicate 150 't')])),+      runTest "a pax header names the path of the entry after it" $+        assertEqual+          "tree"+          (Right (dir [("named by pax", TreeFile False "pax"), ("other", TreeFile False "o")]))+          (treeOf (archiveOf [special 'x' "PaxHeader" (paxBody [("path", "named by pax"), ("mtime", "1234567.5")]), file "ignored" "pax", file "other" "o"])),+      runTest "a pax header's size is the entry's size" $+        assertEqual+          "tree"+          (Right (dir [("f", TreeFile False "abc"), ("g", TreeFile False "y")]))+          (treeOfRaw (member MagicUstar 'x' "PaxHeader" "" (paxBytes [("size", "3")]) <> headerBlock MagicUstar '0' "f" 0 "" <> blocks "abc" <> member MagicUstar '0' "g" "" "y" <> endMark)),+      runTest "a pax global header is passed over, as GitHub's archives carry one" $+        assertEqual+          "tree"+          (Right (dir [("f", TreeFile False "x")]))+          (treeOf (archiveOf [special 'g' "pax_global_header" (paxBody [("comment", "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed")]), directory "repo", file "repo/f" "x"])),+      runTest "a pax global header that sets what an entry would be is refused" $+        let refusedKey key = assertEqual (T.pack (BC.unpack key)) (Left ("cannot get archive member name: Unsupported pax global extended header attribute '" <> T.pack (BC.unpack key) <> "'")) (treeOfRaw (member MagicUstar 'g' "pax_global_header" "" (paxBytes [("comment", "c"), (key, "v")]) <> member MagicUstar '0' "f" "" "x" <> endMark))+         in allFailures (map refusedKey ["path", "linkpath", "size", "mtime", "atime", "ctime", "uid", "gid", "uname", "gname", "hdrcharset", "GNU.sparse", "GNU.sparse.major", "LIBARCHIVE.creationtime", "LIBARCHIVE.xattr.user.k", "SCHILY.xattr.user.k", "SCHILY.realsize", "SUN.holesdata"]),+      runTest "a pax global header of other attributes is accepted" $+        let acceptedKey key = assertEqual (T.pack (BC.unpack key)) (Right (dir [("f", TreeFile False "x")])) (treeOfRaw (member MagicUstar 'g' "pax_global_header" "" (paxBytes [(key, "v")]) <> member MagicUstar '0' "f" "" "x" <> endMark))+         in allFailures (map acceptedKey ["comment", "SCHILY.xattr", "LIBARCHIVE.other", "vendor.key"]),+      runTest "an empty pax global header is refused" $+        assertEqual "refused" (Left "cannot get archive member name: Invalid empty pax global extended header") (treeOfRaw (member MagicUstar 'g' "pax_global_header" "" "" <> member MagicUstar '0' "f" "" "x" <> endMark)),+      runTest "a malformed record in a pax global header warns, naming the entry after it" $+        assertEqual+          "unpacked"+          (["getting archive member 'f': Ignoring malformed pax attributes: malformed attribute size field"], Right (dir [("f", TreeFile False "x")]))+          (unpackRaw (member MagicUstar 'g' "pax_global_header" "" "x9 comment=c\n" <> member MagicUstar '0' "f" "" "x" <> endMark)),+      runTest "a pax body is read as it arrives, so a refused global attribute stops the reader before the rest of the body" $+        let body = paxBytes [("path", "x"), ("comment", BC.replicate 1990 'c')]+            refusal = TarHeaderFailure Nothing "Unsupported pax global extended header attribute 'path'"+         in assertEqual "standing" (Stopped refusal) (standingAfter [headerBlock MagicUstar 'g' "pax_global_header" (BS.length body) "", BS.take 700 body]),+      runTest "a malformed pax record warns, naming the member, and is ignored" $+        assertEqual+          "unpacked"+          (["getting archive member 'f': Ignoring malformed pax attributes: malformed attribute size field"], Right (dir [("f", TreeFile False "x"), ("g", TreeFile False "y")]))+          (unpackBytes (archiveOf [special 'x' "PaxHeader" "x9 path=no\n", file "f" "x", file "g" "y"])),+      runTest "a malformed pax record drops the names before it" $+        assertEqual+          "unpacked"+          (["getting archive member 'f': Ignoring malformed pax attributes: malformed attribute size field"], Right (dir [("f", TreeFile False "x")]))+          (unpackRaw (member MagicUstar 'x' "PaxHeader" "" (paxBytes [("path", "named")] <> "x9 comment=c\n") <> member MagicUstar '0' "f" "" "x" <> endMark)),+      runTest "a pax value is applied before its record's newline is checked" $+        assertEqual+          "unpacked"+          (["getting archive member 'f': Malformed pax attributes"], Right (dir [("f", TreeFile False "abc"), ("g", TreeFile False "y")]))+          (unpackRaw (member MagicUstar 'x' "PaxHeader" "" "9 size=3X" <> headerBlock MagicUstar '0' "f" 0 "" <> blocks "abc" <> member MagicUstar '0' "g" "" "y" <> endMark)),+      runTest "a pax path past a mebibyte is not applied" $+        let (warnings, tree) = unpackRaw (member MagicUstar 'x' "PaxHeader" "" (paxBytes [("path", BC.replicate 1048577 'p')]) <> member MagicUstar '0' "f" "" "x" <> endMark)+         in assertEqual "unpacked" (1, Right (dir [("f", TreeFile False "x")])) (length warnings, tree),+      runTest "a hard link entry names its target" $+        assertEqual+          "tree"+          (Right (dir [("a", TreeFile False "same"), ("b", TreeFile False "same")]))+          (treeOf (archiveOf [file "a" "same", hardLink "b" "a"])),+      runTest "a ustar hard link keeps no body, whatever size its header holds" $+        assertEqual+          "tree"+          (Right (dir [("a", TreeFile False "same"), ("l", TreeFile False "same")]))+          (treeOfRaw (member MagicUstar '0' "a" "" "same" <> headerBlock MagicUstar '1' "l" 512 "a")),+      runTest "a hard link whose header the bidder does not take keeps its body" $+        assertEqual+          "tree"+          (Right (dir [("a", TreeFile False "same"), ("b", TreeFile False "b"), ("l", TreeFile False "same")]))+          (treeOfRaw (member MagicUstar '0' "a" "" "same" <> headerBlock MagicOddVersion '1' "l" 512 "a" <> BS.replicate 512 0x7a <> member MagicUstar '0' "b" "" "b" <> endMark)),+      runTest "a link a GNU long link header gives is a hard link on a regular entry" $+        assertEqual+          "tree"+          (Right (dir [("a", TreeFile False "same"), ("b", TreeFile False "same")]))+          (treeOfRaw (member MagicGnu '0' "a" "" "same" <> longLink "a" <> member MagicGnu '0' "b" "" "" <> endMark)),+      runTest "a pax linkpath is a hard link on a directory entry" $+        assertEqual+          "tree"+          (Right (dir [("a", TreeFile False "same"), ("d", TreeFile False "same")]))+          (treeOfRaw (member MagicUstar '0' "a" "" "same" <> member MagicUstar 'x' "PaxHeader" "" (paxBytes [("linkpath", "a")]) <> member MagicUstar '5' "d/" "" "" <> endMark)),+      runTest "a GNU long link header gives a symlink its target" $+        assertEqual+          "tree"+          (Right (dir [("s", TreeSymlink (BC.replicate 150 't'))]))+          (treeOfRaw (longLink (BC.replicate 150 't') <> member MagicGnu '2' "s" "" "" <> endMark)),+      runTest "a long link header past a mebibyte gives no link, with a warning" $+        assertEqual+          "unpacked"+          (["getting archive member 'f': Special header too large: 1048577 > 1MiB"], Right (dir [("f", TreeFile False "x")]))+          (unpackRaw (member MagicGnu 'K' "././@LongLink" "" (BC.replicate 1048577 'k') <> member MagicGnu '0' "f" "" "x" <> endMark)),+      runTest "a regular entry whose name ends in a slash is a directory" $+        assertEqual+          "tree"+          (Right (dir [("d", dir [("f", TreeFile False "x")]), ("g", TreeFile False "y")]))+          (treeOf (archiveOf [(file "d/" "") {TarEntry.entryTarPath = "d/"}, file "d/f" "x", file "g" "y"])),+      runTest "an empty input is an empty archive" $+        assertEqual "unpacked" ([], Right (dir [])) (unpackBytes BL.empty),+      runTest "bytes that are not an archive are refused as libarchive refuses them" $+        assertEqual "refused" (Left "Failed to open archive (Unrecognized archive format)") (treeOfRaw "this is not a tar archive"),+      runTest "a page of markup is refused as no archive, not as a damaged one" $+        assertEqual "refused" (Left "Failed to open archive (Unrecognized archive format)") (treeOfRaw (BC.replicate 600 '<')),+      runTest "a damaged header after the first is refused" $+        let archive = archiveOf [file "a" "x", file "b" "y"]+            damaged = BL.take 1024 archive <> BL.map (const 0x41) (BL.take 512 (BL.drop 1024 archive)) <> BL.drop 1536 archive+         in assertEqual "refused" (Left "cannot get archive member name: Damaged tar archive (bad header checksum)") (failureOf (treeOf damaged)),+      runTest "an archive that ends inside a file is refused" $+        assertEqual+          "refused"+          (Left "cannot read file from tarball: Truncated tar archive detected while reading data")+          (failureOf (treeOf (BL.take 600 (archiveOf [file "a" (BL.replicate 1000 0x61)])))),+      runTest "an archive that ends in a file's padding is refused with the bytes it lacked" $+        assertEqual+          "refused"+          (Left "cannot read file from tarball: Truncated input file (needed 412 bytes, only 0 available)")+          (failureOf (treeOf (BL.take 612 (archiveOf [file "a" (BL.replicate 100 0x61)])))),+      runTest "an archive that ends in a skipped body is refused with the bytes it lacked" $+        assertEqual+          "refused"+          (Left "cannot get archive member name: Truncated input file (needed 512 bytes, only 50 available)")+          (treeOfRaw (headerBlock MagicGnu 'D' "d/" 100 "" <> BS.replicate 50 0x78)),+      runTest "an archive that ends in a long name's padding is refused with the bytes it lacked" $+        assertEqual+          "refused"+          (Left "failed to extract archive (Truncated input file (needed 512 bytes, only 10 available))")+          (treeOfRaw (headerBlock MagicGnu 'L' "././@LongLink" 10 "" <> "long-name\0")),+      runTest "every chunking of an archive reads the same" $+        let archive = BL.toStrict (archiveOf [file "a" (BL.replicate 700 0x61), symlink "l" "a", directory "d", file "d/b" "b"])+            whole = snd (unpackChunks [archive])+            byteWise = snd (unpackChunks (map BS.singleton (BS.unpack archive)))+         in assertEqual "unpacked" whole byteWise,+      runTest "every chunking of an archive of pax and GNU headers reads the same" $+        let archive =+              BS.concat+                [ member MagicUstar 'g' "pax_global_header" "" (paxBytes [("comment", "c")]),+                  member MagicUstar 'x' "PaxHeader" "" (paxBytes [("path", "named by pax"), ("comment", BC.replicate 600 'c'), ("size", "4")]),+                  headerBlock MagicUstar '0' "ignored" 0 "" <> blocks "data",+                  longLink "named by pax",+                  member MagicGnu '0' "hard" "" "",+                  endMark+                ]+            whole = snd (unpackChunks [archive])+            byteWise = snd (unpackChunks (map BS.singleton (BS.unpack archive)))+         in assertEqual "unpacked" (Right (dir [("hard", TreeFile False "data"), ("named by pax", TreeFile False "data")])) whole `andThen` assertEqual "chunked" whole byteWise,+      runTestM "entry names and link targets are copies, so none keeps its chunk alive" $+        let archive = BL.toStrict (archiveOf [directory "top", file "top/a" "x", file ("top/" <> replicate 120 'n') "y", symlink "top/s" (replicate 150 't'), hardLink "top/h" "top/a"])+         in case snd (unpackChunks [archive]) of+              Left failure -> pure (Fail (fetchMessage failure))+              Right tree -> do+                inside <- mapM (withinChunk archive) (namesIn tree)+                pure (assertEqual "names read" 5 (length inside) `andThen` assertEqual "names inside the chunk" (replicate 5 False) inside)+    ]+  where+    failureOf = either (Left . fetchMessage) (const (Right ()))++-- ---------------------------------------------------------------------------+-- The sink+-- ---------------------------------------------------------------------------++-- | Place entries in order, as the sink places them.+placed :: [ArchiveEntry Text] -> ([Text], Either FetchFailure (Tree Text))+placed = go [] emptySink+  where+    go warnings sink entries = case entries of+      [] -> (warnings, finishSink sink)+      entry : rest -> case sinkEntry sink entry of+        (Left failure, given) -> (warnings ++ given, Left failure)+        (Right updated, given) -> go (warnings ++ given) updated rest++at :: ByteString -> ArchiveNode Text -> ArchiveEntry Text+at = ArchiveEntry++-- | The rules of upstream's tar sink.+testTarSink :: IO [Bool]+testTarSink = do+  putStrLn "fetch/tar-sink"+  sequence+    [ runTest "the last entry at a path wins" $+        assertEqual "tree" (Right (dir [("a", TreeFile False "second"), ("b", TreeFile False "b")])) (treeIn [at "a" (ArchiveFile False "first"), at "a" (ArchiveFile False "second"), at "b" (ArchiveFile False "b")]),+      runTest "a directory onto a directory changes nothing" $+        assertEqual "tree" (Right (dir [("d", dir [("f", TreeFile False "x")]), ("e", dir [])])) (treeIn [at "d" ArchiveDirectory, at "d/f" (ArchiveFile False "x"), at "d" ArchiveDirectory, at "e" ArchiveDirectory]),+      runTest "a non-empty directory is not replaced" $+        assertEqual "refused" (Left (FetchFailure [] "cannot create '/d', conflicting non-empty directory")) (treeIn [at "d/f" (ArchiveFile False "x"), at "d" (ArchiveFile False "y")]),+      runTest "an empty directory is replaced" $+        assertEqual "tree" (Right (dir [("d", TreeFile False "y"), ("e", dir [])])) (treeIn [at "d" ArchiveDirectory, at "d" (ArchiveFile False "y"), at "e" ArchiveDirectory]),+      runTest "an entry under a file is refused" $+        assertEqual "refused" (Left (FetchFailure [] "parent of '/a/b' is not a directory")) (treeIn [at "a" (ArchiveFile False "x"), at "a/b" (ArchiveFile False "y")]),+      runTest "a path is read as CanonPath reads it" $+        assertEqual "tree" (Right (dir [("b", TreeFile False "x"), ("c", TreeFile False "y")])) (treeIn [at "./a/../b" (ArchiveFile False "x"), at "/c//" (ArchiveFile False "y")]),+      runTest "a hard link made before its target is replaced keeps what the target was, with a warning" $+        assertEqual+          "placed"+          ( [ "'/t' is replaced, though a hard link makes it the same file as '/l'. Older versions of Nix resolved hard links differently, so this archive unpacks to a different store path than it used to."+            ],+            Right (dir [("l", TreeFile False "old"), ("t", TreeFile False "new")])+          )+          (placed [at "t" (ArchiveFile False "old"), at "l" (ArchiveHardLink "t"), at "t" (ArchiveFile False "new")]),+      runTest "a hard link made after its target is replaced names what replaced it" $+        assertEqual+          "placed"+          ([], Right (dir [("l", TreeFile False "new"), ("t", TreeFile False "new")]))+          (placed [at "t" (ArchiveFile False "old"), at "t" (ArchiveFile False "new"), at "l" (ArchiveHardLink "t")]),+      runTest "replacing one of three linked paths names the other two" $+        assertEqual+          "warnings"+          ["'/b' is replaced, though a hard link makes it the same file as '/a', '/c'. Older versions of Nix resolved hard links differently, so this archive unpacks to a different store path than it used to."]+          (fst (placed [at "a" (ArchiveFile False "x"), at "b" (ArchiveHardLink "a"), at "c" (ArchiveHardLink "a"), at "b" (ArchiveFile False "y")])),+      runTest "a hard link to nothing is refused, naming the link" $+        assertEqual "refused" (Left (FetchFailure ["while creating a hard link from '/l' to '/x'"] "target does not exist")) (treeIn [at "l" (ArchiveHardLink "x")]),+      runTest "a hard link to a directory is refused" $+        assertEqual "refused" (Left (FetchFailure ["while creating a hard link from '/l' to '/d'"] "target is a directory")) (treeIn [at "d" ArchiveDirectory, at "l" (ArchiveHardLink "d")]),+      runTest "a device is refused by its file type" $+        assertEqual "refused" (Left (FetchFailure [] "file 'top/dev' in tarball has unsupported file type 8192")) (treeIn [at "top/dev" (ArchiveSpecial 8192)]),+      runTest "one top-level directory is the tree" $+        assertEqual "tree" (Right (dir [("f", TreeFile False "x")])) (treeIn [at "pkg/f" (ArchiveFile False "x")]),+      runTest "two top-level directories are kept" $+        assertEqual "tree" (Right (dir [("a", dir [("f", TreeFile False "x")]), ("b", dir [("g", TreeFile False "y")])])) (treeIn [at "a/f" (ArchiveFile False "x"), at "b/g" (ArchiveFile False "y")]),+      runTest "one top-level file is kept under the root" $+        assertEqual "tree" (Right (dir [("f", TreeFile False "x")])) (treeIn [at "f" (ArchiveFile False "x")]),+      runTest "a root replaced by a file is refused" $+        assertEqual "refused" (Left (FetchFailure [] "the archive's root is not a directory")) (treeIn [at "." (ArchiveFile False "x")]),+      runTest "a name upstream's tree builder refuses is refused, at any depth" $+        let refusedName name = assertEqual (T.pack (BC.unpack name)) (Left (treeBuilderRefusal name)) (treeIn [at ("top/" <> name <> "/f") (ArchiveFile False "x")])+         in allFailures (map refusedName [".git", ".GIT", ".Git", "git~1", "GIT~1", ".git ", ".git.", ".git . .", ".git:stream", ".git\\x"])+              `andThen` assertEqual "deep" (Left (treeBuilderRefusal ".git")) (treeIn [at "top/a/b/c/.git" (ArchiveFile False "x"), at "top/a/b/other" (ArchiveFile False "y")]),+      runTest "a name that only resembles one is kept" $+        let keptName name = assertEqual (T.pack (BC.unpack name)) (Right (dir [(name, TreeFile False "x")])) (treeIn [at name (ArchiveFile False "x")])+         in allFailures (map keptName [".gitignore", ".github", ".gitmodules", "git~", "git~0", "git~2", "x.git", ".gi", "git", "git~1x", ".git x", "..git"]),+      runTest "the first refusal is the one a depth-first write in name order meets, a name after what it holds" $+        assertEqual "first" (Left (treeBuilderRefusal ".git")) (treeIn [at "GIT~1/.git" (ArchiveFile False "x"), at "a/.GIT" (ArchiveFile False "y")])+          `andThen` assertEqual "sorted" (Left (treeBuilderRefusal ".GIT")) (treeIn [at "a/.git" (ArchiveFile False "x"), at ".GIT" (ArchiveFile False "y")]),+      runTest "an archive holding such a name is refused" $+        assertEqual "refused" (Left (fetchMessage (treeBuilderRefusal ".git"))) (either (Left . fetchMessage) Right (treeOf (archiveOf [directory "pkg", directory "pkg/.git", file "pkg/.git/config" "x"])))+    ]+  where+    treeIn = snd . placed++-- | Upstream's refusal of a name its tree builder will not hold.+treeBuilderRefusal :: ByteString -> FetchFailure+treeBuilderRefusal name =+  FetchFailure [] ("adding '" <> shown <> "' to a tree builder: failed to insert entry: invalid name for a tree entry - " <> shown <> " (libgit2 error code = 14)")+  where+    shown = T.pack (BC.unpack name)++-- ---------------------------------------------------------------------------+-- Properties+-- ---------------------------------------------------------------------------++-- | A tree's NAR, from its pieces with each blob its own bytes.+narOfPieces :: Tree ByteString -> ByteString+narOfPieces tree = BS.concat (map piece (narPieces (fromIntegral . BS.length) tree))+  where+    piece p = case p of+      NarBytes bytes -> bytes+      NarContents _ contents -> contents++-- | A tree as nova-cache's NAR holds one.+narEntryOf :: Tree ByteString -> NAR.NarEntry+narEntryOf tree = case tree of+  TreeFile isExecutable contents -> NAR.NarRegular isExecutable contents+  TreeSymlink target -> NAR.NarSymlink target+  TreeDirectory entries -> NAR.NarDirectory (Map.toList (Map.map narEntryOf entries))++-- | A tree whose directories each hold something, its names from the+-- characters a ustar name holds, some long enough to need a prefix or a+-- GNU long name.+genTree :: Int -> QC.Gen (Tree ByteString)+genTree depth = dir <$> QC.listOf1 ((,) <$> genName <*> genNode)+  where+    genNode =+      QC.frequency+        [ (4, TreeFile <$> QC.arbitrary <*> (BS.pack <$> QC.resize 1200 (QC.listOf QC.arbitrary))),+          (1, TreeSymlink . BC.pack <$> QC.listOf1 (QC.elements nameChars)),+          (if depth > 0 then 2 else 0, genTree (depth - 1))+        ]+    genName = QC.oneof [short, long]+    short = BC.pack <$> QC.resize 12 (QC.listOf1 (QC.elements nameChars)) `QC.suchThat` (\name -> name `notElem` [".", ".."] && not (".git" `isPrefixOf` map toLower name))+    long = BC.pack <$> (QC.choose (90, 130) >>= (`QC.vectorOf` QC.elements nameChars))+    nameChars = ['a' .. 'z'] ++ ['A' .. 'Z'] ++ ['0' .. '9'] ++ "._-"++-- | A tree's entries in the order a writer lists them, a directory before+-- what it holds.  Paths join with a slash on every platform: the tar+-- package writes a GNU long name as it is given, so a native separator+-- would reach the archive on Windows.+entriesOf :: Tree ByteString -> [Tar.GenEntry BL.ByteString FilePath FilePath]+entriesOf = go ""+  where+    go prefix node = case node of+      TreeDirectory entries -> concatMap (\(name, sub) -> visit (joined prefix (BC.unpack name)) sub) (Map.toList entries)+      _ -> []+    visit path node = case node of+      TreeFile isExecutable contents -> [(if isExecutable then executable else file) path (BL.fromStrict contents)]+      TreeSymlink target -> [symlink path (BC.unpack target)]+      TreeDirectory _ -> directory path : go path node+    joined prefix name = if null prefix then name else prefix <> "/" <> name++-- | Entries this many make one run of structural NAR bytes.+largeRunEntries :: Int+largeRunEntries = 100000++-- | The longest a large run may take to join: far past a linear join and+-- far under a quadratic one.+largeRunMicroseconds :: Int+largeRunMicroseconds = 10 * 1000000++-- | The reader and the sink unpack an archive written from a tree to that+-- tree, however it is chunked; a tree's NAR pieces are its NAR, and a+-- directory of very many entries joins its structural bytes in one run.+testArchiveProperties :: IO [Bool]+testArchiveProperties = do+  putStrLn "fetch/archive-properties"+  unpacks <-+    property $+      QC.forAll (genTree 2) $ \tree ->+        QC.forAll (QC.listOf1 (QC.choose (1, 2000))) $ \sizes ->+          let archive = BL.toStrict (archiveOf (entriesOf tree))+           in snd (unpackChunks (chunked sizes archive)) == Right (dereferenceSingleton tree)+  pieces <- property (QC.forAll (genTree 2) (\tree -> narOfPieces tree == NAR.serialise (narEntryOf tree)))+  let largeRun = dir [(BC.pack (show index), TreeSymlink "t") | index <- [1 .. largeRunEntries]]+  joined <- timeout largeRunMicroseconds (evaluate (case narPieces (fromIntegral . BS.length) largeRun of [NarBytes bytes] -> BS.length bytes; other -> negate (length other)))+  sequence+    [ runTest "an archive written from a tree unpacks to that tree" unpacks,+      runTest "a tree's NAR pieces are its NAR" pieces,+      runTest "a directory of very many entries is one piece, joined in time" $+        assertEqual "joined" (Just (BS.length (NAR.serialise (narEntryOf largeRun)))) joined+    ]+  where+    chunked sizes = go (cycle sizes)+      where+        go sizesLeft remaining+          | BS.null remaining = []+          | otherwise = case sizesLeft of+              size : more -> BS.take size remaining : go more (BS.drop size remaining)+              [] -> [remaining]++-- ---------------------------------------------------------------------------+-- fetchTarball+-- ---------------------------------------------------------------------------++-- | @builtins.fetchTarball@ unpacks in process, as upstream does: the+-- tree is the archive's own, its path the one its NAR gives, and a pair+-- of names a volume folds keeps both names.  An unpacked archive's files+-- are numbered blobs under the scratch directory.+testFetchTarballIO :: IO [Bool]+testFetchTarballIO = do+  putStrLn "fetch/fetch-tarball-io"+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-fetch-tarball"+      storeDir = StoreDir (root </> "store")+      pathText = canonPathValue . T.pack+      fileUrl path = "file://" <> pathText path+      fetchOf path = "builtins.fetchTarball \"" <> T.concatMap nixEscaped (fileUrl path) <> "\""+      nixEscaped c = if c == '"' || c == '\\' then T.pack ['\\', c] else T.singleton c+      write name = BL.writeFile (root </> name)+      expectedPath tree = either (const Nothing) Just (makeFixedOutputPath "source" "sha256" NarIngestion (sha256Digest (NAR.serialise (narEntryOf tree))))+      fetchedAs tree name = do+        fetched <- evalNixIOStore storeDir root (fetchOf (root </> name))+        pure $ case fetched of+          Right val -> assertEqual "path" (expectedPath tree) (fetchedStorePath val)+          Left err -> Fail err+      refusedAs message expr = do+        fetched <- evalNixIOStore storeDir root expr+        pure (assertEqual "refused" (Left message) (void fetched))+      twoTops = dir [("a", dir [("f", TreeFile False "f\n")]), ("b", dir [("g", TreeFile False "g\n")])]+      folded = dir [("Makefile", TreeFile False "upper\n"), ("makefile", TreeFile False "lower\n"), ("run", TreeFile True "#!/bin/sh\n")]+  forceRemoveIfExists root+  createDirectoryIfMissing True (root </> "plain-directory")+  write "two.tar.gz" (GZip.compress (archiveOf [directory "a", file "a/f" "f\n", directory "b", file "b/g" "g\n"]))+  write "dotgit.tar" (archiveOf [directory "pkg", directory "pkg/.git", file "pkg/.git/config" "x\n"])+  write "folded.tar" (archiveOf [directory "pkg", file "pkg/Makefile" "upper\n", file "pkg/makefile" "lower\n", executable "pkg/run" "#!/bin/sh\n"])+  write "folded.tar.zst" (BL.fromStrict (Zstd.compress Zstd.defaultCompressionLevel (BL.toStrict (archiveOf [directory "pkg", file "pkg/Makefile" "upper\n", file "pkg/makefile" "lower\n", executable "pkg/run" "#!/bin/sh\n"]))))+  results <-+    sequence+      [ runTestM "a tarball with two top-level directories keeps both" (fetchedAs twoTops "two.tar.gz"),+        runTestM "a zstd tarball unpacks to the same tree as a plain one" $+          andThen <$> fetchedAs folded "folded.tar" <*> fetchedAs folded "folded.tar.zst",+        runTestM "a pair of names the store's volume folds keeps both names" $ do+          fetched <- evalNixIOStore storeDir root (fetchOf (root </> "folded.tar"))+          case fetched >>= maybe (Left "not a store path") Right . fetchedStorePath of+            Left err -> pure (Fail err)+            Right sp -> do+              let dest = storePathToFilePath storeDir sp+              sensitivity <- probeCaseSensitivity (unStoreDir storeDir)+              Hash.NixHash onDisk <- ExecBit.narHashOfPath (volumeCaseHack sensitivity) dest+              pure (assertEqual "NAR on disk" (sha256Digest (NAR.serialise (narEntryOf folded))) onDisk),+        runTestM "a tarball that is not there is refused in upstream's words" $+          refusedAs ("tarball \"" <> pathText (root </> "absent.tar.gz") <> "\" does not exist.") (fetchOf (root </> "absent.tar.gz")),+        runTestM "a directory is refused as no tarball" $+          refusedAs ("tarball \"" <> pathText (root </> "plain-directory") <> "\" is a directory, not a file.") (fetchOf (root </> "plain-directory")),+        runTestM "a tarball holding a name upstream's tree builder refuses is refused in its words" $+          refusedAs (fetchMessage (treeBuilderRefusal ".git")) (fetchOf (root </> "dotgit.tar")),+        runTestM "an unpacked archive's files are numbered blobs under the scratch directory" $ do+          let scratch = root </> "scratch"+          createDirectoryIfMissing True scratch+          source <- chunkSource (BL.toChunks (GZip.compress (archiveOf [directory "pkg", file "pkg/a" "first", file "pkg/b" "second", symlink "pkg/l" "a"])))+          (warnings, unpacked) <- unpackArchive scratch source+          case unpacked of+            Left failure -> pure (Fail (fetchMessage failure))+            Right tree -> do+              contents <- readBlobs scratch tree+              pure (assertEqual "unpacked" ([], [0, 1], dir [("a", TreeFile False "first"), ("b", TreeFile False "second"), ("l", TreeSymlink "a")]) (warnings, blobNumbers tree, contents))+      ]+  forceRemoveIfExists root+  pure results++-- | A pull source that gives the chunks in order, then the end.+chunkSource :: [ByteString] -> IO (IO ByteString)+chunkSource chunks = do+  remaining <- newIORef chunks+  pure $ atomicModifyIORef' remaining $ \case+    chunk : rest -> (rest, chunk)+    [] -> ([], BS.empty)++-- | A tree with each blob read back from the scratch directory.+readBlobs :: FilePath -> Tree Blob -> IO (Tree ByteString)+readBlobs scratch tree = case tree of+  TreeFile isExecutable blob -> TreeFile isExecutable <$> BS.readFile (blobFile scratch blob)+  TreeSymlink target -> pure (TreeSymlink target)+  TreeDirectory entries -> TreeDirectory <$> traverse (readBlobs scratch) entries++-- | The numbers of a tree's blobs, in the order of its names.+blobNumbers :: Tree Blob -> [Int]+blobNumbers tree = case tree of+  TreeFile _ blob -> [blobNumber blob]+  TreeSymlink _ -> []+  TreeDirectory entries -> concatMap blobNumbers (Map.elems entries)
+ test/Test/BuildUser.hs view
@@ -0,0 +1,446 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | Build users ("Nix.Builder.BuildUser").+--+-- 'testBuildUsersPure' holds the setting, the refusal of a build user's+-- connection and the choice of a member to upstream's rules, the choice+-- over a model of the user database.  The rest needs root and a group of+-- build users: CI's Linux build makes @nixbld@ and two members, then runs+-- 'buildUsersRootChild' under sudo, which builds as them, unsandboxed and+-- in the sandbox, and checks whom a build ran as, what its output is, that+-- a node another user owns fails the build, that a process a build left+-- is killed, and that a build waits for a free member.+module Test.BuildUser+  ( testBuildUsersPure,+    testBuildUsersUnprivilegedIO,+    buildUsersRootFlag,+    buildUsersRootChild,+  )+where++import Control.Monad.State.Strict (State, evalState, gets, modify', runState)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BS8+import Data.List (nub)+import qualified Data.Map.Strict as Map+import Data.Set (Set)+import qualified Data.Set as Set+import qualified Data.Text as T+import Data.Word (Word32)+import Nix.Builder.BuildUser (BuildUsers (NoBuildUsers), Member (..), ProcessPrivilege (..), UserDatabase (..), acquireBuildUser, buildUsersFor, defaultBuildUsersGroup, peerInBuildUsersGroup, userPoolDir, waitingForBuildUserMessage, withBuildUser, worldWritableMessage)+import System.FilePath ((</>))+import qualified System.Info+import qualified Test.QuickCheck as QC++#if defined(mingw32_HOST_OS)++import System.Directory (doesDirectoryExist, getTemporaryDirectory, removePathForcibly)+import System.Exit (exitFailure)+import System.IO (hPutStrLn, stderr)+import Test.Harness (TestResult (..), andThen, assertEqual, runTest, runTestM, testLogger)++#else++import Control.Concurrent.Async (race, wait, withAsync)+import Control.Concurrent.MVar (newEmptyMVar, takeMVar, tryPutMVar)+import Control.Exception (bracket, finally)+import Control.Monad (unless, void, when)+import Data.Bits ((.&.))+import Data.Foldable (traverse_)+import Data.IORef (modifyIORef', newIORef, readIORef)+import Data.Maybe (catMaybes)+import Foreign.C.Error (Errno (..), eINVAL, ePERM)+import Foreign.C.Types (CInt (..), CUInt (..))+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (Ptr)+import qualified Nix.Builder as Builder+import qualified Nix.Builder.Sandbox.Spawn as Spawn+import Nix.Logger (plainLogger)+import Nix.Store (Store (..), closeStore, openStore)+import Nix.Store.Path (StoreDir (..), defaultStoreDir, storePathToFilePath, storePathToText)+import Nix.Store.Path.Internal (StorePath (..))+import System.Directory (createDirectoryIfMissing, doesDirectoryExist, doesFileExist, getTemporaryDirectory, removePathForcibly)+import System.Exit (exitFailure)+import System.FileLock (SharedExclusive (Exclusive), tryLockFile, unlockFile)+import System.IO (hPutStrLn, stderr)+import System.Posix.Files (fileMode, fileOwner, getSymbolicLinkStatus, setFileMode, setOwnerAndGroup)+import qualified System.Posix.User.ByteString as User+import Test.Builder (linuxSandboxConfig)+import Test.Harness (TestResult (..), andThen, assertEqual, mkTestBuildDrv, runTest, runTestM, testDrvPath, testLogger)+import Text.Read (readMaybe)++#endif++-- ---------------------------------------------------------------------------+-- Without root+-- ---------------------------------------------------------------------------++-- | The setting, the refusal of a peer, and the choice of a member.+testBuildUsersPure :: IO [Bool]+testBuildUsersPure = do+  putStrLn "builder/build-users"+  sequence+    [ runTest "build-users-group defaults to nixbld for root and to nothing for anyone else, and builds run as its members only for root with it set" $+        assertEqual "root's default" "nixbld" (defaultBuildUsersGroup RunsAsRoot)+          `andThen` assertEqual "another's default" "" (defaultBuildUsersGroup RunsUnprivileged)+          `andThen` assertEqual "root with a group" supported (buildUsersFor RunsAsRoot pool "nixbld" /= NoBuildUsers)+          `andThen` assertEqual "root with none" NoBuildUsers (buildUsersFor RunsAsRoot pool "")+          `andThen` assertEqual "another with a group" NoBuildUsers (buildUsersFor RunsUnprivileged pool "nixbld"),+      runTest "the user pool is in upstream's state directory, or the one NIX_STATE_DIR names, a POSIX path on every system" $+        assertEqual "default" "/nix/var/nix/userpool" (userPoolDir Nothing)+          `andThen` assertEqual "named" "/s/userpool" (userPoolDir (Just "/s")),+      runTest "a peer whose primary group is the build users' is refused, and no other" $+        assertEqual "build user" True (peerInBuildUsersGroup "nixbld" (Just "nixbld"))+          `andThen` assertEqual "another group" False (peerInBuildUsersGroup "nixbld" (Just "users"))+          `andThen` assertEqual "no group" False (peerInBuildUsersGroup "nixbld" Nothing)+          `andThen` assertEqual "no setting" False (peerInBuildUsersGroup "" (Just "")),+      runTest "a group that is missing, has no members or names a missing user is refused in upstream's words" $+        assertEqual "missing" (Left "the group 'nixbld' specified in 'build-users-group' does not exist") (fst (acquired Map.empty Set.empty []))+          `andThen` assertEqual "empty" (Left "the build users group 'nixbld' has no members") (fst (acquired (Map.singleton "nixbld" (buildGid, [])) Set.empty []))+          `andThen` assertEqual "a missing member" (Left "the user 'ghost' in the group 'nixbld' does not exist") (fst (acquired (groupOf ["ghost"]) Set.empty [])),+      runTest "the first member whose lock is free is taken, with its supplementary groups but the build users' own, and those after it are not looked up" $+        let (outcome, model) = acquired (groupOf (memberNames 3)) (Set.singleton (uidOf 1)) []+         in assertEqual "taken" (Right (Just (Member (uidOf 2) buildGid [kvmGid], uidOf 2))) outcome+              `andThen` assertEqual "locks" (Set.fromList [uidOf 1, uidOf 2]) (modelLocked model)+              `andThen` assertEqual "looked up" ["nixbld2", "nixbld1"] (modelLookedUp model),+      runTest "with every member taken there is none to take, and no lock is held" $+        let locked = Set.fromList (map uidOf [1, 2])+            (outcome, model) = acquired (groupOf (memberNames 2)) locked []+         in assertEqual "none" (Right Nothing) outcome `andThen` assertEqual "locks" locked (modelLocked model),+      runTest "a member that is the user nova-nix runs as is refused in upstream's words, and its lock given back" $+        let (outcome, model) = acquired (groupOf (memberNames 2)) Set.empty [uidOf 1]+         in assertEqual "refused" (Left "the Nix user should not be a member of 'nixbld'") outcome+              `andThen` assertEqual "locks" Set.empty (modelLocked model),+      runTest "a lock file that cannot be opened refuses the build with the reason" $+        assertEqual "refused" (Left unopenableReason) (evalState (acquireBuildUser (modelDatabase (groupOf (memberNames 2)) (Set.singleton (uidOf 1))) [] "nixbld") (Model Set.empty [])),+      runTestM "the member taken is the first in the group's order whose lock is free, and the only lock taken is its own" $ do+        result <-+          QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} $+            QC.forAll ((,) <$> QC.choose (1, 6) <*> QC.sublistOf (map uidOf [1 .. 6])) $ \(count, lockedList) ->+              let locked = Set.fromList lockedList+                  (outcome, model) = acquired (groupOf (memberNames count)) locked []+                  firstFree = take 1 [uid | n <- [1 .. count], let uid = uidOf n, Set.notMember uid locked]+               in case (outcome, firstFree) of+                    (Right (Just (member, lock)), [uid]) -> memberUid member QC.=== uid QC..&&. lock QC.=== uid QC..&&. modelLocked model QC.=== Set.insert uid locked+                    (Right Nothing, []) -> modelLocked model QC.=== locked+                    _ -> QC.counterexample (show outcome) False+        pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result))),+      runTest "the waiting line and the refusal of a directory others may write are upstream's" $+        assertEqual "waiting" "waiting for a free build user ID for '/nix/store/x.drv'" (waitingForBuildUserMessage "/nix/store/x.drv")+          `andThen` assertEqual "world-writable" "Path \"/tmp\" is world-writable or a symlink. That's not allowed for security." (worldWritableMessage "/tmp")+    ]+  where+    pool = "/nix/var/nix/userpool"+    supported = System.Info.os `elem` ["linux", "darwin"]+    acquired groups locked own = runState (acquireBuildUser (modelDatabase groups Set.empty) own "nixbld") (Model locked [])++-- | What the model of the user database holds of the pool: the uids whose+-- locks are held, and the users looked up, the latest first.+data Model = Model+  { modelLocked :: !(Set Word32),+    modelLookedUp :: ![BS.ByteString]+  }++-- | A user database holding the groups given, whose every member+-- @nixbldN@ is a user with uid 'uidOf' N and the build users' group as its+-- primary group, and is also in @kvm@; the lock file of each uid in the set+-- given cannot be opened.+modelDatabase :: Map.Map BS.ByteString (Word32, [BS.ByteString]) -> Set Word32 -> UserDatabase (State Model) Word32+modelDatabase groups unopenable =+  UserDatabase+    { udGroup = \name -> pure (Map.lookup name groups),+      udUser = \name -> do+        modify' (\model -> model {modelLookedUp = name : modelLookedUp model})+        pure (Map.lookup name users),+      udGroups = \_ primary -> pure (nub [primary, kvmGid, buildGid]),+      udTryLock = \uid ->+        if Set.member uid unopenable+          then pure (Left unopenableReason)+          else do+            taken <- gets (Set.member uid . modelLocked)+            if taken+              then pure (Right Nothing)+              else Right (Just uid) <$ modify' (\model -> model {modelLocked = Set.insert uid (modelLocked model)}),+      udRelease = \uid -> modify' (\model -> model {modelLocked = Set.delete uid (modelLocked model)})+    }+  where+    users = Map.fromList [(name, (uid, buildGid)) | n <- [1 .. 6], let name = memberName n, let uid = uidOf n]++-- | The model's reason a lock file cannot be opened.+unopenableReason :: T.Text+unopenableReason = "opening user lock \"/nix/var/nix/userpool/30001\": permission denied"++-- | The build users' group of the model, holding these members.+groupOf :: [BS.ByteString] -> Map.Map BS.ByteString (Word32, [BS.ByteString])+groupOf members = Map.singleton "nixbld" (buildGid, members)++-- | The model's first members, in order.+memberNames :: Int -> [BS.ByteString]+memberNames count = map memberName [1 .. count]++-- | The model's member N.+memberName :: Int -> BS.ByteString+memberName n = "nixbld" <> BS8.pack (show n)++-- | The model's uid of member N.+uidOf :: Int -> Word32+uidOf n = 30000 + fromIntegral n++-- | The model's build users' group and the other group its members are in.+buildGid, kvmGid :: Word32+buildGid = 30000+kvmGid = 78++-- ---------------------------------------------------------------------------+-- Without root, in IO+-- ---------------------------------------------------------------------------++-- | What a process that is not root may not do: kill a build user's+-- processes, which the shim refuses before it forks, since its child could+-- only become the caller and kill the caller's every other process; and+-- take a build user at all, which 'withBuildUser' refuses before it makes+-- the pool, whatever privilege 'buildUsersFor' was told of.  The suite+-- runs as a user that is not root, and as root these are passed over.  On+-- Windows, which has no build users, there is no shim to ask, and a build+-- user is never taken.+testBuildUsersUnprivilegedIO :: IO [Bool]+testBuildUsersUnprivilegedIO = do+  putStrLn "builder/build-users-unprivileged"+  root <- runsAsRoot+  if root+    then sequence [runTest "a process that is not root takes no build user (skipped: running as root)" Pass]+    else do+      temporary <- getTemporaryDirectory+      let scratch = temporary </> "nova-nix-test-build-users-unprivileged"+          pool = scratch </> "userpool"+      sequence+        [ runTestM "the shim refuses to kill a user's processes for a caller that is not root, before it forks" shimRefusal,+          runTestM "a process that is not root takes no build user, and makes no pool, whatever privilege it named" $ do+            removePathForcibly scratch+            taken <- withBuildUser testLogger (buildUsersFor RunsAsRoot pool "nixbld") "/nix/store/x.drv" (\_ -> pure ())+            made <- doesDirectoryExist pool+            pure $ case taken of+              Left message ->+                assertEqual "refusal" "builds run as the members of 'nixbld' only for root, and this process is not root" message+                  `andThen` assertEqual "pool made" False made+              Right ()+                | supported -> Fail "a build user was taken by a process that is not root"+                | otherwise -> assertEqual "pool made" False made+        ]+  where+    supported = System.Info.os `elem` ["linux", "darwin"]++-- | Whether this process runs as root.  Never on Windows.+runsAsRoot :: IO Bool++-- | The shim's refusal, for a caller that is not root, to kill another+-- user's processes, and of uid 0's: each answered before any child is+-- forked, as the errno the shim returns says, where a fork would answer 0+-- and the child's status.  The other user is @nobody@, whom the caller+-- cannot become, so a shim that forked anyway would still kill nothing.+shimRefusal :: IO TestResult++#if defined(mingw32_HOST_OS)++runsAsRoot = pure False++shimRefusal = pure Pass++#else++runsAsRoot = (== 0) <$> User.getEffectiveUserID++shimRefusal = do+  nobody <- User.getUserEntryForName "nobody"+  refused <- alloca $ \statusPtr -> c_nn_kill_user (fromIntegral (User.userID nobody)) statusPtr+  rootRefused <- alloca $ \statusPtr -> c_nn_kill_user 0 statusPtr+  pure (assertEqual "another user" (errnoValue ePERM) refused `andThen` assertEqual "root" (errnoValue eINVAL) rootRefused)+  where+    errnoValue (Errno number) = number++foreign import ccall safe "nn_kill_user"+  c_nn_kill_user :: CUInt -> Ptr CInt -> IO CInt++#endif++-- ---------------------------------------------------------------------------+-- As root+-- ---------------------------------------------------------------------------++-- | The flag that makes the suite the root child that builds as build+-- users, given the sandbox helper, the static busybox, a directory to make+-- and remove that no ancestor of every user may write and every user may+-- search, and the group of build users.+buildUsersRootFlag :: String+buildUsersRootFlag = "--build-users-root"++-- | Run the checks that build as build users, printing each, and exit with+-- a failure when one fails.+buildUsersRootChild :: [String] -> IO ()++#if defined(mingw32_HOST_OS)++buildUsersRootChild _ = hPutStrLn stderr "build users need Linux or macOS" *> exitFailure++#else++buildUsersRootChild arguments = case arguments of+  [helper, busybox, root, group] -> do+    results <- rootChecks helper busybox root (BS8.pack group) `finally` removePathForcibly root+    let failed = length (filter not results)+    putStrLn (show (length results) <> " build-user checks, " <> show failed <> " failed")+    when (failed > 0) exitFailure+  _ -> hPutStrLn stderr ("usage: " <> buildUsersRootFlag <> " HELPER BUSYBOX ROOT GROUP") *> exitFailure++-- | The checks, in a store under the directory given.+rootChecks :: FilePath -> FilePath -> FilePath -> BS.ByteString -> IO [Bool]+rootChecks helper busybox root group = do+  putStrLn "builder/build-users-as-root"+  removePathForcibly root+  createDirectoryIfMissing True root+  setFileMode root 0o755+  members <- memberUids group+  groupId <- User.groupID <$> User.getGroupEntryForName group+  busyboxBytes <- Spawn.filePathBytes busybox+  helperThere <- doesFileExist helper+  nobody <- User.getUserEntryForName "nobody"+  let storeDir = StoreDir (root </> "store")+      pool = root </> "state" </> "userpool"+      unsandboxed store = (Builder.defaultBuildConfig (stDir store)) {Builder.bcBuildUsers = buildUsersFor RunsAsRoot pool group}+      sandboxed store = (unsandboxed store) {Builder.bcSandbox = linuxSandboxConfig helper busyboxBytes}+      sandboxAvailable = System.Info.os == "linux" && helperThere+      outPath letter = StorePath (T.replicate 32 (T.singleton letter))+      onDisk = storePathToFilePath storeDir+      build config store sp script = Builder.buildDerivation config store (mkTestBuildDrv "/bin/sh" sp script) testDrvPath+      rootOwnedReadOnly path = do+        status <- getSymbolicLinkStatus path+        pure (assertEqual "owner" 0 (fileOwner status) `andThen` assertEqual "write bits" 0 (fileMode status .&. 0o222))+  bracket (openStore testLogger storeDir) closeStore $ \store ->+    sequence+      [ runTestM "an unsandboxed build runs as a member of the build users' group, with the group alone, leading a session of its own, and its output is root's and read-only" $ do+          let sp = outPath 'a' "unsandboxed-uid"+          built <- build (unsandboxed store) store sp "{ id -u; id -G; echo $$ $(cut -d ' ' -f 6 /proc/$$/stat); } > $out"+          succeeded built $ do+            written <- BS8.lines <$> BS.readFile (onDisk sp)+            owner <- rootOwnedReadOnly (onDisk sp)+            pure $ case map BS8.words written of+              [[uid], groups, [pid, session]] ->+                assertEqual "a build user's uid" True (maybe False (`elem` members) (readMaybe (BS8.unpack uid)))+                  `andThen` assertEqual "groups" [BS8.pack (show groupId)] (nub groups)+                  `andThen` assertEqual "its own session" pid session+                  `andThen` owner+              _ -> Fail ("the build wrote " <> T.pack (show written)),+        if sandboxAvailable+          then runTestM "a sandboxed build runs as the sandbox's user, which maps to a member of the build users' group, and its output is root's and read-only" $ do+            let sp = outPath 'b' "sandboxed-uid"+            built <- build (sandboxed store) store sp "/bin/busybox cat /proc/self/uid_map > $out"+            succeeded built $ do+              mapping <- BS8.words <$> BS.readFile (onDisk sp)+              owner <- rootOwnedReadOnly (onDisk sp)+              pure $ case mapping of+                [inside, outside, count] ->+                  assertEqual "inside" "1000" inside+                    `andThen` assertEqual "a build user's uid" True (maybe False (`elem` members) (readMaybe (BS8.unpack outside)))+                    `andThen` assertEqual "count" "1" count+                    `andThen` owner+                _ -> Fail ("the map was " <> T.pack (show mapping))+          else runTest "a sandboxed build as a build user (skipped: no sandbox helper on Linux here)" Pass,+        if sandboxAvailable+          then runTestM "a sandboxed build as root with no build users is refused" $ do+            built <- build ((sandboxed store) {Builder.bcBuildUsers = NoBuildUsers}) store (outPath 'c' "refused") "echo ran > $out"+            pure $ case built of+              Builder.BuildFailure message _ -> assertEqual "refusal" True ("needs build users" `T.isInfixOf` message)+              Builder.BuildSuccess _ -> Fail "a sandboxed build ran as root"+          else runTest "a sandboxed build as root with no build users (skipped: no sandbox helper on Linux here)" Pass,+        runTestM "an output holding a node another user owns fails the build, naming the node, which is left as it was" $ do+          let foreignDir = root </> "foreign"+              foreignFile = foreignDir </> "file"+              sp = outPath 'd' "foreign"+          createDirectoryIfMissing True foreignDir+          setFileMode foreignDir 0o755+          BS.writeFile foreignFile "another user's\n"+          setOwnerAndGroup foreignFile (User.userID nobody) (User.userGroupID nobody)+          -- So a build user may link it, as Linux's protected_hardlinks+          -- lets a user link a file it may read and write.+          setFileMode foreignFile 0o666+          built <- build (unsandboxed store) store sp ("mkdir $out && ln " <> T.pack foreignFile <> " $out/linked")+          after <- getSymbolicLinkStatus foreignFile+          pure $ case built of+            Builder.BuildFailure message _ ->+              assertEqual "named" True (("invalid ownership on file '" <> T.pack (onDisk sp </> "linked") <> "'") `T.isInfixOf` message)+                `andThen` assertEqual "still another's" (User.userID nobody) (fileOwner after)+                `andThen` assertEqual "its mode" 0o666 (fileMode after .&. 0o777)+            Builder.BuildSuccess _ -> Fail "an output holding another user's file was registered",+        runTestM "a build below a directory every user may write is refused in upstream's words" $ do+          let open = root </> "open"+          createDirectoryIfMissing True open+          setFileMode open 0o777+          built <- bracket (openStore testLogger (StoreDir (open </> "store"))) closeStore $ \openedStore ->+            build (unsandboxed openedStore) openedStore (outPath 'h' "under-open") "echo ran > $out"+          pure $ case built of+            Builder.BuildFailure message _ -> assertEqual "refusal" True (worldWritableMessage open `T.isInfixOf` message)+            Builder.BuildSuccess _ -> Fail "a build below a directory every user may write ran",+        runTestM "a process a build leaves behind is killed once the build ends" $ do+          let sp = outPath 'f' "leftover"+          built <- build (unsandboxed store) store sp "sleep 600 </dev/null >/dev/null 2>&1 & echo $! > $out"+          succeeded built $ do+            pid <- readMaybe . BS8.unpack . BS8.strip <$> BS.readFile (onDisk sp)+            case pid of+              Nothing -> pure (Fail "the build wrote no process id")+              Just number -> assertEqual "ended" 0 <$> c_nova_test_await_exit number leftoverWaitMillis,+        runTestM "a build waits while every build user is taken, says so once, and runs once one is free" $ do+          createDirectoryIfMissing True pool+          held <- catMaybes <$> traverse (\uid -> tryLockFile (pool </> show uid) Exclusive) members+          waiting <- newEmptyMVar+          logged <- newIORef []+          let drvText = storePathToText defaultStoreDir testDrvPath+              logger =+                plainLogger+                  ( \_ message -> do+                      modifyIORef' logged (message :)+                      when (message == waitingForBuildUserMessage drvText) (void (tryPutMVar waiting ()))+                  )+                  (const (pure ()))+              sp = outPath 'g' "waited"+          -- A build that ends before it waits ends the check, rather than+          -- leaving it waiting for a line that never comes.+          built <-+            withAsync+              (build (unsandboxed store) store {stLogger = logger} sp "echo ran > $out")+              ( \running -> do+                  first <- race (takeMVar waiting) (wait running)+                  either (\() -> traverse_ unlockFile (take 1 held) *> wait running) pure first+              )+              `finally` traverse_ unlockFile (drop 1 held)+          messages <- readIORef logged+          pure $+            assertEqual "every member held" (length members) (length held)+              `andThen` succeededWith built+              `andThen` assertEqual "said once" 1 (length (filter (== waitingForBuildUserMessage drvText) messages))+      ]+  where+    succeeded built check = case built of+      Builder.BuildSuccess _ -> check+      Builder.BuildFailure message code -> pure (Fail ("the build failed (" <> T.pack (show code) <> "): " <> message))+    succeededWith built = case built of+      Builder.BuildSuccess _ -> Pass+      Builder.BuildFailure message code -> Fail ("the build failed (" <> T.pack (show code) <> "): " <> message)++-- | The uids of a group's members.+memberUids :: BS.ByteString -> IO [Word32]+memberUids group = do+  entry <- User.getGroupEntryForName group+  users <- traverse User.getUserEntryForName (User.groupMembers entry)+  unless (length users >= 2) (hPutStrLn stderr "the group of build users needs two members for these checks")+  pure (map (fromIntegral . User.userID) users)++-- | How long a process a build left behind is given to end once the build+-- has, which a kill ends at once and a sleep of ten minutes does not.+leftoverWaitMillis :: CInt+leftoverWaitMillis = 10000++foreign import ccall safe "nova_test_await_exit"+  c_nova_test_await_exit :: CInt -> CInt -> IO CInt++#endif
+ test/Test/Builder.hs view

8031 lines of diff, too many to show among the others: show this file

+ test/Test/CData.hs view
@@ -0,0 +1,1960 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | Tests of the evaluator's C data layer (symbols, attribute sets,+-- thunks, values and the arena) and the bytecode it runs.+module Test.CData+  ( arenaGuardChildFlag,+    arenaGuardChild,+    testArenaGuard,+    testSymbol,+    testCAttrSet,+    testCThunk,+    testBytecodePerElement,+    testBytecodeCountSpill,+    testValueCountWidths,+    testLambdaShape,+    testUnknownTags,+    testBytecodeTags,+    testBytecodeCorrupt,+    testBytecodeCompile,+  )+where++import Control.Exception (ErrorCall (..), displayException, evaluate, finally, throwIO, try)+import Control.Monad (foldM, unless, void, when, (>=>))+import qualified Data.ByteString as BS+import qualified Data.ByteString.Unsafe as BSU+import Data.Functor ((<&>))+import Data.IORef (modifyIORef', newIORef, readIORef, writeIORef)+import Data.Int (Int64)+import Data.List (find, sort, sortOn)+import qualified Data.Map.Strict as Map+import Data.Maybe (isJust, isNothing)+import Data.Ord (Down (..))+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import Data.Word (Word32, Word8)+import Foreign.C.Types (CChar, CInt (..), CSize (..))+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (Ptr, castPtr, nullPtr)+import Foreign.Storable (Storable, peekByteOff, poke, pokeByteOff, sizeOf)+import Nix.Builtins (builtinEnv)+import Nix.Eval (BuiltinArg (..), NixValue (..), StringContext (..), StringContextElement (..), Thunk (..), attrSetFromMap, attrSetLookup, emptyEnv, eval, evalBytecode, evalParsed, evaluated, mkStr, readThunkValue, runPureEval, unrestrictedPolicy)+import Nix.Eval.AllocSite (EnvSite (..), SetSite (..))+import Nix.Eval.Builtin (Builtin, builtinIndex, builtinName)+import qualified Nix.Eval.Builtin as Builtin+import Nix.Eval.CAttrSet (CAttrSetStep (..), cattrsetFind, cattrsetFreeze, cattrsetFromNames, cattrsetIndex, cattrsetInsert, cattrsetLookup, cattrsetMember, cattrsetNew, cattrsetRemoveKeys, cattrsetSetValue, cattrsetSize, cattrsetUnion, cattrsetUpdate, cattrsetWalk, cattrsetWalkNext, flatCAttrSet)+import Nix.Eval.CBytecode (attrkeyStatic, attrsRec, binaryAdd, bindNamed, captureNone, captureSlots, captureWithScopes, cbcArg1, cbcArg2, cbcArg3, cbcData, cbcDataCount, cbcEmit, cbcEmitData, cbcEmitString, cbcFlags, cbcOpCount, cbcOpcode, cbcShortArg, cbcStringText, formalName, formalNamedSet, formalSet, formalSharedDefault, strpartInterp, strpartLit, unaryNegate, pattern OpApp, pattern OpAssert, pattern OpAttrs, pattern OpBinary, pattern OpHasAttr, pattern OpIf, pattern OpIndStr, pattern OpLambda, pattern OpLet, pattern OpList, pattern OpLitBool, pattern OpLitFloat, pattern OpLitInt, pattern OpLitNull, pattern OpLitPath, pattern OpLitUri, pattern OpResolvedVar, pattern OpSelect, pattern OpStr, pattern OpUnary, pattern OpVar, pattern OpWith, pattern OpWithVar)+import Nix.Eval.CCtxStr (cctxstrNew)+import Nix.Eval.CLambda (clambdaAllowExtra, clambdaFormalCount, clambdaFormalsType, clambdaNew, clambdaShape, clambdaShapeAllowExtra, clambdaShapeFormalCount, clambdaShapeFormalsType)+import Nix.Eval.CList (CList (..), clistFromThunks)+import Nix.Eval.CPrimop (cprimopAppNew)+import Nix.Eval.CStats (SiteCounts (..))+import Nix.Eval.CStatus (CStatusError (..), arenaLive)+import Nix.Eval.CStr (cstrNew)+import Nix.Eval.CThunk (cthunkBool, cthunkGetBool, cthunkGetInt, cthunkMarkBlackhole, cthunkNewBc, cthunkNewComputedInt, cthunkNull, cthunkPayload, cthunkPrimop, cthunkSetComputedInt, cthunkSetComputedNull, cthunkState, cthunkValueTag)+import Nix.Eval.Compile (BcBinding (..), BcBindingCounts (..), BcBindings (..), BcCaptureInfo (..), BcInheritedName (..), BcInheritedNames, compileExpr, compileFormalsToEval, decodeBcCaptureInfo, decodeBinaryOp, decodeUnaryOp, encodeBinaryOp, encodeUnaryOp, foldBcBindings, foldBcCapturedSlots, foldBcInheritedNames, reassembleInt64)+import Nix.Eval.EvalFormals (EvalFormal (..), EvalFormals (..), FormalDefault (..), LambdaName (..))+import Nix.Eval.SourcePos (PosIdx (..), RecordedPos (..), lookupPos, newPosRecorder, noPos, printPos, recordPos)+import Nix.Eval.Symbol (Symbol (..), invalidSymbolId, symbolCount, symbolIntern, symbolLen, symbolText)+import Nix.Eval.Types (AttrEntry (..), AttrSet (..), Env (..), attrSetAllPairs, attrSetFindName, attrSetFoldM, attrSetKeys, attrSetLookupSymbolEntry, attrSetMapWithKey, attrSetMemberSymbol, attrSetToMap, newEnv, readComputed, tieFrame, pattern ThunkComputed, pattern ValueBool, pattern ValueNull)+import Nix.Expr.Types+import Nix.Parser (parseNix)+import Nix.Store.Path.Internal (StorePath (..))+import System.Directory (getTemporaryDirectory)+import System.Environment (getExecutablePath)+import System.Exit (ExitCode (..), exitWith)+import System.IO (hPutStrLn, stderr)+import qualified System.Process as Proc+import Test.Harness (TestResult (..), andThen, assertEqual, assertEval, censusStoreHash, compiledBindings, decodeFormals, evalNix, evalNixIO, inTestSession, runTest, runTestM, setLayerRhsMax, setMaxLayers, sitesAdded, testOrigin, testPos)+import qualified Test.QuickCheck as QC++-- ---------------------------------------------------------------------------+-- Arena lifecycle guard (C FFI)+-- ---------------------------------------------------------------------------++-- | The argument that turns this executable into the child of+-- 'testArenaGuard'.  The child reaches the C layer outside any+-- evaluation session, which the suite cannot do in its own process:+-- 'main' runs every group in one session ('inTestSession').+arenaGuardChildFlag :: String+arenaGuardChildFlag = "--arena-guard-child"++-- | One way a library user reaches the C layer, with what the child must+-- report for it.+data ArenaGuardPath = ArenaGuardPath+  { -- | The child's argument.+    guardName :: !String,+    -- | The suite's name for the case.+    guardClaim :: !Text,+    -- | What the child must report.+    guardOutcome :: !GuardOutcome,+    -- | The child's body, run outside any evaluation session.+    guardAction :: !(IO ())+  }++-- | What a guard child must report for its path.+data GuardOutcome+  = -- | 'ArenaNotInitialized', naming this C entry point.+    RefusedAt !Text+  | -- | No exception: the path needs no arena.+    Served++-- | The line a guard child prints when its path raised nothing.+servedLine :: String+servedLine = "served without an exception"++-- | The paths a library user reaches the C layer by.  The first C call+-- of each of the first five lands in a different sub-arena, and of each+-- of the next four in a different tracker of the objects the arena's+-- teardown frees one by one (cbits/nn_tracker.h), where an object made+-- outside every session would be freed by the next session's end under+-- whoever held it.  One runs a whole session first, so both ends of the+-- window are covered.  One reads a symbol, which the table answers+-- outside the window as it answers an id it does not hold.  Two read+-- the shared @null@, @true@ and @false@ thunks, which must be valid in+-- every window: were they arena cells behind a process-lifetime CAF,+-- forcing one outside the window would poison it with+-- 'ArenaNotInitialized' for every later arena, and forcing one inside a+-- session would leave it pointing into memory the session's end frees,+-- a use-after-free the ASan job reports.  One evaluates an empty string+-- before anything else in a fresh arena: its payload of no words sits+-- at data offset 0, which the store does not hold yet, so a read there+-- fails the store's bounds assertion.  The last three show that a+-- session tears the arena down as it returns and as an exception leaves+-- it, and that a nested session leaves the arena to the one around it.+arenaGuardPaths :: [ArenaGuardPath]+arenaGuardPaths =+  [ noArena "compile" "nn_bc_emit" evalNamelessProgram,+    noArena "thunk" "nn_thunk_new_computed_int" (void (evaluated (VInt 1))),+    noArena "string" "nn_str_new" (void (evaluated (mkStr "a"))),+    noArena "symbol" "nn_symbol_intern" (void (symbolIntern "a")),+    noArena "env" "nn_env_new" (void (evaluated VNull >>= \nullCell -> newEnv EnvClosure Nothing [nullCell])),+    -- A plain lambda (formals type 0) with no env, builtin 0 applied to+    -- the shared null cell, and a context string with no text: each+    -- allocator stores what it is given without reading it, so the+    -- tracker's refusal is what stops it.+    noArena "set" "nn_attrset_new" (void (cattrsetNew SetLiteral 1)),+    noArena "lambda" "nn_lambda_new" (void (clambdaNew nullPtr 0 0 0 0 0 0)),+    noArena "partial-application" "nn_primop_app_new" (void (cprimopAppNew 0 0 [cthunkNull])),+    noArena "context-string" "nn_ctxstr_new" (void (cctxstrNew nullPtr 0)),+    noArena "after-session" "nn_bc_emit" (inTestSession (pure ()) >> evalNamelessProgram),+    noArena "symbol-read" "nn_symbol_text" (void (evaluate (symbolText (Symbol 1)))),+    ArenaGuardPath+      { guardName = "constants-outside-window",+        guardClaim = "the null, true and false thunks read correctly outside every session and in a later one",+        guardOutcome = Served,+        guardAction = readConstants >> inTestSession readConstants+      },+    ArenaGuardPath+      { guardName = "constants-across-cycles",+        guardClaim = "the null, true and false thunks read correctly across two sessions",+        guardOutcome = Served,+        guardAction = inTestSession readConstants >> inTestSession readConstants+      },+    ArenaGuardPath+      { guardName = "empty-string-first",+        guardClaim = "an empty string evaluated first in a fresh arena reads no data word",+        guardOutcome = Served,+        guardAction = inTestSession $ case runPureEval (eval emptyEnv (EStr [])) of+          Right (VStr bytes _) | BS.null bytes -> pure ()+          other -> throwIO (ErrorCall ("the empty string evaluated to " ++ show other))+      },+    ArenaGuardPath+      { guardName = "session-returns",+        guardClaim = "a session tears the arena down as it returns",+        guardOutcome = Served,+        guardAction = inTestSession (pure ()) >> arenaGone "a session that returned"+      },+    ArenaGuardPath+      { guardName = "session-throws",+        guardClaim = "a session tears the arena down as an exception leaves it",+        guardOutcome = Served,+        guardAction = do+          left <- try (inTestSession (throwIO (ErrorCall "inside the session")))+          case left of+            Left (ErrorCall _) -> arenaGone "a session an exception left"+            Right () -> throwIO (ErrorCall "the exception did not leave the session")+      },+    ArenaGuardPath+      { guardName = "nested-session",+        guardClaim = "a nested session leaves the arena to the session around it",+        guardOutcome = Served,+        guardAction = inTestSession $ do+          inTestSession (pure ())+          live <- arenaLive+          unless live (throwIO (ErrorCall "the nested session tore the outer session's arena down"))+          readConstants+      }+  ]+  where+    noArena name site = ArenaGuardPath name ("no arena: " <> T.pack name <> " raises ArenaNotInitialized at " <> site) (RefusedAt site)+    arenaGone what = do+      live <- arenaLive+      when live (throwIO (ErrorCall (what ++ " left the arena live")))+    -- A small program forced to its result.  It names nothing, so its+    -- first C call compiles it rather than interning a name.+    evalNamelessProgram = case parseNix "/tmp" (SourceText "<expr>") "5 * 2 + 1" of+      Left err -> throwIO (ErrorCall (show err))+      Right parsed -> void (evaluate (runPureEval (evalParsed (builtinEnv unrestrictedPolicy 0 []) parsed)))+    -- Read through the IO accessors: a pure read of a constant is itself+    -- a constant GHC may share between the cycles, and the second would+    -- then read nothing.  A wrong cell is a broken outcome rather than the+    -- guard under test, so it leaves the child by another exception.+    readConstants = do+      found <- mapM (evaluated >=> readCell . unThunk) [VNull, VBool True, VBool False]+      unless (found == [(ThunkComputed, ValueNull, 0), (ThunkComputed, ValueBool, 1), (ThunkComputed, ValueBool, 0)]) $+        throwIO (ErrorCall ("the constants read back as " ++ show found))+    readCell ptr = (,,) <$> cthunkState ptr <*> cthunkValueTag ptr <*> cthunkGetBool ptr++-- | Child body: run one path with no arena and print what it raised, or+-- 'servedLine'.  Exit 0 either way; a segfault, a sanitizer report or+-- any other exception type surfaces as the process's own exit code.+arenaGuardChild :: String -> IO ()+arenaGuardChild name = case [guardAction path | path <- arenaGuardPaths, guardName path == name] of+  [action] -> do+    outcome <- try action+    putStrLn $ case outcome of+      Left (err :: CStatusError) -> displayException err+      Right () -> servedLine+  _ -> hPutStrLn stderr ("unknown arena guard path: " ++ name) >> exitWith (ExitFailure 2)++-- ---------------------------------------------------------------------------+-- Tests: upstream's startup names, and the call, select and abort errors+-- ---------------------------------------------------------------------------++-- | The smallest slot count whose byte size exceeds @UINT32_MAX@.+-- The env pages refuse an env or a list's items array of that many+-- before touching a page, so inside a live arena it fails without+-- exhausting anything.+slotCountPastUInt32 :: Int+slotCountPastUInt32 = fromIntegral (maxBound :: Word32) `div` sizeOf (nullPtr :: Ptr ()) + 1++-- | One byte past the longest string the symbol table or a string arena+-- can hold.+lengthPastUInt32 :: Int+lengthPastUInt32 = fromIntegral (maxBound :: Word32) + 1++-- | Run an action on a ByteString whose length claims 'lengthPastUInt32'+-- bytes over one real byte, so no 4 GiB buffer is needed.  Sound only+-- because each C function it reaches refuses on the length before+-- reading: one that read would run out of bounds here.+withOversizedBytes :: (BS.ByteString -> IO a) -> IO a+withOversizedBytes use =+  alloca $ \byte -> do+    poke byte (0 :: CChar)+    use =<< BSU.unsafePackCStringLen (byte, lengthPastUInt32)++-- | The interner itself, for the one refusal no name reaches: the library+-- interns names given as text, and no test can build 4 GiB of text.+foreign import ccall unsafe "nn_symbol_intern"+  c_nn_symbol_intern :: Ptr CChar -> CSize -> IO Word32++-- | The list constructor itself, for the one refusal no list reaches: a+-- list is built from the cells it holds, and no test can hold the half a+-- billion a refused count needs.+foreign import ccall unsafe "nn_list_new"+  c_nn_list_new :: Ptr (Ptr ()) -> Word32 -> IO CInt++-- | Intern an oversized name through the C entry point, answering what it+-- returns.+internOversizedSymbol :: IO Word32+internOversizedSymbol =+  withOversizedBytes $ \bytes ->+    BSU.unsafeUseAsCStringLen bytes $ \(ptr, len) -> c_nn_symbol_intern ptr (fromIntegral len)++-- | Reaching the C layer outside an evaluation session raises+-- 'ArenaNotInitialized' naming the entry point, rather than a SIGSEGV.+-- Each such path runs in a child process.+-- The live side of the same check runs in this process, under the+-- suite's bracket: a refusal with the arena up is 'CAllocationFailed'.+testArenaGuard :: IO [Bool]+testArenaGuard = do+  putStrLn "arena/guard"+  self <- getExecutablePath+  children <-+    mapM+      ( \path -> runTestM (guardClaim path) $ do+          (code, out, err) <- Proc.readCreateProcessWithExitCode (Proc.proc self [arenaGuardChildFlag, guardName path]) ""+          let message = T.pack out+          pure $ case (code, guardOutcome path) of+            (ExitSuccess, RefusedAt site)+              | "withEvalSession" `T.isInfixOf` message && site `T.isInfixOf` message -> Pass+              | otherwise -> Fail ("message does not name withEvalSession and " <> site <> ": " <> message)+            (ExitSuccess, Served)+              | T.strip message == T.pack servedLine -> Pass+              | otherwise -> Fail ("expected no exception, got: " <> message)+            (ExitFailure n, _) -> Fail ("child exited " <> T.pack (show n) <> " (negative is a signal): " <> T.pack err)+      )+      arenaGuardPaths+  live <-+    sequence+      [ liveRefusal "an env whose slots pass UINT32_MAX bytes" "nn_env_new" (void (tieFrame EnvLet Nothing slotCountPastUInt32 (const (pure [])))),+        -- The list's items come from the same pages, so the same count is+        -- refused there, with a status: a NULL would read as the empty list.+        runTestM "live arena: a list past UINT32_MAX slot bytes is refused with a status" $ do+          status <- alloca (\out -> c_nn_list_new out (fromIntegral slotCountPastUInt32))+          pure (assertEqual "status" (-1) status),+        -- A length a string's uint32_t cannot hold, refused rather than+        -- truncated to a shorter string, in the value arena and in the+        -- code's.+        liveRefusal "a string longer than UINT32_MAX bytes" "nn_str_new" (void (withOversizedBytes cstrNew)),+        liveRefusal "a code string longer than UINT32_MAX bytes" "nn_bc_emit_string" (void (withOversizedBytes cbcEmitString))+      ]+  tableIntact <-+    runTestM "a symbol longer than UINT32_MAX bytes is refused, leaving the table unchanged" $ do+      before <- symbolCount+      refused <- internOversizedSymbol+      after <- symbolCount+      sym <- symbolIntern "after-a-refusal"+      pure $+        if refused == 0 && before == after && symbolText sym == "after-a-refusal"+          then Pass+          else Fail ("answer " <> T.pack (show refused) <> ", count " <> T.pack (show before) <> " -> " <> T.pack (show after) <> ", text " <> symbolText sym)+  pure (children ++ live ++ [tableIntact])+  where+    liveRefusal what site action =+      runTestM ("live arena: " <> what <> " raises CAllocationFailed at " <> site) $ do+        alive <- arenaLive+        outcome <- try action+        pure $ case (alive, outcome) of+          (True, Left (CAllocationFailed refused _)) | refused == T.unpack site -> Pass+          (True, Left err) -> Fail ("expected CAllocationFailed at " <> site <> ", got " <> T.pack (show err))+          (True, Right ()) -> Fail "no exception raised"+          (False, _) -> Fail "arenaLive is False inside the suite's bracket"++-- ---------------------------------------------------------------------------+-- Symbol interning (C FFI)+-- ---------------------------------------------------------------------------++testSymbol :: IO [Bool]+testSymbol = do+  putStrLn "symbol"+  sequence+    [ runTestM "intern returns non-zero" $ do+        sym <- symbolIntern "hello"+        pure (if unSymbol sym /= 0 then Pass else Fail "got symbol 0"),+      runTestM "intern same string returns same symbol" $ do+        sym1 <- symbolIntern "name"+        sym2 <- symbolIntern "name"+        pure (assertEqual "same symbol" sym1 sym2),+      runTestM "intern different strings returns different symbols" $ do+        sym1 <- symbolIntern "foo"+        sym2 <- symbolIntern "bar"+        pure (if sym1 /= sym2 then Pass else Fail "symbols should differ"),+      runTestM "symbolText round-trips" $ do+        sym <- symbolIntern "version"+        let txt = symbolText sym+        pure (assertEqual "text" "version" txt),+      runTestM "symbolLen correct" $ do+        sym <- symbolIntern "outputs"+        pure (assertEqual "len" 7 (symbolLen sym)),+      runTestM "empty string interns" $ do+        sym <- symbolIntern ""+        pure (assertEqual "text and length" ("", 0) (symbolText sym, symbolLen sym)),+      runTestM "the invalid symbol id reads as no name" $+        pure (assertEqual "text and length" ("", 0) (symbolText (Symbol invalidSymbolId), symbolLen (Symbol invalidSymbolId))),+      -- The table answers an id past its count as it answers the invalid+      -- one, so only the readers' check tells the defect from no name.+      runTestM "reading a symbol id past the table's count raises CInvariantViolated" $ do+        count <- symbolCount+        let unheld = Symbol (count + 1)+        text <- try (evaluate (symbolText unheld))+        len <- try (evaluate (symbolLen unheld))+        pure (assertEqual "sites" (Just "nn_symbol_text", Just "nn_symbol_len") (violatedAt text, violatedAt len)),+      runTestM "symbolCount tracks unique entries" $ do+        _ <- symbolIntern "alpha"+        _ <- symbolIntern "beta"+        _ <- symbolIntern "alpha"+        count <- symbolCount+        -- count includes all symbols interned in this bracket,+        -- so at least the ones from prior tests plus alpha + beta+        pure (if count >= 2 then Pass else Fail ("count too low: " <> T.pack (show count))),+      runTestM "many symbols (stress)" $ do+        let names = map (\i -> "pkg_" <> T.pack (show (i :: Int))) [1 .. 1000]+        syms <- mapM symbolIntern names+        -- All unique+        let unique = length (Set.fromList (map unSymbol syms))+        pure (assertEqual "1000 unique" 1000 unique)+    ]+  where+    violatedAt :: Either CStatusError a -> Maybe String+    violatedAt = \case+      Left (CInvariantViolated site _) -> Just site+      _ -> Nothing++-- ---------------------------------------------------------------------------+-- C attribute set (FFI)+-- ---------------------------------------------------------------------------++testCAttrSet :: IO [Bool]+testCAttrSet = do+  putStrLn "cattrset"+  sequence+    [ runTestM "a new set holds no entries" $ do+        set <- cattrsetNew SetLiteral 16+        cattrsetFreeze set+        n <- cattrsetSize set+        pure (assertEqual "size" 0 n),+      runTestM "insert + freeze + lookup" $ do+        set <- cattrsetNew SetLiteral 4+        kName <- symbolIntern "name"+        kVer <- symbolIntern "version"+        nameCell <- textCell "hello"+        verCell <- textCell "1.0"+        cattrsetInsert set kName noPos nameCell+        cattrsetInsert set kVer noPos verCell+        cattrsetFreeze set+        result <- cattrsetLookup set kName+        pure (assertEqual "lookup name" (Just nameCell) result),+      runTestM "lookup missing key returns Nothing" $ do+        set <- cattrsetNew SetLiteral 4+        kFoo <- symbolIntern "foo"+        kBar <- symbolIntern "bar"+        cattrsetInsert set kFoo noPos cthunkNull+        cattrsetFreeze set+        result <- cattrsetLookup set kBar+        pure (assertEqual "lookup bar" Nothing result),+      runTestM "size after freeze" $ do+        set <- cattrsetNew SetLiteral 4+        keys <- mapM symbolIntern ["a", "b", "c"]+        mapM_ (\key -> cattrsetInsert set key noPos cthunkNull) keys+        cattrsetFreeze set+        n <- cattrsetSize set+        pure (assertEqual "size" 3 n),+      runTestM "duplicate keys: last writer wins" $ do+        set <- cattrsetNew SetLiteral 4+        kName <- symbolIntern "name"+        first <- textCell "first"+        second <- textCell "second"+        cattrsetInsert set kName noPos first+        cattrsetInsert set kName noPos second+        cattrsetFreeze set+        n <- cattrsetSize set+        result <- cattrsetLookup set kName+        pure (assertEqual "size and value" (1, Just second) (n, result)),+      -- Inserted from the highest symbol id down, so freeze has to sort.+      runTestM "a walk reads the keys in symbol order" $ do+        set <- cattrsetNew SetLiteral 8+        inserted <- mapM symbolIntern ["zzz", "aaa", "mmm"]+        mapM_ (\key -> cattrsetInsert set key noPos cthunkNull) (sortOn Down inserted)+        cattrsetFreeze set+        keys <- map (\(name, _, _) -> name) <$> walkedEntries set+        pure (assertEqual "keys" (sort inserted) keys),+      runTestM "union right-biased" $ do+        setA <- cattrsetNew SetLiteral 4+        setB <- cattrsetNew SetLiteral 4+        kX <- symbolIntern "x"+        kY <- symbolIntern "y"+        kZ <- symbolIntern "z"+        fromA <- textCell "fromA"+        fromB <- textCell "fromB"+        onlyA <- textCell "onlyA"+        onlyB <- textCell "onlyB"+        cattrsetInsert setA kX noPos fromA+        cattrsetInsert setA kZ noPos onlyA+        cattrsetInsert setB kX noPos fromB+        cattrsetInsert setB kY noPos onlyB+        cattrsetFreeze setA+        cattrsetFreeze setB+        merged <- cattrsetUnion SetUpdate setA setB+        n <- cattrsetSize merged+        found <- mapM (cattrsetLookup merged) [kX, kY, kZ]+        pure (assertEqual "size and entries" (3, map Just [fromB, onlyB, onlyA]) (n, found)),+      runTestM "stress: 10k entries" $ do+        set <- cattrsetNew SetLiteral 1024+        syms <- mapM (\i -> symbolIntern ("key_" <> T.pack (show (i :: Int)))) [1 .. 10000]+        mapM_ (\sym -> cattrsetInsert set sym noPos cthunkNull) syms+        cattrsetFreeze set+        n <- cattrsetSize set+        -- Spot-check a lookup from the middle of the key range+        hit <- case drop 5000 syms of+          middleSym : _ -> cattrsetLookup set middleSym+          [] -> pure Nothing+        pure+          ( if n == 10000 && isJust hit+              then Pass+              else Fail ("size=" <> T.pack (show n))+          ),+      -- The index of an absent name is the C side's NN_ATTRSET_NOT_FOUND.+      runTestM "a name table's index finds each name at its sorted position and none for an absent name" $ do+        syms <- mapM (\i -> symbolIntern ("index_" <> T.pack (show (i :: Int)))) [1 .. 100]+        absent <- symbolIntern "index_absent"+        table <- cattrsetFromNames SetScope (reverse syms)+        found <- mapM (cattrsetIndex table) (sort syms)+        missing <- cattrsetIndex table absent+        pure+          ( if found == map Just [0 .. 99] && isNothing missing+              then Pass+              else Fail ("found=" <> T.pack (show found) <> " missing=" <> T.pack (show missing))+          ),+      -- A position travels with its entry: through both sorts freeze uses+      -- (insertion up to 64 entries, the tagged sort past that), the dedup+      -- that keeps a key's last insert, the growth from the default+      -- capacity that moves the positions within their block, a union+      -- that keeps the right side's on a clash, and a key removal.  The+      -- pool is small enough that inserts repeat keys and large enough to+      -- pass the 64-entry switch.+      runTestM "positions follow their entries through freeze, union and removal" $ do+        pool <- mapM (\i -> symbolIntern ("pos_" <> T.pack (show (i :: Int)))) [1 .. 100]+        let genInserts = QC.listOf ((,) <$> QC.elements pool <*> QC.arbitrary)+            build inserts = do+              set <- cattrsetNew SetLiteral 0+              mapM_ (\(key, pos) -> cattrsetInsert set key (PosIdx pos) cthunkNull) inserts+              cattrsetFreeze set+              pure set+            property =+              QC.forAll (QC.resize 200 ((,,) <$> genInserts <*> genInserts <*> QC.sublistOf pool)) $ \(left, right, removed) ->+                QC.ioProperty $ do+                  leftSet <- build left+                  rightSet <- build right+                  merged <- cattrsetUnion SetUpdate leftSet rightSet+                  kept <- cattrsetRemoveKeys SetRemoveAttrs leftSet removed+                  actual <- mapM entryPositions [leftSet, merged, kept]+                  let leftModel = Map.fromList left+                      rightModel = Map.fromList right+                  pure (actual QC.=== [leftModel, Map.union rightModel leftModel, Map.withoutKeys leftModel (Set.fromList removed)])+        quickCheckPasses property,+      -- lookup answers Nothing for a value not filled yet; find finds it.+      runTestM "a name table finds each name with no value until its value is written" $ do+        written <- symbolIntern "table_written"+        unwritten <- symbolIntern "table_unwritten"+        cell <- textCell "filled"+        table <- cattrsetFromNames SetScope [written, unwritten]+        let set = flatCAttrSet table+        before <- mapM (cattrsetFind set) [written, unwritten]+        cattrsetIndex table written >>= mapM_ (\i -> cattrsetSetValue table i cell)+        after <- mapM (cattrsetFind set) [written, unwritten]+        members <- mapM (cattrsetMember set) [written, unwritten]+        lookups <- mapM (cattrsetLookup set) [written, unwritten]+        pure+          ( assertEqual "before the write" [Just (noPos, nullPtr), Just (noPos, nullPtr)] before+              `andThen` assertEqual "after the write" [Just (noPos, cell), Just (noPos, nullPtr)] after+              `andThen` assertEqual "members" [True, True] members+              `andThen` assertEqual "lookups" [Just cell, Nothing] lookups+          ),+      -- A set holds the last insert of each name, in symbol order, which+      -- a map of the inserts models.  A walk reads every entry in that+      -- order, and a find of a name its entry, the null pointer of a name+      -- table not yet filled among the values.  The inserts repeat names+      -- and pass the 64 entries at which freeze changes sorts.+      runTestM "a walk of a set and a find of each name read the last insert of each name, in symbol order" $ do+        pool <- mapM (\i -> symbolIntern ("walk_" <> T.pack (show (i :: Int)))) [1 .. 100]+        absent <- symbolIntern "walk_absent"+        cells <- mapM textCell ["one", "two", "three"]+        let names = absent : pool+            asEntry entry = (entryPos entry, unThunk (entryThunk entry))+        quickCheckPasses $+          QC.forAll (QC.resize 200 ((,) <$> genValuedInserts pool (nullPtr : cells) <*> QC.sublistOf pool)) $ \(inserts, wanted) -> QC.ioProperty $ do+            set <- buildValued inserts+            walked <- walkedEntries set+            folded <- reverse <$> attrSetFoldM (\acc name entry -> pure ((name, entryPos entry, unThunk (entryThunk entry)) : acc)) [] (AttrSet set)+            keys <- attrSetKeys (AttrSet set)+            asMap <- attrSetToMap (AttrSet set)+            found <- mapM (cattrsetFind set) names+            entries <- mapM (\name -> fmap asEntry <$> attrSetLookupSymbolEntry name (AttrSet set)) names+            members <- mapM (cattrsetMember set) names+            setMembers <- mapM (\name -> attrSetMemberSymbol name (AttrSet set)) names+            firstWanted <- attrSetFindName (`elem` wanted) (AttrSet set)+            let model = insertsModel inserts+                byName = Map.fromList [(name, (pos, value)) | (name, pos, value) <- model]+                modelNames = [name | (name, _, _) <- model]+                modelFound = map (`Map.lookup` byName) names+                modelMembers = map (`Map.member` byName) names+            pure $+              (walked, folded, keys, asMap, found, entries, members, setMembers, firstWanted)+                QC.=== (model, model, map symbolText modelNames, Map.fromList [(symbolText name, Thunk value) | (name, _, value) <- model], modelFound, modelFound, modelMembers, modelMembers, find (`elem` wanted) modelNames),+      -- A chain of updates beside a flattened copy, made by unions, and a+      -- map of it: each update layers while the left's chain holds fewer+      -- than eight sets and the right at most 16 entries, as the copies it+      -- counts show, and every read of the chain, and of each set made+      -- from it, answers as the map's does.  The right operands cross 16+      -- entries, and the chains eight sets.+      runTestM "a chain of updates reads as its flattened copy and a map of it, and layers as upstream's does" $ do+        pool <- mapM (\i -> symbolIntern ("chain_" <> T.pack (show (i :: Int)))) [1 .. 40]+        absent <- symbolIntern "chain_absent"+        cells <- mapM textCell ["one", "two", "three"]+        let names = absent : pool+            sized n = QC.resize n (genValuedInserts pool cells)+            gen = (,,,) <$> sized 60 <*> (QC.chooseInt (1, 12) >>= \n -> QC.vectorOf n (sized 20)) <*> QC.sublistOf pool <*> sized 20+            modelOf inserts = Map.fromList [(name, (pos, value)) | (name, pos, value) <- insertsModel inserts]+            asWalk model = [(name, pos, value) | (name, (pos, value)) <- Map.toAscList model]+            step (set, copy, model, layers, steps) (right, rightModel) = do+              made <- newIORef set+              added <- sitesAdded (cattrsetUpdate SetUpdate set right >>= writeIORef made)+              updated <- readIORef made+              copied <- cattrsetUnion SetUpdate copy right+              let merged = Map.union rightModel model+                  layered = not (Map.null model) && not (Map.null rightModel) && layers < setMaxLayers && Map.size rightModel <= setLayerRhsMax+                  expected = if layered then Map.size rightModel else Map.size merged+                  chained = if layered then layers + 1 else 1+              pure (updated, copied, merged, chained, (fmap sitesUpdateCopied added, Right (fromIntegral expected)) : steps)+        quickCheckPasses $+          QC.forAll gen $ \(baseInserts, rightsInserts, removed, otherInserts) -> QC.ioProperty $ do+            base <- buildValued baseInserts+            rights <- mapM buildValued rightsInserts+            other <- buildValued otherInserts+            let otherModel = modelOf otherInserts+            (chain, copy, model, _, steps) <- foldM step (base, base, modelOf baseInserts, 1 :: Int, []) (zip rights (map modelOf rightsInserts))+            walked <- walkedEntries chain+            copyWalked <- walkedEntries copy+            size <- cattrsetSize chain+            found <- mapM (cattrsetFind chain) names+            looked <- mapM (cattrsetLookup chain) names+            members <- mapM (cattrsetMember chain) names+            keys <- attrSetKeys (AttrSet chain)+            asMap <- attrSetToMap (AttrSet chain)+            kept <- cattrsetRemoveKeys SetRemoveAttrs chain removed >>= walkedEntries+            unions <- mapM (>>= walkedEntries) [cattrsetUnion SetUpdate chain other, cattrsetUnion SetUpdate other chain]+            updates <- mapM (>>= walkedEntries) [cattrsetUpdate SetUpdate chain other, cattrsetUpdate SetUpdate other chain]+            mapped <- attrSetMapWithKey SetMapAttrs (const pure) (AttrSet chain) >>= walkedEntries . unAttrSet+            let counted = reverse (map fst steps)+                expectedCounts = reverse (map snd steps)+                both = [asWalk (Map.union otherModel model), asWalk (Map.union model otherModel)]+            pure $+              QC.conjoin+                [ QC.counterexample "the copies" (counted QC.=== expectedCounts),+                  QC.counterexample "the walk and the size" ((walked, copyWalked, fromIntegral size) QC.=== (asWalk model, asWalk model, Map.size model)),+                  QC.counterexample "the reads by name" ((found, looked, members) QC.=== (map (`Map.lookup` model) names, map (fmap snd . (`Map.lookup` model)) names, map (`Map.member` model) names)),+                  QC.counterexample "the keys and the map" ((keys, asMap) QC.=== (map symbolText (Map.keys model), Map.fromList [(symbolText name, Thunk value) | (name, (_, value)) <- Map.toList model])),+                  QC.counterexample "the removal" (kept QC.=== asWalk (Map.withoutKeys model (Set.fromList removed))),+                  QC.counterexample "the unions and the updates" ((unions, updates) QC.=== (both, both)),+                  QC.counterexample "mapAttrs" (mapped QC.=== [(name, noPos, value) | (name, (_, value)) <- Map.toAscList model])+                ],+      -- The action answers False the nth time it is asked, so a walk in+      -- lockstep asks of the first n pairs and no more, or of every pair+      -- when the sets end first.+      runTestM "a walk of two sets in lockstep asks of each pair in order and of none past the first it fails" $ do+        pool <- mapM (\i -> symbolIntern ("lockstep_" <> T.pack (show (i :: Int)))) [1 .. 30]+        cells <- mapM textCell ["one", "two"]+        quickCheckPasses $+          QC.forAll ((,,) <$> genValuedInserts pool cells <*> genValuedInserts pool cells <*> QC.chooseInt (1, 40)) $ \(leftInserts, rightInserts, failAt) -> QC.ioProperty $ do+            left <- buildValued leftInserts+            right <- buildValued rightInserts+            let leftEntries = insertsModel leftInserts+                rightEntries = insertsModel rightInserts+            asked <- newIORef []+            let holds pairLeft pairRight = do+                  modifyIORef' asked ((pairLeft, pairRight) :)+                  (/= failAt) . length <$> readIORef asked+                pairs = zip [(name, Thunk value) | (name, _, value) <- leftEntries] [(name, Thunk value) | (name, _, value) <- rightEntries]+            answer <- attrSetAllPairs holds (AttrSet left) (AttrSet right)+            askedPairs <- reverse <$> readIORef asked+            pure $+              (answer, askedPairs)+                QC.=== (failAt > length pairs && length leftEntries == length rightEntries, take failAt pairs)+    ]+  where+    -- A new cell per call, so a lookup's answer identifies the entry it found.+    textCell text = unThunk <$> evaluated (mkStr text)+    quickCheckPasses property = do+      result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} property+      pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))+    entryPositions set = Map.fromList . map (\(name, PosIdx pos, _) -> (name, pos)) <$> walkedEntries set+    genValuedInserts pool values = QC.listOf ((,,) <$> QC.elements pool <*> (PosIdx <$> QC.arbitrary) <*> QC.elements values)+    buildValued inserts = do+      set <- cattrsetNew SetLiteral 0+      mapM_ (\(name, pos, value) -> cattrsetInsert set name pos value) inserts+      cattrsetFreeze set+      pure set+    -- The entries a set built from these inserts holds: the last insert+    -- of each name, in symbol order.+    insertsModel inserts = [(name, pos, value) | (name, (pos, value)) <- Map.toAscList (Map.fromList [(name, (pos, value)) | (name, pos, value) <- inserts])]+    walkedEntries set = cattrsetWalk set >>= walkFrom+    walkFrom walk =+      cattrsetWalkNext walk >>= \case+        CAttrSetDone -> pure []+        CAttrSetEntry name pos value rest -> ((name, pos, value) :) <$> walkFrom rest++-- ---------------------------------------------------------------------------+-- C thunk arena (FFI)+-- ---------------------------------------------------------------------------++testCThunk :: IO [Bool]+testCThunk = do+  putStrLn "cthunk"+  -- Arena is already initialized by main's bracket.+  -- Each test uses the shared arena (thunks accumulate - that's fine).+  sequence+    [ runTestM "new pending + state" $ do+        ptr <- cthunkNewBc 0 pendingEnv+        state <- cthunkState ptr+        pure (assertEqual "state" 0 state),+      runTestM "new computed + state" $ do+        ptr <- cthunkNewComputedInt 7+        state <- cthunkState ptr+        pure (assertEqual "state" 1 state),+      runTestM "payload round-trips (pending)" $ do+        ptr <- cthunkNewBc 0 pendingEnv+        payload <- cthunkPayload ptr+        pure (assertEqual "payload" pendingEnv payload),+      runTestM "an inline value round-trips (computed)" $ do+        ptr <- cthunkNewComputedInt 42+        val <- cthunkGetInt ptr+        pure (assertEqual "value" 42 val),+      runTestM "mark_blackhole succeeds on pending" $ do+        ptr <- cthunkNewBc 0 pendingEnv+        ok <- cthunkMarkBlackhole ptr+        state <- cthunkState ptr+        pure+          ( if ok && state == 2+              then Pass+              else Fail ("ok=" <> T.pack (show ok) <> " state=" <> T.pack (show state))+          ),+      runTestM "mark_blackhole fails on computed" $ do+        ptr <- cthunkNewComputedInt 1+        ok <- cthunkMarkBlackhole ptr+        pure (if not ok then Pass else Fail "should have failed"),+      runTestM "mark_blackhole fails on blackhole" $ do+        ptr <- cthunkNewBc 0 pendingEnv+        _ <- cthunkMarkBlackhole ptr+        ok <- cthunkMarkBlackhole ptr+        pure (if not ok then Pass else Fail "should have failed"),+      runTestM "set_computed stores into a blackhole" $ do+        ptr <- cthunkNewBc 0 pendingEnv+        _ <- cthunkMarkBlackhole ptr+        stored <- cthunkSetComputedInt ptr 5+        state <- cthunkState ptr+        newVal <- cthunkGetInt ptr+        pure+          ( if stored && newVal == 5 && state == 1+              then Pass+              else Fail ("stored=" <> T.pack (show stored) <> " new=" <> T.pack (show newVal) <> " state=" <> T.pack (show state))+          ),+      -- set_computed accepts PENDING (direct memoization, no blackhole step)+      runTestM "set_computed stores into a pending thunk" $ do+        ptr <- cthunkNewBc 0 pendingEnv+        stored <- cthunkSetComputedInt ptr 3+        pure (if stored then Pass else Fail "refused a PENDING thunk"),+      runTestM "set_computed refuses a computed thunk and keeps its value" $ do+        ptr <- cthunkNewComputedInt 1+        stored <- cthunkSetComputedInt ptr 2+        kept <- cthunkGetInt ptr+        pure+          ( if not stored && kept == 1+              then Pass+              else Fail ("stored=" <> T.pack (show stored) <> " kept=" <> T.pack (show kept))+          ),+      -- The shared cells are one static each for the whole process, so a+      -- transition that ran on one would change every null, boolean or+      -- builtin bound under its own name.+      runTestM "the shared null, boolean and builtin cells refuse every transition" $ do+        builtinCells <- mapM (cthunkPrimop . builtinIndex) [Builtin.Abort, Builtin.ZipAttrsWith]+        let cells = [cthunkNull, cthunkBool True, cthunkBool False] ++ builtinCells+        marked <- mapM cthunkMarkBlackhole cells+        stored <- mapM cthunkSetComputedNull cells+        values <- mapM (readThunkValue . Thunk) cells+        let expected = map Just [VNull, VBool True, VBool False, VBuiltin Builtin.Abort [], VBuiltin Builtin.ZipAttrsWith []]+        pure+          ( if not (or (marked ++ stored)) && values == expected+              then Pass+              else Fail ("accepted=" <> T.pack (show (marked, stored)) <> " values=" <> T.pack (show values))+          ),+      -- Past the arena's first block, so allocation chains new ones and+      -- every cell keeps its own value across them.+      runTestM "stress: 100k thunks" $ do+        let values = [1 .. 100000]+        cells <- mapM cthunkNewComputedInt values+        held <- mapM cthunkGetInt cells+        pure (assertEqual "cells holding their own value" (length values) (length (filter id (zipWith (==) held values)))),+      runTestM "every builtin's own cell holds that builtin, with no argument taken" $ do+        held <- mapM (\builtin -> (,) builtin <$> (cthunkPrimop (builtinIndex builtin) >>= readThunkValue . Thunk)) [minBound .. maxBound]+        let wrong = [builtinName builtin | (builtin, value) <- held, value /= Just (VBuiltin builtin [])]+        pure (if null wrong then Pass else Fail ("wrong cells: " <> T.intercalate ", " wrong)),+      runTestM "a builtin value a cell holds reads back as itself, each argument as it was taken" $+        quickCheckPasses $+          QC.forAll genBuiltinValue $ \(builtin, arguments) -> QC.ioProperty $ do+            taken <- traverse takenArgument arguments+            let value = VBuiltin builtin taken+            stored <- evaluated value >>= readThunkValue+            pure (stored QC.=== Just value),+      -- Each binding's thunk memoizes a partial application in its cell:+      -- f holds a function taken forced, g also an argument held as a+      -- thunk, m a pattern, and t is a builtin with nothing taken.  Each+      -- is read back from its cell at every call.+      runTestM "a partial application a binding memoizes is applied as it was taken" $ do+        tmpBase <- getTemporaryDirectory+        result <-+          evalNixIO+            tmpBase+            "let f = builtins.foldl' (a: b: a + b); g = f 10; m = builtins.match \"a(.)\"; t = builtins.tryEval; in [ (g [ 1 2 ]) (g [ ]) (f 0 [ 5 ]) (m \"ab\") (m \"x\") (t (throw \"x\")).success ] == [ 13 10 5 [ \"b\" ] null false ]"+        pure (assertEqual "result" (Right (VBool True)) result),+      runTestM "a handle equals only the C object it names" $ do+        one <- evaluated (VInt 1)+        copy <- evaluated (VInt 1)+        set <- attrSetFromMap SetLiteral (Map.singleton "a" one)+        setCopy <- attrSetFromMap SetLiteral (Map.singleton "a" one)+        list <- clistFromThunks [unThunk one]+        listCopy <- clistFromThunks [unThunk one]+        env <- newEnv EnvClosure Nothing [one]+        envCopy <- newEnv EnvClosure Nothing [one]+        found <- attrSetLookup "a" set+        storedSet <- evaluated (VAttrs set) >>= readThunkValue+        storedList <- evaluated (VList list) >>= readThunkValue+        pure+          ( assertEqual "read back from C" (Just one, Just (VAttrs set), Just (VList list)) (found, storedSet, storedList)+              `andThen` assertEqual "a copy" (False, False, False, False) (one == copy, set == setCopy, list == listCopy, env == envCopy)+          ),+      -- No C object lives at the null address, so a show that read one+      -- would fault here.+      runTest "a handle shows as its address without reading C memory" $+        let address = show (nullPtr :: Ptr ())+         in assertEqual+              "shown"+              ("Thunk {unThunk = " <> address <> "}", "AttrSet {unAttrSet = " <> address <> "}", "CList {unCList = " <> address <> "}", "Env " <> address)+              (show (Thunk nullPtr), show (AttrSet nullPtr), show (CList nullPtr), show (Env nullPtr))+    ]+  where+    -- These cells are never forced, so the shared empty env serves as the+    -- env their code would run in.+    pendingEnv = case emptyEnv of Env envPtr -> castPtr envPtr+    takenArgument (Left n) = pure (ArgForced (VInt n))+    takenArgument (Right n) = ArgDeferred . Thunk <$> cthunkNewComputedInt n+    quickCheckPasses property = do+      result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} property+      pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))++-- | A builtin and the arguments a partial application of it holds: each+-- an integer taken forced ('Left') or held in a cell of its own+-- ('Right').  Up to two, the most any builtin's partial application+-- takes, and any builtin, since a cell holds what it is given.+genBuiltinValue :: QC.Gen (Builtin, [Either Int64 Int64])+genBuiltinValue = do+  builtin <- QC.elements [minBound .. maxBound]+  count <- QC.chooseInt (0, 2)+  arguments <- QC.vectorOf count (QC.oneof [Left <$> QC.arbitrary, Right <$> QC.arbitrary])+  pure (builtin, arguments)++-- ---------------------------------------------------------------------------+-- Bytecode shared across elements+-- ---------------------------------------------------------------------------++-- | The instructions and data words evaluating a source adds to the+-- bytecode store, which only the session's end frees.  The source must+-- evaluate to an integer computed from everything it builds, so each+-- element has been forced when the counts are read.+bytecodeGrowth :: Text -> IO (Either Text (Word32, Word32))+bytecodeGrowth source = do+  opsBefore <- cbcOpCount+  dataBefore <- cbcDataCount+  forced <- case evalNix source of+    Right (VInt n) -> Right <$> evaluate n+    Right other -> pure (Left ("expected an integer, got " <> T.pack (show other)))+    Left err -> pure (Left err)+  opsAfter <- cbcOpCount+  dataAfter <- cbcDataCount+  pure ((opsAfter - opsBefore, dataAfter - dataBefore) <$ forced)++-- | A source builds one element or two hundred, and the bytecode it adds+-- is the same: the code each element runs is shared, never compiled per+-- element.  A first run at one element is discarded, so anything compiled+-- once per process is not counted against either size.+assertNoPerElementBytecode :: (Text -> Text) -> IO TestResult+assertNoPerElementBytecode sourceFor = do+  _ <- bytecodeGrowth (sourceFor "1")+  one <- bytecodeGrowth (sourceFor "1")+  many <- bytecodeGrowth (sourceFor "200")+  pure $ case (one, many) of+    (Right atOne, Right atMany) ->+      assertEqual "instructions and data words added at 1 element and at 200" atOne atMany+    (Left err, _) -> Fail err+    (_, Left err) -> Fail err++testBytecodePerElement :: IO [Bool]+testBytecodePerElement = do+  putStrLn "bytecode/per-element"+  let summed body n = "builtins.foldl' (a: b: a + b) 0 (" <> body n <> ")"+      indices n = "builtins.genList (i: i) " <> n+  sequence+    [ runTestM "map adds no bytecode per element" $+        assertNoPerElementBytecode (summed (\n -> "builtins.map (x: x + 1) (" <> indices n <> ")")),+      runTestM "genList adds no bytecode per element" $+        assertNoPerElementBytecode (summed ("builtins.genList (i: i * 2) " <>)),+      runTestM "concatMap adds no bytecode per element" $+        assertNoPerElementBytecode (summed (\n -> "builtins.concatMap (x: [ x x ]) (" <> indices n <> ")")),+      runTestM "mapAttrs adds no bytecode per attribute" $+        assertNoPerElementBytecode+          ( summed+              (\n -> "builtins.attrValues (builtins.mapAttrs (name: v: v + 1) (builtins.listToAttrs (builtins.genList (i: { name = toString i; value = i; }) " <> n <> ")))")+          ),+      runTestM "zipAttrsWith adds no bytecode per attribute" $+        assertNoPerElementBytecode+          ( summed+              (\n -> "builtins.attrValues (builtins.zipAttrsWith (name: vs: builtins.length vs) (builtins.genList (i: { ${toString i} = i; }) " <> n <> "))")+          ),+      runTestM "inherit (from) in an attr set adds no bytecode per evaluation" $+        assertNoPerElementBytecode (summed ("builtins.genList (i: { inherit ({ v = i; }) v; }.v) " <>)),+      runTestM "inherit (from) in a recursive attr set adds no bytecode per evaluation" $+        assertNoPerElementBytecode (summed ("builtins.genList (i: rec { inherit ({ v = i; }) v; }.v) " <>)),+      runTestM "inherit (from) in a let adds no bytecode per evaluation" $+        assertNoPerElementBytecode (summed ("builtins.genList (i: let inherit ({ v = i; }) v; in v) " <>))+    ]++-- | Bytecode short_arg spill: op-level payload counts at or above the+-- 0xFFFF sentinel move to the first data word, so literals are not+-- capped at 65535 elements.  The two exact-boundary list cases pin the+-- inline maximum (65534) and the first spilled count (65535); the rest+-- drive each counted-op kind (list, attrs, let, string parts, attr path)+-- well past the inline maximum.+testBytecodeCountSpill :: IO [Bool]+testBytecodeCountSpill = do+  putStrLn "bytecode/count-spill"+  let listOf n = "builtins.length [ " <> T.unwords (replicate n "1") <> " ]"+      bigAttrsBody = T.concat [T.pack ("a" <> show i <> " = " <> show i <> "; ") | i <- [0 :: Int .. 69999]]+  sequence+    [ runTest "list literal at the inline count maximum (65534)" $+        assertEval "spill-list-inline-max" (listOf 65534) (VInt 65534),+      runTest "list literal at the first spilled count (65535)" $+        assertEval "spill-list-first-spill" (listOf 65535) (VInt 65535),+      runTest "spilled list preserves element order" $+        assertEval+          "spill-list-order"+          ("builtins.elemAt [ " <> T.unwords (map (T.pack . show) [0 :: Int .. 69999]) <> " ] 69999")+          (VInt 69999),+      runTest "spilled attrset literal binds every attribute" $+        assertEval+          "spill-attrs-count"+          ("builtins.length (builtins.attrNames { " <> bigAttrsBody <> "})")+          (VInt 70000),+      runTest "spilled attrset lookup reads the right value" $+        assertEval+          "spill-attrs-lookup"+          ("{ " <> bigAttrsBody <> "}.a69999")+          (VInt 69999),+      runTest "spilled let binds every name" $+        assertEval+          "spill-let"+          ("let " <> T.concat [T.pack ("v" <> show i <> " = " <> show i <> "; ") | i <- [0 :: Int .. 69999]] <> "in v69999")+          (VInt 69999),+      runTest "spilled interpolated string keeps every part" $+        assertEval+          "spill-string-parts"+          ("builtins.stringLength \"" <> T.concat (replicate 70000 "${\"x\"}") <> "\"")+          (VInt 70000),+      runTest "spilled attr path walks (set ? long.path)" $+        assertEval+          "spill-attrpath"+          ("{ } ? " <> T.intercalate "." (map (\i -> T.pack ("p" <> show i)) [0 :: Int .. 69999]))+          (VBool False)+    ]++-- | C value structs carry element counts as a full uint32; a narrower+-- count would wrap at 65536 and size the C array smaller than the fill+-- loop that follows it.  Both cases marshal counts past that boundary+-- and force the value twice - the first force writes the C struct (the+-- marshal side), the second reads it back off the computed thunk cell+-- (the unmarshal side).+testValueCountWidths :: IO [Bool]+testValueCountWidths = do+  putStrLn "value/count-widths"+  let formalsBody = T.intercalate ", " [T.pack ("a" <> show i) | i <- [0 :: Int .. 69999]]+  sequence+    [ runTest "lambda with 70000 formals round-trips through the C closure" $+        assertEval+          "width-lambda-formals"+          ( "let f = { "+              <> formalsBody+              <> " }: 1; in builtins.seq (builtins.functionArgs f) (builtins.length (builtins.attrNames (builtins.functionArgs f)))"+          )+          (VInt 70000),+      runTest "string context with 70000 elements round-trips through the C thunk" $+        assertEval+          "width-ctxstr-elems"+          ( "let s = builtins.appendContext \"x\" (builtins.listToAttrs (builtins.genList (i: { "+              <> "name = \"/nix/store/00000000000000000000000000000000-p\" + builtins.toString i; "+              <> "value = { path = true; }; }) 70000)); "+              <> "in builtins.seq s (builtins.length (builtins.attrNames (builtins.getContext s)))"+          )+          (VInt 70000)+    ]++-- ---------------------------------------------------------------------------+-- Bytecode tags: what the compiler writes decodes back, and nothing else does+-- ---------------------------------------------------------------------------++-- | Where an operator's tag pair fails to be inverses: each operator whose+-- tag decodes to something else, then each byte that decodes to an+-- operator written as another byte.  Every constructor and every byte is+-- checked, as both domains are finite.+operatorTagMismatches :: (Bounded op, Enum op, Eq op, Show op) => (op -> Word8) -> (Word8 -> Maybe op) -> [Text]+operatorTagMismatches encode decode =+  [ T.pack (show op) <> " reads back from its tag as " <> T.pack (show (decode (encode op)))+  | op <- [minBound .. maxBound],+    decode (encode op) /= Just op+  ]+    ++ [ "byte " <> T.pack (show tag) <> " reads as " <> T.pack (show op) <> ", which is written as " <> T.pack (show (encode op))+       | tag <- [minBound .. maxBound],+         Just op <- [decode tag],+         encode op /= tag+       ]++-- | A compiled child read back as the expression the round trips below+-- compile it from: an integer literal or a resolved variable.  Any other+-- opcode reads as a variable naming it, which nothing generated equals.+childExpr :: Word32 -> IO Expr+childExpr idx = do+  op <- cbcOpcode idx+  lo <- cbcArg1 idx+  hi <- cbcArg2 idx+  pure $ case op of+    OpLitInt -> ELit (NixInt (reassembleInt64 lo hi))+    OpResolvedVar -> EResolvedVar (fromIntegral lo) (fromIntegral hi)+    _ -> EVar ("<opcode " <> T.pack (show op) <> ">")++-- | A recorded position read back in the test origin.  One that does not+-- read back as text reads as line 0, which nothing generated has.+srcPosBack :: PosIdx -> IO SrcPos+srcPosBack idx =+  lookupPos idx <&> \case+    Just (PosInText line column) -> testPos line column+    _ -> testPos 0 0++-- | Decoded formals read back as the parser's formals they compile from.+formalsBack :: EvalFormals -> IO Formals+formalsBack formals = case formals of+  EFName name -> pure (FormalName (symbolText name))+  EFSet _ entries ellipsis -> do+    back <- traverse formalBack entries+    pure (FormalSet back ellipsis)+  EFNamedSet _ name entries ellipsis -> do+    back <- traverse formalBack entries+    pure (FormalNamedSet (symbolText name) back ellipsis)+  where+    formalBack (EvalFormal name def) = Formal (symbolText name) <$> traverse childExpr (defaultCode def)+    defaultCode = \case+      NoDefault -> Nothing+      Default code -> Just code+      SharedDefault code -> Just code++-- | A binding read from the bytecode read back as the binding it compiles+-- from.  An inherited name's select is the compiler's own and has no+-- counterpart.+bindingBack :: BcBinding -> IO Binding+bindingBack binding = case binding of+  BcNamed pos sym valIdx -> NamedBinding <$> srcPosBack pos <*> pure (StaticKey (symbolText (Symbol sym))) <*> childExpr valIdx+  BcDynamic pos keyIdx valIdx -> NamedBinding <$> srcPosBack pos <*> (DynamicKey <$> childExpr keyIdx) <*> childExpr valIdx+  BcInherit pos sym valIdx -> Inherit <$> srcPosBack pos <*> pure (symbolText (Symbol sym)) <*> childExpr valIdx+  BcInheritFrom fromIdx names -> do+    from <- childExpr fromIdx+    inherited <- inheritedNameList names+    InheritFrom from <$> sequence [(`InheritedName` symbolText (Symbol sym)) <$> srcPosBack pos | BcInheritedName pos sym _ <- inherited]++-- | Capture info read from the bytecode read back as the capture info it+-- compiles from.+capturesBack :: BcCaptureInfo -> IO CaptureInfo+capturesBack info = case info of+  BcNoCaptureInfo -> pure NoCaptureInfo+  BcCaptures slots -> Captures <$> capturedPairs slots+  BcCapturesWithScopes slots -> CapturesWithScopes <$> capturedPairs slots+  where+    capturedPairs slots = reverse <$> foldBcCapturedSlots (\acc level idx -> pure ((fromIntegral level, fromIntegral idx) : acc)) [] slots++-- | Bindings in source order, or the first binding tag the compiler never+-- writes.+bindingList :: BcBindings -> IO (Either Word32 [BcBinding])+bindingList = fmap (fmap reverse) . foldBcBindings (pure . Left) (\acc binding -> pure ((binding :) <$> acc)) (Right [])++-- | The names of an @inherit (from)@ binding in source order.+inheritedNameList :: BcInheritedNames -> IO [BcInheritedName]+inheritedNameList = fmap reverse . foldBcInheritedNames (\acc name -> pure (name : acc)) []++-- | A closure keeps its formals type, ellipsis flag and formal count in+-- one word (cbits/nn_lambda.h): the type in the top two bits, the flag+-- below it and the count in the 29 bits left.  Each field reads back as+-- packed at both ends of its range, and a count the word cannot hold is+-- refused before anything is allocated.+testLambdaShape :: IO [Bool]+testLambdaShape = do+  putStrLn "cbits/lambda-shape"+  let maxFormals = clambdaShapeFormalCount maxBound+      unpack shape = (clambdaShapeFormalsType shape, clambdaShapeAllowExtra shape, clambdaShapeFormalCount shape)+      fields = [(formalsType, flag, count) | formalsType <- [0, 1, 2], flag <- [0, 1], count <- [0, 1, maxFormals - 1, maxFormals]]+  sequence+    [ runTest "the count takes the 29 bits below the flag" $+        assertEqual "largest count" (2 ^ (29 :: Int) - 1) maxFormals,+      runTest "every type and flag with a count at either end of its range reads back as packed" $+        assertEqual "mismatches" [] [packed | packed@(formalsType, flag, count) <- fields, unpack (clambdaShape formalsType flag count) /= packed],+      runTest "a nonzero flag packs as 1" $+        assertEqual "flag" 1 (clambdaShapeAllowExtra (clambdaShape 2 255 0)),+      runTestM "a closure reads back the shape it was made with" $ do+        lam <- clambdaNew nullPtr 0 2 0 0 1 3+        formalsType <- clambdaFormalsType lam+        flag <- clambdaAllowExtra lam+        count <- clambdaFormalCount lam+        pure (assertEqual "shape" (2, 1, 3) (formalsType, flag, count)),+      runTestM "a count the shape cannot hold is refused" $ do+        outcomes <-+          mapM+            try+            [ clambdaNew nullPtr 0 1 0 0 0 (maxFormals + 1),+              clambdaNew nullPtr 0 1 0 0 0 maxBound+            ]+        let site = \case+              Left (CAllocationFailed at _) -> Just at+              _ -> Nothing+        pure (assertEqual "refusals" (replicate 2 (Just "nn_lambda_new")) (map site outcomes))+    ]++-- | A closure's formals type, a formal's default kind and a string+-- context element's tag each hold one of the values the C side names+-- (@NN_FORMALS_*@, the kinds cbits/nn_lambda.h lists for a formal entry,+-- and @NN_SCE_*@).  Only memory written past the library holds another,+-- so each test writes one in place, at the field's offset in the struct+-- cbits/nn_lambda.h or cbits/nn_ctxstr.h lays out, and restores the+-- field once the read has refused it.+testUnknownTags :: IO [Bool]+testUnknownTags = do+  putStrLn "cbits/unknown-tags"+  sequence+    [ runTestM "a closure whose shape holds no formals type raises CInvariantViolated" $ do+        name <- symbolIntern "x"+        cell <- evaluated (VLambda emptyEnv (EFName name) 0)+        lam <- cthunkPayload (unThunk cell)+        outcome <- withFieldAt lam lambdaShapeOffset (clambdaShape unnamedTag 0 0) (readComputed (unThunk cell))+        pure (assertEqual "site" (Just "nn_lambda_formals_type") (violatedAt outcome)),+      runTestM "a closure whose formal holds no default kind raises CInvariantViolated" $ do+        name <- symbolIntern "x"+        cell <- evaluated (VLambda emptyEnv (EFSet AnonymousLambda [EvalFormal name NoDefault] False) 0)+        lam <- cthunkPayload (unThunk cell)+        entries <- peekByteOff lam pointerBytes+        outcome <- withFieldAt entries entryKindOffset (unknownTag :: Word32) (readComputed (unThunk cell))+        pure (assertEqual "site" (Just "nn_lambda_entry_kind") (violatedAt outcome)),+      runTestM "a string context element with no known tag raises CInvariantViolated" $ do+        cell <- evaluated (VStr "ztext" (StringContext (Set.singleton (SCPlain (StorePath censusStoreHash "zname")))))+        ctxstr <- cthunkPayload (unThunk cell)+        outcome <- withFieldAt ctxstr firstElementOffset unnamedTag (readComputed (unThunk cell))+        pure (assertEqual "site" (Just "nn_ctxstr_elem_tag") (violatedAt outcome))+    ]+  where+    -- No NN_FORMALS_* or NN_SCE_* tag is 3, the one value of a shape's+    -- two bits of formals type the tags leave unnamed.+    unnamedTag = 3 :: Word8+    pointerBytes = sizeOf (nullPtr :: Ptr ())+    -- An nn_lambda_t's shape follows its two pointers and three words,+    -- and its entries are its second pointer.+    lambdaShapeOffset = 2 * pointerBytes + 3 * sizeOf (0 :: Word32)+    -- A formal entry's kind follows its name's symbol.+    entryKindOffset = sizeOf (0 :: Word32)+    -- An nn_ctxstr_t's elements follow its text pointer and its count,+    -- padded to their pointer alignment, and an element's tag is its+    -- first byte.+    firstElementOffset = 2 * pointerBytes+    withFieldAt :: (Storable a) => Ptr () -> Int -> a -> IO b -> IO (Either CStatusError b)+    withFieldAt ptr offset value act = do+      original <- peekByteOff ptr offset+      pokeByteOff ptr offset (value `asTypeOf` original)+      try act `finally` pokeByteOff ptr offset original+    violatedAt = \case+      Left (CInvariantViolated site _) -> Just site+      _ -> Nothing++testBytecodeTags :: IO [Bool]+testBytecodeTags = do+  putStrLn "bytecode/tags"+  sequence+    [ runTest "every unary operator's tag reads back as it, and no other byte reads as an operator" $+        assertEqual "mismatches" [] (operatorTagMismatches encodeUnaryOp decodeUnaryOp),+      runTest "every binary operator's tag reads back as it, and no other byte reads as an operator" $+        assertEqual "mismatches" [] (operatorTagMismatches encodeBinaryOp decodeBinaryOp),+      runTestM "a compiled lambda's formals and capture info read back as compiled" . quickCheckPasses $+        QC.forAll ((,) <$> genFormals <*> genCaptureInfo) $ \(formals, captures) -> QC.ioProperty $ do+          idx <- compileExpr (ELambda formals (ELit NixNull) captures)+          flags <- cbcFlags idx+          formalsOff <- cbcArg1 idx+          captureOff <- cbcArg3 idx+          decodedFormals <- decodeFormals flags formalsOff >>= traverse formalsBack+          decodedCaptures <- decodeBcCaptureInfo captureOff >>= traverse capturesBack+          pure ((decodedFormals, decodedCaptures) QC.=== (Just formals, Right captures)),+      runTestM "a lambda stored in a cell reads back with the symbols it was stored with" . quickCheckPasses $+        QC.forAll ((,) <$> genFormals <*> QC.oneof [pure Nothing, Just <$> genName]) $ \(formals, binding) -> QC.ioProperty $ do+          name <- maybe (pure AnonymousLambda) (fmap NamedLambda . symbolIntern) binding+          lambda <- (\stored -> VLambda emptyEnv stored 0) . namedBy name <$> compileFormalsToEval formals+          cell <- evaluated lambda+          (QC.=== lambda) <$> readComputed (unThunk cell),+      -- Upstream's addAttr in parser-state.hh names the function an+      -- attribute path's last name binds, and ExprLambda::setName in+      -- nixexpr.cc the function that is its body.+      runTestM "a set pattern bound to a static name reads back named, as does the one its body is" $ do+        let inner = ELambda (FormalSet [Formal "a" Nothing] False) (ELit NixNull) NoCaptureInfo+            outer = ELambda (FormalNamedSet "args" [] True) inner NoCaptureInfo+            boundBy key = ELet [NamedBinding (testPos 1 1) key outer] (ELit NixNull) NoCaptureInfo+            -- The two names a binding's lambda and its body decode with.+            lambdaNames expr = do+              bindings <- compileExpr expr >>= compiledBindings >>= bindingList+              case bindings of+                Right [binding]+                  | Just outerIdx <- boundValue binding -> do+                      outerFormals <- formalsAt outerIdx+                      innerFormals <- formalsAt =<< cbcArg2 outerIdx+                      pure (lambdaNameOf =<< outerFormals, lambdaNameOf =<< innerFormals)+                _ -> pure (Nothing, Nothing)+            -- The value a static or a dynamic name is bound to.+            boundValue = \case+              BcNamed _ _ valIdx -> Just valIdx+              BcDynamic _ _ valIdx -> Just valIdx+              _ -> Nothing+            formalsAt idx = do+              flags <- cbcFlags idx+              decodeFormals flags =<< cbcArg1 idx+            lambdaNameOf = \case+              EFSet name _ _ -> Just name+              EFNamedSet name _ _ _ -> Just name+              EFName _ -> Nothing+        named <- lambdaNames (boundBy (StaticKey "f"))+        dynamic <- lambdaNames (boundBy (DynamicKey (ELit (NixInt 0))))+        bare <- formalsAt =<< compileExpr inner+        f <- NamedLambda <$> symbolIntern "f"+        pure $+          assertEqual "static" (Just f, Just f) named+            `andThen` assertEqual "dynamic" (Just AnonymousLambda, Just AnonymousLambda) dynamic+            `andThen` assertEqual "unbound" (Just AnonymousLambda) (lambdaNameOf =<< bare),+      runTestM "a compiled let's bindings, their counts and its capture info read back as compiled" . quickCheckPasses $+        QC.forAll ((,) <$> QC.listOf genBinding <*> genCaptureInfo) $ \(bindings, captures) -> QC.ioProperty $ do+          idx <- compileExpr (ELet bindings (ELit NixNull) captures)+          compiled@(BcBindings (BcBindingCounts names dynamics) _ _ _) <- compiledBindings idx+          decodedBindings <- bindingList compiled >>= traverse (traverse bindingBack)+          decodedCaptures <- cbcArg3 idx >>= decodeBcCaptureInfo >>= traverse capturesBack+          pure ((decodedBindings, (names, dynamics), decodedCaptures) QC.=== (Right bindings, nameCounts bindings, Right captures))+    ]+  where+    -- A set pattern under the name a binding gives it.+    namedBy name = \case+      EFSet _ entries ellipsis -> EFSet name entries ellipsis+      EFNamedSet _ arg entries ellipsis -> EFNamedSet name arg entries ellipsis+      plain@(EFName _) -> plain+    -- The names bindings bind statically, one per static key, inherited+    -- variable and inherited name, and the bindings with a dynamic name.+    nameCounts bindings = (sum (map staticNames bindings), length [() | NamedBinding _ (DynamicKey _) _ <- bindings])+    staticNames = \case+      NamedBinding _ (StaticKey _) _ -> 1+      NamedBinding _ (DynamicKey _) _ -> 0+      Inherit {} -> 1+      InheritFrom _ inherited -> length inherited+    quickCheckPasses property = do+      result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} property+      pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))+    genName = QC.elements ["a", "b", "x", "self", "args"]+    genChild =+      QC.oneof+        [ ELit . NixInt <$> QC.arbitrary,+          EResolvedVar <$> QC.chooseInt (0, 8) <*> QC.chooseInt (0, 64)+        ]+    genPos = testPos <$> QC.chooseInt (1, 4096) <*> QC.chooseInt (1, 4096)+    genCaptureInfo =+      let pairs = QC.listOf ((,) <$> QC.chooseInt (0, 64) <*> QC.chooseInt (0, 4096))+       in QC.oneof [pure NoCaptureInfo, Captures <$> pairs, CapturesWithScopes <$> pairs]+    genFormals =+      let entries = QC.listOf (Formal <$> genName <*> QC.oneof [pure Nothing, Just <$> genChild])+       in QC.oneof+            [ FormalName <$> genName,+              FormalSet <$> entries <*> QC.arbitrary,+              FormalNamedSet <$> genName <*> entries <*> QC.arbitrary+            ]+    genBinding =+      QC.oneof+        [ NamedBinding <$> genPos <*> QC.oneof [StaticKey <$> genName, DynamicKey <$> genChild] <*> genChild,+          Inherit <$> genPos <*> genName <*> genChild,+          InheritFrom <$> genChild <*> QC.listOf (InheritedName <$> genPos <*> genName)+        ]++-- | A tag none of the compiler's encoders writes, in any of the fields the+-- corrupt-bytecode tests put it in.+unknownTag :: (Num a) => a+unknownTag = 200++-- | Whether hand-built code at a bytecode index fails to evaluate with the+-- corrupt-bytecode error for @what@ holding 'unknownTag'.+assertCorruptBytecode :: Text -> Word32 -> IO TestResult+assertCorruptBytecode what = assertCorruptBytecodeAt what unknownTag++-- | Whether hand-built code at a bytecode index fails to evaluate with the+-- corrupt-bytecode error for @what@ holding @value@.  The outcome, and a+-- value it holds (which the failure message shows), are forced inside the+-- action, so an exception a decoder raises instead, as the evaluator runs+-- or once the value is inspected, reaches 'runTestM' as a failure rather+-- than escaping after it.+assertCorruptBytecodeAt :: Text -> Int -> Word32 -> IO TestResult+assertCorruptBytecodeAt what value idx = do+  outcome <- evaluate (runPureEval (evalBytecode emptyEnv idx))+  evaluate $ case outcome of+    Left err -> assertEqual "error" ("corrupt bytecode: unknown " <> what <> " " <> T.pack (show value)) err+    Right val -> Fail ("expected the corrupt-bytecode error but got: " <> T.pack (show val))++testBytecodeCorrupt :: IO [Bool]+testBytecodeCorrupt = do+  putStrLn "bytecode/corrupt"+  sequence+    [ runTestM "an unknown opcode is a corrupt-bytecode error" $+        cbcEmit unknownTag 0 0 0 0 0 >>= assertCorruptBytecode "opcode",+      runTestM "an unknown unary operator tag is a corrupt-bytecode error" $ do+        operand <- literalOne+        cbcEmit OpUnary unknownTag 0 operand 0 0 >>= assertCorruptBytecode "unary operator tag",+      runTestM "an unknown binary operator tag is a corrupt-bytecode error" $ do+        left <- literalOne+        right <- literalOne+        cbcEmit OpBinary unknownTag 0 left right 0 >>= assertCorruptBytecode "binary operator tag",+      runTestM "an unknown formals type is a corrupt-bytecode error" $+        lambdaWith unknownTag captureNone >>= assertCorruptBytecode "formals type",+      runTestM "an unknown capture info tag in a lambda is a corrupt-bytecode error" $+        lambdaWith formalName unknownTag >>= assertCorruptBytecode "capture info tag",+      runTestM "an unknown capture info tag in a recursive attribute set is a corrupt-bytecode error" $ do+        bindingsOff <- bindingWords []+        captureOff <- cbcEmitData unknownTag+        cbcEmit OpAttrs 1 0 bindingsOff captureOff 0 >>= assertCorruptBytecode "capture info tag",+      runTestM "an unknown binding tag in an attribute set is a corrupt-bytecode error" $ do+        bindingsOff <- bindingWords [unknownTag]+        cbcEmit OpAttrs 0 1 bindingsOff 0 0 >>= assertCorruptBytecode "binding tag",+      runTestM "an unknown attribute set flag is a corrupt-bytecode error" $ do+        bindingsOff <- bindingWords []+        cbcEmit OpAttrs unknownTag 0 bindingsOff 0 0 >>= assertCorruptBytecode "attribute set flag",+      runTestM "an unknown binding tag in a let is a corrupt-bytecode error" $ do+        bindingsOff <- bindingWords [unknownTag]+        captureOff <- cbcEmitData captureNone+        body <- literalOne+        cbcEmit OpLet 0 1 bindingsOff body captureOff >>= assertCorruptBytecode "binding tag",+      -- A let of one slot, which no binding fills, with one share.+      runTestM "a share naming a slot past its frame is a corrupt-bytecode error" $ do+        let sharing slot target = do+              bindingsOff <- dataWords 1 [0, 1, slot, target]+              captureOff <- cbcEmitData captureNone+              body <- literalOne+              cbcEmit OpLet 0 0 bindingsOff body captureOff+        sharer <- sharing unknownTag 0 >>= assertCorruptBytecode "share slot"+        shared <- sharing 0 unknownTag >>= assertCorruptBytecode "share slot"+        pure (sharer `andThen` shared),+      -- A recursive set whose counts give it a dynamic name, so its names+      -- are in a name table, and whose one binding is a static name.+      runTestM "a share naming a symbol its frame does not bind is a corrupt-bytecode error" $ do+        Symbol bound <- symbolIntern "zcorruptBound"+        let sharing name target = do+              value <- literalOne+              bindingsOff <- dataWords 1 [1, 1, name, target, bindNamed, attrkeyStatic, bound, value, 0]+              captureOff <- cbcEmitData captureNone+              cbcEmit OpAttrs attrsRec 1 bindingsOff captureOff 0+        sharer <- sharing unknownTag bound >>= assertCorruptBytecode "share symbol"+        shared <- sharing bound unknownTag >>= assertCorruptBytecode "share symbol"+        pure (sharer `andThen` shared),+      runTestM "an unknown formal default kind is a corrupt-bytecode error" $ do+        Symbol name <- symbolIntern "zcorruptFormal"+        body <- literalOne+        formalsOff <- dataWords invalidSymbolId [1, 0, name, unknownTag, body]+        captureOff <- cbcEmitData captureNone+        cbcEmit OpLambda formalSet 0 formalsOff body captureOff >>= assertCorruptBytecode "formal default kind",+      -- Two formals whose defaults each share the other's slot, called+      -- with an argument that holds neither.  The walk from slot 0 passes+      -- through both formals' defaults and fails on slot 1, the next.+      runTestM "a cycle of shared defaults is a corrupt-bytecode error" $ do+        Symbol first <- symbolIntern "zcycleFirst"+        Symbol second <- symbolIntern "zcycleSecond"+        toSecond <- cbcEmit OpResolvedVar 0 0 0 1 0+        toFirst <- cbcEmit OpResolvedVar 0 0 0 0 0+        body <- literalOne+        formalsOff <- dataWords invalidSymbolId [2, 0, first, formalSharedDefault, toSecond, second, formalSharedDefault, toFirst]+        captureOff <- cbcEmitData captureNone+        lambda <- cbcEmit OpLambda formalSet 0 formalsOff body captureOff+        argument <- bindingWords [] >>= \bindingsOff -> cbcEmit OpAttrs 0 0 bindingsOff 0 0+        cbcEmit OpApp 0 0 lambda argument 0 >>= assertCorruptBytecodeAt "shared default slot" 1+    ]+  where+    literalOne = cbcEmit OpLitInt 0 0 1 0 0+    -- Data words built by hand, first to last; answers the offset of the+    -- first.+    dataWords firstWord rest = cbcEmitData firstWord <* mapM_ cbcEmitData rest+    -- @x: 1@, built by hand with the given formals type and capture tag.+    lambdaWith formalsType captureTag = do+      Symbol name <- symbolIntern "x"+      formalsOff <- cbcEmitData name+      captureOff <- cbcEmitData captureTag+      body <- literalOne+      cbcEmit OpLambda formalsType 0 formalsOff body captureOff+    -- A binding list's words, built by hand: its three counts zero, then+    -- the words given.  Answers the offset of the first.+    bindingWords = dataWords 0 . (0 :) . (0 :)++-- | An inherited name and whether its select reads that name, as the one+-- path segment, from slot 0 of the env it runs in.+inheritedSelect :: BcInheritedName -> IO (Text, Bool)+inheritedSelect (BcInheritedName _ sym selectIdx) = do+  op <- cbcOpcode selectIdx+  pathLen <- cbcShortArg selectIdx+  target <- cbcArg1 selectIdx+  pathOff <- cbcArg2 selectIdx+  targetOp <- cbcOpcode target+  level <- cbcArg1 target+  slot <- cbcArg2 target+  keyTag <- cbcData pathOff+  keySym <- cbcData (pathOff + 1)+  pure+    ( symbolText (Symbol sym),+      op == OpSelect && pathLen == 1 && targetOp == OpResolvedVar && level == 0 && slot == 0 && keyTag == attrkeyStatic && keySym == sym+    )++testBytecodeCompile :: IO [Bool]+testBytecodeCompile = do+  putStrLn "bytecode"+  -- Arena (including bytecode store) already initialized by main's bracket.+  sequence+    [ runTestM "compile ELit NixInt" $ do+        idx <- compileExpr (ELit (NixInt 42))+        op <- cbcOpcode idx+        a1 <- cbcArg1 idx+        a2 <- cbcArg2 idx+        pure+          ( if op == OpLitInt && a1 == 42 && a2 == 0+              then Pass+              else Fail ("op=" <> T.pack (show op) <> " a1=" <> T.pack (show a1))+          ),+      runTestM "compile ELit NixInt negative" $ do+        idx <- compileExpr (ELit (NixInt (-1)))+        op <- cbcOpcode idx+        a1 <- cbcArg1 idx+        a2 <- cbcArg2 idx+        -- -1 as uint64 = 0xFFFFFFFFFFFFFFFF, lo=0xFFFFFFFF, hi=0xFFFFFFFF+        pure+          ( if op == OpLitInt && a1 == 0xFFFFFFFF && a2 == 0xFFFFFFFF+              then Pass+              else+                Fail+                  ( "a1="+                      <> T.pack (show a1)+                      <> " a2="+                      <> T.pack (show a2)+                  )+          ),+      runTestM "compile ELit NixBool" $ do+        idxT <- compileExpr (ELit (NixBool True))+        idxF <- compileExpr (ELit (NixBool False))+        opT <- cbcOpcode idxT+        opF <- cbcOpcode idxF+        saT <- cbcShortArg idxT+        saF <- cbcShortArg idxF+        pure+          ( if opT == OpLitBool && saT == 1 && opF == OpLitBool && saF == 0+              then Pass+              else Fail "bool encoding mismatch"+          ),+      runTestM "compile ELit NixNull" $ do+        idx <- compileExpr (ELit NixNull)+        op <- cbcOpcode idx+        pure (assertEqual "opcode" OpLitNull op),+      runTestM "compile EResolvedVar" $ do+        idx <- compileExpr (EResolvedVar 3 7)+        op <- cbcOpcode idx+        a1 <- cbcArg1 idx+        a2 <- cbcArg2 idx+        pure+          ( if op == OpResolvedVar && a1 == 3 && a2 == 7+              then Pass+              else+                Fail+                  ( "op="+                      <> T.pack (show op)+                      <> " a1="+                      <> T.pack (show a1)+                      <> " a2="+                      <> T.pack (show a2)+                  )+          ),+      runTestM "compile EVar" $ do+        idx <- compileExpr (EVar "hello")+        op <- cbcOpcode idx+        sym <- cbcArg1 idx+        let symText = symbolText (Symbol sym)+        pure+          ( if op == OpVar && symText == "hello"+              then Pass+              else Fail ("op=" <> T.pack (show op) <> " sym=" <> symText)+          ),+      runTestM "compile EApp" $ do+        idx <- compileExpr (EApp (EVar "f") (ELit (NixInt 1)))+        op <- cbcOpcode idx+        funcIdx <- cbcArg1 idx+        argIdx <- cbcArg2 idx+        funcOp <- cbcOpcode funcIdx+        argOp <- cbcOpcode argIdx+        pure+          ( if op == OpApp && funcOp == OpVar && argOp == OpLitInt+              then Pass+              else+                Fail+                  ( "op="+                      <> T.pack (show op)+                      <> " funcOp="+                      <> T.pack (show funcOp)+                      <> " argOp="+                      <> T.pack (show argOp)+                  )+          ),+      runTestM "compile EIf" $ do+        idx <-+          compileExpr+            (EIf (ELit (NixBool True)) (ELit (NixInt 1)) (ELit (NixInt 2)))+        op <- cbcOpcode idx+        condIdx <- cbcArg1 idx+        thenIdx <- cbcArg2 idx+        elseIdx <- cbcArg3 idx+        condOp <- cbcOpcode condIdx+        thenA1 <- cbcArg1 thenIdx+        elseA1 <- cbcArg1 elseIdx+        pure+          ( if op == OpIf && condOp == OpLitBool && thenA1 == 1 && elseA1 == 2+              then Pass+              else Fail "if structure mismatch"+          ),+      runTestM "compile EBinary" $ do+        idx <-+          compileExpr+            (EBinary OpAdd (ELit (NixInt 10)) (ELit (NixInt 20)))+        op <- cbcOpcode idx+        fl <- cbcFlags idx+        leftIdx <- cbcArg1 idx+        rightIdx <- cbcArg2 idx+        leftA1 <- cbcArg1 leftIdx+        rightA1 <- cbcArg1 rightIdx+        pure+          ( if op == OpBinary && fl == binaryAdd && leftA1 == 10 && rightA1 == 20+              then Pass+              else Fail "binary structure mismatch"+          ),+      runTestM "compile EUnary" $ do+        idx <- compileExpr (EUnary OpNegate (ELit (NixInt 5)))+        op <- cbcOpcode idx+        fl <- cbcFlags idx+        operandIdx <- cbcArg1 idx+        operandA1 <- cbcArg1 operandIdx+        pure+          ( if op == OpUnary && fl == unaryNegate && operandA1 == 5+              then Pass+              else Fail "unary structure mismatch"+          ),+      runTestM "compile EList" $ do+        idx <-+          compileExpr+            (EList [ELit (NixInt 1), ELit (NixInt 2), ELit (NixInt 3)])+        op <- cbcOpcode idx+        count <- cbcShortArg idx+        dataOff <- cbcArg1 idx+        c0 <- cbcData dataOff+        c1 <- cbcData (dataOff + 1)+        c2 <- cbcData (dataOff + 2)+        c0a1 <- cbcArg1 c0+        c1a1 <- cbcArg1 c1+        c2a1 <- cbcArg1 c2+        pure+          ( if op == OpList && count == 3 && c0a1 == 1 && c1a1 == 2 && c2a1 == 3+              then Pass+              else+                Fail+                  ( "op="+                      <> T.pack (show op)+                      <> " count="+                      <> T.pack (show count)+                  )+          ),+      runTestM "compile EStr with interpolation" $ do+        idx <-+          compileExpr+            (EStr [StrLit "hello ", StrInterp (EVar "name"), StrLit "!"])+        op <- cbcOpcode idx+        count <- cbcShortArg idx+        dataOff <- cbcArg1 idx+        -- 3 parts x 2 words each = 6 data words+        tag0 <- cbcData dataOff+        _val0 <- cbcData (dataOff + 1)+        tag1 <- cbcData (dataOff + 2)+        val1 <- cbcData (dataOff + 3)+        tag2 <- cbcData (dataOff + 4)+        -- tag0=0(lit), tag1=1(interp), tag2=0(lit)+        interpOp <- cbcOpcode val1+        pure+          ( if op == OpStr+              && count == 3+              && tag0 == strpartLit+              && tag1 == strpartInterp+              && tag2 == strpartLit+              && interpOp == OpVar+              then Pass+              else+                Fail+                  ( "op="+                      <> T.pack (show op)+                      <> " count="+                      <> T.pack (show count)+                      <> " tag0="+                      <> T.pack (show tag0)+                      <> " tag1="+                      <> T.pack (show tag1)+                  )+          ),+      runTestM "compile EWith" $ do+        idx <- compileExpr (EWith (EVar "lib") (EVar "x"))+        op <- cbcOpcode idx+        scopeIdx <- cbcArg1 idx+        bodyIdx <- cbcArg2 idx+        scopeOp <- cbcOpcode scopeIdx+        bodyOp <- cbcOpcode bodyIdx+        pure+          ( if op == OpWith && scopeOp == OpVar && bodyOp == OpVar+              then Pass+              else Fail "with structure mismatch"+          ),+      runTestM "compile EAssert" $ do+        idx <- compileExpr (EAssert (ELit (NixBool True)) (ELit (NixInt 1)))+        op <- cbcOpcode idx+        condIdx <- cbcArg1 idx+        bodyIdx <- cbcArg2 idx+        condOp <- cbcOpcode condIdx+        bodyOp <- cbcOpcode bodyIdx+        pure+          ( if op == OpAssert && condOp == OpLitBool && bodyOp == OpLitInt+              then Pass+              else Fail "assert structure mismatch"+          ),+      runTestM "compile ELambda (FormalName)" $ do+        idx <-+          compileExpr+            (ELambda (FormalName "x") (EResolvedVar 0 0) NoCaptureInfo)+        op <- cbcOpcode idx+        fl <- cbcFlags idx+        bodyIdx <- cbcArg2 idx+        bodyOp <- cbcOpcode bodyIdx+        pure+          ( if op == OpLambda && fl == formalName && bodyOp == OpResolvedVar+              then Pass+              else+                Fail+                  ( "op="+                      <> T.pack (show op)+                      <> " flags="+                      <> T.pack (show fl)+                  )+          ),+      runTestM "compile ELet" $ do+        idx <-+          compileExpr+            ( ELet+                [NamedBinding (testPos 1 5) (StaticKey "x") (ELit (NixInt 42))]+                (EResolvedVar 0 0)+                NoCaptureInfo+            )+        op <- cbcOpcode idx+        count <- cbcShortArg idx+        bodyIdx <- cbcArg2 idx+        bodyOp <- cbcOpcode bodyIdx+        pure+          ( if op == OpLet && count == 1 && bodyOp == OpResolvedVar+              then Pass+              else+                Fail+                  ( "op="+                      <> T.pack (show op)+                      <> " count="+                      <> T.pack (show count)+                  )+          ),+      runTestM "compile EAttrs" $ do+        idx <-+          compileExpr+            ( EAttrs+                False+                [NamedBinding (testPos 1 3) (StaticKey "a") (ELit (NixInt 1))]+                NoCaptureInfo+            )+        op <- cbcOpcode idx+        fl <- cbcFlags idx+        count <- cbcShortArg idx+        pure+          ( if op == OpAttrs && fl == 0 && count == 1+              then Pass+              else Fail "attrs structure mismatch"+          ),+      runTestM "compile EAttrs recursive" $ do+        idx <-+          compileExpr+            ( EAttrs+                True+                [ NamedBinding (testPos 1 7) (StaticKey "x") (ELit (NixInt 1)),+                  NamedBinding (testPos 1 14) (StaticKey "y") (EResolvedVar 0 0)+                ]+                (Captures [(0, 0)])+            )+        op <- cbcOpcode idx+        fl <- cbcFlags idx+        count <- cbcShortArg idx+        pure+          ( if op == OpAttrs && fl == 1 && count == 2+              then Pass+              else+                Fail+                  ( "flags="+                      <> T.pack (show fl)+                      <> " count="+                      <> T.pack (show count)+                  )+          ),+      runTestM "compile ESelect" $ do+        idx <-+          compileExpr+            (ESelect (EVar "x") [StaticKey "a"] Nothing)+        op <- cbcOpcode idx+        fl <- cbcFlags idx+        pure+          ( if op == OpSelect && fl == 0+              then Pass+              else Fail ("flags=" <> T.pack (show fl))+          ),+      runTestM "compile ESelect with default" $ do+        idx <-+          compileExpr+            (ESelect (EVar "x") [StaticKey "a"] (Just (ELit NixNull)))+        op <- cbcOpcode idx+        fl <- cbcFlags idx+        defIdx <- cbcArg3 idx+        defOp <- cbcOpcode defIdx+        pure+          ( if op == OpSelect && fl == 1 && defOp == OpLitNull+              then Pass+              else Fail ("flags=" <> T.pack (show fl))+          ),+      runTestM "compile EHasAttr" $ do+        idx <-+          compileExpr+            (EHasAttr (EVar "x") [StaticKey "a", StaticKey "b"])+        op <- cbcOpcode idx+        pathLen <- cbcShortArg idx+        pure+          ( if op == OpHasAttr && pathLen == 2+              then Pass+              else+                Fail+                  ( "op="+                      <> T.pack (show op)+                      <> " pathLen="+                      <> T.pack (show pathLen)+                  )+          ),+      runTestM "op_count grows after compilation" $ do+        before <- cbcOpCount+        _ <- compileExpr (EApp (EVar "f") (ELit (NixInt 1)))+        after <- cbcOpCount+        pure+          ( if after > before+              then Pass+              else+                Fail+                  ( "before="+                      <> T.pack (show before)+                      <> " after="+                      <> T.pack (show after)+                  )+          ),+      runTestM "compile ELit NixFloat" $ do+        idx <- compileExpr (ELit (NixFloat 3.14))+        op <- cbcOpcode idx+        pure (assertEqual "opcode" OpLitFloat op),+      runTestM "compile ELit NixUri" $ do+        idx <- compileExpr (ELit (NixUri "https://example.com"))+        op <- cbcOpcode idx+        uri <- cbcArg1 idx >>= cbcStringText+        pure+          ( if op == OpLitUri && uri == "https://example.com"+              then Pass+              else Fail "uri mismatch"+          ),+      runTestM "compile ELit NixPath" $ do+        idx <- compileExpr (ELit (NixPath "/nix/store/foo"))+        op <- cbcOpcode idx+        path <- cbcArg1 idx >>= cbcStringText+        pure+          ( if op == OpLitPath && path == "/nix/store/foo"+              then Pass+              else Fail "path mismatch"+          ),+      runTestM "compile inherit-from binding" $ do+        idx <-+          compileExpr+            ( EAttrs+                False+                [InheritFrom (EVar "s") [InheritedName (testPos 1 15) "x", InheritedName (testPos 1 17) "y"]]+                NoCaptureInfo+            )+        op <- cbcOpcode idx+        count <- cbcShortArg idx+        bindings <- compiledBindings idx >>= bindingList+        case bindings of+          Right [BcInheritFrom _ names]+            | op == OpAttrs && count == 1 -> do+                selects <- inheritedNameList names >>= mapM inheritedSelect+                pure (assertEqual "inherited names and their selects" [("x", True), ("y", True)] selects)+          _ -> pure (Fail "inherit binding mismatch"),+      -- A plain inherit has no lookup of its own: it carries the variable,+      -- bound like any other, for the evaluator to read in the outer env.+      runTestM "compile plain inherit with the variable it copies" $ do+        idx <- compileExpr (EAttrs False [Inherit (testPos 1 11) "x" (EResolvedVar 0 0)] NoCaptureInfo)+        bindings <- compiledBindings idx >>= bindingList+        case bindings of+          Right [BcInherit _ sym valIdx] -> do+            valOp <- cbcOpcode valIdx+            pure $+              if symbolText (Symbol sym) == "x" && valOp == OpResolvedVar+                then Pass+                else Fail "expected x to carry the resolved variable"+          _ -> pure (Fail "expected one inherit binding"),+      -- Every kind of binding carries the position it was parsed at+      -- through the bytecode, and reads it back with its file.+      runTestM "compile records each binding's position" $ do+        let at = SrcPos (SourceFile "/positions/set.nix")+        idx <-+          compileExpr+            ( EAttrs+                False+                [ NamedBinding (at 2 3) (StaticKey "a") (ELit (NixInt 1)),+                  Inherit (at 3 11) "x" (EResolvedVar 0 0),+                  InheritFrom (EResolvedVar 0 0) [InheritedName (at 4 22) "y"]+                ]+                NoCaptureInfo+            )+        bindings <- compiledBindings idx >>= bindingList+        let positionsOf binding = case binding of+              BcNamed pos _ _ -> pure [pos]+              BcDynamic pos _ _ -> pure [pos]+              BcInherit pos _ _ -> pure [pos]+              BcInheritFrom _ names -> map (\(BcInheritedName pos _ _) -> pos) <$> inheritedNameList names+        readBack <- traverse (mapM positionsOf >=> mapM lookupPos . concat) bindings+        pure $+          assertEqual+            "positions read back"+            (Right (map Just [PosInFile "/positions/set.nix" 2 3, PosInFile "/positions/set.nix" 3 11, PosInFile "/positions/set.nix" 4 22]))+            readBack,+      -- Recording a position and reading it back keeps its file, line and+      -- column, text with no file reads back as such, and a line or+      -- column past 32 bits is unrecordable, as it is in upstream's table.+      -- One recorder sees every case, so the origin it remembers changes+      -- under it as a compilation's never does.+      runTestM "a recorded position reads back as it was recorded" $ do+        recorder <- newPosRecorder+        let wordCeiling = fromIntegral (maxBound :: Word32)+            genOrigin =+              QC.oneof+                [ SourceFile <$> QC.elements ["/a.nix", "/nix/store/00000000000000000000000000000000-s/default.nix", "C:\\work\\f.nix", "/caf\233.nix"],+                  pure testOrigin+                ]+            genCoordinate = QC.oneof [QC.chooseInt (1, 4096), QC.chooseInt (1, wordCeiling), QC.chooseInt (wordCeiling + 1, maxBound)]+            expected (SrcPos origin line column)+              | line > wordCeiling || column > wordCeiling = Nothing+              | otherwise = Just $ case origin of+                  SourceFile path -> PosInFile path line column+                  SourceText _ -> PosInText line column+            property =+              QC.forAll (SrcPos <$> genOrigin <*> genCoordinate <*> genCoordinate) $ \pos ->+                QC.ioProperty (recordPos recorder pos >>= lookupPos <&> (QC.=== expected pos))+        result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} property+        pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result))),+      -- Upstream's Pos::print with its origin (position.cc) writes a file+      -- by its path and text with no file as string in guillemets, then+      -- the line and the column; noPos is its empty Pos (nixexpr.cc's+      -- PosTable::operator[] at 2.24.9, pos-table.cc at 2.36.0), line 0+      -- and column 0, in none in guillemets, and a column of 0 is left+      -- out.+      runTestM "a position prints as upstream's messages write it" $ do+        recorder <- newPosRecorder+        inFile <- recordPos recorder (SrcPos (SourceFile "/positions/set.nix") 2 3)+        inText <- recordPos recorder (testPos 12 345)+        printed <- mapM printPos [inFile, inText, noPos]+        pure (assertEqual "printed" ["/positions/set.nix:2:3", "\x00ABstring\x00BB:12:345", "\x00ABnone\x00BB:0"] printed),+      runTestM "compile ELambda (FormalSet)" $ do+        idx <-+          compileExpr+            ( ELambda+                (FormalSet [Formal "a" Nothing, Formal "b" (Just (ELit (NixInt 0)))] False)+                (EResolvedVar 0 0)+                NoCaptureInfo+            )+        op <- cbcOpcode idx+        fl <- cbcFlags idx+        pure+          ( if op == OpLambda && fl == formalSet+              then Pass+              else Fail ("flags=" <> T.pack (show fl))+          ),+      runTestM "compile ELambda (FormalNamedSet)" $ do+        idx <-+          compileExpr+            ( ELambda+                (FormalNamedSet "args" [Formal "x" Nothing] True)+                (EResolvedVar 0 0)+                NoCaptureInfo+            )+        op <- cbcOpcode idx+        fl <- cbcFlags idx+        pure+          ( if op == OpLambda && fl == formalNamedSet+              then Pass+              else Fail ("flags=" <> T.pack (show fl))+          ),+      runTestM "compile CaptureInfo (Captures)" $ do+        idx <-+          compileExpr+            ( ELambda+                (FormalName "x")+                (EResolvedVar 0 0)+                (Captures [(1, 2), (3, 4)])+            )+        op <- cbcOpcode idx+        capOff <- cbcArg3 idx+        capTag <- cbcData capOff+        capCount <- cbcData (capOff + 1)+        capL0 <- cbcData (capOff + 2)+        capI0 <- cbcData (capOff + 3)+        capL1 <- cbcData (capOff + 4)+        capI1 <- cbcData (capOff + 5)+        pure+          ( if op == OpLambda+              && capTag == captureSlots+              && capCount == 2+              && capL0 == 1+              && capI0 == 2+              && capL1 == 3+              && capI1 == 4+              then Pass+              else+                Fail+                  ( "capTag="+                      <> T.pack (show capTag)+                      <> " capCount="+                      <> T.pack (show capCount)+                  )+          ),+      runTestM "compile CaptureInfo (CapturesWithScopes)" $ do+        idx <-+          compileExpr+            ( ELambda+                (FormalName "x")+                (EResolvedVar 0 0)+                (CapturesWithScopes [(0, 0)])+            )+        capOff <- cbcArg3 idx+        capTag <- cbcData capOff+        pure (assertEqual "captureTag" captureWithScopes capTag),+      runTestM "compile EWithVar" $ do+        idx <- compileExpr (EWithVar "dynamic")+        op <- cbcOpcode idx+        sym <- cbcArg1 idx+        pure+          ( if op == OpWithVar && symbolText (Symbol sym) == "dynamic"+              then Pass+              else Fail "withvar mismatch"+          ),+      runTestM "compile EIndStr" $ do+        idx <- compileExpr (EIndStr [StrLit "indented"])+        op <- cbcOpcode idx+        count <- cbcShortArg idx+        pure+          ( if op == OpIndStr && count == 1+              then Pass+              else Fail "indstr mismatch"+          )+    ]
+ test/Test/Cli.hs view
@@ -0,0 +1,3926 @@+{-# LANGUAGE ScopedTypeVariables #-}++-- | Tests of the command line and the configuration it reads.+module Test.Cli+  ( testProfileCLI,+    testE2E,+    testExecWrapperCLI,+    testUncaughtIOFailureCLI,+    testClosedStdoutCLI,+    testKeyCLI,+    testImportFromDerivationCLI,+    testCheckCLI,+    testDevelopCLI,+    testBuildUmaskCLI,+    testTerminationCLI,+    testSandboxSessionsCLI,+    testBuildCoresCLI,+    testTargetArgsCLI,+    testOutLinkCLI,+    testTrustCLI,+    testSubstituterListingsCLI,+    cliJsonPath,+    writeCliJsonFlag,+    testCliReference,+    testNixConfig,+    testEvalPolicyCLI,+    testFetchRetryCLI,+    testResultPrinterCLI,+    testConfigBytesCLI,+    testNixConfigHomeCLI,+    testStoreChoiceCLI,+  )+where++import qualified Codec.Archive.Tar as Tar+import qualified Codec.Compression.GZip as GZip+import Control.Exception (IOException, bracket, bracket_, displayException, try)+import Control.Monad (filterM, forM_, void, when)+import DaemonLink (daemonAddress, isolatedStoreEnvironment)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BS8+import qualified Data.ByteString.Lazy as BL+import Data.Char (isAsciiLower, isAsciiUpper)+import Data.Foldable (for_, toList, traverse_)+import Data.Functor.Identity (Identity (..))+import Data.List (findIndex, inits, intercalate, isInfixOf, isPrefixOf, isSuffixOf, nub, sort, stripPrefix)+import Data.List.NonEmpty (NonEmpty (..))+import qualified Data.Map.Strict as Map+import Data.Maybe (catMaybes, fromMaybe, isJust, listToMaybe, maybeToList)+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import qualified Data.Text.IO as TIO+import Data.Time.Clock (getCurrentTime)+import Data.Time.Format (defaultTimeLocale, formatTime)+import Data.Word (Word32)+import HttpFixture (Reply (..), httpResponse, withHttpServer, withKeepAliveDirectoryServer)+import Nix.Builder (BuildResult (..))+import qualified Nix.Builder.Cores as Cores+import Nix.CacheDirectory (directoryUrl)+import qualified Nix.Cli.Args as Cli+import qualified Nix.Cli.Reference as Ref+import Nix.Config (NixConfig (..))+import qualified Nix.Config as Config+import Nix.Daemon.Dial (AddressPresence (..), addressPresence)+import Nix.Derivation (Platform (..), currentPlatform, platformToText)+import Nix.Develop.Environment (BuildEnvironment (..), Variable (..), parseBuildEnvironment)+import Nix.Eval.CanonPath (canonPathValue)+import Nix.Hash (FileIngestionMethod (..), makeFixedOutputPath, makeTextPath, sha256Digest)+import qualified Nix.Hash as Hash+import Nix.HostPath (hostPathFromBytes)+import Nix.Json (Json (..), parseJson)+import qualified Nix.Profile.Generation as Gen+import Nix.Push.Directory (ed25519SeedBytes)+import Nix.Store (Store (..), addToStore, canonicalizeMetadata, closeStore, isValid, openStore)+import qualified Nix.Store.ExecBit as ExecBit+import Nix.Store.Metadata (executablePermissions, readOnlyPermissions)+import Nix.Store.Path (StoreDir (..), StorePath, defaultStoreDir, parseStorePathBaseName, storePathToFilePath, storePathToText)+import Nix.Store.Path.Internal (StorePath (..))+import qualified NovaCache.NAR as NAR+import qualified NovaCache.Signing as Signing+import System.Directory (createDirectoryIfMissing, doesDirectoryExist, getTemporaryDirectory)+import qualified System.Directory as Dir+import System.Environment (getEnvironment)+import System.Exit (ExitCode (..))+import System.FilePath (searchPathSeparator, takeDirectory, takeFileName, (</>))+import System.IO (IOMode (WriteMode), hClose, hSetBinaryMode, withBinaryFile)+import System.IO.Error (ioeGetErrorString)+import qualified System.Info as SI+import qualified System.OsPath as OP+import qualified System.Process as Proc+import Test.Builder (startWaitMicros, waitUntil, waitUntilWithin)+import Test.Harness (TestResult (..), allFailures, andThen, asciiOsPath, assertEqual, assertLeft, assertRight, canonicalAs, envSpelling, evalAndBuild, evalNixIOStore, fetchedStorePath, findTestShell, forceRemoveIfExists, genJson, hostToolsAttrs, makeGitFixture, nixQuotedPath, profileFixture, runTest, runTestM, selfHoldingDerivation, selfHoldingPrinted, selfHoldingPrintedStrict, signedTestNarInfo, symlinksAvailable, tarFile, testLogger, throwawayKey, trustPe)+import qualified Test.QuickCheck as QC+import Text.Read (readMaybe)++-- ---------------------------------------------------------------------------+-- Tests: profiles+-- ---------------------------------------------------------------------------++-- | The profile commands through the real CLI, in an environment whose+-- every home, state and configuration directory is under the test's own+-- root, which the test checks before it runs anything: adding puts a+-- program under ~/.nix-profile/bin, listing prints upstream's lines and+-- JSON, each generation is a root the collector keeps, removing takes the+-- program off, and a profile of another store or a store upstream Nix+-- manages is refused; a rollback brings back an earlier generation, the+-- history prints upstream's lines, and wiping it deletes old generations,+-- whose roots the next collection drops along with what only they kept.+testProfileCLI :: IO [Bool]+testProfileCLI = do+  putStrLn "cli/profile"+  canLink <- symlinksAvailable+  shell <- findTestShell+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-cli-profile"+  ambient <- isolatedStoreEnvironment root+  if not canLink+    then [] <$ putStrLn "  SKIP  a profile's links need symlink privilege (Windows needs Developer Mode or elevation)"+    else bracket_ (forceRemoveIfExists root >> mapM_ (createDirectoryIfMissing True . (root </>)) ["work", "home", "home-xdg", "home-state-link", "real", "hist"]) (forceRemoveIfExists root) $ do+      -- Built, if it is not, with the ambient environment cabal needs, then+      -- run by its path, so the isolated environment reaches only it.+      _ <- Proc.readCreateProcessWithExitCode (Proc.proc "cabal" ["run", "-v0", "exe:nova-nix", "--", "--version"]) ""+      (_, listed, _) <- Proc.readCreateProcessWithExitCode (Proc.proc "cabal" ["list-bin", "-v0", "exe:nova-nix"]) ""+      let exe = fromMaybe "nova-nix" (listToMaybe (reverse (filter (not . null) (lines (filter (/= '\r') listed)))))+          locations homeDir stateVars extra =+            [ ("HOME", homeDir),+              ("USERPROFILE", homeDir),+              ("ZDOTDIR", homeDir),+              ("LOCALAPPDATA", root </> "local-app-data"),+              ("XDG_DATA_HOME", root </> "xdg-data"),+              ("XDG_CONFIG_HOME", root </> "xdg-config"),+              ("XDG_CONFIG_DIRS", root </> "xdg-dirs"),+              ("NIX_CONF_DIR", root </> "system")+            ]+              ++ stateVars+              ++ extra+          -- The variables that decide whether stdout is styled, which no+          -- run inherits.+          colourVariables = ["NO_COLOR", "NOCOLOR", "CLICOLOR_FORCE", "FORCE_COLOR"]+          isolated given config =+            ("NIX_CONFIG", "substituters =\ntrusted-public-keys =\n" <> config)+              : given+              ++ filter (\(key, _) -> key `notElem` ("NIX_CONFIG" : "NIX_USER_CONF_FILES" : "NIX_CONFIG_HOME" : "NIX_PATH" : "NIX_STATE_HOME" : "XDG_STATE_HOME" : colourVariables ++ map fst given)) ambient+          -- A run's process, given variables that name no location beside+          -- the locations.+          processIn settings given config args = (Proc.proc exe args) {Proc.env = Just (isolated (settings ++ given) config), Proc.cwd = Just (root </> "work")}+          refusedRun = "the test refused to run: a location is outside " <> root+          home = root </> "home"+          state = [("NIX_STATE_HOME", root </> "state")]+          vars = locations home state []+          onWindows = SI.os == "mingw32"+          -- Each run is refused, without starting the binary, unless every+          -- location it is given, and the state directory, profiles and+          -- links the binary computes from them on this host, are under the+          -- root.  On Windows a state directory NIX_STATE_HOME does not name+          -- is the Local AppData folder, which no variable moves.+          runIn = runWith []+          -- A run with variables that name no location beside the+          -- locations it is given.+          runWith settings given config args = do+            inside <- locationsUnder given+            if inside+              then Proc.readCreateProcessWithExitCode (processIn settings given config args) ""+              else pure (ExitFailure 1, "", refusedRun)+          -- A run in the default locations whose stdout is read as bytes,+          -- since a profile's history is not ASCII, with variables beside+          -- them.  stderr is read once stdout ends, which a run that writes+          -- little there allows.+          bytesIn settings args = do+            inside <- locationsUnder vars+            if inside+              then Proc.withCreateProcess ((processIn settings vars "" args) {Proc.std_out = Proc.CreatePipe, Proc.std_err = Proc.CreatePipe}) $ \_ out err process -> do+                printed <- maybe (pure BS.empty) BS.hGetContents out+                complaint <- maybe (pure BS.empty) BS.hGetContents err+                code <- Proc.waitForProcess process+                pure (code, printed, complaint)+              else pure (ExitFailure 1, BS.empty, BS8.pack refusedRun)+          locationsUnder given = do+            rootPath <- OP.encodeFS root+            stateHome <- case (lookup "NIX_STATE_HOME" given, onWindows) of+              (Just dir, _) -> Just . Gen.NixStateHome <$> OP.encodeFS dir+              (Nothing, True) -> pure Nothing+              (Nothing, False) -> Just . Gen.XdgStateHome <$> traverse OP.encodeFS (lookup "XDG_STATE_HOME" given)+            homeDir <- traverse OP.encodeFS (lookup (if onWindows then "USERPROFILE" else "HOME") given)+            let under path = OP.splitDirectories rootPath `isPrefixOf` OP.splitDirectories path+                computed = case (stateHome, homeDir) of+                  (Just stateFrom, Just homeFrom) ->+                    let env = Gen.ProfileEnvironment stateFrom homeFrom+                     in all under [Gen.stateDirectory env, Gen.profilesDirectory env, Gen.profileLinkPath Gen.HomeProfileLink env, Gen.profileLinkPath Gen.StateProfileLink env]+                  _ -> False+            pure (all ((root `isPrefixOf`) . snd) given && computed)+          nn = runIn vars ""+          outcome (code, out, err) = "exit " <> T.pack (show code) <> "; stdout=" <> T.pack out <> "; stderr=" <> T.pack err+          succeeded run@(code, _, _) check = if code == ExitSuccess then check else Fail (outcome run)+          stderrLines (_, _, err) = lines (filter (/= '\r') err)+          profiles = root </> "state" </> "profiles"+          helloPath = home </> ".nix-profile" </> "bin" </> "hello"+          worldPath = home </> ".nix-profile" </> "bin" </> "world"+          hello = profileFixture 'a' "hello-1.0"+          world = profileFixture 'b' "world-2.0"+          other = profileFixture 'c' "other-1.0"+          script message = "#!/bin/sh\necho " <> message <> "\n"+          stage name = root </> "stage" </> name+          writeStaged path bytes = createDirectoryIfMissing True (takeDirectory path) *> BS.writeFile path bytes+          -- A read that fails is the test's to report, not the suite's.+          readIfThere path = either (\(_ :: IOException) -> Nothing) Just <$> try (BS.readFile path)+          linkIfThere path = either (\(_ :: IOException) -> Nothing) Just <$> try (Dir.getSymbolicLinkTarget path)+          twoOutputs =+            "derivation { name = \"two-1.0\"; system = builtins.currentSystem; builder = "+              <> nixQuotedPath (T.unpack shell)+              <> "; outputs = [ \"out\" \"dev\" ]; args = [ \"-c\" \"echo out > $out; echo dev > $dev\" ]; }"+      do+        -- The store is under a linked directory, so the tree names a+        -- directory it expands at a spelling other than the store's.+        Dir.createDirectoryLink (root </> "real") (root </> "via")+        store <- openStore testLogger (StoreDir (root </> "via" </> "store"))+        let storeDir = stDir store+            storeArg = unStoreDir storeDir+            inStore = storePathToFilePath storeDir+            canonical = storePathToText defaultStoreDir+        writeStaged (stage "hello" </> "bin" </> "hello") (script "hello from the profile")+        writeStaged (stage "world" </> "bin" </> "world") (script "world")+        writeStaged (stage "other" </> "bin" </> "hello") (script "the other hello")+        forM_ [stage "hello" </> "bin" </> "hello", stage "world" </> "bin" </> "world", stage "other" </> "bin" </> "hello"] ExecBit.markExecutable+        mapM_ (\(name, path) -> addToStore store (stage name) path Nothing []) [("hello", hello), ("world", world), ("other", other)]+        closeStore store+        listedEmpty <- nn ["profile", "list", "--store", storeArg]+        emptyLink <- linkIfThere (home </> ".nix-profile")+        addHello <- nn ["profile", "add", "--store", storeArg, inStore hello]+        helloContent <- readIfThere helloPath+        ran <-+          if SI.os == "mingw32"+            then pure Nothing+            else Just <$> Proc.readProcessWithExitCode (T.unpack shell) [helloPath] ""+        listedText <- nn ["profile", "list", "--store", storeArg]+        listedStyled <- runWith [("FORCE_COLOR", "1")] vars "" ["profile", "list", "--store", storeArg]+        listedUnstyled <- runWith [("CLICOLOR_FORCE", ""), ("NOCOLOR", "")] vars "" ["profile", "list", "--store", storeArg]+        listedJson <- nn ["profile", "list", "--json", "--store", storeArg]+        prettyJson <- nn ["profile", "list", "--json", "--pretty", "--store", storeArg]+        compactJson <- nn ["profile", "list", "--pretty", "--json", "--no-pretty", "--store", storeArg]+        conflicting <- nn ["profile", "add", "--store", storeArg, inStore other]+        prioritised <- nn ["profile", "add", "--priority", "4", "--store", storeArg, inStore other]+        otherContent <- readIfThere helloPath+        addWorld <- nn ["profile", "add", "--store", storeArg, inStore world]+        roots <- nn ["store", "gc", "--print-roots", "--store", storeArg]+        removed <- nn ["profile", "remove", "--store", storeArg, "hello", "other"]+        helloAfter <- Dir.doesPathExist helloPath+        worldAfter <- Dir.doesPathExist worldPath+        collected <- nn ["store", "gc", "--store", storeArg]+        generationsKept <- traverse (\n -> Dir.doesPathExist (profiles </> ("profile-" <> show (n :: Int) <> "-link") </> "manifest.json")) [1, 2, 3, 4]+        helloKept <- Dir.doesPathExist (inStore hello)+        index <- nn ["profile", "remove", "--store", storeArg, "3"]+        nothingSelected <- nn ["profile", "remove", "--store", storeArg]+        built <- nn ["profile", "add", "--store", storeArg, "--expr", T.unpack twoOutputs]+        toInstall <- nn ["profile", "add", "--store", storeArg, "--expr", "(" <> T.unpack twoOutputs <> ") // { meta.outputsToInstall = [ \"dev\" ]; }"]+        specified <- nn ["profile", "add", "--store", storeArg, "--expr", "(" <> T.unpack twoOutputs <> ").dev // { outputSpecified = true; }"]+        builtJson <- nn ["profile", "list", "--json", "--store", storeArg]+        refusedOther <- nn ["profile", "add", "--store", root </> "other-store", "--expr", T.unpack twoOutputs]+        otherStoreMade <- Dir.doesPathExist (root </> "other-store" </> ".nova-nix")+        listedOther <- nn ["profile", "list", "--store", root </> "other-store"]+        createDirectoryIfMissing True (root </> "up" </> "nix" </> "store")+        writeStaged (root </> "up" </> "nix" </> "var" </> "nix" </> "db" </> "db.sqlite") ""+        upstream <- nn ["profile", "add", "--store", root </> "up" </> "nix" </> "store", inStore hello]+        xdgCases <-+          if onWindows+            then [] <$ putStrLn "  SKIP  XDG_STATE_HOME: Windows reads the Local AppData folder in its place"+            else do+              xdgListed <- runIn (locations (root </> "home-xdg") [("XDG_STATE_HOME", root </> "xdg-state")] []) "" ["profile", "list", "--store", storeArg]+              xdgLink <- linkIfThere (root </> "home-xdg" </> ".nix-profile")+              sequence+                [ runTest "with NIX_STATE_HOME unset, profiles are in XDG_STATE_HOME's nix" $+                    succeeded xdgListed (assertEqual "link" (Just (root </> "xdg-state" </> "nix" </> "profiles" </> "profile")) xdgLink)+                ]+        stateLinked <- runIn (locations (root </> "home-state-link") [("NIX_STATE_HOME", root </> "state-link")] []) "use-xdg-base-directories = true\n" ["profile", "list", "--store", storeArg]+        stateLink <- linkIfThere (root </> "state-link" </> "profile")+        homeLinkMade <- Dir.doesPathExist (root </> "home-state-link" </> ".nix-profile")+        -- A profile --profile names, for rollbacks and the history, with+        -- packages of its own, added after the collection above, which took+        -- what no root kept then.+        let historyProfile = root </> "hist" </> "profile"+            alpha = profileFixture 'd' "alpha-1.0"+            beta = profileFixture 'f' "beta-2.0"+            onHistory args = nn (["profile"] ++ args ++ ["--store", storeArg, "--profile", historyProfile])+            historyLink n = historyProfile <> "-" <> show (n :: Int) <> "-link"+            historyLinks = traverse (fmap isJust . linkIfThere . historyLink) [1, 2, 3, 4]+            historyArgs = ["profile", "history", "--store", storeArg, "--profile", historyProfile]+            utcDay = T.pack . formatTime defaultTimeLocale "%Y-%m-%d" <$> getCurrentTime+            defaultProfileState = (,) . sort <$> Dir.listDirectory profiles <*> linkIfThere (profiles </> "profile")+        writeStaged (stage "alpha" </> "bin" </> "alpha") (script "alpha")+        writeStaged (stage "beta" </> "bin" </> "beta") (script "beta")+        historyStore <- openStore testLogger storeDir+        mapM_ (\(name, path) -> addToStore historyStore (stage name) path Nothing []) [("alpha", alpha), ("beta", beta)]+        closeStore historyStore+        dayBefore <- utcDay+        historyMade <- traverse onHistory [["add", inStore alpha], ["add", inStore beta], ["remove", "alpha"]]+        rolledBack <- onHistory ["rollback"]+        rolledLink <- linkIfThere historyProfile+        alphaBack <- Dir.doesPathExist (historyProfile </> "bin" </> "alpha")+        rolledTo <- onHistory ["rollback", "--to", "3"]+        toLink <- linkIfThere historyProfile+        alphaOff <- Dir.doesPathExist (historyProfile </> "bin" </> "alpha")+        dryRolled <- onHistory ["rollback", "--dry-run"]+        dryLink <- linkIfThere historyProfile+        missingVersion <- onHistory ["rollback", "--to", "9"]+        badUnit <- onHistory ["rollback", "--to", "5x", "--to", "2"]+        toOldest <- onHistory ["rollback", "--to", "1"]+        noOlder <- onHistory ["rollback"]+        backToSecond <- onHistory ["rollback", "--to", "2"]+        afterRollback <- onHistory ["remove", "beta"]+        fourthLink <- linkIfThere historyProfile+        wipeDry <- onHistory ["wipe-history", "--dry-run"]+        wipeRecent <- onHistory ["wipe-history", "--older-than", "1d"]+        linksKept <- historyLinks+        wipeUnsuffixed <- onHistory ["wipe-history", "--older-than", "14"]+        wipeZero <- onHistory ["wipe-history", "--older-than", "0d"]+        defaultBefore <- defaultProfileState+        wipeForeign <- nn ["profile", "wipe-history", "--store", root </> "other-store"]+        rollbackForeign <- nn ["profile", "rollback", "--store", root </> "other-store"]+        defaultAfter <- defaultProfileState+        -- The first two generations' links take a store path's time, a+        -- second past the epoch, long before any cutoff.  The other two keep+        -- the time they were made, where the paths they lead to have a store+        -- path's time too, so a date of theirs is their link's own.+        mapM_ (canonicalizeMetadata . historyLink) [1, 2]+        printedHistory <- bytesIn [] historyArgs+        colouredHistory <- bytesIn [("FORCE_COLOR", "1")] historyArgs+        -- NO_COLOR counts as set whatever its value, as upstream reads it:+        -- given one, and given none, which reads as set on Windows too.+        uncolouredHistory <- bytesIn [("FORCE_COLOR", "1"), ("NO_COLOR", "1")] historyArgs+        blankNoColourHistory <- bytesIn [("FORCE_COLOR", "1"), ("NO_COLOR", "")] historyArgs+        dayAfter <- utcDay+        wipeOld <- onHistory ["wipe-history", "--older-than", "5d"]+        oldLinks <- historyLinks+        wipeAll <- onHistory ["wipe-history"]+        allLinks <- historyLinks+        swept <- nn ["store", "gc", "--store", storeArg]+        betaSwept <- not <$> Dir.doesPathExist (inStore beta)+        alphaKept <- Dir.doesPathExist (inStore alpha)+        let jsonOf paths = "{\"elements\":{" <> T.intercalate "," paths <> "},\"version\":3}"+            elementJson name priority paths = "\"" <> name <> "\":{\"active\":true,\"priority\":" <> T.pack (show (priority :: Int)) <> ",\"storePaths\":[" <> T.intercalate "," ["\"" <> path <> "\"" | path <- paths] <> "]}"+            builtPaths = case builtJson of+              (ExitSuccess, out, _) -> either (const []) pathsOf (parseJson (T.strip (T.pack out)))+              _ -> []+            pathsOf json = case json of+              JsonObject top | Just (JsonObject elements) <- Map.lookup "elements" top -> [(name, [p | JsonString p <- paths]) | (name, JsonObject element) <- Map.toList elements, Just (JsonArray paths) <- [Map.lookup "storePaths" element]]+              _ -> []+            outputOf name = filter (T.isSuffixOf ("-two-1.0" <> name))+            ranWell (code, _, _) = code == ExitSuccess+            exitOf (code, _, _) = code+            -- A version line names the day its generation was made, which+            -- for a generation this run made is the day it began or ended.+            undated line = foldr (\day -> T.replace ("(" <> day <> ")") "(DAY)") line [dayBefore, dayAfter]+            historyIs (code, printed, complaint) expected = case (code, TE.decodeUtf8' (BS8.filter (/= '\r') printed)) of+              (ExitSuccess, Right text) -> assertEqual "lines" expected (map undated (T.lines text))+              _ -> Fail ("exit " <> T.pack (show code) <> "; stdout=" <> T.pack (show printed) <> "; stderr=" <> T.pack (show complaint))+            historyLines = versionLines ("", "")+            colouredLines = versionLines ("\ESC[1m", "\ESC[32;1m")+            versionLines (bold, green) =+              [ "Version " <> bold <> "1" <> reset bold <> " (1970-01-01):",+                "  alpha: \x2205 -> 1.0",+                "",+                "Version " <> bold <> "2" <> reset bold <> " (1970-01-01) <- 1:",+                "  beta: \x2205 -> 2.0",+                "",+                "Version " <> bold <> "3" <> reset bold <> " (DAY) <- 2:",+                "  alpha: 1.0 -> \x2205",+                "",+                "Version " <> green <> "4" <> reset green <> " (DAY) <- 3:",+                "  alpha: \x2205 -> 1.0",+                "  beta: 2.0 -> \x2205"+              ]+            reset escape = if T.null escape then "" else "\ESC[0m"+            staleRecordOf n line = "removing stale link from \"" `isPrefixOf` line && "hist" `isInfixOf` line && ("profile-" <> show n <> "-link\"") `isSuffixOf` line+        (++ xdgCases)+          <$> sequence+            [ runTest "profile list of a profile that is not there prints nothing and makes ~/.nix-profile" $+                succeeded listedEmpty (assertEqual "stdout" "" (let (_, out, _) = listedEmpty in out) `andThen` assertEqual "link" (Just (root </> "state" </> "profiles" </> "profile")) emptyLink),+              runTest "profile add puts the program under ~/.nix-profile/bin" $+                succeeded addHello (assertEqual "bin/hello" (Just (script "hello from the profile")) helloContent),+              runTest "the program runs through ~/.nix-profile/bin" $+                case ran of+                  Nothing -> Pass+                  Just (code, out, err) -> assertEqual "run" (ExitSuccess, "hello from the profile\n") (code, out) `andThen` assertEqual "stderr" "" err,+              runTest "profile list prints upstream's lines, the name in bold where colour is forced and in neither a pipe nor under NOCOLOR"+                $ succeeded listedText . succeeded listedStyled . succeeded listedUnstyled+                $ let printed (_, out, _) = lines (filter (/= '\r') out)+                      paths = "Store paths:        " <> inStore hello+                   in assertEqual "a pipe" ["Name:               hello", paths] (printed listedText)+                        `andThen` assertEqual "forced" ["Name:               \ESC[1mhello\ESC[0m", paths] (printed listedStyled)+                        `andThen` assertEqual "NOCOLOR" ["Name:               hello", paths] (printed listedUnstyled),+              runTest "profile list --json prints the manifest, paths in the canonical spelling"+                $ succeeded listedJson+                $ assertEqual "json" (jsonOf [elementJson "hello" 5 [canonical hello]]) (let (_, out, _) = listedJson in T.strip (T.pack out)),+              runTest "profile list --json --pretty indents the manifest, and a later --no-pretty puts it on one line"+                $ succeeded prettyJson . succeeded compactJson+                $ let (_, compactOut, _) = compactJson+                      (_, prettyOut, _) = prettyJson+                   in case parseJson (T.strip (T.pack compactOut)) of+                        Right json ->+                          assertEqual "indented" (Ref.renderIndentedJson json) (TE.encodeUtf8 (T.pack (filter (/= '\r') prettyOut)))+                            `andThen` assertEqual "one line" 1 (length (lines compactOut))+                        Left err -> Fail err,+              runTest "a file at one path in two packages of one priority fails the add in upstream's words, with nova-nix's commands" $+                case conflicting of+                  (ExitFailure 1, _, _) ->+                    assertEqual "first line" (Just "error: An existing package already provides the following file:") (listToMaybe (stderrLines conflicting))+                      `andThen` assertEqual "hint" True (("         nova-nix profile remove hello" :: String) `elem` stderrLines conflicting)+                  _ -> Fail (outcome conflicting),+              runTest "each generation is a root, listed by its link"+                $ succeeded addWorld . succeeded roots+                $ let (_, out, _) = roots+                      rootLinks = [takeFileName (takeWhile (/= ' ') line) | line <- lines (filter (/= '\r') out)]+                   in assertEqual "links" ["profile-1-link", "profile-2-link", "profile-3-link"] (filter ("profile-" `isPrefixOf`) rootLinks),+              runTest "profile remove takes the program off, in upstream's words, and keeps the rest"+                $ succeeded removed+                $ assertEqual "lines" ["removing 'hello'", "removing 'other'", "removed 2 packages, kept 1 packages"] (stderrLines removed)+                  `andThen` assertEqual "bin/hello, bin/world" (False, True) (helloAfter, worldAfter),+              runTest "store gc keeps every generation and what only an old one holds" $+                succeeded collected (assertEqual "generations" [True, True, True, True] generationsKept `andThen` assertEqual "hello" True helloKept),+              runTest "a lower priority number puts a package's file in place of one already there" $+                succeeded prioritised (assertEqual "bin/hello" (Just (script "the other hello")) otherContent),+              runTest "a number is refused as upstream refuses an index" $+                assertEqual "index" (ExitFailure 1, ["error: 'nova-nix profile' does not support indices ('3')"]) (let (code, _, _) = index in code, stderrLines index),+              runTest "profile remove with nothing selected is a usage error, before the profile is read" $+                assertEqual "usage" (ExitFailure 1, ["profile remove: no packages specified"]) (let (code, _, _) = nothingSelected in code, stderrLines nothingSelected),+              runTest "a derivation is built and added for every output, the one its outputSpecified selects, or those meta.outputsToInstall names" $+                succeeded built . succeeded toInstall . succeeded specified $+                  case (lookup "two" builtPaths, lookup "two-1" builtPaths, lookup "two-2" builtPaths) of+                    (Just every, Just installed, Just selected) ->+                      assertEqual "every output" 2 (length every)+                        `andThen` assertEqual "outputsToInstall" (outputOf "-dev" every) installed+                        `andThen` assertEqual "outputSpecified" (outputOf "-dev" every) selected+                    _ -> Fail (T.pack (show builtPaths)),+              runTest "a profile whose generation is in another store is refused before anything is built" $+                case refusedOther of+                  (ExitFailure 1, _, _) ->+                    assertEqual "names the flags" True (any (\line -> "--store" `isInfixOf` line && "--profile" `isInfixOf` line) (stderrLines refusedOther))+                      `andThen` assertEqual "nothing built" False otherStoreMade+                  _ -> Fail (outcome refusedOther),+              runTest "profile list refuses a profile whose generation is in another store, as the commands that change one do" $+                case listedOther of+                  (ExitFailure 1, "", _) -> assertEqual "names the flags" True (any (\line -> "--store" `isInfixOf` line && "--profile" `isInfixOf` line) (stderrLines listedOther))+                  _ -> Fail (outcome listedOther),+              runTest "a store upstream Nix manages is refused, as build refuses it" $+                case upstream of+                  (ExitFailure 1, _, err) | "profile add: " `isPrefixOf` err -> Pass+                  _ -> Fail (outcome upstream),+              runTest "use-xdg-base-directories links the default profile from the state directory, not the home" $+                succeeded stateLinked (assertEqual "link" (Just (root </> "state-link" </> "profiles" </> "profile")) stateLink `andThen` assertEqual "home link" False homeLinkMade),+              runTest "a rollback switches the profile to the generation before the current one, which brings back what a later change took off" $+                case filter (not . ranWell) historyMade of+                  [] -> succeeded rolledBack (assertEqual "line" ["switching profile from version 3 to 2"] (stderrLines rolledBack) `andThen` assertEqual "link" (Just "profile-2-link") rolledLink `andThen` assertEqual "bin/alpha" True alphaBack)+                  failed -> Fail (T.intercalate "; " (map outcome failed)),+              runTest "rollback --to switches the profile to the generation it names" $+                succeeded rolledTo (assertEqual "line" ["switching profile from version 2 to 3"] (stderrLines rolledTo) `andThen` assertEqual "link" (Just "profile-3-link") toLink `andThen` assertEqual "bin/alpha" False alphaOff),+              runTest "rollback --dry-run says where it would switch the profile, and switches nothing" $+                succeeded dryRolled (assertEqual "line" ["switching profile from version 3 to 2"] (stderrLines dryRolled) `andThen` assertEqual "link" (Just "profile-3-link") dryLink),+              runTest "a rollback to a generation the profile lacks, or from its oldest, and one with any --to that does not read, are refused in upstream's words" $+                assertEqual "--to 9" (ExitFailure 1, ["error: profile version 9 does not exist"]) (exitOf missingVersion, stderrLines missingVersion)+                  `andThen` assertEqual "--to 5x before a --to that reads" (ExitFailure 1, ["error: invalid unit specifier 'X'"]) (exitOf badUnit, stderrLines badUnit)+                  `andThen` succeeded toOldest (assertEqual "from the oldest" (ExitFailure 1, ["error: no profile version older than the current (1) exists"]) (exitOf noOlder, stderrLines noOlder)),+              runTest "a change after a rollback makes the generation after the newest, not after the current one"+                $ succeeded backToSecond . succeeded afterRollback+                $ assertEqual "link" (Just "profile-4-link") fourthLink,+              runTest "wipe-history --dry-run names every generation but the current one, and --older-than keeps those made since its cutoff"+                $ succeeded wipeDry . succeeded wipeRecent+                $ assertEqual "dry run" ["would remove profile version 1", "would remove profile version 2", "would remove profile version 3"] (stderrLines wipeDry)+                  `andThen` assertEqual "since the cutoff" [] (stderrLines wipeRecent)+                  `andThen` assertEqual "links" [True, True, True, True] linksKept,+              runTest "an --older-than without its d, or of fewer than one day, is refused in upstream's words" $+                assertEqual "14" (ExitFailure 1, ["error: invalid number of days specifier '14', expected something like '14d'"]) (exitOf wipeUnsuffixed, stderrLines wipeUnsuffixed)+                  `andThen` assertEqual "0d" (ExitFailure 1, ["error: invalid number of days specifier '0d'"]) (exitOf wipeZero, stderrLines wipeZero),+              runTest "rollback and wipe-history refuse a profile whose current generation is in another store, and change nothing" $+                case (exitOf wipeForeign, exitOf rollbackForeign) of+                  (ExitFailure 1, ExitFailure 1) ->+                    assertEqual "names the flags" [True, True] [any (\line -> "--store" `isInfixOf` line && "--profile" `isInfixOf` line) (stderrLines run) | run <- [wipeForeign, rollbackForeign]]+                      `andThen` assertEqual "the default profile" defaultBefore defaultAfter+                  _ -> Fail (outcome wipeForeign <> "; " <> outcome rollbackForeign),+              runTest "profile history prints each generation's day in UTC by its link's own time, and what changed from the one before it, in upstream's lines" $+                historyIs printedHistory historyLines,+              runTest "profile history sets the current generation's number in green and the others' in bold where colour is forced, and in neither under NO_COLOR" $+                historyIs colouredHistory colouredLines `andThen` historyIs uncolouredHistory historyLines `andThen` historyIs blankNoColourHistory historyLines,+              runTest "wipe-history --older-than deletes what was made before its cutoff but the newest of those" $+                succeeded wipeOld (assertEqual "line" ["removing profile version 1"] (stderrLines wipeOld) `andThen` assertEqual "links" [False, True, True, True] oldLinks),+              runTest "wipe-history deletes every generation but the current one" $+                succeeded wipeAll (assertEqual "lines" ["removing profile version 2", "removing profile version 3"] (stderrLines wipeAll) `andThen` assertEqual "links" [False, False, False, True] allLinks),+              runTest "the next collection drops the deleted generations' records in upstream's line and deletes what only they kept"+                $ succeeded swept+                $ assertEqual "stale records" [1, 2, 3] [n | n <- [1, 2, 3 :: Int], any (staleRecordOf n) (stderrLines swept)]+                  `andThen` assertEqual "beta deleted, alpha kept" (True, True) (betaSwept, alphaKept)+            ]++-- ---------------------------------------------------------------------------+-- Tests: CLI Integration (Phase 2, Batch 5)+-- ---------------------------------------------------------------------------++-- | A tree holding a reserved device stem, a colon and a trailing dot,+-- names POSIX holds and Windows does not, in the order a sorted listing+-- gives them.+reservedNameFiles :: [(FilePath, BS.ByteString)]+reservedNameFiles = [("aux.c", "device\n"), ("dot.", "dot\n"), ("key:value", "colon\n")]++-- | Where upstream stores 'reservedNameFiles' as a coerced source+-- directory named @src@ (nix-instantiate 2.33.2, @"${./src}"@) and as+-- the tree of a fetchTarball (with @--store 'local?root=...'@, which+-- holds it under exactly these names).+reservedNameSourcePath, reservedNameTarballPath :: StorePath+reservedNameSourcePath = StorePath "42hs0hrpla9b23iz9p3nj0px0np0jv6f" "src"+reservedNameTarballPath = StorePath "rlwykawmqrmdiq4xmcr4rf2zxf6y9k09" "source"++testE2E :: IO [Bool]+testE2E = do+  putStrLn "cli/e2e"+  shell <- findTestShell+  sequence+    [ -- End-to-end: eval -> build a simple derivation+      runTestM "e2e eval -> build" $ do+        tmpBase <- getTemporaryDirectory+        let tmpStore = tmpBase </> "nova-nix-test-e2e1"+        forceRemoveIfExists tmpStore+        -- Build the Nix source with the discovered shell path.+        -- Nix strings use \\ for literal backslash, \" for literal quote.+        let nixEscape = T.concatMap (\c -> if c == '\\' then "\\\\" else if c == '"' then "\\\"" else T.singleton c)+            e2eSource =+              T.concat+                [ "derivation { name = \"e2e-test\"; system = builtins.currentSystem; " <> hostToolsAttrs,+                  "builder = \"" <> nixEscape shell <> "\"; ",+                  "args = [\"-c\" \"mkdir -p $out && echo e2e > $out/e2e.txt\"]; }"+                ]+        result <- evalAndBuild (StoreDir tmpStore) e2eSource+        ret <- case result of+          Left err -> pure (Fail err)+          Right (BuildSuccess _, store) -> do+            closeStore store+            pure Pass+          Right (BuildFailure msg code, store) -> do+            closeStore store+            pure (Fail ("build failed (" <> T.pack (show code) <> "): " <> msg))+        forceRemoveIfExists tmpStore+        forceRemoveIfExists (tmpBase </> "nova-nix-e2e-tmp")+        pure ret,+      -- Every eval-time store writer must register, not only toFile: an+      -- unrecorded write reaches drvInputSrcs and the build dies with+      -- "path '...' is not valid".+      runTestM "e2e eval-time store writes register as derivation inputs" $ do+        tmpBase <- getTemporaryDirectory+        let tmpStore = tmpBase </> "nova-nix-test-e2e-inputs"+            srcDir = tmpBase </> "nova-nix-test-e2e-inputs-src"+            nixEscape = T.concatMap (\c -> if c == '\\' then "\\\\" else if c == '"' then "\\\"" else T.singleton c)+            drvWith srcExpr =+              T.concat+                [ "derivation { name = \"inputs-test\"; system = builtins.currentSystem; ",+                  "builder = \"" <> nixEscape shell <> "\"; ",+                  "args = [\"-c\" \"echo ok > $out\"]; ",+                  "src = " <> srcExpr <> "; }"+                ]+        forceRemoveIfExists tmpStore+        forceRemoveIfExists srcDir+        Dir.createDirectoryIfMissing True srcDir+        writeFile (srcDir </> "f.txt") "content\n"+        let cases =+              [ ("toFile", "builtins.toFile \"note\" \"text\""),+                -- A path LITERAL, not a string, so it must be spelled the+                -- way the evaluator spells path values: the lexer rejects a+                -- backslash, and a native Windows temp dir is full of them.+                -- Through 'canonPathValue' rather than a separator replace,+                -- because a backslash is an ordinary file-name character on+                -- POSIX and only a separator on Windows.+                ("path", "builtins.path { path = " <> canonPathValue (T.pack srcDir) <> "; name = \"sd\"; }")+              ]+        outcomes <-+          mapM+            ( \(label, expr) -> do+                result <- evalAndBuild (StoreDir tmpStore) (drvWith expr)+                pure (label, result)+            )+            cases+        let failures =+              [ label <> ": " <> reason+              | (label, result) <- outcomes,+                Just reason <-+                  [ case result of+                      Left err -> Just err+                      Right (BuildFailure msg _, _) -> Just msg+                      Right (BuildSuccess _, _) -> Nothing+                  ]+              ]+        mapM_+          ( \(_, result) -> case result of+              Right (_, store) -> closeStore store+              Left _ -> pure ()+          )+          outcomes+        forceRemoveIfExists tmpStore+        forceRemoveIfExists srcDir+        pure $ case failures of+          [] -> Pass+          errs -> Fail (T.intercalate "; " errs),+      -- POSIX holds names Windows reserves, and upstream stores them as+      -- their bytes there.  A coerced source and a fetchTarball+      -- tree holding a device stem, a colon and a trailing dot restore+      -- with exactly those names, under the paths upstream computes+      -- for them ('reservedNameSourcePath'), as the raw copy they+      -- replace stored them.+      runTestM "e2e sources holding names Windows reserves restore with their names" $+        if SI.os == "mingw32"+          then Pass <$ putStrLn "  SKIP  a Windows volume cannot hold these names"+          else do+            tmpBase <- getTemporaryDirectory+            environment <- getEnvironment+            let root = tmpBase </> "nova-nix-test-e2e-names"+                srcDir = root </> "src"+                stage = root </> "stage"+                tarball = root </> "names.tar.gz"+                tmpStore = tmpBase </> "nova-nix-test-e2e-names-store"+                nixEscape = T.concatMap (\c -> if c == '\\' then "\\\\" else if c == '"' then "\\\"" else T.singleton c)+                source =+                  T.concat+                    [ "derivation { name = \"names\"; system = builtins.currentSystem; ",+                      "builder = \"" <> nixEscape shell <> "\"; ",+                      "args = [\"-c\" \"echo ok > $out\"]; ",+                      "srcs = [ " <> canonPathValue (T.pack srcDir) <> " ",+                      "(builtins.fetchTarball \"file://" <> nixEscape (T.pack tarball) <> "\") ]; }"+                    ]+                -- bsdtar would otherwise add AppleDouble entries for+                -- any extended attributes the files carry.+                tarProcess =+                  (Proc.proc "tar" ["-czf", tarball, "-C", stage, "top"])+                    { Proc.env = Just (("COPYFILE_DISABLE", "1") : environment)+                    }+                writeTree dir = do+                  createDirectoryIfMissing True dir+                  mapM_ (\(name, bytes) -> BS.writeFile (dir </> name) bytes) reservedNameFiles+                storedAs store sp = do+                  let dest = storePathToFilePath (stDir store) sp+                  present <- doesDirectoryExist dest+                  if not present+                    then pure (Just (spName sp <> ": no tree at " <> T.pack dest))+                    else do+                      names <- sort <$> Dir.listDirectory dest+                      contents <- traverse (BS.readFile . (dest </>)) names+                      valid <- isValid store sp+                      pure $+                        if valid && zip names contents == reservedNameFiles+                          then Nothing+                          else Just (spName sp <> " valid " <> T.pack (show valid) <> ", stored as " <> T.pack (show (zip names contents)))+            forceRemoveIfExists root+            forceRemoveIfExists tmpStore+            writeTree srcDir+            writeTree (stage </> "top")+            (tarCode, _, tarErr) <- Proc.readCreateProcessWithExitCode tarProcess ""+            verdict <- case tarCode of+              ExitFailure n -> pure (Fail ("tar exited " <> T.pack (show n) <> ": " <> T.pack tarErr))+              ExitSuccess -> do+                built <- evalAndBuild (StoreDir tmpStore) source+                case built of+                  Left err -> pure (Fail err)+                  Right (BuildFailure msg _, store) -> Fail msg <$ closeStore store+                  Right (BuildSuccess _, store) -> do+                    problems <- catMaybes <$> traverse (storedAs store) [reservedNameSourcePath, reservedNameTarballPath]+                    closeStore store+                    pure (if null problems then Pass else Fail (T.intercalate "; " problems))+            forceRemoveIfExists root+            forceRemoveIfExists tmpStore+            pure verdict,+      -- The tree the issue compared with nix-instantiate's: an evaluation+      -- alone, which registers nothing, leaves it as upstream's+      -- addToStoreFromDump does, a file 0444 and an executable 0555, each+      -- with the store's time, whatever modes the archive held.+      runTestM "an eval-time fetchTarball's tree takes upstream's modes and the store's time" $+        if SI.os == "mingw32"+          then Pass <$ putStrLn "  SKIP  the modes the issue compares are POSIX's"+          else do+            tmpBase <- getTemporaryDirectory+            environment <- getEnvironment+            let root = tmpBase </> "nova-nix-test-eval-tarball"+                stage = root </> "stage"+                tarball = root </> "tree.tar.gz"+                storeDir = StoreDir (root </> "store")+                nixEscape = T.concatMap (\c -> if c == '\\' then "\\\\" else if c == '"' then "\\\"" else T.singleton c)+                tarProcess =+                  (Proc.proc "tar" ["-czf", tarball, "-C", stage, "top"])+                    { Proc.env = Just (("COPYFILE_DISABLE", "1") : environment)+                    }+            forceRemoveIfExists root+            createDirectoryIfMissing True (stage </> "top")+            BS.writeFile (stage </> "top" </> "data") "data\n"+            BS.writeFile (stage </> "top" </> "run") "#!/bin/sh\n"+            ExecBit.markExecutable (stage </> "top" </> "run")+            (tarCode, _, tarErr) <- Proc.readCreateProcessWithExitCode tarProcess ""+            verdict <- case tarCode of+              ExitFailure n -> pure (Fail ("tar exited " <> T.pack (show n) <> ": " <> T.pack tarErr))+              ExitSuccess -> do+                fetched <- evalNixIOStore storeDir root ("builtins.fetchTarball \"file://" <> nixEscape (T.pack tarball) <> "\"")+                case fetched of+                  Right val | Just sp <- fetchedStorePath val -> do+                    let dest = storePathToFilePath storeDir sp+                    foldr andThen Pass+                      <$> traverse+                        (uncurry canonicalAs)+                        [(executablePermissions, dest), (readOnlyPermissions, dest </> "data"), (executablePermissions, dest </> "run")]+                  other -> pure (Fail ("fetchTarball gave " <> T.pack (show other)))+            forceRemoveIfExists root+            pure verdict,+      -- The writer half of the eval-write pair: an interrupted earlier+      -- run's truncated file at a toFile path must be rewritten, not+      -- adopted on bare existence (adopting it would register such a file+      -- valid under the full content's hash, seal it read-only, and let a+      -- build consume it).+      runTestM "a truncated pre-existing toFile write is rewritten, not adopted" $ do+        tmpBase <- getTemporaryDirectory+        let tmpStore = tmpBase </> "nova-nix-test-tofile-verify"+            nixEscape = T.concatMap (\c -> if c == '\\' then "\\\\" else if c == '"' then "\\\"" else T.singleton c)+            goodText = "the full intended content" :: Text+            goodBytes = TE.encodeUtf8 goodText+        forceRemoveIfExists tmpStore+        case makeTextPath "note" (sha256Digest goodBytes) [] of+          Left err -> pure (Fail ("test store path rejected: " <> T.pack (show err)))+          Right sp -> do+            let dest = storePathToFilePath (StoreDir tmpStore) sp+            Dir.createDirectoryIfMissing True (takeDirectory dest)+            BS.writeFile dest (TE.encodeUtf8 "the full")+            let expr =+                  "derivation { name = \"tofile-verify\"; system = builtins.currentSystem; "+                    <> "builder = \""+                    <> nixEscape shell+                    <> "\"; "+                    <> "args = [\"-c\" \"echo ok > $out\"]; "+                    <> "src = builtins.toFile \"note\" \""+                    <> goodText+                    <> "\"; }"+            result <- evalAndBuild (StoreDir tmpStore) expr+            rewritten <- BS.readFile dest+            outcome <- case result of+              Left err -> pure (Fail err)+              Right (BuildFailure msg _, store) -> closeStore store >> pure (Fail msg)+              Right (BuildSuccess _, store) -> do+                registered <- isValid store sp+                closeStore store+                pure $+                  if rewritten == goodBytes && registered+                    then Pass+                    else Fail "adopted the truncated file instead of rewriting it"+            forceRemoveIfExists tmpStore+            pure outcome,+      -- Same guarantee for the tree writer behind builtins.path: a+      -- corrupted partial tree at the computed path is cleared and+      -- re-unpacked, never adopted.+      runTestM "a corrupted pre-existing builtins.path tree is re-copied, not adopted" $ do+        tmpBase <- getTemporaryDirectory+        let tmpStore = tmpBase </> "nova-nix-test-path-verify"+            srcDir = tmpBase </> "nova-nix-test-path-verify-src"+            nixEscape = T.concatMap (\c -> if c == '\\' then "\\\\" else if c == '"' then "\\\"" else T.singleton c)+        forceRemoveIfExists tmpStore+        forceRemoveIfExists srcDir+        Dir.createDirectoryIfMissing True srcDir+        BS.writeFile (srcDir </> "f.txt") (TE.encodeUtf8 "real content\n")+        entry <- NAR.serialiseFromPath srcDir+        case makeFixedOutputPath "sd" "sha256" NarIngestion (sha256Digest (NAR.serialise entry)) of+          Left err -> pure (Fail ("test store path rejected: " <> T.pack (show err)))+          Right sp -> do+            let dest = storePathToFilePath (StoreDir tmpStore) sp+            Dir.createDirectoryIfMissing True dest+            BS.writeFile (dest </> "f.txt") (TE.encodeUtf8 "partial garbage")+            let expr =+                  "derivation { name = \"path-verify\"; system = builtins.currentSystem; "+                    <> "builder = \""+                    <> nixEscape shell+                    <> "\"; "+                    <> "args = [\"-c\" \"echo ok > $out\"]; "+                    <> "src = builtins.path { path = "+                    <> canonPathValue (T.pack srcDir)+                    <> "; name = \"sd\"; }; }"+            result <- evalAndBuild (StoreDir tmpStore) expr+            outcome <- case result of+              Left err -> pure (Fail err)+              Right (BuildFailure msg _, store) -> closeStore store >> pure (Fail msg)+              Right (BuildSuccess _, store) -> do+                -- Strict bytes: a lazy read here holds the file open past+                -- the cleanup below, and Windows refuses to delete it.+                adopted <- BS.readFile (dest </> "f.txt")+                registered <- isValid store sp+                closeStore store+                pure $+                  if adopted == TE.encodeUtf8 "real content\n" && registered+                    then Pass+                    else Fail ("adopted the corrupted tree: " <> T.pack (show adopted))+            forceRemoveIfExists tmpStore+            forceRemoveIfExists srcDir+            pure outcome,+      -- The build path joins the per-path lock protocol that delete,+      -- materialize and register use.  Lock files persist+      -- by design, so the one guarding the output is the observable+      -- evidence the build took it; without it two concurrent builds share+      -- a build directory and interleave into one tree.+      runTestM "e2e a build takes its output's path lock" $ do+        tmpBase <- getTemporaryDirectory+        let tmpStore = tmpBase </> "nova-nix-test-e2e-lock"+            nixEscape = T.concatMap (\c -> if c == '\\' then "\\\\" else if c == '"' then "\\\"" else T.singleton c)+            lockSource =+              T.concat+                [ "derivation { name = \"lock-test\"; system = builtins.currentSystem; ",+                  "builder = \"" <> nixEscape shell <> "\"; ",+                  "args = [\"-c\" \"echo locked > $out\"]; }"+                ]+        forceRemoveIfExists tmpStore+        result <- evalAndBuild (StoreDir tmpStore) lockSource+        ret <- case result of+          Left err -> pure (Fail err)+          Right (BuildFailure msg code, store) -> do+            closeStore store+            pure (Fail ("build failed (" <> T.pack (show code) <> "): " <> msg))+          Right (BuildSuccess sp, store) -> do+            closeStore store+            let outPath = storePathToFilePath (StoreDir tmpStore) sp+            locked <- Dir.doesFileExist (outPath <> ".lock")+            pure $+              if locked+                then Pass+                else Fail "no lock file beside the built output"+        forceRemoveIfExists tmpStore+        forceRemoveIfExists (tmpBase </> "nova-nix-e2e-tmp")+        pure ret,+      -- Parse error produces Left+      runTestM "e2e parse error" $ do+        tmpBase <- getTemporaryDirectory+        let tmpStore = tmpBase </> "nova-nix-test-e2e2"+        forceRemoveIfExists tmpStore+        result <- evalAndBuild (StoreDir tmpStore) "{{ invalid nix"+        forceRemoveIfExists tmpStore+        pure $ case result of+          Left msg ->+            if "parse error" `T.isInfixOf` msg+              then Pass+              else Fail ("expected parse error, got: " <> msg)+          Right _ -> Fail "expected error but got success",+      -- Eval error produces Left+      runTestM "e2e eval error" $ do+        tmpBase <- getTemporaryDirectory+        let tmpStore = tmpBase </> "nova-nix-test-e2e3"+        forceRemoveIfExists tmpStore+        result <- evalAndBuild (StoreDir tmpStore) "derivation { }"+        forceRemoveIfExists tmpStore+        pure $ case result of+          Left msg ->+            if "error" `T.isInfixOf` T.toLower msg+              then Pass+              else Fail ("expected eval error, got: " <> msg)+          Right _ -> Fail "expected error but got success",+      -- E2E with subprocess: nova-nix eval on a .nix file+      runTestM "e2e nova-nix eval subprocess" $ do+        tmpBase <- getTemporaryDirectory+        let tmpDir = tmpBase </> "nova-nix-test-e2e-sub"+            nixFile = tmpDir </> "test.nix"+        ambient <- isolatedStoreEnvironment tmpDir+        forceRemoveIfExists tmpDir+        createDirectoryIfMissing True tmpDir+        writeFile nixFile "1 + 2"+        -- Run nova-nix eval via Process+        (exitCode, stdoutStr, stderrStr) <-+          Proc.readCreateProcessWithExitCode+            (Proc.proc "cabal" ["run", "exe:nova-nix", "--", "eval", nixFile]) {Proc.env = Just ambient}+            ""+        forceRemoveIfExists tmpDir+        pure $ case exitCode of+          ExitSuccess ->+            let nonEmpty = filter (not . T.null) (T.lines (T.pack stdoutStr))+                lastLine = case reverse nonEmpty of+                  (l : _) -> Just l+                  [] -> Nothing+             in if lastLine == Just "3"+                  then Pass+                  else Fail ("expected 3 as last line, got: " <> T.pack stdoutStr)+          ExitFailure code ->+            Fail ("nova-nix eval failed (" <> T.pack (show code) <> "): stderr=" <> T.pack stderrStr)+    ]++-- | Exercise the real CLI: testing 'execWrapperConfig' alone cannot catch+-- a sub-parser that never passes the option to it. The foreign builder is+-- deliberately "-c", so only launching it through the shell can succeed.+testExecWrapperCLI :: IO [Bool]+testExecWrapperCLI = do+  putStrLn "cli/exec-wrapper"+  shell <- findTestShell+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-cli-wrapper"+  ambient <- isolatedStoreEnvironment root+  let system = platformToText (if currentPlatform == X86_64_Windows then X86_64_Linux else X86_64_Windows)+      wrapper = ["--exec-wrapper", T.unpack (system <> "=" <> shell)]+      otherWrapper = ["--exec-wrapper", T.unpack (platformToText currentPlatform <> "=" <> shell)]+      source =+        "derivation { name = \"cli-wrapper\"; system = \""+          <> T.unpack system+          <> "\"; builder = \"-c\"; args = [\"printf wrapped > \\\"$out\\\"\"]; }"+      target = ["--expr", source]+      isolatedEnv =+        ("NIX_CONFIG", "substituters =\ntrusted-public-keys =\n")+          : ("XDG_CONFIG_HOME", root </> "config")+          : filter (\(key, _) -> key `notElem` ["NIX_CONFIG", "NIX_CONFIG_HOME", "XDG_CONFIG_HOME"]) ambient+      runCLI args =+        Proc.readCreateProcessWithExitCode+          ((Proc.proc "cabal" (["run", "-v0", "exe:nova-nix", "--"] ++ args)) {Proc.env = Just isolatedEnv})+          ""+      buildCases =+        [ ("before build", wrapper ++ ["build"] ++ target),+          ("before target", ["build"] ++ wrapper ++ target),+          ("after target", ["build"] ++ target ++ wrapper),+          ("repeated across build", otherWrapper ++ ["build"] ++ target ++ wrapper)+        ]+      errorCases =+        [ ("missing value", ["build"] ++ target ++ ["--exec-wrapper"], "--exec-wrapper requires a value"),+          ("malformed spec", ["build"] ++ target ++ ["--exec-wrapper", "invalid"], "--exec-wrapper expects SYSTEM=PATH, got: invalid"),+          ("duplicate system", wrapper ++ ["build"] ++ target ++ wrapper, "--exec-wrapper names " <> system <> " twice"),+          ("missing launcher", ["build"] ++ target ++ ["--exec-wrapper", T.unpack system ++ "=" ++ (root </> "missing-launcher")], "does not exist")+        ]+  bracket_+    (forceRemoveIfExists root >> createDirectoryIfMissing True root)+    (forceRemoveIfExists root)+    ( do+        builds <-+          mapM+            ( \(label, args) -> runTestM ("CLI wrapper " <> label) $ do+                (code, out, err) <- runCLI (args ++ ["--store", root </> T.unpack label, "--no-out-link"])+                case (code, reverse (filter (not . null) (lines out))) of+                  (ExitSuccess, path : _) -> assertEqual "wrapped output" "wrapped" <$> BS.readFile path+                  _ -> pure (Fail ("CLI failed: " <> T.pack (show code) <> "; stdout=" <> T.pack out <> "; stderr=" <> T.pack err))+            )+            buildCases+        errors <-+          mapM+            ( \(label, args, expected) -> runTestM ("CLI wrapper " <> label) $ do+                (code, _, err) <- runCLI args+                pure $+                  if code /= ExitSuccess && expected `T.isInfixOf` T.pack err+                    then Pass+                    else Fail ("expected failure containing " <> expected <> ", got " <> T.pack (show (code, err)))+            )+            errorCases+        pure (builds ++ errors)+    )++-- | A failure no command handles prints as upstream's handleExceptions+-- prints one, a single @error:@ line and exit status 1, not GHC's+-- "Uncaught exception" report.  A derivation whose context names a path+-- the store never registered meets the store's refusal while its @.drv@+-- is written, before anything builds.+testUncaughtIOFailureCLI :: IO [Bool]+testUncaughtIOFailureCLI = do+  putStrLn "cli/uncaught-io-failure"+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-cli-io-failure"+  ambient <- isolatedStoreEnvironment root+  let missing :: String+      missing = "/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-gone"+      source =+        "derivation { name = \"unregistered\"; system = builtins.currentSystem; builder = \"/bin/sh\"; dep = builtins.appendContext \"\" { \""+          <> missing+          <> "\" = { path = true; }; }; }"+      isolatedEnv =+        ("NIX_CONFIG", "substituters =\ntrusted-public-keys =\n")+          : ("XDG_CONFIG_HOME", root </> "config")+          : filter (\(key, _) -> key `notElem` ["NIX_CONFIG", "NIX_CONFIG_HOME", "XDG_CONFIG_HOME"]) ambient+  bracket_+    (forceRemoveIfExists root >> createDirectoryIfMissing True root)+    (forceRemoveIfExists root)+    ( do+        (code, _, err) <-+          Proc.readCreateProcessWithExitCode+            ((Proc.proc "cabal" ["run", "-v0", "exe:nova-nix", "--", "build", "--expr", source, "--store", root </> "store"]) {Proc.env = Just isolatedEnv})+            ""+        sequence+          [ runTest "uncaught I/O failure exits 1" (assertEqual "exit code" (ExitFailure 1) code),+            runTest "uncaught I/O failure prints upstream's error line" $+              assertEqual "stderr" ["error: path '" <> missing <> "' is not valid"] (map (filter (/= '\r')) (lines err))+          ]+    )++-- | Runs whose stdout is a pipe nothing reads, as after @| head -1@ has+-- read its line.  Upstream's writes through @std::cout@ then fail with+-- the stream's error state alone, SIGPIPE being blocked+-- (@unix::startSignalHandlerThread@ in libutil\/unix\/signals.cc), so+-- nothing is reported and the command ends with its own status+-- (@processExpr@ in nix-instantiate.cc): an eval or @--help@ exits 0, and+-- @store delete@, which prints each path as it deletes it, deletes every+-- path it names.  The read end is closed before the process starts, so+-- its first write meets it.+testClosedStdoutCLI :: IO [Bool]+testClosedStdoutCLI = do+  putStrLn "cli/closed-stdout"+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-cli-closed-stdout"+  ambient <- isolatedStoreEnvironment root+  let store = root </> "store"+      doomed = [T.unpack (T.replicate 32 letter) <> "-doomed" | letter <- ["a", "b"]]+      isolatedEnv =+        ("NIX_CONFIG", "substituters =\ntrusted-public-keys =\n")+          : ("XDG_CONFIG_HOME", root </> "config")+          : filter (\(key, _) -> key `notElem` ["NIX_CONFIG", "NIX_CONFIG_HOME", "XDG_CONFIG_HOME"]) ambient+      runClosed args =+        bracket Proc.createPipe (\(readEnd, writeEnd) -> hClose readEnd >> hClose writeEnd) $ \(readEnd, writeEnd) -> do+          hClose readEnd+          Proc.withCreateProcess+            ( (Proc.proc "cabal" (["run", "-v0", "exe:nova-nix", "--"] ++ args))+                { Proc.env = Just isolatedEnv,+                  Proc.std_out = Proc.UseHandle writeEnd,+                  Proc.std_err = Proc.CreatePipe+                }+            )+            $ \_ _ errPipe process -> do+              err <- maybe (pure BS.empty) BS.hGetContents errPipe+              code <- Proc.waitForProcess process+              pure (code, filter (not . BS.null) (BS8.lines (BS8.filter (/= '\r') err)))+      quiet label args =+        runTestM ("CLI " <> label <> " into a closed pipe exits 0 and reports nothing") $+          assertEqual "status and stderr" (ExitSuccess, []) <$> runClosed args+  bracket_+    (forceRemoveIfExists root >> createDirectoryIfMissing True store >> mapM_ (\name -> BS.writeFile (store </> name) "doomed\n") doomed)+    (forceRemoveIfExists root)+    $ sequence+      [ quiet "--help" ["--help"],+        quiet "eval" ["eval", "--expr", "1 + 2"],+        runTestM "CLI store delete into a closed pipe deletes every path it names and exits 0" $ do+          (code, err) <- runClosed (["store", "delete", "--store", store] ++ doomed)+          left <- filterM (Dir.doesPathExist . (store </>)) doomed+          pure (assertEqual "status, stderr and what is left" (ExitSuccess, ["finding garbage collector roots..."], []) (code, err, left))+      ]++-- | @key generate-secret@ and @key convert-secret-to-public@ through the+-- binary: the bytes each writes, with no line feed after them, the+-- generated key's public key as nova-cache derives it from the seed,+-- upstream's documented pair, and the refusals with their status.+testKeyCLI :: IO [Bool]+testKeyCLI = do+  putStrLn "cli/key"+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-cli-key"+  ambient <- isolatedStoreEnvironment root+  let isolatedEnv =+        ("NIX_CONFIG", "substituters =\ntrusted-public-keys =\n")+          : ("NIX_CONF_DIR", root </> "system")+          : ("XDG_CONFIG_HOME", root </> "config")+          : ("XDG_CONFIG_DIRS", root </> "config-dirs")+          : filter (\(key, _) -> key `notElem` ["NIX_CONFIG", "NIX_CONF_DIR", "NIX_USER_CONF_FILES", "XDG_CONFIG_HOME", "XDG_CONFIG_DIRS"]) ambient+      upstreamSecret = "cache.example.org-0:E7lAO+MsPwTFfPXsdPtW8GKui/5ho4KQHVcAGnX+Tti1V4dUxoVoqLyWJ4YESuZJwQ67GVIksDt47og+tPVUZw=="+  bracket_ (forceRemoveIfExists root) (forceRemoveIfExists root) $ do+    -- Built, if it is not, with the ambient environment cabal needs, then+    -- run by its path, so stdin and stdout reach it as bytes.+    _ <- Proc.readCreateProcessWithExitCode (Proc.proc "cabal" ["run", "-v0", "exe:nova-nix", "--", "--version"]) ""+    (_, listed, _) <- Proc.readCreateProcessWithExitCode (Proc.proc "cabal" ["list-bin", "-v0", "exe:nova-nix"]) ""+    let exe = fromMaybe "nova-nix" (listToMaybe (reverse (filter (not . null) (lines (filter (/= '\r') listed)))))+        run = runWithBytes exe isolatedEnv+    generated@(_, secret, _) <- run ["key", "generate-secret", "--key-name", "cache.example.org-1"] ""+    converted <- run ["key", "convert-secret-to-public"] secret+    upstream <- run ["key", "convert-secret-to-public"] (upstreamSecret <> "\n")+    corrupt <- run ["key", "convert-secret-to-public"] "no-colon"+    short <- run ["key", "convert-secret-to-public"] "k:AAAA"+    nameless <- run ["key", "generate-secret"] ""+    let derived = either (const Nothing) (Just . TE.encodeUtf8 . Signing.renderPublicKey) (Signing.parseSecretKey (TE.decodeLatin1 secret) >>= Signing.toPublicKey)+    sequence+      [ runTest "generate-secret prints the name, a colon and 88 characters of base64, with no line feed" $+          assertEqual "status, length after the name, stderr" (ExitSuccess, Just 88, "") (fst3 generated, BS.length <$> BS.stripPrefix "cache.example.org-1:" secret, thd3 generated),+        runTest "convert-secret-to-public prints the generated key's public key, the one its seed gives, with no line feed" $+          assertEqual "status, stdout, stderr" (ExitSuccess, derived, "") (fst3 converted, Just (snd3 converted), thd3 converted),+        runTest "convert-secret-to-public prints for upstream's example key, echoed, the public key upstream's documentation prints" $+          assertEqual "status and stdout" (ExitSuccess, "cache.example.org-0:tVeHVMaFaKi8lieGBErmScEOuxlSJLA7eO6IPrT1VGc=") (fst3 upstream, snd3 upstream),+        runTest "a key that does not read fails with status 1 and upstream's report, and one of the wrong size with upstream's line" $+          assertEqual+            "status, stdout, stderr"+            [ (ExitFailure 1, "", "error:\n       " <> TE.encodeUtf8 (T.singleton '\x2026') <> " while decoding key named ''\n\n       error: key is corrupt\n"),+              (ExitFailure 1, "", "error: secret key is not valid\n")+            ]+            [corrupt, short],+        runTest "generate-secret without --key-name is refused in upstream's words" $+          assertEqual "status and stderr" (ExitFailure 1, "key generate-secret: required argument '--key-name' is missing\n") (fst3 nameless, BS8.filter (/= '\r') (thd3 nameless))+      ]+  where+    fst3 (code, _, _) = code+    snd3 (_, out, _) = out+    thd3 (_, _, err) = err++-- | Run a program with bytes on its stdin: its status and the bytes it+-- wrote to stdout and stderr.+runWithBytes :: FilePath -> [(String, String)] -> [String] -> BS.ByteString -> IO (ExitCode, BS.ByteString, BS.ByteString)+runWithBytes exe environment args input =+  Proc.withCreateProcess+    (Proc.proc exe args) {Proc.env = Just environment, Proc.std_in = Proc.CreatePipe, Proc.std_out = Proc.CreatePipe, Proc.std_err = Proc.CreatePipe}+    $ \inPipe outPipe errPipe process -> do+      mapM_ (`hSetBinaryMode` True) (catMaybes [inPipe, outPipe, errPipe])+      traverse_ (\toChild -> BS.hPut toChild input >> hClose toChild) inPipe+      out <- maybe (pure BS.empty) BS.hGetContents outPipe+      err <- maybe (pure BS.empty) BS.hGetContents errPipe+      code <- Proc.waitForProcess process+      pure (code, out, err)++-- ---------------------------------------------------------------------------+-- Tests: realising a string's context+-- ---------------------------------------------------------------------------++-- | Import from derivation through the real CLI: a build imports and reads+-- an output it builds and one it substitutes, a value forced before the+-- build reads the same after it, the outputs and what they reference are+-- readable under restrict-eval and pure-eval, @eval --aterm@ builds as+-- @build@ does, @eval@ refuses a derivation it computed in upstream's+-- words, builds an output that may not be substituted and refuses one+-- that may, and reads what a fetcher fetched.+testImportFromDerivationCLI :: IO [Bool]+testImportFromDerivationCLI = do+  putStrLn "cli/import-from-derivation"+  shell <- findTestShell+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-cli-ifd"+  ambient <- isolatedStoreEnvironment root+  let isolatedEnvWith extraConfig =+        ("NIX_CONFIG", "substituters =\ntrusted-public-keys =\n" <> extraConfig)+          : ("XDG_CONFIG_HOME", root </> "config")+          : ("XDG_CACHE_HOME", root </> "cache")+          : filter (\(key, _) -> key `notElem` ["NIX_CONFIG", "NIX_CONFIG_HOME", "XDG_CONFIG_HOME", "XDG_CACHE_HOME"]) ambient+      runCLIWith extraConfig args =+        Proc.readCreateProcessWithExitCode+          ((Proc.proc "cabal" (["run", "-v0", "exe:nova-nix", "--"] ++ args)) {Proc.env = Just (isolatedEnvWith extraConfig)})+          ""+      runCLI = runCLIWith ""+      nixString text = "\"" <> T.replace "${" "\\${" (T.replace "\"" "\\\"" (T.replace "\\" "\\\\" text)) <> "\""+      system = nixString (platformToText currentPlatform)+      derivationOf name script extra =+        "derivation { name = " <> nixString name <> "; system = " <> system <> "; builder = " <> nixString shell <> "; args = [ \"-c\" " <> nixString script <> " ]; " <> hostToolsAttrs <> extra <> " }"+      -- A build of its own makes the file the expression imports and the+      -- one it reads; what the top derivation writes is what it read.+      ifd = derivationOf "ifd-made" "mkdir $out && printf '{ v = \"built\"; }' > $out/default.nix && printf data > $out/data" ""+      topWriting value = derivationOf "ifd-top" "printf %s \"$value\" > $out" ("value = " <> value <> ";")+      -- A value forced before the build and read after it.+      built = T.unpack ("let made = " <> ifd <> "; before = { kept = \"kept\"; }; read = builtins.seq before.kept ((import made).v + builtins.readFile \"${made}/data\"); in " <> topWriting "before.kept + read")+      substitutedBytes = "{ v = \"substituted\"; }" :: BS.ByteString+      fixedAttrs = "outputHashMode = \"flat\"; outputHashAlgo = \"sha256\"; outputHash = \"" <> Hash.bytesToHexText (sha256Digest substitutedBytes) <> "\";"+      substituted = T.unpack ("let fetched = " <> derivationOf "ifd-fetched.nix" "exit 1" fixedAttrs <> "; in " <> topWriting "(import fetched).v")+      readOnly = "import (derivation { name = \"ifd-read-only\"; system = \"x86_64-linux\"; builder = \"/bin/sh\"; })"+      -- The file read is in a dependency of the output imported, which the+      -- output's references name: readable only through its closure.  The+      -- output names it by its logical path, which a build in a store kept+      -- elsewhere would rewrite to where it is kept, so the path is put+      -- together from the dependency's base name, which keeps its context.+      dependency = derivationOf "ifd-dependency" "mkdir $out && printf depvalue > $out/value" ""+      reading = derivationOf "ifd-reading" "mkdir $out && printf 'builtins.readFile \"/nix/%s/%s/value\"' store \"$dependencyName\" > $out/default.nix" ("dependencyName = builtins.baseNameOf \"${" <> dependency <> "}\";")+      throughDependency = T.unpack (topWriting ("import (" <> reading <> ")"))+      -- A build of something else adds both derivations, as every+      -- derivation evaluation recorded goes in, and builds neither.+      unsubstitutable = derivationOf "ifd-unsubstitutable" "mkdir $out && printf built-read-only > $out/data" "allowSubstitutes = false;"+      substitutable = derivationOf "ifd-substitutable" "mkdir $out && printf never > $out/data" ""+      holder = T.unpack ("builtins.seq (" <> unsubstitutable <> ").drvPath (builtins.seq (" <> substitutable <> ").drvPath (" <> derivationOf "ifd-holder" "printf held > $out" "" <> "))")+      readData derivation = T.unpack ("builtins.readFile \"${" <> derivation <> "}/data\"")+      stage = root </> "stage"+      tarball = root </> "fetched.tar.gz"+      repo = root </> "repo"+      fileUrl path = "file://" <> canonPathValue (T.pack path)+      tarProcess =+        (Proc.proc "tar" ["-czf", tarball, "-C", stage, "top"])+          { Proc.env = Just (("COPYFILE_DISABLE", "1") : ambient)+          }+      evalAt store source = runCLI ["eval", "--expr", source, "--store", root </> store]+      lastLineOf err = listToMaybe (reverse (filter (not . T.null) (map T.strip (T.lines (T.pack err)))))+      refusesImport line =+        "error: cannot build '/nix/store/" `T.isPrefixOf` line+          && "-ifd-made.drv^out' during evaluation because the option 'allow-import-from-derivation' is disabled" `T.isSuffixOf` line+      -- A store upstream Nix's database manages, holding the derivation+      -- of substitutable and not its output.+      upstreamRoot = root </> "upstream"+      upstreamStore = upstreamRoot </> "nix" </> "store"+      upstreamDb = upstreamRoot </> "nix" </> "var" </> "nix" </> "db" </> "db.sqlite"+      substitutableDrvPath = T.unpack ("(" <> substitutable <> ").drvPath")+      buildWith extraConfig store source flags = runCLIWith extraConfig (["build", "--expr", source, "--store", root </> store, "--no-out-link"] ++ flags)+      build = buildWith ""+      printed out = listToMaybe (reverse (filter (not . null) (lines (filter (/= '\r') out))))+      contentsOf out = maybe (pure Nothing) (fmap Just . BS.readFile) (printed out)+      outcome (code, out, err) = "exit " <> T.pack (show code) <> "; stdout=" <> T.pack out <> "; stderr=" <> T.pack err+      narInfoTarget out = "/" <> TE.encodeUtf8 (spHash out) <> ".narinfo"+      substitutedNar = NAR.serialise (NAR.NarRegular False substitutedBytes)+  fetchedOut <- either (fail . show) pure (makeFixedOutputPath "ifd-fetched.nix" "sha256" FlatIngestion (sha256Digest substitutedBytes))+  (trustedKey, fetchedNarInfo) <- either fail pure (signedTestNarInfo fetchedOut [] "nar/fetched.nar" substitutedNar)+  let route target _+        | target == narInfoTarget fetchedOut = Send (httpResponse "200 OK" (TE.encodeUtf8 fetchedNarInfo))+        | target == "/nar/fetched.nar" = Send (httpResponse "200 OK" substitutedNar)+        | otherwise = Send (httpResponse "404 Not Found" "missing")+  bracket_+    (forceRemoveIfExists root >> createDirectoryIfMissing True root)+    (forceRemoveIfExists root)+    ( do+        madeRun@(_, madeOut, _) <- build "built" built []+        made <- contentsOf madeOut+        -- The same store, where the outputs are valid now.+        flagOffRun@(flagOffCode, _, flagOffErr) <- build "built" built ["--no-allow-import-from-derivation"]+        configOffRun@(configOffCode, _, configOffErr) <- buildWith "allow-import-from-derivation = false\n" "import-off" built []+        tracedRun@(_, tracedOut, tracedErr) <- buildWith "trace-import-from-derivation = true\n" "traced" built []+        traced <- contentsOf tracedOut+        restrictedRun@(_, restrictedOut, _) <- build "restricted" throughDependency ["--restrict-eval"]+        restricted <- contentsOf restrictedOut+        pureRun@(_, pureOut, _) <- build "pure" throughDependency ["--pure-eval"]+        pureRead <- contentsOf pureOut+        atermRun@(atermCode, atermOut, _) <- runCLI ["eval", "--aterm", "--expr", built, "--store", root </> "aterm"]+        holderRun@(holderCode, _, _) <- build "read-only-build" holder []+        unsubstitutableRun@(_, unsubstitutableOut, _) <- evalAt "read-only-build" (readData unsubstitutable)+        substitutableRun@(substitutableCode, _, substitutableErr) <- evalAt "read-only-build" (readData substitutable)+        (_, drvPathOut, _) <- evalAt "upstream-source" substitutableDrvPath+        (_, atermOfSubstitutable, _) <- runCLI ["eval", "--aterm", "--expr", T.unpack substitutable, "--store", root </> "upstream-source"]+        createDirectoryIfMissing True upstreamStore+        createDirectoryIfMissing True (takeDirectory upstreamDb)+        BS.writeFile upstreamDb ""+        forM_ (printed drvPathOut) $ \quoted ->+          BS.writeFile (upstreamStore </> takeFileName (filter (/= '"') quoted)) (BS8.pack (filter (`notElem` ("\r\n" :: String)) atermOfSubstitutable))+        upstreamRun@(upstreamCode, _, upstreamErr) <- runCLI ["eval", "--expr", readData substitutable, "--store", upstreamStore]+        -- What eval writes, read-only by default and under --read-write-mode.+        BS.writeFile (root </> "eval-source.txt") "a source\n"+        let pathExpr = T.unpack ("builtins.path { path = " <> nixString (T.pack (root </> "eval-source.txt")) <> "; }")+            toFileExpr = "builtins.toFile \"eval-written\" \"written\""+        computedRun@(computedCode, computedOut, _) <- evalAt "eval-read-only" toFileExpr+        computedStoreMade <- Dir.doesPathExist (root </> "eval-read-only")+        upstreamPathRun@(upstreamPathCode, upstreamPathOut, _) <- runCLI ["eval", "--expr", pathExpr, "--store", upstreamStore]+        upstreamPathWritten <- maybe (pure False) (\line -> Dir.doesPathExist (upstreamStore </> takeFileName (filter (/= '"') line))) (printed upstreamPathOut)+        -- An evaluation that made nothing adds nothing there, and one that+        -- must write is refused.+        nothingMadeRun@(nothingMadeCode, nothingMadeOut, _) <- runCLI ["eval", "--read-write-mode", "--expr", "1", "--store", upstreamStore]+        neededWriteRun@(neededWriteCode, _, _) <- runCLI ["eval", "--read-write-mode", "--expr", toFileExpr, "--store", upstreamStore]+        -- A pinned fetch, then the same fetch with its source gone.+        createDirectoryIfMissing True (root </> "fetch-source")+        BS.writeFile (root </> "fetch-source" </> "eval-pinned") "pinned\n"+        let pinnedExpr = T.unpack ("builtins.fetchurl { url = " <> nixString (fileUrl (root </> "fetch-source" </> "eval-pinned")) <> "; sha256 = \"" <> Hash.bytesToHexText (sha256Digest "pinned\n") <> "\"; }")+        firstFetchRun@(_, firstFetchOut, _) <- evalAt "eval-fetching" pinnedExpr+        Dir.removeFile (root </> "fetch-source" </> "eval-pinned")+        secondFetchRun@(secondFetchCode, secondFetchOut, _) <- evalAt "eval-fetching" pinnedExpr+        writtenRun@(writtenCode, writtenOut, _) <- runCLI ["eval", "--read-write-mode", "--expr", toFileExpr, "--store", root </> "eval-read-write"]+        readBackRun@(_, readBackOut, _) <- evalAt "eval-read-write" ("builtins.readFile (" <> toFileExpr <> ")")+        evalBuiltRun@(_, evalBuiltOut, _) <-+          runCLI ["eval", "--read-write-mode", "--expr", T.unpack ("let made = " <> ifd <> "; in (import made).v + builtins.readFile \"${made}/data\""), "--store", root </> "eval-built"]+        evalSubstitutedRun@(_, evalSubstitutedOut, _) <-+          withHttpServer route $ \base _ _ ->+            runCLI ["eval", "--read-write-mode", "--substituter", T.unpack base, "--trusted-key", T.unpack trustedKey, "--expr", T.unpack ("(import (" <> derivationOf "ifd-fetched.nix" "exit 1" fixedAttrs <> ")).v"), "--store", root </> "eval-substituted"]+        createDirectoryIfMissing True (stage </> "top")+        BS.writeFile (stage </> "top" </> "default.nix") "{ v = \"from a tarball\"; }\n"+        tarballRun <-+          if SI.os == "mingw32"+            then pure Nothing+            else do+              (tarCode, _, tarErr) <- Proc.readCreateProcessWithExitCode tarProcess ""+              case tarCode of+                ExitFailure _ -> pure (Just (tarCode, "", tarErr))+                ExitSuccess -> Just <$> evalAt "fetching" (T.unpack ("(import \"${builtins.fetchTarball " <> nixString (fileUrl tarball) <> "}/default.nix\").v"))+        _ <- makeGitFixture repo [("VERSION", "1.2.3\n")]+        gitRun@(_, gitOut, _) <- evalAt "fetching" (T.unpack ("builtins.readFile \"${builtins.fetchGit { url = " <> nixString (T.pack repo) <> "; }}/VERSION\""))+        substitutedRun@(_, substitutedOut, _) <-+          withHttpServer route $ \base _ _ ->+            build "substituted" substituted ["--substituter", T.unpack base, "--trusted-key", T.unpack trustedKey]+        fetched <- contentsOf substitutedOut+        refusedRun@(refusedCode, _, refusedErr) <- runCLI ["eval", "--expr", readOnly, "--store", root </> "read-only"]+        readOnlyStoreMade <- Dir.doesPathExist (root </> "read-only")+        let lastLine = lastLineOf refusedErr+        sequence+          [ runTest "build imports and reads an output it builds, and a value forced before the build reads the same after it" $+              if made == Just "keptbuiltdata" then Pass else Fail (outcome madeRun),+            -- realiseContext refuses before it builds, once the paths are+            -- valid (primops.cc), naming the first Built element as+            -- upstream renders it (DerivedPath::Built::to_string in+            -- derived-path.cc).+            runTest "--no-allow-import-from-derivation refuses an import from a derivation whose output is valid, in upstream's words" $+              if flagOffCode == ExitFailure 1 && maybe False refusesImport (lastLineOf flagOffErr) then Pass else Fail (outcome flagOffRun),+            runTest "allow-import-from-derivation = false in NIX_CONFIG refuses an import from a derivation before anything is built" $+              if configOffCode == ExitFailure 1 && maybe False refusesImport (lastLineOf configOffErr) && not ("[build]" `isInfixOf` configOffErr)+                then Pass+                else Fail (outcome configOffRun),+            -- The warning comes before the build (realiseContext in+            -- primops.cc at 2.34.9), so it precedes the build's own lines.+            runTest "trace-import-from-derivation in NIX_CONFIG warns of the import, naming its output, before the build" $+              case break ("[build]  ifd-made" `isInfixOf`) (lines tracedErr) of+                (before, _ : _)+                  | traced == Just "keptbuiltdata",+                    any (\line -> "warning: built '/nix/store/" `isPrefixOf` line && "-ifd-made.drv^out' during evaluation due to an import from derivation" `isSuffixOf` line) before ->+                      Pass+                _ -> Fail (outcome tracedRun),+            runTest "build imports an output a cache holds, and runs no builder for it" $+              if fetched == Just "substituted" then Pass else Fail (outcome substitutedRun),+            runTest "an output built during evaluation, and a file in what it references, are readable under restrict-eval" $+              if restricted == Just "depvalue" then Pass else Fail (outcome restrictedRun),+            runTest "an output built during evaluation, and a file in what it references, are readable under pure-eval" $+              if pureRead == Just "depvalue" then Pass else Fail (outcome pureRun),+            runTest "eval --aterm adds and builds what an import from derivation names, as plain nix-instantiate does" $+              if atermCode == ExitSuccess && "keptbuiltdata" `T.isInfixOf` T.pack atermOut then Pass else Fail (outcome atermRun),+            -- Upstream's read-only evaluation refuses a substitution and+            -- builds an output that may not be substituted+            -- (PathSubstitutionGoal::init in substitution-goal.cc at+            -- 2.24.9, PathSubstitutionGoal::substitute at 2.36.0, and+            -- DerivationGoal::haveDerivation in derivation-goal.cc).+            runTest "eval builds an output of a derivation the store holds that may not be substituted, and reads it" $+              if holderCode == ExitSuccess && printed unsubstitutableOut == Just "\"built-read-only\"" then Pass else Fail (outcome holderRun <> "; " <> outcome unsubstitutableRun),+            runTest "eval refuses to substitute an output of a derivation the store holds, in upstream's words" $+              case lastLineOf substitutableErr of+                Just line+                  | substitutableCode == ExitFailure 1,+                    "error: cannot substitute path '/nix/store/" `T.isPrefixOf` line,+                    "-ifd-substitutable' - no write access to the Nix store" `T.isSuffixOf` line ->+                      Pass+                _ -> Fail (outcome substitutableRun),+            -- Upstream's substitution goal refuses before anything is built+            -- or written (PathSubstitutionGoal::init in substitution-goal.cc+            -- at 2.24.9, PathSubstitutionGoal::substitute at 2.36.0), so the+            -- store's own refusal is never reached.+            runTest "eval refuses to substitute an output in a store upstream Nix manages in upstream's words, before refusing the store" $+              case lastLineOf upstreamErr of+                Just line+                  | upstreamCode == ExitFailure 1,+                    "error: cannot substitute path '/nix/store/" `T.isPrefixOf` line,+                    "-ifd-substitutable' - no write access to the Nix store" `T.isSuffixOf` line ->+                      Pass+                _ -> Fail (outcome upstreamRun),+            -- nix-instantiate --eval computes these paths without writing+            -- them (prim_toFile and addPath in primops.cc).+            runTest "eval prints a toFile result's path and makes no store" $+              if computedCode == ExitSuccess && printed computedOut == printed writtenOut && not computedStoreMade then Pass else Fail (outcome computedRun <> "; " <> outcome writtenRun),+            runTest "eval prints a builtins.path copy's path in a store upstream Nix manages, writing nothing there" $+              case printed upstreamPathOut of+                Just line+                  | upstreamPathCode == ExitSuccess,+                    "\"/nix/store/" `isPrefixOf` line,+                    "-eval-source.txt\"" `isSuffixOf` line,+                    not upstreamPathWritten ->+                      Pass+                _ -> Fail (outcome upstreamPathRun),+            runTest "eval --read-write-mode that makes nothing adds nothing, so a store upstream Nix manages refuses nothing" $+              if nothingMadeCode == ExitSuccess && printed nothingMadeOut == Just "1" then Pass else Fail (outcome nothingMadeRun),+            runTest "eval --read-write-mode that must write in a store upstream Nix manages is refused" $+              if neededWriteCode == ExitFailure 1 then Pass else Fail (outcome neededWriteRun),+            -- Upstream's local store adds a fetch as it lands, in any mode+            -- (downloadFile in tarball.cc), so its next evaluation takes the+            -- pinned fetch's early exit (fetch in fetchTree.cc).+            runTest "eval registers what a pinned fetch writes, so a second eval of it needs no source" $+              if secondFetchCode == ExitSuccess && isJust (printed firstFetchOut) && printed secondFetchOut == printed firstFetchOut+                then Pass+                else Fail (outcome firstFetchRun <> "; " <> outcome secondFetchRun),+            -- Upstream's read-write evaluation adds what it makes as it goes+            -- (prim_toFile in primops.cc), so a later evaluation finds it+            -- valid.+            runTest "eval --read-write-mode writes and registers a toFile result, which a read-only eval then reads" $+              if writtenCode == ExitSuccess && printed readBackOut == Just "\"written\"" then Pass else Fail (outcome writtenRun <> "; " <> outcome readBackRun),+            runTest "eval --read-write-mode imports and reads an output it builds" $+              if printed evalBuiltOut == Just "\"builtdata\"" then Pass else Fail (outcome evalBuiltRun),+            runTest "eval --read-write-mode imports an output a cache holds, through --substituter and --trusted-key" $+              if printed evalSubstitutedOut == Just "\"substituted\"" then Pass else Fail (outcome evalSubstitutedRun),+            runTest "eval imports a fetchTarball result through its context" $+              case tarballRun of+                Nothing -> Pass+                Just run@(_, tarballOut, _) -> if printed tarballOut == Just "\"from a tarball\"" then Pass else Fail (outcome run),+            runTest "eval reads a fetchGit result through its context" $+              if printed gitOut == Just "\"1.2.3\\n\"" then Pass else Fail (outcome gitRun),+            runTest "eval refuses an import from a derivation in upstream's words, under its line of context, and makes no store" $+              case lastLine of+                Just line+                  | refusedCode == ExitFailure 1,+                    "error: path '/nix/store/" `T.isPrefixOf` line,+                    "-ifd-read-only.drv' is not valid" `T.isSuffixOf` line,+                    "while realising the context of path '/nix/store/" `T.isInfixOf` T.pack refusedErr,+                    not readOnlyStoreMade ->+                      Pass+                _ -> Fail (outcome refusedRun)+          ]+    )++-- | @build --check@ and @keep-failed@ through the real CLI, which the+-- tests of the build itself cannot show: that the flags and the setting+-- reach the build, that a check which passes prints the path a build+-- prints, that one which finds a difference exits with upstream's status+-- for it, and what a build that fails keeps and names on stderr.+testCheckCLI :: IO [Bool]+testCheckCLI = do+  putStrLn "cli/check"+  shell <- findTestShell+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-cli-check"+  ambient <- isolatedStoreEnvironment root+  let isolatedEnv configText =+        ("NIX_CONFIG", "substituters =\ntrusted-public-keys =\n" <> configText)+          : ("XDG_CONFIG_HOME", root </> "config")+          : filter (\(key, _) -> key `notElem` ["NIX_CONFIG", "NIX_CONFIG_HOME", "XDG_CONFIG_HOME"]) ambient+      runCLIWith configText args =+        Proc.readCreateProcessWithExitCode+          ((Proc.proc "cabal" (["run", "-v0", "exe:nova-nix", "--"] ++ args)) {Proc.env = Just (isolatedEnv configText)})+          ""+      nixString text = "\"" <> T.replace "${" "\\${" (T.replace "\"" "\\\"" (T.replace "\\" "\\\\" text)) <> "\""+      expression name script =+        T.unpack+          ( "derivation { name = "+              <> nixString name+              <> "; system = builtins.currentSystem; builder = "+              <> nixString shell+              <> "; args = [ \"-c\" "+              <> nixString script+              <> " ]; }"+          )+      -- Its output holds its own path, which a rebuild beside the valid+      -- output writes as the scratch path and the check rewrites.+      same = expression "check-same" "echo $out > $out"+      -- Its output holds the hash of its own path cut in two, where no+      -- rewrite of the whole hash reaches it, so a rebuild at a scratch+      -- path comes out different.+      differing =+        expression+          "check-differs"+          "stem=${out%-check-differs}; front=${stem%????????????????}; printf '%s\\n%s\\n' \"$front\" \"${stem#\"$front\"}\" > \"$out\""+      -- It leaves a file where it works, then fails.+      failing = expression "keep-failed" "echo left > left; exit 1"+      buildWith configText source store flags = runCLIWith configText (["build", "--expr", source, "--store", root </> store, "--no-out-link"] ++ flags)+      build = buildWith ""+      printed out = listToMaybe (reverse (filter (not . null) (lines (filter (/= '\r') out))))+      outcome (code, out, err) = "exit " <> T.pack (show code) <> "; stdout=" <> T.pack out <> "; stderr=" <> T.pack err+      stderrLines err = lines (filter (/= '\r') err)+      -- The directories upstream's note names, in the order it names them.+      keptDirs err = [dir | line <- stderrLines err, Just quoted <- [stripPrefix "note: keeping build directory \"" line], Just dir <- [stripSuffix "\"" quoted]]+      stripSuffix suffix text = reverse <$> stripPrefix (reverse suffix) (reverse text)+      -- What the builder left in the directory a note names, if it is+      -- there.+      leftIn dir = do+        present <- Dir.doesFileExist (dir </> "left")+        if present then Just <$> BS.readFile (dir </> "left") else pure Nothing+      buildsUnder store = do+        let builds = root </> store </> ".nova-nix" </> "builds"+        present <- doesDirectoryExist builds+        if present then Dir.listDirectory builds else pure []+  bracket_+    (forceRemoveIfExists root >> createDirectoryIfMissing True root)+    (forceRemoveIfExists root)+    ( do+        sameBuilt@(_, sameOut, _) <- build same "same" []+        sameChecked@(sameCode, sameCheckedOut, sameErr) <- build same "same" ["--check"]+        unbuilt@(unbuiltCode, _, unbuiltErr) <- build same "unbuilt" ["--check"]+        differingBuilt@(_, differingOut, _) <- build differing "differing" []+        differingChecked@(differingCode, _, differingErr) <- build differing "differing" ["--check"]+        keptChecked@(keptCode, _, keptErr) <- build differing "differing" ["--check", "--keep-failed"]+        keptRebuild <- traverse (\path -> Dir.doesPathExist (path <> ".check")) (printed differingOut)+        flagKept@(flagKeptCode, _, flagKeptErr) <- build failing "failing-flag" ["-K"]+        flagLeft <- traverse leftIn (keptDirs flagKeptErr)+        configKept@(configKeptCode, _, configKeptErr) <- buildWith "keep-failed = true\n" failing "failing-config" []+        configLeft <- traverse leftIn (keptDirs configKeptErr)+        removed@(removedCode, _, removedErr) <- build failing "failing-removed" []+        removedLeft <- buildsUnder "failing-removed"+        sequence+          [ runTest "a check that passes exits 0 and prints the path the build printed" $+              case (printed sameOut, sameCode) of+                (Just path, ExitSuccess)+                  | printed sameCheckedOut == Just path && "[check]" `T.isInfixOf` T.pack sameErr -> Pass+                _ -> Fail ("build: " <> outcome sameBuilt <> "; check: " <> outcome sameChecked),+            runTest "a check with no valid output exits 1 with upstream's message" $+              if unbuiltCode == ExitFailure 1 && "are not valid, so checking is not possible" `T.isInfixOf` T.pack unbuiltErr+                then Pass+                else Fail (outcome unbuilt),+            runTest "a check that finds a difference exits 104 with upstream's message" $+              case printed differingOut of+                Just path+                  | differingCode == ExitFailure 104+                      && ("may not be deterministic: output \"" <> T.pack path <> "\" differs\n") `T.isInfixOf` T.pack differingErr+                      && null (keptDirs differingErr) ->+                      Pass+                _ -> Fail ("build: " <> outcome differingBuilt <> "; check: " <> outcome differingChecked),+            -- The check's failure keeps its build directory too, as any+            -- failure does under keep-failed.+            runTest "a check under --keep-failed that finds a difference keeps the rebuild as PATH.check and names it" $+              case (printed differingOut, keptDirs keptErr) of+                (Just path, [_])+                  | keptCode == ExitFailure 104+                      && ("may not be deterministic: output \"" <> T.pack path <> "\" differs from \"" <> T.pack path <> ".check\"") `T.isInfixOf` T.pack keptErr+                      && keptRebuild == Just True ->+                      Pass+                _ -> Fail ("check: " <> outcome keptChecked <> "; kept: " <> T.pack (show keptRebuild)),+            -- Upstream prints its note when it cleans up after the+            -- builder, before the failure is reported.+            runTest "a build that fails under -K keeps the directory its builder worked in and names it before the failure" $+              case (flagLeft, findIndex ("note: keeping build directory " `isPrefixOf`) (stderrLines flagKeptErr), findIndex ("build failed" `isPrefixOf`) (stderrLines flagKeptErr)) of+                ([Just "left\n"], Just note, Just failure)+                  | flagKeptCode == ExitFailure 1 && note < failure -> Pass+                _ -> Fail (outcome flagKept <> "; left: " <> T.pack (show flagLeft)),+            runTest "a build that fails with keep-failed in nix.conf keeps its directory" $+              if configKeptCode == ExitFailure 1 && configLeft == [Just "left\n"]+                then Pass+                else Fail (outcome configKept <> "; left: " <> T.pack (show configLeft)),+            runTest "a build that fails without keep-failed keeps no directory and names none" $+              if removedCode == ExitFailure 1 && null (keptDirs removedErr) && null removedLeft+                then Pass+                else Fail (outcome removed <> "; left under builds: " <> T.pack (show removedLeft))+          ]+    )++-- | @develop@ and @print-dev-env@ through the built CLI, over+-- test/data/develop/shell.nix: what a command, a phase and the+-- environment flags see, the refusals before and after the capture and+-- their order, the descriptors the command starts with after a+-- substitution over HTTP, structured attributes' files, the JSON+-- layouts, the temporary files left behind, and that a second run builds+-- nothing.  The binary runs itself, with every descriptor of the suite's+-- closed, and reads get-env.sh from the repository's data directory.+-- The fixture's builder is a bash whose @declare -p@, given no name,+-- prints declare commands, which get-env.sh reads: macOS's /bin/bash 3.2+-- prints @NAME=value@ lines there, from which it captures no variable.+-- The same bash leads @PATH@, so that it is the shell too, which needs+-- @declare -A@ under structured attributes.  Each command removes the+-- fresh @NIX_BUILD_TOP@ the rcfile makes, which macOS's @mktemp -t@ puts+-- in the user's temporary directory whatever @TMPDIR@ says.  On Windows+-- both commands are refused.+testDevelopCLI :: IO [Bool]+testDevelopCLI = do+  putStrLn "cli/develop"+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-cli-develop"+  ambient <- isolatedStoreEnvironment root+  let store = root </> "store"+      marker = root </> "marker"+      shellTemp = root </> "tmp"+      isolatedNames = ["NIX_CONFIG", "NIX_CONF_DIR", "NIX_USER_CONF_FILES", "NIX_CONFIG_HOME", "XDG_CONFIG_HOME", "XDG_CONFIG_DIRS", "XDG_STATE_HOME", "XDG_DATA_HOME", "NIX_STATE_HOME", "HOME", "ZDOTDIR", "BASH_ENV", "ENV", "TMPDIR", "NIX_DATA_DIR", "nova_nix_datadir", "DEVELOP_KEEP", "DEVELOP_DROP", "DEVELOP_NEW"]+      isolatedEnv dataDir =+        [ ("NIX_CONFIG", "substituters =\ntrusted-public-keys =\n"),+          ("NIX_CONF_DIR", root </> "system"),+          ("NIX_USER_CONF_FILES", ""),+          ("XDG_CONFIG_HOME", root </> "home" </> "config"),+          ("XDG_STATE_HOME", root </> "home" </> "state"),+          ("XDG_DATA_HOME", root </> "home" </> "data"),+          ("NIX_STATE_HOME", root </> "home" </> "nix"),+          ("HOME", root </> "home"),+          ("ZDOTDIR", root </> "home"),+          ("TMPDIR", shellTemp),+          ("NIX_DATA_DIR", dataDir),+          ("DEVELOP_KEEP", "kept"),+          ("DEVELOP_DROP", "dropped")+        ]+          <> filter ((`notElem` isolatedNames) . fst) ambient+  if SI.os == "mingw32"+    then do+      let refused args = runTestM ("nova-nix " <> T.pack (unwords args) <> " is refused on Windows") $ do+            (code, _, err) <- Proc.readCreateProcessWithExitCode ((Proc.proc "cabal" (["run", "-v0", "exe:nova-nix", "--"] ++ args)) {Proc.env = Just (isolatedEnv "data")}) ""+            pure $+              if code == ExitFailure 1 && listToMaybe (reverse (lines (filter (/= '\r') err))) == Just "error: develop and print-dev-env do not run on Windows yet"+                then Pass+                else Fail ("exit " <> T.pack (show code) <> ": " <> T.pack err)+      bracket_+        (forceRemoveIfExists root >> createDirectoryIfMissing True root)+        (forceRemoveIfExists root)+        (sequence [refused ["develop", "--expr", "1"], refused ["print-dev-env", "--expr", "1"]])+    else do+      builder <- declaringBash+      case builder of+        Nothing -> [True] <$ putStrLn "  SKIP  no bash whose declare -p prints declare commands"+        Just bash -> do+          (built, _, buildErr) <- Proc.readCreateProcessWithExitCode (Proc.proc "cabal" ["build", "-v0", "exe:nova-nix"]) ""+          (_, listed, _) <- Proc.readCreateProcessWithExitCode (Proc.proc "cabal" ["list-bin", "-v0", "exe:nova-nix"]) ""+          dataDir <- Dir.makeAbsolute "data"+          fixture <- Dir.makeAbsolute ("test" </> "data" </> "develop" </> "shell.nix")+          case (built, lines listed) of+            (ExitSuccess, [binary]) ->+              bracket_+                (forceRemoveIfExists root >> mapM_ (createDirectoryIfMissing True) [root </> "home", shellTemp])+                (forceRemoveIfExists root)+                (runDevelopCLI bash binary fixture (isolatedEnv dataDir) root store marker shellTemp)+            _ -> sequence [runTest "the CLI builds" (Fail (T.pack buildErr))]+  where+    -- A bash get-env.sh can run: the first whose declare -p, given no+    -- name as get-env.sh gives it none, prints a declare command for a+    -- variable.+    declaringBash = do+      onPath <- Dir.findExecutable "bash"+      firstM declares (["/bin/bash", "/usr/bin/bash", "/opt/homebrew/bin/bash", "/usr/local/bin/bash"] <> maybeToList onPath)+    declares candidate = do+      present <- Dir.doesFileExist candidate+      if not present+        then pure False+        else do+          (code, out, _) <- Proc.readCreateProcessWithExitCode (Proc.proc candidate ["-c", "x=1; declare -p"]) ""+          pure (code == ExitSuccess && any ("declare -- x=" `isPrefixOf`) (lines out))+    firstM _ [] = pure Nothing+    firstM check (candidate : rest) = do+      found <- check candidate+      if found then pure (Just candidate) else firstM check rest++-- | The runs of 'testDevelopCLI' on a POSIX host, given the bash the+-- fixture's builder is, the binary, the fixture, the environment, and+-- the root, store, marker file and temporary directory under it.+runDevelopCLI :: FilePath -> FilePath -> FilePath -> [(String, String)] -> FilePath -> FilePath -> FilePath -> FilePath -> IO [Bool]+runDevelopCLI bash binary fixture ambientEnv root store marker shellTemp = do+  let env = ("PATH", takeDirectory bash <> maybe "" (searchPathSeparator :) (lookup "PATH" ambientEnv)) : filter ((/= "PATH") . fst) ambientEnv+      runIn environment args = Proc.readCreateProcessWithExitCode (Proc.proc binary args) {Proc.env = Just environment, Proc.close_fds = True} ""+      run = runIn env+      target command builder markerFile = [command, fixture, "--argstr", "marker", markerFile, "--argstr", "builder", builder, "--no-sandbox"]+      developIn environment storeDir flags = runIn environment (target "develop" bash marker <> ["--store", storeDir] <> flags)+      develop = developIn env+      -- A command that first removes the fresh NIX_BUILD_TOP, which only+      -- an empty directory lets it do.+      inShell script = ["--command", "/bin/sh", "-c", "rmdir \"$NIX_BUILD_TOP\" && " <> script]+      probe = "printf '%s/%s/%s' \"${DEVELOP_KEEP-unset}\" \"${DEVELOP_DROP-unset}\" \"${DEVELOP_NEW-unset}\""+      outcome (code, out, err) = "exit " <> T.pack (show code) <> "; stdout=" <> T.pack out <> "; stderr=" <> T.pack err+      -- Refused with status 1 and the message as stderr's last line, after+      -- what the capture's build logged.+      refusedWith message result@(code, _, err)+        | code == ExitFailure 1 && listToMaybe (reverse (lines err)) == Just message = Pass+        | otherwise = Fail (outcome result)+      structuredTemp = root </> "structured-tmp"+      structuredEnv = ("TMPDIR", structuredTemp) : filter ((/= "TMPDIR") . fst) env+      -- A variant's capture is another derivation, with a marker of its+      -- own, so that the main one counts the main capture's runs alone.+      structured command flags = runIn structuredEnv (target command bash (root </> "structured-marker") <> ["--store", store, "--arg", "structured", "true"] <> flags)+      substituting storeDir flags = run (target "develop" bash (root </> "substitution-marker") <> ["--store", storeDir] <> flags)+  createDirectoryIfMissing True structuredTemp+  seen@(_, seenOut, _) <- develop store (inShell "develop-tool && printf '%s|%s' \"$greeting\" \"$NIX_GCROOT\"")+  exited <- develop store (inShell "exit 7")+  phase <- develop store ["--phase", "build"]+  phaseFlag <- develop store ["--build"]+  ignored <- develop store (["-i", "-k", "DEVELOP_KEEP", "-k", "PATH"] <> inShell probe)+  changed <- develop store (["-u", "DEVELOP_DROP", "-s", "DEVELOP_NEW", "new"] <> inShell probe)+  emptyName <- developIn (("", "x") : env) store (inShell "true")+  unsetIgnored <- develop store ["-i", "-u", "X", "--command", "true"]+  keptWithout <- develop store ["-k", "X", "--command", "true"]+  both <- develop store ["--phase", "build", "--command", "true"]+  scriptFirst <- run (target "develop" bash (root </> "array-marker") <> ["--store", store, "--arg", "arrayOutput", "true", "-i", "-u", "X", "--phase", "build", "--command", "true"])+  unexecutable <- develop store ["-s", "PATH", "/nonexistent", "--command", "true"]+  parseRefused <- develop store ["-u", "X", "-s", "X", "1", "--command", "true"]+  commandless <- develop store ["--command"]+  notBash <- run (target "develop" "/bin/sh" marker <> ["--store", root </> "refused-store", "--command", "true"])+  printed@(_, printedOut, _) <- run (target "print-dev-env" bash marker <> ["--store", store])+  let printedScript = root </> "printed.sh"+  BS.writeFile printedScript (TE.encodeUtf8 (T.pack printedOut))+  sourced <- Proc.readCreateProcessWithExitCode (Proc.proc bash ["-c", ". \"$1\" && rmdir \"$NIX_BUILD_TOP\" && printf '%s' \"$greeting\"", "bash", printedScript]) {Proc.env = Just env} ""+  json@(_, jsonOut, _) <- run (target "print-dev-env" bash marker <> ["--store", store, "--json"])+  pretty@(_, prettyOut, _) <- run (target "print-dev-env" bash marker <> ["--store", store, "--no-pretty", "--json", "--pretty"])+  notPretty@(_, notPrettyOut, _) <- run (target "print-dev-env" bash marker <> ["--store", store, "--pretty", "--json", "--no-pretty"])+  structuredSeen@(_, structuredOut, _) <- structured "develop" (inShell "printf '%s|%s' \"$NIX_ATTRS_SH_FILE\" \"$NIX_ATTRS_JSON_FILE\"")+  structuredRoot <- Dir.canonicalizePath structuredTemp+  structuredFiles <- case T.splitOn "|" (T.pack structuredOut) of+    [shFile, jsonFile] -> do+      sh <- BS.readFile (T.unpack shFile)+      jsonBytes <- BS.readFile (T.unpack jsonFile)+      pure (Right (T.unpack shFile, T.unpack jsonFile, sh, jsonBytes))+    _ -> pure (Left ())+  structuredPrinted@(_, structuredPrintedOut, _) <- structured "print-dev-env" []+  structuredLeft <- sort <$> Dir.listDirectory structuredTemp+  descriptors <- substitutedDescriptors run substituting inShell fixture root "http" withKeepAliveDirectoryServer+  directDescriptors <- substitutedDescriptors run substituting inShell fixture root "file" (\cache use -> use (directoryUrl cache))+  direct <- Proc.readCreateProcessWithExitCode (Proc.proc "/bin/sh" ["-c", "ls /dev/fd/"]) {Proc.env = Just env, Proc.close_fds = True} ""+  gcrootEnvironment <- case T.splitOn "|" (T.pack seenOut) of+    [_, gcroot] -> Right <$> BS.readFile (T.unpack gcroot)+    _ -> pure (Left ())+  refusedStore <- Dir.doesDirectoryExist (root </> "refused-store")+  refusedScripts <- if refusedStore then filter ("-get-env.sh" `isSuffixOf`) <$> Dir.listDirectory (root </> "refused-store") else pure []+  runs <- BS8.lines <$> BS.readFile marker+  leftBehind <- Dir.listDirectory shellTemp+  sequence+    [ runTest "--command sees the captured variables and the build input on PATH" $+        case T.splitOn "|" (T.pack seenOut) of+          [greetingSeen, gcroot]+            | greetingSeen == "tool ran\n" <> fixtureGreeting+                && T.pack store `T.isPrefixOf` gcroot+                && "-develop-fixture-env" `T.isSuffixOf` gcroot ->+                Pass+          _ -> Fail (outcome seen),+      runTest "NIX_GCROOT names the output the environment was read from" $+        assertRight "read" gcrootEnvironment $ \bytes ->+          assertRight "parsed" (parseBuildEnvironment bytes) $+            assertEqual "greeting" (Just (ExportedString fixtureGreeting)) . Map.lookup "greeting" . beVariables,+      runTest "the shell's exit status is the command's" $+        assertEqual "status" (ExitFailure 7) (fst3 exited),+      runTest "--phase and a phase flag run the phase through runPhase" $+        assertEqual "phase" (ExitSuccess, "build phase ran: tool ran\n") (fst3 phase, snd3 phase)+          `andThen` assertEqual "flag" (ExitSuccess, "build phase ran: tool ran\n") (fst3 phaseFlag, snd3 phaseFlag),+      runTest "--ignore-env keeps what --keep-env-var names" $+        assertEqual "seen" (ExitSuccess, "kept/unset/unset") (fst3 ignored, snd3 ignored),+      runTest "--unset-env-var and --set-env-var change the caller's environment" $+        assertEqual "seen" (ExitSuccess, "kept/unset/new") (fst3 changed, snd3 changed),+      runTest "an environment entry with an empty name, which unsetenv refuses, does not stop the shell" $+        assertEqual "status" ExitSuccess (fst3 emptyName),+      runTest "upstream's refusals once the environment is built are its whole lines" $+        refusedWith "error: --unset-env-var does not make sense with --ignore-env" unsetIgnored+          `andThen` refusedWith "error: --keep-env-var does not make sense without --ignore-env" keptWithout+          `andThen` refusedWith "error: you cannot use both '--command' and '--phase'" both,+      runTest "a script that cannot be made is refused before the flags, as upstream makes the script first" $+        refusedWith "error: bash variable is not a string" scriptFirst,+      runTest "a shell that cannot start is reported in upstream's words" $+        refusedWith "error: unable to execute 'bash': No such file or directory" unexecutable,+      runTest "the refusals made as the command line is read are whole lines after error:" $+        refusedWith "error: Cannot set environment variable 'X' that is unset with '--unset-env-var'" parseRefused+          `andThen` refusedWith "error: --command requires at least one argument" commandless,+      runTest "a builder that is not bash is refused in upstream's words, and get-env.sh is not written" $+        refusedWith "error: 'nix develop' only works on derivations that use 'bash' as their builder" notBash+          `andThen` assertEqual "written" [] refusedScripts,+      runTest "after a substitution over HTTP, the command starts with the descriptors a process started directly has" $+        assertRight "substituted" descriptors $ \listing ->+          assertEqual "descriptors" (snd3 direct) listing,+      runTest "after a substitution from a file:// cache, the command starts with the descriptors a process started directly has" $+        assertRight "substituted" directDescriptors $ \listing ->+          assertEqual "descriptors" (snd3 direct) listing,+      runTest "print-dev-env prints a script bash sources, followed by a newline" $+        assertEqual "sourced" (ExitSuccess, T.unpack fixtureGreeting) (fst3 sourced, snd3 sourced)+          `andThen` (if "eval \"${shellHook:-}\"\n\n" `isSuffixOf` printedOut then Pass else Fail (outcome printed)),+      runTest "print-dev-env --json prints the environment on one line where stdout is no terminal, and --pretty and --no-pretty choose, the last winning" $+        case (lines jsonOut, lines prettyOut, lines notPrettyOut) of+          ([line], _ : _ : _, [notPrettyLine]) ->+            assertRight "parsed" (parseBuildEnvironment (TE.encodeUtf8 (T.pack line))) $ \environment ->+              assertEqual "greeting" (Just (ExportedString fixtureGreeting)) (Map.lookup "greeting" (beVariables environment))+                `andThen` assertEqual "pretty" (Right environment) (parseBuildEnvironment (TE.encodeUtf8 (T.pack prettyOut)))+                `andThen` assertEqual "no-pretty" line notPrettyLine+          _ -> Fail (outcome json <> "; " <> outcome pretty <> "; " <> outcome notPretty),+      runTest "under structured attributes the shell reads the files from a directory develop leaves for it" $+        assertRight "files" structuredFiles $ \(shFile, jsonFile, sh, jsonBytes) ->+          assertEqual "status" ExitSuccess (fst3 structuredSeen)+            `andThen` assertEqual "directory" (takeDirectory shFile) (takeDirectory jsonFile)+            `andThen` assertEqual "under TMPDIR, its links resolved" structuredRoot (takeDirectory (takeDirectory shFile))+            `andThen` assertEqual "named" True ("nix-develop-" `isPrefixOf` takeFileName (takeDirectory shFile))+            `andThen` assertEqual "names" (".attrs.sh", ".attrs.json") (takeFileName shFile, takeFileName jsonFile)+            `andThen` assertEqual "written" (True, True) ("greeting" `BS.isInfixOf` sh, "greeting" `BS.isInfixOf` jsonBytes)+            `andThen` assertEqual "left" [takeFileName (takeDirectory shFile)] structuredLeft,+      runTest "print-dev-env names the structured attributes' files in a directory it removes" $+        if fst3 structuredPrinted == ExitSuccess && (T.pack structuredRoot <> "/nix-dev-env-") `T.isInfixOf` T.pack structuredPrintedOut+          then assertEqual "left" 1 (length structuredLeft)+          else Fail (outcome structuredPrinted),+      runTest "the capture is built once" $+        assertEqual "runs" ["ran"] runs,+      runTest "nothing is left in the temporary directory: the rcfile removes itself, and no directory is kept for files there are none of" $+        assertEqual "left" [] leftBehind+    ]+  where+    fixtureGreeting = "it's \"quoted\"\nand on two lines"+    fst3 (code, _, _) = code+    snd3 (_, out, _) = out++-- | What @ls /dev/fd/@ prints in a @develop@ shell whose capture first+-- substitutes the fixture's build input from a binary cache: the input is+-- built into a store of its own, pushed to a directory as a signed cache,+-- and the directory handed to the substitution by its URL, as the given+-- function serves it.  Served over HTTP by a server that keeps its+-- connections open, the substitution leaves one in the HTTP client's pool;+-- read through its @file:\/\/@ URL, it opens the cache's files.  Given the+-- CLI, @develop@ into a store with flags, the command the shell runs, the+-- fixture, the root, a label naming this run's cache and store under it,+-- and the serving.  'Left' with what went wrong.+substitutedDescriptors ::+  ([String] -> IO (ExitCode, String, String)) ->+  (FilePath -> [String] -> IO (ExitCode, String, String)) ->+  (String -> [String]) ->+  FilePath ->+  FilePath ->+  String ->+  (FilePath -> (Text -> IO (ExitCode, String, String)) -> IO (ExitCode, String, String)) ->+  IO (Either Text String)+substitutedDescriptors run develop inShell fixture root label serving = do+  seed <- BS.pack <$> QC.generate (QC.vectorOf ed25519SeedBytes QC.arbitrary)+  case throwawayKey seed of+    Left err -> pure (Left (T.pack err))+    Right (keyText, publicKey) -> do+      let keyFile = root </> ("cache-secret-key-" <> label)+          cache = root </> ("cache-" <> label)+          source = root </> "source-store"+      BS.writeFile keyFile (TE.encodeUtf8 keyText)+      built@(_, builtOut, _) <- run ["build", "--expr", "{ fixture }: builtins.head (import fixture { marker = \"\"; }).buildInputs", "--argstr", "fixture", fixture, "--store", source, "--no-out-link", "--no-sandbox"]+      case listToMaybe (reverse (lines builtOut)) of+        Nothing -> pure (Left ("build: " <> T.pack (show built)))+        Just tool -> do+          pushed <- run ["push", "--cache", "file://" <> cache, "--secret-key-file", keyFile, "--store", source, tool]+          shown <- serving cache $ \base ->+            develop+              (root </> ("substituted-store-" <> label))+              (["--substituter", T.unpack base, "--trusted-key", T.unpack (Signing.renderPublicKey publicKey)] <> inShell "ls /dev/fd/")+          pure $ case shown of+            (ExitSuccess, listing, err)+              | any (\line -> "[subst]" `isInfixOf` line && "develop-tool" `isSuffixOf` line) (lines err) -> Right listing+            _ -> Left ("push: " <> T.pack (show pushed) <> "; develop: " <> T.pack (show shown))++-- | The CLI runs with upstream's file-creation mask, 0022, whatever the one+-- it was started with, so a builder it runs does too.  POSIX only: Windows+-- has no such mask.+testBuildUmaskCLI :: IO [Bool]+testBuildUmaskCLI = do+  putStrLn "cli/build-umask"+  if SI.os == "mingw32"+    then do+      putStrLn "  SKIP  POSIX only"+      pure []+    else do+      tmpBase <- getTemporaryDirectory+      let root = tmpBase </> "nova-nix-test-cli-build-umask"+      ambient <- isolatedStoreEnvironment root+      let configVars = ["NIX_CONFIG", "NIX_CONF_DIR", "NIX_USER_CONF_FILES"]+          expression = "derivation { name = \"umask-cli\"; system = builtins.currentSystem; builder = \"/bin/sh\"; args = [ \"-c\" \"umask > $out\" ]; }"+          started =+            (Proc.proc "/bin/sh" ["-c", "umask 077; exec cabal run -v0 exe:nova-nix -- build --expr \"$1\" --store \"$2\" --no-out-link", "sh", expression, root </> "store"])+              { Proc.env = Just (("NIX_CONFIG", "substituters =\ntrusted-public-keys =\nsandbox = false\n") : ("NIX_CONF_DIR", root </> "system") : ("NIX_USER_CONF_FILES", "") : filter ((`notElem` configVars) . fst) ambient)+              }+      bracket_+        (forceRemoveIfExists root >> createDirectoryIfMissing True root)+        (forceRemoveIfExists root)+        ( do+            (code, out, err) <- Proc.readCreateProcessWithExitCode started ""+            seen <- case (code, listToMaybe (reverse (filter (not . null) (lines out)))) of+              (ExitSuccess, Just path) -> Right . T.strip <$> TIO.readFile path+              _ -> pure (Left ("exit " <> T.pack (show code) <> "; stdout=" <> T.pack out <> "; stderr=" <> T.pack err))+            sequence [runTest "a builder the CLI runs gets upstream's file-creation mask, whatever the CLI was started with" (assertEqual "umask" (Right "0022") seen)]+        )++-- | SIGTERM to the CLI mid-build is an interrupt, as upstream takes+-- SIGINT, SIGTERM and SIGHUP alike: the build ends every process of its+-- builder's group, and the CLI exits 1 saying it was interrupted.  POSIX+-- only: Windows has no SIGTERM.+testTerminationCLI :: IO [Bool]+testTerminationCLI = do+  putStrLn "cli/termination"+  if SI.os == "mingw32"+    then do+      putStrLn "  SKIP  POSIX only"+      pure []+    else do+      tmpBase <- getTemporaryDirectory+      let root = tmpBase </> "nova-nix-test-cli-termination"+      ambient <- isolatedStoreEnvironment root+      let pidFile = root </> "descendant"+          errFile = root </> "stderr"+          configVars = ["NIX_CONFIG", "NIX_CONF_DIR", "NIX_USER_CONF_FILES"]+          -- The builder records the process it starts whole, through a+          -- rename, then waits for it.+          script = "/bin/sleep 100 & echo $! > " <> pidFile <> ".new && /bin/mv " <> pidFile <> ".new " <> pidFile <> "; wait"+          expression = "derivation { name = \"termination-cli\"; system = builtins.currentSystem; builder = \"/bin/sh\"; args = [ \"-c\" \"" <> script <> "\" ]; }"+          isolated = ("NIX_CONFIG", "substituters =\ntrusted-public-keys =\nsandbox = false\n") : ("NIX_CONF_DIR", root </> "system") : ("NIX_USER_CONF_FILES", "") : filter ((`notElem` configVars) . fst) ambient+          alive pid = (\(code, _, _) -> code == ExitSuccess) <$> Proc.readProcessWithExitCode "/bin/kill" ["-0", pid] ""+          descendantOf = do+            recorded <- waitUntil (Dir.doesFileExist pidFile)+            if recorded then Just . BS8.unpack . BS8.strip <$> BS.readFile pidFile else pure Nothing+          -- Whatever the CLI did, the process the builder started does not+          -- outlive the test.+          killLeft = Dir.doesFileExist pidFile >>= \present -> when present (BS.readFile pidFile >>= \pid -> void (Proc.readProcessWithExitCode "/bin/kill" ["-9", BS8.unpack (BS8.strip pid)] ""))+      bracket_+        (forceRemoveIfExists root >> createDirectoryIfMissing True root)+        (killLeft >> forceRemoveIfExists root)+        ( do+            -- Built, if it is not, with the ambient environment cabal needs,+            -- then run by its path, so the signal reaches the CLI itself.+            _ <- Proc.readCreateProcessWithExitCode (Proc.proc "cabal" ["run", "-v0", "exe:nova-nix", "--", "--version"]) ""+            (_, listed, _) <- Proc.readCreateProcessWithExitCode (Proc.proc "cabal" ["list-bin", "-v0", "exe:nova-nix"]) ""+            let exe = fromMaybe "nova-nix" (listToMaybe (reverse (filter (not . null) (lines (filter (/= '\r') listed)))))+            (code, descendant) <- withBinaryFile errFile WriteMode $ \errHandle ->+              Proc.withCreateProcess ((Proc.proc exe ["build", "--expr", expression, "--store", root </> "store", "--no-out-link"]) {Proc.env = Just isolated, Proc.std_err = Proc.UseHandle errHandle}) $ \_ _ _ cli -> do+                descendant <- descendantOf+                cliPid <- Proc.getPid cli+                for_ cliPid $ \pid -> Proc.readProcessWithExitCode "/bin/kill" ["-TERM", show pid] ""+                (,) <$> Proc.waitForProcess cli <*> pure descendant+            gone <- maybe (pure False) (\pid -> waitUntil (not <$> alive pid)) descendant+            said <- BS8.lines <$> BS.readFile errFile+            sequence+              [ runTest "SIGTERM to the CLI mid-build ends its builder's group, and the CLI says it was interrupted and exits 1" $+                  assertEqual "the builder's process, recorded and gone" True gone+                    `andThen` assertEqual "exit" (ExitFailure 1) code+                    `andThen` assertEqual "said" True ("error: interrupted by the user" `elem` said)+              ]+        )++-- | Every session the CLI makes builds under the sandbox settings, an+-- import from a derivation included: under @sandbox = true@ a derivation+-- that sets @__noChroot@ is refused with upstream's error, which is decided+-- before the system is probed and so holds on every platform, and under+-- @--relaxed-sandbox@, given after the command, it builds unsandboxed.+-- Each run has a store of its own, so none finds an output another built.+-- A read-only session writes no @.drv@, and builds only a derivation the+-- store holds and only an output that may not be substituted, so for+-- @eval@ and @trust@ a read-write evaluation of the derivation's path+-- writes it first, building nothing, and the derivation sets+-- @allowSubstitutes = false@.+testSandboxSessionsCLI :: IO [Bool]+testSandboxSessionsCLI = do+  putStrLn "cli/sandbox-sessions"+  shell <- findTestShell+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-cli-sandbox-sessions"+  ambient <- isolatedStoreEnvironment root+  let configVars = ["NIX_CONFIG", "NIX_CONF_DIR", "NIX_USER_CONF_FILES", "NIX_CONFIG_HOME", "XDG_CONFIG_HOME", "XDG_CACHE_HOME"]+      isolatedEnv =+        ("NIX_CONFIG", "substituters =\ntrusted-public-keys =\nsandbox = true\n")+          : ("NIX_CONF_DIR", root </> "system")+          : ("NIX_USER_CONF_FILES", "")+          : ("XDG_CONFIG_HOME", root </> "config")+          : ("XDG_CACHE_HOME", root </> "cache")+          : filter ((`notElem` configVars) . fst) ambient+      runCLI store args =+        Proc.readCreateProcessWithExitCode+          ((Proc.proc "cabal" (["run", "-v0", "exe:nova-nix", "--"] ++ args ++ ["--store", root </> store])) {Proc.env = Just isolatedEnv})+          ""+      nixString text = "\"" <> T.replace "${" "\\${" (T.replace "\"" "\\\"" (T.replace "\\" "\\\\" text)) <> "\""+      unsandboxable name script extra =+        "derivation { name = " <> nixString name <> "; system = builtins.currentSystem; builder = " <> nixString shell <> "; args = [ \"-c\" " <> nixString script <> " ]; __noChroot = true; allowSubstitutes = false; " <> extra <> " }"+      made = unsandboxable "sandbox-session-read" "printf made > $out" ""+      reading = "builtins.readFile (" <> made <> ")"+      top = unsandboxable "sandbox-session-top" "printf %s \"$made\" > $out" ("made = " <> reading <> ";")+      writingDrv = ["eval", "--read-write-mode", "--expr", T.unpack ("(" <> made <> ").drvPath")]+      sessions :: [(Text, [[String]], [String], Text)]+      sessions =+        [ ("eval", [writingDrv], ["eval"], reading),+          ("eval --read-write-mode", [], ["eval", "--read-write-mode"], reading),+          ("build", [], ["build", "--no-out-link"], top),+          ("trust", [writingDrv], ["trust"], top)+        ]+      refusal = "has '__noChroot' set, but that's not allowed when 'sandbox' is 'true'"+      outcome (code, out, err) = "exit " <> T.pack (show code) <> "; stdout=" <> T.pack out <> "; stderr=" <> T.pack err+      runSession (index, (label, preparing, command, expression)) = do+        let refusedStore = "refused-" <> show index+            relaxedStore = "relaxed-" <> show index+        refusedPrepared <- traverse (runCLI refusedStore) preparing+        refused <- runCLI refusedStore (command ++ ["--expr", T.unpack expression])+        relaxedPrepared <- traverse (runCLI relaxedStore) preparing+        relaxed <- runCLI relaxedStore (take 1 command ++ ["--relaxed-sandbox"] ++ drop 1 command ++ ["--expr", T.unpack expression])+        pure (label, refusedPrepared ++ relaxedPrepared, refused, relaxed)+  bracket_+    (forceRemoveIfExists root)+    (forceRemoveIfExists root)+    ( do+        runs <- traverse runSession (zip [0 :: Int ..] sessions)+        sequence+          [ runTest (label <> " refuses a __noChroot derivation an evaluation builds under sandbox = true, and builds it under --relaxed-sandbox") $+              case (filter (\(code, _, _) -> code /= ExitSuccess) prepared, refused, relaxed) of+                ([], (ExitFailure _, _, refusedErr), (ExitSuccess, _, _)) | refusal `T.isInfixOf` T.pack refusedErr -> Pass+                (failedPreparing, _, _) -> Fail ("preparing: " <> T.intercalate ", " (map outcome failedPreparing) <> "; refused: " <> outcome refused <> "; relaxed: " <> outcome relaxed)+          | (label, prepared, refused, relaxed) <- runs+          ]+    )++-- | nix.conf's cores reaches a builder the CLI runs, and with nothing+-- setting it, or a cores of 0, the builder is told the machine's count, a+-- positive number.+testBuildCoresCLI :: IO [Bool]+testBuildCoresCLI = do+  putStrLn "cli/build-cores"+  shell <- findTestShell+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-cli-build-cores"+  ambient <- isolatedStoreEnvironment root+  let configVars = ["NIX_CONFIG", "NIX_CONF_DIR", "NIX_USER_CONF_FILES"]+      -- No nix.conf of the machine's is read: the system file is looked+      -- for under the run's root and an empty NIX_USER_CONF_FILES names+      -- no user file, so NIX_CONFIG alone sets cores.+      buildWith nixConfig store =+        Proc.readCreateProcessWithExitCode+          ( (Proc.proc "cabal" ["run", "-v0", "exe:nova-nix", "--", "build", "--expr", expression, "--store", root </> store, "--no-out-link"])+              { Proc.env =+                  Just+                    ( ("NIX_CONFIG", "substituters =\ntrusted-public-keys =\n" <> nixConfig)+                        : ("NIX_CONF_DIR", root </> "system")+                        : ("NIX_USER_CONF_FILES", "")+                        : filter ((`notElem` configVars) . fst) ambient+                    )+              }+          )+          ""+      nixString text = "\"" <> T.replace "${" "\\${" (T.replace "\"" "\\\"" (T.replace "\\" "\\\\" text)) <> "\""+      expression =+        T.unpack+          ("derivation { name = \"cores-cli\"; system = builtins.currentSystem; builder = " <> nixString shell <> "; args = [ \"-c\" \"echo $NIX_BUILD_CORES > $out\" ]; }")+      echoed (code, out, err) = case (code, listToMaybe (reverse (filter (not . null) (lines (filter (/= '\r') out))))) of+        (ExitSuccess, Just path) -> Right . T.strip <$> TIO.readFile path+        _ -> pure (Left ("exit " <> T.pack (show code) <> "; stdout=" <> T.pack out <> "; stderr=" <> T.pack err))+  bracket_+    (forceRemoveIfExists root >> createDirectoryIfMissing True root)+    (forceRemoveIfExists root)+    ( do+        configured <- buildWith "cores = 3\n" "configured" >>= echoed+        unset <- buildWith "" "unset" >>= echoed+        zero <- buildWith "cores = 0\n" "zero" >>= echoed+        hardware <- Cores.hardwareConcurrency+        sequence+          [ runTest "nix.conf's cores is a CLI build's NIX_BUILD_CORES" $+              assertEqual "configured" (Right "3") configured,+            -- Off Linux there is no cgroup limit to read, so the count is+            -- the hardware's; on Linux the runner's cgroup may limit it.+            runTest "with nothing setting cores a CLI build is told the machine's count" $+              case unset of+                Right value+                  | Just (count :: Word32) <- readMaybe (T.unpack value),+                    count > 0,+                    SI.os == "linux" || count == Cores.defaultCores Nothing hardware ->+                      Pass+                other -> Fail ("unset: " <> T.pack (show other) <> "; hardware count " <> T.pack (show hardware)),+            runTest "a cores of 0 is told the same count as nothing setting it" $+              assertEqual "zero" unset zero+          ]+    )++-- | A target and its arguments through the real CLI: a directory's+-- @default.nix@, a @\<NAME\>@ the search path finds, read as+-- @import \<NAME\>@ reads it, and a function called with @--arg@ and+-- @--argstr@, its defaults filling the rest, as @nix-instantiate --eval@+-- and @nix-build@ call one.  @eval@ calls a function only when an+-- argument is given, and under @--aterm@ always; @build@ calls the value+-- before @-A@ selects from it and once it has.  Where the command line+-- can hold a byte with no UTF-8 reading (POSIX), each value it gives+-- keeps that byte.+testTargetArgsCLI :: IO [Bool]+testTargetArgsCLI = do+  putStrLn "cli/target-args"+  shell <- findTestShell+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-cli-target-args"+  ambient <- isolatedStoreEnvironment root+  let isolatedEnv =+        ("NIX_CONFIG", "substituters =\ntrusted-public-keys =\n")+          : ("XDG_CONFIG_HOME", root </> "config")+          : filter (\(key, _) -> key `notElem` ["NIX_CONFIG", "NIX_CONFIG_HOME", "XDG_CONFIG_HOME", "NIX_PATH"]) ambient+      runCLI args =+        Proc.readCreateProcessWithExitCode+          ((Proc.proc "cabal" (["run", "-v0", "exe:nova-nix", "--"] ++ args)) {Proc.env = Just isolatedEnv})+          ""+      build args = runCLI (["build", "--store", root </> "store", "--no-out-link"] ++ args)+      builder = nixQuotedPath (T.unpack shell)+      derivationWriting name content = "derivation { name = " <> name <> "; system = builtins.currentSystem; builder = " <> builder <> "; args = [ \"-c\" \"printf " <> content <> " > $out\" ]; }"+      files =+        [ ("f.nix", "{ x, y ? 2 }: x + y"),+          ("needs.nix", "{ x, y }: x"),+          ("only-x.nix", "{ x }: x"),+          ("evaldir" </> "default.nix", "\"read from default.nix\""),+          ("pkg" </> "default.nix", "{ name ? \"pkg\" }: " <> derivationWriting "name" "pkg"),+          ("nixpkgs" </> "default.nix", "{ ... }: { hello = " <> derivationWriting "\"hello\"" "hello" <> "; }"),+          ("ellipsis.nix", "{ x, ... }@given: given.z"),+          ("functor.nix", "{ k = 10; __functor = self: { x }: x + self.k; }")+        ]+      -- A store path holding a default.nix whose value is a path literal,+      -- which names a place in the store path when the file is read as+      -- import reads it, and the file's on-disk directory otherwise.+      storeDerivation = "derivation { name = \"store-target\"; system = builtins.currentSystem; " <> hostToolsAttrs <> "builder = " <> builder <> "; args = [ \"-c\" \"mkdir $out; printf ./data > $out/default.nix; printf hi > $out/data\" ]; }"+      md5OfFf = "\"00594fd4f42ba43fc1ca0427a0576295\""+      lastLine out = listToMaybe (reverse (filter (not . null) (lines (filter (/= '\r') out))))+      printed (code, out, _) = case code of+        ExitSuccess -> lastLine out+        ExitFailure _ -> Nothing+      errorLines (code, _, err) = (code, lines (filter (/= '\r') err))+      outcome (code, out, err) = "exit " <> T.pack (show code) <> "; stdout=" <> T.pack out <> "; stderr=" <> T.pack err+      prints expected run = if printed run == Just expected then Pass else Fail (outcome run)+      missingLines name =+        [ "error: cannot evaluate a function that has an argument without a value ('" <> name <> "')",+          "       Nix attempted to evaluate a function as a top level expression; in",+          "       this case it must have its arguments supplied either by default",+          "       values, or passed explicitly with '--arg' or '--argstr'. See",+          "       https://nixos.org/manual/nix/stable/language/constructs.html#functions."+        ]+      at = (root </>)+  bracket_+    ( do+        forceRemoveIfExists root+        mapM_ (\(name, source) -> createDirectoryIfMissing True (takeDirectory (at name)) >> BS.writeFile (at name) (TE.encodeUtf8 source)) files+    )+    (forceRemoveIfExists root)+    ( do+        uncalled <- runCLI ["eval", at "f.nix"]+        called <- runCLI ["eval", "--arg", "x", "1", at "f.nix"]+        stringArg <- runCLI ["eval", "--argstr", "s", "hi", "--expr", "{ s }: s + \"!\""]+        missing <- runCLI ["eval", "--arg", "y", "1", at "needs.nix"]+        unused <- runCLI ["eval", "--arg", "x", "1", "--arg", "z", "throw \"never\"", at "only-x.nix"]+        directory <- runCLI ["eval", at "evaldir"]+        defaulted <- build [at "pkg"]+        renamed <- build ["--argstr", "name", "renamed", at "pkg"]+        found <- build ["--nix-path", "nixpkgs=" <> at "nixpkgs", "<nixpkgs>", "-A", "hello"]+        imported <- build ["--nix-path", "nixpkgs=" <> at "nixpkgs", "--expr", "(import <nixpkgs> { }).hello"]+        notFound <- build ["<nope>"]+        builtContent <- traverse BS.readFile (printed found)+        ellipsis <- runCLI ["eval", "--arg", "x", "1", "--arg", "z", "2", at "ellipsis.nix"]+        functor <- runCLI ["eval", "--arg", "x", "1", at "functor.nix"]+        strictCalled <- runCLI ["eval", "--strict", "--arg", "x", "1", "--expr", "{ x }: { a = x + 1; }"]+        lazyCalled <- runCLI ["eval", "--arg", "x", "1", "--expr", "{ x }: { a = x + 1; }"]+        aterm <- runCLI ["eval", "--aterm", at "pkg"]+        storeOutput <- build ["--expr", T.unpack storeDerivation]+        let storeBase = maybe "" takeFileName (printed storeOutput)+            storeEntry = "st=/nix/store/" <> storeBase+        storeTarget <- runCLI ["eval", "--store", root </> "store", "--nix-path", storeEntry, "<st>"]+        storeImport <- runCLI ["eval", "--store", root </> "store", "--nix-path", storeEntry, "--expr", "import <st>"]+        bytes <-+          if SI.os == "mingw32"+            then [True] <$ putStrLn "  SKIP  a command-line value keeps a byte with no UTF-8 reading: a Windows command line cannot hold one"+            else do+              (_, listed, _) <- Proc.readCreateProcessWithExitCode (Proc.proc "cabal" ["list-bin", "-v0", "exe:nova-nix"]) ""+              -- The shell makes the byte, 0xFF, so no codec on this side+              -- stands between it and the binary's arguments, and the+              -- binary runs itself: cabal run drops such a byte from the+              -- arguments it passes on (cabal-install 3.18.2).+              let withFf script =+                    Proc.readCreateProcessWithExitCode+                      ((Proc.proc (T.unpack shell) ["-c", "ff=$(printf '\\377'); " <> script, fromMaybe "nova-nix" (lastLine listed), at "evaldir"]) {Proc.env = Just isolatedEnv})+                      ""+              argstr <- withFf "exec \"$0\" eval --argstr s \"$ff\" --expr '{ s }: builtins.hashString \"md5\" s'"+              argExpr <- withFf "exec \"$0\" eval --arg s \"\\\"$ff\\\"\" --expr '{ s }: builtins.hashString \"md5\" s'"+              expr <- withFf "exec \"$0\" eval --expr \"builtins.hashString \\\"md5\\\" \\\"$ff\\\"\""+              searchName <- withFf "NIX_PATH=\"$ff=$1\" exec \"$0\" eval \"<$ff>\""+              badName <- withFf "exec \"$0\" eval --arg \"$ff\" 1 --expr '{ ... }: 1'"+              sequence+                [ runTest "--argstr keeps a byte with no UTF-8 reading" $+                    prints md5OfFf argstr,+                  runTest "--arg parses its expression's bytes" $+                    prints md5OfFf argExpr,+                  runTest "--expr parses its expression's bytes" $+                    prints md5OfFf expr,+                  runTest "a <NAME> is looked up by its bytes" $+                    prints "\"read from default.nix\"" searchName,+                  runTest "an argument name with no UTF-8 reading is refused, as an attribute name here is text" $+                    assertEqual "name" (ExitFailure 1, ["error: --arg: invalid UTF-8 in argument name"]) (errorLines badName)+                ]+        (++ bytes)+          <$> sequence+            [ runTest "eval prints a function given no argument, as nix-instantiate --eval does" $+                prints "<LAMBDA>" uncalled,+              runTest "eval calls a function with --arg, its default filling the rest" $+                prints "3" called,+              runTest "eval calls a function with --argstr's string" $+                prints "\"hi!\"" stringArg,+              runTest "a function missing an argument fails with upstream's message" $+                assertEqual "missing" (ExitFailure 1, missingLines "x") (errorLines missing),+              runTest "an --arg the function does not take is neither passed nor evaluated" $+                prints "1" unused,+              runTest "eval reads a directory's default.nix" $+                prints "\"read from default.nix\"" directory,+              runTest "build reads a directory's default.nix and calls its function with the defaults" $+                case printed defaulted of+                  Just path | "-pkg" `isSuffixOf` path -> Pass+                  _ -> Fail (outcome defaulted),+              runTest "build calls the function with --argstr's string" $+                case printed renamed of+                  Just path | "-renamed" `isSuffixOf` path -> Pass+                  _ -> Fail (outcome renamed),+              runTest "build <nixpkgs> -A hello calls the function the search path finds and selects from what it gives" $+                if isJust (printed found) && printed found == printed imported && builtContent == Just "hello"+                  then Pass+                  else Fail (outcome found <> "; the import: " <> outcome imported),+              runTest "a <NAME> the search path does not hold fails as the expression <NAME> does" $+                assertEqual "not found" (ExitFailure 1, ["error: file 'nope' was not found in the Nix search path (add it using $NIX_PATH or -I)"]) (errorLines notFound),+              runTest "a function that takes ... is passed every argument" $+                prints "2" ellipsis,+              runTest "a set with __functor is called as the function its functor gives" $+                prints "11" functor,+              runTest "--strict evaluates the whole of what the call gives" $+                prints "{ a = 2; }" strictCalled `andThen` prints "{ a = <CODE>; }" lazyCalled,+              runTest "--aterm takes a file target and calls its function with the defaults" $+                case printed aterm of+                  Just line | "Derive(" `isPrefixOf` line, "-pkg\"" `isInfixOf` line -> Pass+                  _ -> Fail (outcome aterm),+              runTest "a <NAME> in the store is read as import <NAME> reads it, its path literals naming places in the store path" $+                case (printed storeTarget, printed storeImport) of+                  (Just fromTarget, Just fromImport)+                    | not (null storeBase), fromTarget == fromImport, fromTarget == "/nix/store/" <> storeBase <> "/data" -> Pass+                  _ -> Fail (outcome storeOutput <> "; the target: " <> outcome storeTarget <> "; the import: " <> outcome storeImport)+            ]+    )++-- | The link a build makes to its output, through the real CLI run in a+-- directory of the test's own: @./result@ when no flag names another,+-- with @-NAME@ appended for an output other than @out@, each a root that+-- @store gc@ keeps, as nix-build links and roots them; with+-- @--no-out-link@ no link and no root.  The parse and the names are+-- checked on their own first.+testOutLinkCLI :: IO [Bool]+testOutLinkCLI = do+  putStrLn "cli/out-link"+  shell <- findTestShell+  canLink <- symlinksAvailable+  projectDir <- Dir.getCurrentDirectory+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-cli-out-link"+  ambient <- isolatedStoreEnvironment root+  let linkedDir = root </> "linked"+      unlinkedDir = root </> "unlinked"+      isolatedEnv =+        ("NIX_CONFIG", "substituters =\ntrusted-public-keys =\n")+          : ("XDG_CONFIG_HOME", root </> "config")+          : filter (\(key, _) -> key `notElem` ["NIX_CONFIG", "NIX_CONFIG_HOME", "XDG_CONFIG_HOME"]) ambient+      -- cabal finds the project from the directory it runs in, which is+      -- the directory the link is made in, so the project is named.+      runIn dir args =+        Proc.readCreateProcessWithExitCode+          ((Proc.proc "cabal" (["run", "-v0", "--project-dir", projectDir, "exe:nova-nix", "--"] ++ args)) {Proc.env = Just isolatedEnv, Proc.cwd = Just dir})+          ""+      expression =+        T.unpack+          ( "derivation { name = \"out-link\"; system = builtins.currentSystem; builder = "+              <> nixQuotedPath (T.unpack shell)+              <> "; outputs = [ \"out\" \"dev\" ]; args = [ \"-c\" \"echo out > $out; echo dev > $dev\" ]; }"+          )+      buildIn dir store flags = runIn dir (["build", "--expr", expression, "--store", root </> store] ++ flags)+      collectIn dir store = runIn dir ["store", "gc", "--store", root </> store]+      printed (code, out, _) = case code of+        ExitSuccess -> listToMaybe (reverse (filter (not . null) (lines (filter (/= '\r') out))))+        ExitFailure _ -> Nothing+      outcome (code, out, err) = "exit " <> T.pack (show code) <> "; stdout=" <> T.pack out <> "; stderr=" <> T.pack err+      linkTarget path = either (\(_ :: IOException) -> Nothing) Just <$> try (Dir.getSymbolicLinkTarget path)+      parsed = fmap Cli.optCommand . Cli.parseArgs+      buildOf = Cli.CmdBuild (Cli.TargetExpr "1") Nothing+  parses <-+    sequence+      [ runTest "build links ./result unless --out-link names another path, or --no-out-link or --no-link none" $+          assertEqual "no flag" (Right (buildOf (Cli.OutLinkAt "result"))) (parsed ["build", "--expr", "1"])+            `andThen` assertEqual "--out-link" (Right (buildOf (Cli.OutLinkAt "out"))) (parsed ["build", "-o", "out", "--expr", "1"])+            `andThen` assertEqual "--no-out-link" (Right (buildOf Cli.NoOutLink)) (parsed ["build", "--expr", "1", "--no-out-link"])+            `andThen` assertEqual "--no-link" (Right (buildOf Cli.NoOutLink)) (parsed ["build", "--no-link", "--expr", "1"])+            `andThen` assertEqual "--no-out-link twice" (Right (buildOf Cli.NoOutLink)) (parsed ["build", "--no-out-link", "--expr", "1", "--no-out-link"]),+        runTest "a --no-out-link after an --out-link links nothing, as nix-build's later flag wins" $+          assertEqual "--no-out-link" (Right (buildOf Cli.NoOutLink)) (parsed ["build", "-o", "out", "--no-out-link", "--expr", "1"])+            `andThen` assertEqual "--no-link" (Right (buildOf Cli.NoOutLink)) (parsed ["build", "-o", "out", "--expr", "1", "--no-link"]),+        runTest "an --out-link after a --no-out-link links its path, as nix-build's later flag wins" $+          assertEqual "--no-out-link" (Right (buildOf (Cli.OutLinkAt "out"))) (parsed ["build", "--no-out-link", "--expr", "1", "--out-link", "out"])+            `andThen` assertEqual "--no-link" (Right (buildOf (Cli.OutLinkAt "out"))) (parsed ["build", "--no-link", "-o", "out", "--expr", "1"]),+        runTest "a second --out-link replaces the first, as nix-build's later flag wins" $+          assertEqual "two links" (Right (buildOf (Cli.OutLinkAt "b"))) (parsed ["build", "-o", "a", "--expr", "1", "--out-link", "b"]),+        runTest "an output other than out is linked with -NAME appended to the out-link, as nix-build names it" $+          assertEqual "out" (Just "result") (Cli.outLinkFor (Cli.OutLinkAt "result") "out")+            `andThen` assertEqual "dev" (Just "result-dev") (Cli.outLinkFor (Cli.OutLinkAt "result") "dev")+            `andThen` assertEqual "a path" (Just ("links" </> "hello-bin")) (Cli.outLinkFor (Cli.OutLinkAt ("links" </> "hello")) "bin")+            `andThen` assertEqual "no link" Nothing (Cli.outLinkFor Cli.NoOutLink "dev")+      ]+  runs <-+    bracket_+      (forceRemoveIfExists root >> mapM_ (createDirectoryIfMissing True) [linkedDir, unlinkedDir])+      (forceRemoveIfExists root)+      ( do+          linked <-+            if not canLink+              then [] <$ putStrLn "  SKIP  a build's link needs symlink privilege"+              else do+                outBuilt <- buildIn linkedDir "linked-store" []+                devBuilt <- buildIn linkedDir "linked-store" ["-A", "dev"]+                outLink <- linkTarget (linkedDir </> "result")+                devLink <- linkTarget (linkedDir </> "result-dev")+                collected@(collectedCode, _, _) <- collectIn linkedDir "linked-store"+                kept <- traverse Dir.doesPathExist (catMaybes [printed outBuilt, printed devBuilt])+                sequence+                  [ runTest "build links its output from ./result" $+                      case printed outBuilt of+                        Just path | outLink == Just path -> Pass+                        _ -> Fail (outcome outBuilt <> "; link: " <> T.pack (show outLink)),+                    runTest "build links an output other than out from ./result-NAME" $+                      case printed devBuilt of+                        Just path | devLink == Just path -> Pass+                        _ -> Fail (outcome devBuilt <> "; link: " <> T.pack (show devLink)),+                    runTest "store gc keeps the outputs a build's links root" $+                      if collectedCode == ExitSuccess && kept == [True, True]+                        then Pass+                        else Fail (outcome collected <> "; kept: " <> T.pack (show kept))+                  ]+          unlinkedBuilt <- buildIn unlinkedDir "unlinked-store" ["--no-out-link"]+          left <- Dir.listDirectory unlinkedDir+          unlinkedCollected@(unlinkedCode, _, _) <- collectIn unlinkedDir "unlinked-store"+          survived <- traverse Dir.doesPathExist (printed unlinkedBuilt)+          unlinked <-+            runTest "build --no-out-link links nothing, and store gc then deletes the output" $+              if null left && unlinkedCode == ExitSuccess && survived == Just False+                then Pass+                else Fail (outcome unlinkedBuilt <> "; left: " <> T.pack (show left) <> "; gc: " <> outcome unlinkedCollected)+          -- nix-build realises only the output outputName names: with+          -- out valid and dev deleted, building out builds nothing.+          let marked = T.unpack ("derivation { name = \"one-output\"; system = builtins.currentSystem; builder = " <> nixQuotedPath (T.unpack shell) <> "; outputs = [ \"out\" \"dev\" ]; args = [ \"-c\" \"echo the-builder-ran >&2; echo out > $out; echo dev > $dev\" ]; }")+              buildMarked flags = runIn unlinkedDir (["build", "--expr", marked, "--store", root </> "one-output-store", "--no-out-link"] ++ flags)+          devBuilt <- buildMarked ["-A", "dev"]+          deleted <- traverse (\path -> runIn unlinkedDir ["store", "delete", "--store", root </> "one-output-store", path]) (printed devBuilt)+          outBuilt@(_, _, outErr) <- buildMarked []+          devGone <- traverse (fmap not . Dir.doesPathExist) (printed devBuilt)+          oneOutput <-+            runTest "build realises only the output its outputName names, as nix-build does" $+              case (deleted, printed outBuilt, devGone) of+                (Just (ExitSuccess, _, _), Just _, Just True)+                  | not ("the-builder-ran" `isInfixOf` outErr) -> Pass+                _ -> Fail (outcome outBuilt <> "; dev: " <> outcome devBuilt <> "; dev gone: " <> T.pack (show devGone))+          pure (linked ++ [unlinked, oneOutput])+      )+  pure (parses ++ runs)++-- ---------------------------------------------------------------------------+-- Tests: trust+-- ---------------------------------------------------------------------------++-- | @trust@ end to end: a derivation built by a seed a loopback server+-- serves, taking an archive it serves too, both fetched by+-- builtin:fetchurl into a store of the run's own, scanned, and reported,+-- and two fixed-output derivations whose builder is a host program, which+-- trust must not build: one the server holds as a binary cache, which is+-- substituted and scanned, and one it does not, which is not read.  Each+-- host program fails if it runs, and a failed build stops the command.+-- The archive's program is the seed's bytes, so the report names it as+-- the seed.  The report is read as lines and, from a second run, as+-- JSON.+testTrustCLI :: IO [Bool]+testTrustCLI = do+  putStrLn "cli/trust"+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-cli-trust"+  ambient <- isolatedStoreEnvironment root+  let archive = BL.toStrict (GZip.compress (Tar.write [tarFile "tool/bin/tool.exe" (BL.fromStrict trustPe), tarFile "tool/bin/run.sh" "#!/bin/sh\necho hi\n"]))+      madeBytes = "what a host program would make\n" :: BS.ByteString+      unheldBytes = "what no cache holds\n" :: BS.ByteString+      madeNar = NAR.serialise (NAR.NarRegular False madeBytes)+      isolatedEnv =+        ("NIX_CONFIG", "substituters =\ntrusted-public-keys =\n")+          : ("NIX_CONF_DIR", root </> "system")+          : ("NIX_USER_CONF_FILES", "")+          : filter ((`notElem` ["NIX_CONFIG", "NIX_CONF_DIR", "NIX_USER_CONF_FILES"]) . fst) ambient+      fixedAttrs bytes = "outputHashMode = \"flat\"; outputHashAlgo = \"sha256\"; outputHash = \"" <> Hash.bytesToHexText (sha256Digest bytes) <> "\";"+      fetch base name target bytes =+        "derivation { name = \"" <> name <> "\"; url = \"" <> base <> target <> "\"; system = \"builtin\"; builder = \"builtin:fetchurl\"; " <> fixedAttrs bytes <> " }"+      hostBuilt name bytes =+        "derivation { name = \"" <> name <> "\"; system = \"x86_64-linux\"; builder = \"/bin/sh\"; args = [ \"-c\" \"exit 1\" ]; " <> fixedAttrs bytes <> " }"+      expression base =+        "let seed = "+          <> fetch base "seed.exe" "/seed" trustPe+          <> "; archive = "+          <> fetch base "tool.tar.gz" "/archive" archive+          <> "; made = "+          <> hostBuilt "made.txt" madeBytes+          <> "; unheld = "+          <> hostBuilt "unheld.txt" unheldBytes+          <> "; in derivation { name = \"tool\"; system = \"x86_64-linux\"; builder = \"${seed}\"; args = [ \"${archive}\" \"${made}\" \"${unheld}\" ]; }"+      narInfoTarget out = "/" <> TE.encodeUtf8 (spHash out) <> ".narinfo"+  seedOut <- either (fail . show) pure (makeFixedOutputPath "seed.exe" "sha256" FlatIngestion (sha256Digest trustPe))+  archiveOut <- either (fail . show) pure (makeFixedOutputPath "tool.tar.gz" "sha256" FlatIngestion (sha256Digest archive))+  madeOut <- either (fail . show) pure (makeFixedOutputPath "made.txt" "sha256" FlatIngestion (sha256Digest madeBytes))+  unheldOut <- either (fail . show) pure (makeFixedOutputPath "unheld.txt" "sha256" FlatIngestion (sha256Digest unheldBytes))+  (trustedKey, madeNarInfo) <- either fail pure (signedTestNarInfo madeOut [] "nar/made.nar" madeNar)+  let route target _+        | target == "/seed" = Send (httpResponse "200 OK" trustPe)+        | target == "/archive" = Send (httpResponse "200 OK" archive)+        | target == narInfoTarget madeOut = Send (httpResponse "200 OK" (TE.encodeUtf8 madeNarInfo))+        | target == "/nar/made.nar" = Send (httpResponse "200 OK" madeNar)+        | otherwise = Send (httpResponse "404 Not Found" "missing")+  (code, out, err, seen, (jsonCode, jsonOut, jsonErr)) <-+    bracket_ (forceRemoveIfExists root >> createDirectoryIfMissing True root) (forceRemoveIfExists root) $+      withHttpServer route $ \base requests _ -> do+        let trustRun flags =+              Proc.readCreateProcessWithExitCode+                ((Proc.proc "cabal" (["run", "-v0", "exe:nova-nix", "--", "trust", "--store", root </> "store", "--substituter", T.unpack base, "--trusted-key", T.unpack trustedKey, "--expr", T.unpack (expression base)] ++ flags)) {Proc.env = Just isolatedEnv})+                ""+        (code, out, err) <- trustRun []+        seen <- requests+        jsonRun <- trustRun ["--json", "--no-pretty"]+        pure (code, out, err, seen, jsonRun)+  let path = storePathToText defaultStoreDir+      asked = [narInfoTarget madeOut, "/nar/made.nar", narInfoTarget unheldOut]+  sequence+    [ runTest "trust fetches what a builtin fetches, substitutes what a cache holds, scans both, and builds nothing" $+        case code of+          ExitSuccess ->+            assertEqual+              "stdout"+              [ "Fixed-output inputs run as builders: 1",+                "  " <> path seedOut,+                "    fetched by builtin:fetchurl",+                "    builder of 1 derivation: " <> path seedOut,+                "    PE image: the fetched file",+                "Fixed-output inputs holding prebuilt code: 1",+                "  " <> path archiveOut,+                "    fetched by builtin:fetchurl",+                "    PE image: tool/bin/tool.exe, the bytes of " <> path seedOut,+                "Fixed-output inputs not fully read: 1",+                "  " <> path unheldOut,+                "    built in the closure by /bin/sh, its bytes pinned by its hash",+                "    not read: the store does not hold it",+                "Fixed-output inputs holding no prebuilt code: 1",+                "Builders outside the closure: 1",+                "  /bin/sh, for 2 derivations",+                "Builders in input sources: 0",+                "Builtin builders: 1",+                "  builtin:fetchurl, for 2 derivations",+                "Input sources: 0",+                "This reports what the closure relies on, not whether any of it is safe."+              ]+              (map (T.filter (/= '\r')) (T.lines (T.pack out)))+          _ -> Fail ("exited " <> T.pack (show code) <> ": " <> T.pack err),+      runTest "trust asks the caches for each input no builtin fetches before it reports one as not read" $+        assertEqual "requests" (sort asked) (sort (nub (filter (`elem` asked) seen))),+      runTest "trust --json prints the same report as one JSON document on one line" $+        case (jsonCode, parseJson (T.strip (T.pack jsonOut))) of+          (ExitSuccess, Right report) ->+            let input output = member "fixedOutputInputs" report >>= member (path output)+                field name output = input output >>= member name+                classes = case member "fixedOutputInputs" report of+                  Just (JsonObject inputs) -> Map.map (member "class") inputs+                  _ -> Map.empty+             in assertEqual "one line" 1 (length (T.lines (T.strip (T.pack jsonOut))))+                  `andThen` assertEqual+                    "classes"+                    ( Map.fromList+                        [ (path seedOut, Just (JsonString "runAsBuilder")),+                          (path archiveOut, Just (JsonString "holdsPrebuiltCode")),+                          (path madeOut, Just (JsonString "holdsNoPrebuiltCode")),+                          (path unheldOut, Just (JsonString "notFullyRead"))+                        ]+                    )+                    classes+                  `andThen` assertEqual+                    "the archive's program, the seed's bytes"+                    ( Just+                        ( JsonArray+                            [ JsonObject+                                ( Map.fromList+                                    [ ("kind", JsonString "peImage"),+                                      ("file", JsonNull),+                                      ("member", JsonString "tool/bin/tool.exe"),+                                      ("sha256", JsonString (Hash.bytesToHexText (sha256Digest trustPe))),+                                      ("sameBytesAs", JsonArray [JsonString (path seedOut)])+                                    ]+                                )+                            ]+                        )+                    )+                    (field "prebuiltCode" archiveOut)+                  `andThen` assertEqual+                    "builders"+                    (Just (JsonObject (Map.singleton "/bin/sh" (JsonInt 2))), Just (JsonObject (Map.singleton "builtin:fetchurl" (JsonInt 2))))+                    (member "buildersOutsideClosure" report, member "builtinBuilders" report)+          (ExitSuccess, Left failure) -> Fail ("not JSON: " <> failure)+          _ -> Fail ("exited " <> T.pack (show jsonCode) <> ": " <> T.pack jsonErr)+    ]+  where+    member name value = case value of+      JsonObject members -> Map.lookup name members+      _ -> Nothing++-- | A substituter listed twice is asked once, at its first listing, as+-- upstream drops a repeated one: a loopback cache holds the narinfo of a+-- builtin:fetchurl output but not its NAR, which is a substitute gone, so+-- every listing left asks for the NAR again before the build fetches the+-- file itself.  The NAR is asked for once however the listing repeats,+-- in nix.conf or between nix.conf and @--substituter@, and twice for two+-- spellings of the cache, one with a trailing slash, which upstream also+-- takes for two substituters.+testSubstituterListingsCLI :: IO [Bool]+testSubstituterListingsCLI = do+  putStrLn "cli/substituter-listings"+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-cli-substituter-listings"+  ambient <- isolatedStoreEnvironment root+  let fileBytes = "what the cache lacks the NAR of\n" :: BS.ByteString+      narTarget = "/nar/listed.nar"+      expression base = "derivation { name = \"listed.txt\"; system = \"builtin\"; builder = \"builtin:fetchurl\"; url = \"" <> base <> "/file\"; outputHashMode = \"flat\"; outputHashAlgo = \"sha256\"; outputHash = \"" <> Hash.bytesToHexText (sha256Digest fileBytes) <> "\"; }"+      environment config =+        ("NIX_CONFIG", config)+          : ("NIX_CONF_DIR", root </> "system")+          : ("NIX_USER_CONF_FILES", "")+          : filter ((`notElem` ["NIX_CONFIG", "NIX_CONF_DIR", "NIX_USER_CONF_FILES"]) . fst) ambient+  out <- either (fail . show) pure (makeFixedOutputPath "listed.txt" "sha256" FlatIngestion (sha256Digest fileBytes))+  (trustedKey, narInfo) <- either fail pure (signedTestNarInfo out [] (T.drop 1 (TE.decodeUtf8 narTarget)) (NAR.serialise (NAR.NarRegular False fileBytes)))+  let route target _+        | target == "/" <> TE.encodeUtf8 (spHash out) <> ".narinfo" = Send (httpResponse "200 OK" (TE.encodeUtf8 narInfo))+        | target == "/file" = Send (httpResponse "200 OK" fileBytes)+        | otherwise = Send (httpResponse "404 Not Found" "missing")+      -- A build in a store of its own, with nix.conf's substituters as+      -- given and the flags after them: its status and how often the NAR+      -- was asked for.+      buildWith label listed flags = withHttpServer route $ \base requests _ -> do+        let config = "substituters = " <> T.unwords (map ($ base) listed) <> "\ntrusted-public-keys = " <> trustedKey <> "\n"+        (code, _, err) <-+          Proc.readCreateProcessWithExitCode+            ((Proc.proc "cabal" (["run", "-v0", "exe:nova-nix", "--", "build", "--store", root </> label, "--no-out-link", "--expr", T.unpack (expression base)] ++ map ($ T.unpack base) flags)) {Proc.env = Just (environment (T.unpack config))})+            ""+        seen <- requests+        pure (code, length (filter (== narTarget) seen), err)+      asks expected (code, asked, err)+        | (code, asked) == (ExitSuccess, expected) = Pass+        | otherwise = Fail ("exit " <> T.pack (show code) <> ", the NAR asked for " <> T.pack (show asked) <> " times; stderr=" <> T.pack err)+  bracket_ (forceRemoveIfExists root >> createDirectoryIfMissing True root) (forceRemoveIfExists root) $ do+    inConfig <- buildWith "in-config" [id, id] []+    withFlag <- buildWith "with-flag" [id] [const "--substituter", id]+    spelledTwice <- buildWith "spelled-twice" [id, (<> "/")] []+    sequence+      [ runTest "a substituter nix.conf lists twice is asked once" $+          asks 1 inConfig,+        runTest "a substituter nix.conf lists and --substituter names again is asked once" $+          asks 1 withFlag,+        runTest "a substituter spelled with a trailing slash and without is two, as upstream reads them" $+          asks 2 spelledTwice+      ]++-- ---------------------------------------------------------------------------+-- Tests: the CLI reference+-- ---------------------------------------------------------------------------++-- | Where the reference's JSON is committed, from the repository root.+cliJsonPath :: FilePath+cliJsonPath = "docs" </> "cli.json"++-- | The argument that writes 'Ref.referenceJson' to 'cliJsonPath' in place+-- of running the suite.+writeCliJsonFlag :: String+writeCliJsonFlag = "--write-cli-json"++-- | The reference against the parser it documents, the committed JSON+-- against the reference, and each example that shows output against what+-- the CLI prints.+testCliReference :: IO [Bool]+testCliReference = do+  putStrLn "cli/reference"+  committed <- try (BS.readFile cliJsonPath)+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-cli-reference"+  ambient <- isolatedStoreEnvironment root+  let -- No nix.conf of the machine's is read: each directory the config+      -- files are looked for in is under the run's own root.+      isolatedEnv =+        ("NIX_CONFIG", "substituters =\ntrusted-public-keys =\n")+          : ("NIX_CONF_DIR", root </> "system")+          : ("XDG_CONFIG_HOME", root </> "config")+          : ("XDG_CONFIG_DIRS", root </> "config-dirs")+          : filter (\(key, _) -> key `notElem` ["NIX_CONFIG", "NIX_CONF_DIR", "NIX_USER_CONF_FILES", "NIX_CONFIG_HOME", "XDG_CONFIG_HOME", "XDG_CONFIG_DIRS"]) ambient+      runCLI args =+        Proc.readCreateProcessWithExitCode+          ((Proc.proc "cabal" (["run", "-v0", "exe:nova-nix", "--"] ++ args)) {Proc.env = Just isolatedEnv})+          ""+      printsHelp label args = runTestM label $ do+        (code, out, err) <- runCLI args+        pure $ case code of+          ExitSuccess -> assertEqual "stdout" Ref.helpLines (map (T.filter (/= '\r')) (T.lines (T.pack out)))+          _ -> Fail ("exited " <> T.pack (show code) <> ": " <> T.pack err)+      shown =+        [ example+        | entry <- Ref.globalForm : map Ref.command Ref.commandNames,+          example <- toList (Ref.commandExamples entry),+          not (null (Ref.exampleOutput example))+        ]+  checks <-+    sequence+      [ runTest "docs/cli.json is the reference's JSON" $ case committed of+          Left (err :: IOException) -> Fail (T.pack (cliJsonPath <> ": " <> displayException err <> "; " <> regenerateCliJson))+          Right bytes+            | bytes == Ref.referenceJson -> Pass+            | otherwise -> Fail (T.pack (cliJsonPath <> " differs from what Nix.Cli.Reference renders; " <> regenerateCliJson)),+        runTest "every command a flag lists accepts it" $+          allPass+            [ case Cli.parseArgs args of+                Right opts | cliSelects name (Cli.optCommand opts) -> Pass+                other -> Fail (T.pack (unwords args <> ": " <> show (Cli.optCommand <$> other)))+            | (flagName, entry) <- referenceFlags,+              Ref.CommandFlag names <- [Ref.flagScope entry],+              name <- toList names,+              spelling <- toList (Ref.flagSpellings entry),+              let args = cliLine name flagName spelling (cliValue entry)+            ],+        -- The other way round, so --help lists exactly what each command+        -- takes after its words.  A global flag is answered anywhere, and+        -- a spelling two commands give different flags, as build's and+        -- develop's --check, is the other flag's there.+        runTest "no command takes, after its words, a flag the reference does not list for it" $+          allPass+            [ case Cli.parseArgs args of+                Right opts | cliSelects name (Cli.optCommand opts) -> Fail (T.pack (unwords args))+                _ -> Pass+            | (flagName, entry) <- referenceFlags,+              Ref.CommandFlag names <- [Ref.flagScope entry],+              name <- Ref.commandNames,+              name `notElem` names,+              spelling <- toList (Ref.flagSpellings entry),+              spelling `notElem` commandSpellings name,+              let args = cliLine name flagName spelling (cliValue entry)+            ],+        runTest "a global flag is answered on its own" $+          allPass+            [ case Cli.parseArgs [T.unpack spelling] of+                Right opts | Cli.optCommand opts `elem` [Cli.CmdHelp, Cli.CmdVersion] -> Pass+                other -> Fail (spelling <> ": " <> T.pack (show (Cli.optCommand <$> other)))+            | flagName <- Ref.globalFlags,+              spelling <- toList (Ref.flagSpellings (Ref.flag flagName))+            ],+        runTest "a global flag is answered after each command's words and after its operands" $+          allPass+            [ case Cli.optCommand <$> Cli.parseArgs args of+                Right answer | Just answer == globalAnswer flagName -> Pass+                other -> Fail (T.pack (unwords args <> ": " <> show other))+            | flagName <- Ref.globalFlags,+              spelling <- toList (Ref.flagSpellings (Ref.flag flagName)),+              prefix <- nub (concatMap cliPrefixes Ref.commandNames ++ [cliWords name ++ cliOperands name flagName | name <- Ref.commandNames]),+              let args = prefix ++ [T.unpack spelling]+            ],+        -- A flag with values is asked for them when the line ends before+        -- it has them all; one without parses when it ends a complete+        -- line, where a clause that wanted a value would have nothing to+        -- take.+        runTest "a flag asks for values exactly when its entry names them" $+          allPass+            [ let values = cliValue entry+                  missing = Left (cliShortfall flagName spelling values)+                  given count = Cli.optCommand <$> Cli.parseArgs (prefix ++ [T.unpack spelling] ++ take count values)+                  complete = prefix ++ operands ++ [T.unpack spelling]+               in case (values, Cli.parseArgs complete) of+                    (_ : _, _) | all ((== missing) . given) [0 .. length values - 1] -> Pass+                    ([], Right _) | given 0 /= missing -> Pass+                    (_, completed) -> Fail (T.pack (unwords (prefix ++ [T.unpack spelling]) <> ": " <> show (map given [0 .. length values]) <> "; " <> unwords complete <> ": " <> show (Cli.optCommand <$> completed)))+            | (flagName, entry) <- referenceFlags,+              (prefix, operands) <- case Ref.flagScope entry of+                Ref.GlobalFlag -> [([], [])]+                Ref.CommandFlag names -> [(cliWords name, cliOperands name flagName) | name <- toList names],+              spelling <- toList (Ref.flagSpellings entry)+            ],+        runTest "every example parses as the command it documents" $+          allPass+            ( [ exampleParses (`elem` [Cli.CmdHelp, Cli.CmdVersion]) example+              | example <- toList (Ref.commandExamples Ref.globalForm)+              ]+                ++ [ exampleParses (cliSelects name) example+                   | name <- Ref.commandNames,+                     example <- toList (Ref.commandExamples (Ref.command name))+                   ]+            ),+        runTest "spellings are well formed and name one flag each where they apply" $+          let spellings = [(scope, spelling) | (_, entry) <- referenceFlags, scope <- scopeCommands (Ref.flagScope entry), spelling <- toList (Ref.flagSpellings entry)]+              scopeCommands scope = case scope of+                Ref.GlobalFlag -> [Nothing]+                Ref.CommandFlag names -> map Just (toList names)+              longFormed = all (\part -> not (T.null part) && T.all isAsciiLower part) . T.splitOn "-"+              wellFormed entry =+                all longFormed (Ref.flagLong entry : toList (Ref.flagAlias entry))+                  && maybe True isAsciiLetter (Ref.flagShort entry)+           in assertEqual "malformed" [] [Ref.flagLong entry | (_, entry) <- referenceFlags, not (wellFormed entry)]+                `andThen` assertEqual "repeated" [] [spelling | (spelling, count) <- Map.toList (Map.fromListWith (+) [(spelling, 1 :: Int) | spelling <- spellings]), count > 1],+        -- A value of 1 or 0 moves each from its default, a Boolean that is+        -- on by default by 0, and sandbox, whose values are words, by+        -- relaxed.+        runTest "every setting is one nix.conf resolves" $+          let moves setting value = either (const False) (/= Config.defaultNixConfig) (Config.resolveConfig [Config.ConfigAssignment (TE.encodeUtf8 (Ref.settingName setting)) value])+           in allPass+                [ if any (moves setting) ["1", "0", "relaxed"] then Pass else Fail (Ref.settingName setting <> ": none of 1, 0 and relaxed moves the configuration")+                | setting <- toList (Ref.configSettings Ref.configuration)+                ],+        runTest "help lists --no-allow-import-from-derivation" $+          if any ("--no-allow-import-from-derivation" `T.isInfixOf`) Ref.helpLines then Pass else Fail (T.unlines Ref.helpLines),+        runTest "marked text closes every code span, and help prints no marks" $+          let marked =+                [ text+                | entry <- Ref.globalForm : map Ref.command Ref.commandNames,+                  text <-+                    Ref.commandDescription entry+                      : map Ref.formSummary (toList (Ref.commandForms entry))+                      ++ map Ref.exampleDescription (toList (Ref.commandExamples entry))+                ]+                  ++ [Ref.flagDescription (Ref.flag name) | name <- Ref.flagNames]+                  ++ [Ref.settingDescription setting | setting <- toList (Ref.configSettings Ref.configuration)]+                  ++ [Ref.configDescription Ref.configuration]+           in assertEqual "unclosed" [] (filter (odd . T.count (T.singleton Ref.codeMark)) marked)+                `andThen` assertEqual "printed" [] (filter (T.any (== Ref.codeMark)) Ref.helpLines),+        runTest "help fits its width" $+          assertEqual "longer" [] (filter ((> Ref.helpWidth) . T.length) Ref.helpLines),+        runTest "an example reads as it is typed" $+          assertEqual "shell" "nova-nix eval --expr '1 + 2'" (Ref.exampleCommandLine (Ref.Example "" ("eval" :| ["--expr", "1 + 2"]) []))+            `andThen` assertEqual "quote" "'it'\\''s'" (Ref.shellQuote "it's")+            `andThen` assertEqual "empty" "''" (Ref.shellQuote "")+            `andThen` assertEqual "zsh's equals expansion" "'=ls'" (Ref.shellQuote "=ls"),+        runTestM "a quoted argument reads back as itself" $ do+          result <-+            QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} $+              QC.forAll genShellText $+                \text -> readShellWord (Ref.shellQuote text) QC.=== Just text+          pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result))),+        runTestM "wrapped text keeps its words and fits its width" $ do+          result <-+            QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} $+              QC.forAll ((,) <$> QC.chooseInt (1, 40) <*> genWrapText) $ \(width, text) ->+                let wrapped = Ref.wrapWords width text+                 in T.words (T.unwords wrapped) QC.=== T.words text+                      QC..&&. all (\line -> T.length line <= width || length (T.words line) == 1) wrapped+          pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result))),+        runTestM "indented JSON parses back to the value it came from" $ do+          result <-+            QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} $+              QC.forAll (genJson 3) $ \json ->+                (parseJson =<< either (Left . T.pack . show) Right (TE.decodeUtf8' (Ref.renderIndentedJson json))) QC.=== Right json+          pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))+      ]+  ran <-+    bracket_+      (forceRemoveIfExists root >> createDirectoryIfMissing True root)+      (forceRemoveIfExists root)+      ( do+          examples <-+            mapM+              ( \example -> runTestM ("example prints what it shows: " <> Ref.exampleCommandLine example) $ do+                  (code, out, err) <- runCLI (map T.unpack (toList (Ref.exampleArguments example)))+                  pure $ case code of+                    ExitSuccess -> assertEqual "stdout" (Ref.exampleOutput example) (map (T.filter (/= '\r')) (T.lines (T.pack out)))+                    _ -> Fail ("exited " <> T.pack (show code) <> ": " <> T.pack err)+              )+              shown+          helps <-+            mapM+              (\prefix -> printsHelp ("nova-nix " <> T.pack (unwords prefix) <> " --help prints the help and exits 0") (prefix ++ ["--help"]))+              (nub (concatMap cliPrefixes Ref.commandNames))+          pure (examples ++ helps)+      )+  pure (checks ++ ran)+  where+    referenceFlags = [(name, Ref.flag name) | name <- Ref.flagNames]+    commandSpellings name =+      [ spelling+      | (_, entry) <- referenceFlags,+        Ref.CommandFlag names <- [Ref.flagScope entry],+        name `elem` names,+        spelling <- toList (Ref.flagSpellings entry)+      ]+    regenerateCliJson = "from the repository root, regenerate it with: cabal run --enable-tests -v0 nova-nix-test -- " <> writeCliJsonFlag+    allPass = foldr andThen Pass+    isAsciiLetter c = isAsciiLower c || isAsciiUpper c+    exampleParses accepts example =+      let args = map T.unpack (toList (Ref.exampleArguments example))+       in case Cli.parseArgs args of+            Right opts | accepts (Cli.optCommand opts) -> Pass+            other -> Fail (T.pack (unwords args <> ": " <> show (Cli.optCommand <$> other)))++-- | The arguments that select a command.+cliWords :: Ref.CommandName -> [String]+cliWords = map T.unpack . Ref.commandWords++-- | The words that start a command: its first word, as @store@, through+-- all of them.+cliPrefixes :: Ref.CommandName -> [[String]]+cliPrefixes = drop 1 . inits . cliWords++-- | The command a global flag selects.+globalAnswer :: Ref.FlagName -> Maybe Cli.Command+globalAnswer flagName = case flagName of+  Ref.HelpFlag -> Just Cli.CmdHelp+  Ref.VersionFlag -> Just Cli.CmdVersion+  _ -> Nothing++-- | A value for each value a flag needs, which the parser accepts+-- unchecked: one for each name its entry gives outside brackets.+cliValue :: Ref.FlagEntry -> [String]+cliValue entry = maybe [] (map (const "value") . filter (not . ("[" `T.isPrefixOf`)) . T.words) (Ref.flagArgument entry)++-- | A command line with a flag and its values in it, completed by the+-- operands the command needs: after the flag, or before it for+-- @--command@, which takes every argument after it.+cliLine :: Ref.CommandName -> Ref.FlagName -> Text -> [String] -> [String]+cliLine name flagName spelling values = case flagName of+  Ref.ShellCommandFlag -> cliWords name ++ cliOperands name flagName ++ [T.unpack spelling] ++ values+  _ -> cliWords name ++ [T.unpack spelling] ++ values ++ cliOperands name flagName++-- | What the parser says to a flag given fewer values than it needs:+-- upstream's words after @error: @ for @--command@, under either+-- spelling.+cliShortfall :: Ref.FlagName -> Text -> [String] -> String+cliShortfall flagName spelling values = case (flagName, values) of+  (Ref.ShellCommandFlag, _) -> "error: --command requires at least one argument"+  (_, [_, _]) -> T.unpack spelling <> " requires a name and a value"+  _ -> T.unpack spelling <> " requires a value"++-- | What completes a command line once a flag is in it: the operands the+-- command needs, but an expression when the flag is @--expr@, which gives+-- one.+cliOperands :: Ref.CommandName -> Ref.FlagName -> [String]+cliOperands name flagName = case name of+  Ref.EvalCommand -> expression+  Ref.BuildCommand -> expression+  Ref.DevelopCommand -> expression+  Ref.PrintDevEnvCommand -> expression+  Ref.TrustCommand -> expression+  Ref.PushCommand -> ["--cache", "https://cache.example.org", "hash-name"]+  Ref.StoreDeleteCommand -> ["hash-name"]+  Ref.StoreGcCommand -> []+  Ref.ProfileAddCommand -> expression+  Ref.ProfileRemoveCommand -> ["hello" | flagName /= Ref.AllFlag]+  Ref.ProfileListCommand -> []+  Ref.ProfileHistoryCommand -> []+  Ref.ProfileRollbackCommand -> []+  Ref.ProfileWipeHistoryCommand -> []+  Ref.KeyGenerateSecretCommand -> concat [["--key-name", "value"] | flagName /= Ref.KeyNameFlag]+  Ref.KeyConvertSecretToPublicCommand -> []+  Ref.DaemonCommand -> []+  where+    expression = concat [["--expr", "1"] | flagName /= Ref.ExprFlag]++-- | Whether a parsed command is the reference's command.+cliSelects :: Ref.CommandName -> Cli.Command -> Bool+cliSelects name parsed = case (name, parsed) of+  (Ref.EvalCommand, Cli.CmdEval _) -> True+  (Ref.BuildCommand, Cli.CmdBuild {}) -> True+  (Ref.DevelopCommand, Cli.CmdDevelop {}) -> True+  (Ref.PrintDevEnvCommand, Cli.CmdPrintDevEnv {}) -> True+  (Ref.TrustCommand, Cli.CmdTrust {}) -> True+  (Ref.PushCommand, Cli.CmdPush _) -> True+  (Ref.StoreDeleteCommand, Cli.CmdStoreDelete _) -> True+  (Ref.StoreGcCommand, Cli.CmdStoreGc _) -> True+  (Ref.ProfileAddCommand, Cli.CmdProfileAdd {}) -> True+  (Ref.ProfileRemoveCommand, Cli.CmdProfileRemove {}) -> True+  (Ref.ProfileListCommand, Cli.CmdProfileList {}) -> True+  (Ref.ProfileHistoryCommand, Cli.CmdProfileHistory {}) -> True+  (Ref.ProfileRollbackCommand, Cli.CmdProfileRollback {}) -> True+  (Ref.ProfileWipeHistoryCommand, Cli.CmdProfileWipeHistory {}) -> True+  (Ref.KeyGenerateSecretCommand, Cli.CmdKeyGenerateSecret _) -> True+  (Ref.KeyConvertSecretToPublicCommand, Cli.CmdKeyConvertSecretToPublic) -> True+  (Ref.DaemonCommand, Cli.CmdDaemon {}) -> True+  _ -> False++-- | One word read back as a POSIX shell reads it, for what+-- 'Ref.shellQuote' writes: plain characters, single-quoted runs, and a+-- character escaped by a backslash.  A character the shell would act on+-- is no reading at all.+readShellWord :: Text -> Maybe Text+readShellWord = go ""+  where+    go acc rest = case T.uncons rest of+      Nothing -> Just acc+      Just ('\'', more) -> case T.break (== '\'') more of+        (quoted, closing) -> case T.uncons closing of+          Just (_, after) -> go (acc <> quoted) after+          Nothing -> Nothing+      Just ('\\', more) -> case T.uncons more of+        Just (escaped, after) -> go (T.snoc acc escaped) after+        Nothing -> Nothing+      Just (c, more)+        | c `elem` shellSpecial -> Nothing+        | otherwise -> go (T.snoc acc c) more+    shellSpecial = " \t\n\"#$&()*;<>?[]`{|}~!" :: String++-- | Text with the characters a shell acts on mixed among plain ones.+genShellText :: QC.Gen Text+genShellText = T.pack <$> QC.listOf (QC.elements "a1_-=:/.,@%+ '\"\\$`;&|<>()*?[]#~{}!\t\n")++-- | Words of a few lengths, runs of spaces between them.+genWrapText :: QC.Gen Text+genWrapText = T.pack <$> QC.listOf (QC.elements "abcdefghij        ")++-- | An assignment of a setting the store sends a daemon, under any of the+-- spellings that set it, to a value the setting takes.+genStoreAssignment :: QC.Gen Config.ConfigAssignment+genStoreAssignment =+  QC.oneof+    [ assign (spellings ["substituters", "binary-caches", "trusted-public-keys", "trusted-substituters", "secret-key-files"]) genTokens,+      assign (QC.elements ["require-sigs", "always-allow-substitutes", "sandbox-fallback", "darwin-log-sandbox-violations", "require-drop-supplementary-groups"]) (QC.elements ["true", "false", "yes", "no", "1", "0"]),+      assign (pure "sandbox") (QC.elements ["true", "relaxed", "false"]),+      assign (spellings ["sandbox-paths", "build-chroot-dirs", "allowed-impure-host-deps"]) genTokens,+      assign (QC.elements ["sandbox-build-dir", "sandbox-dev-shm-size", "ssl-cert-file", "build-users-group"]) genToken,+      assign (QC.elements ["filetransfer-retry-attempts", "download-attempts"]) (BS8.pack . show <$> QC.choose (0 :: Int, 99))+    ]+  where+    assign name value = Config.ConfigAssignment <$> name <*> value+    spellings names = (<>) <$> QC.elements ["", "extra-"] <*> QC.elements names+    genTokens = BS8.unwords <$> QC.listOf1 genToken+    genToken = BS8.pack <$> QC.listOf1 (QC.elements ['a' .. 'z'])++-- ---------------------------------------------------------------------------+-- Tests: substituter signature verification (the --trusted-key trust gate)+-- ---------------------------------------------------------------------------++-- | The nix.conf / NIX_CONFIG resolver: parsing, aliases, the extra-+-- append rule, the precedence fold, include expansion over an in-memory+-- file map, and the file cascade.  The trusted-key cases are the+-- security-relevant ones, a plain assignment in a higher source replaces+-- the trusted set, an extra- widens it.+testNixConfig :: IO [Bool]+testNixConfig = do+  putStrLn "config/nix-conf"+  let -- A root the platform agrees is absolute: "/" is not one on+      -- Windows, for System.FilePath and for upstream's canonPath alike.+      root = if SI.os == "mingw32" then "C:\\" else "/"+      etcNix = root </> "etc" </> "nix"+      etcXdg = root </> "etc" </> "xdg"+      etcXdgLocal = root </> "etc" </> "xdg-local"+      configHome = root </> "home" </> "u" </> ".config"+      nixConfigHome = root </> "home" </> "u" </> "nix-config"+      systemConf = etcNix </> "nix.conf"+      xdgConf dir = dir </> "nix" </> "nix.conf"+      -- The expander's one effect, served from an in-memory map: a path+      -- is in it or there is nothing there.+      readFrom files path = Identity (maybe (Left Config.ConfigFileMissing) Right (Map.lookup path files))+      resolveWith files paths env = runIdentity (Config.loadConfig (readFrom files) paths env)+      substitutersOf files paths env = ncSubstituters <$> resolveWith files paths env+      fileMap = Map.mapKeys asciiOsPath . Map.fromList+      -- The same, over the cascade a 'ConfigLocations' computes.+      substitutersAt files locations env = Config.configFilePaths locations >>= \paths -> substitutersOf files paths env+      firstPathOf locations = listToMaybe <$> Config.configFilePaths locations+      -- Successive texts as successive files, weakest first.+      resolveTexts texts =+        let paths = [asciiOsPath (root </> "src" </> (show index ++ ".conf")) | index <- [1 .. length texts]]+         in resolveWith (Map.fromList (zip paths texts)) paths Nothing+      subs = fmap ncSubstituters . resolveTexts+      keys = fmap ncTrustedPublicKeys . resolveTexts+      secretKeyFiles = fmap ncSecretKeyFiles . resolveTexts+      requireSigs = fmap ncRequireSigs . resolveTexts+      fallback = fmap ncFallback . resolveTexts+      keepFailed = fmap ncKeepFailed . resolveTexts+      alwaysAllowSubstitutes = fmap ncAlwaysAllowSubstitutes . resolveTexts+      uris = fmap ncAllowedUris . resolveTexts+      cascade =+        Config.ConfigLocations+          { Config.clConfDir = Nothing,+            Config.clSystemConfDir = Just (asciiOsPath etcNix),+            Config.clUserConfFiles = Nothing,+            Config.clNixConfigHome = Nothing,+            Config.clConfigHome = asciiOsPath configHome,+            Config.clConfigDirs = map asciiOsPath [etcXdg, etcXdgLocal]+          }+      cascadeFiles =+        fileMap+          [ (systemConf, "substituters = https://system"),+            (xdgConf etcXdgLocal, "substituters = https://xdg-local"),+            (xdgConf etcXdg, "substituters = https://xdg"),+            (xdgConf configHome, "substituters = https://home")+          ]+      listVar = BS8.pack . intercalate [searchPathSeparator]+      depth = fmap ncMaxCallDepth . resolveTexts+      depthOf value = depth ["max-call-depth = " <> value]+      refused = either (const True) (const False) . depthOf+      cores = fmap ncCores . resolveTexts+      attempts = fmap ncDownloadAttempts . resolveTexts+      -- Bytes with no UTF-8 reading (0xE9, Latin-1's e-acute).  They are+      -- a host path on POSIX and none on Windows, whose paths are UTF-16,+      -- so the cases holding them branch on whether they spell one.+      latin1 = "caf\xE9" :: BS.ByteString+      -- What a lossy decode would open instead: U+FFFD's UTF-8.+      replaced = "caf\xEF\xBF\xBD"+      nixConfName = asciiOsPath "nix.conf"+  sequence+    [ runTest "parses a whitespace-split substituters list" $+        assertEqual "subs" (Right ["https://a", "https://b"]) (subs ["substituters = https://a https://b"]),+      runTest "a comment truncates the line" $+        assertEqual "comment" (Right ["https://a"]) (subs ["substituters = https://a # not https://b"]),+      runTest "a plain assignment replaces across sources" $+        assertEqual "replace" (Right ["https://b"]) (subs ["substituters = https://a", "substituters = https://b"]),+      runTest "extra- appends within a source set" $+        assertEqual "append" (Right ["https://a", "https://b"]) (subs ["substituters = https://a", "extra-substituters = https://b"]),+      runTest "binary-caches aliases substituters" $+        assertEqual "alias" (Right ["https://a"]) (subs ["binary-caches = https://a"]),+      runTest "extra- composes with an alias" $+        assertEqual "extra-alias" (Right ["https://a", "https://b"]) (subs ["substituters = https://a", "extra-binary-caches = https://b"]),+      runTest "binary-cache-public-keys aliases trusted-public-keys" $+        assertEqual "key-alias" (Right ["k1"]) (keys ["binary-cache-public-keys = k1"]),+      runTest "a higher source plainly replaces the trusted set" $+        assertEqual "trust-replace" (Right ["k2"]) (keys ["trusted-public-keys = k1", "trusted-public-keys = k2"]),+      runTest "a higher source with extra- widens the trusted set" $+        assertEqual "trust-widen" (Right ["k1", "k2"]) (keys ["trusted-public-keys = k1", "extra-trusted-public-keys = k2"]),+      runTest "secret-key-files is a list of files, empty by default, that a higher source replaces and extra- widens" $+        assertEqual "default" (Right []) (secretKeyFiles [])+          `andThen` assertEqual "replace" (Right ["/b"]) (secretKeyFiles ["secret-key-files = /a", "secret-key-files = /b"])+          `andThen` assertEqual "widen" (Right ["/a", "/b", "/c"]) (secretKeyFiles ["secret-key-files = /a /b", "extra-secret-key-files = /c"]),+      runTest "require-sigs is a Boolean, on by default" $+        assertEqual "default" (Right True) (requireSigs [])+          `andThen` assertEqual "off" (Right False) (requireSigs ["require-sigs = false"])+          `andThen` assertEqual "refused" (Left "Boolean setting 'require-sigs' has invalid value 'maybe'") (requireSigs ["require-sigs = maybe"]),+      runTest "fallback is a Boolean, off by default, and build-fallback aliases it" $+        assertEqual "default" (Right False) (fallback [])+          `andThen` assertEqual "on" (Right True) (fallback ["fallback = true"])+          `andThen` assertEqual "alias" (Right True) (fallback ["build-fallback = yes"])+          `andThen` assertEqual "replaced" (Right False) (fallback ["fallback = true", "fallback = false"])+          `andThen` assertEqual "typo" (Left "Boolean setting 'fallback' has invalid value 'ture'") (fallback ["fallback = ture"]),+      runTest "an invalid build-fallback is refused naming fallback, as upstream's error names the setting" $+        assertEqual "alias-typo" (Left "Boolean setting 'fallback' has invalid value 'maybe'") (fallback ["build-fallback = maybe"]),+      runTest "keep-failed is a Boolean, off by default" $+        assertEqual "default" (Right False) (keepFailed [])+          `andThen` assertEqual "on" (Right True) (keepFailed ["keep-failed = yes"])+          `andThen` assertEqual "replaced" (Right False) (keepFailed ["keep-failed = true", "keep-failed = false"])+          `andThen` assertEqual "typo" (Left "Boolean setting 'keep-failed' has invalid value 'maybe'") (keepFailed ["keep-failed = maybe"]),+      runTest "always-allow-substitutes is a Boolean, off by default" $+        assertEqual "default" (Right False) (alwaysAllowSubstitutes [])+          `andThen` assertEqual "on" (Right True) (alwaysAllowSubstitutes ["always-allow-substitutes = true"])+          `andThen` assertEqual "replaced" (Right False) (alwaysAllowSubstitutes ["always-allow-substitutes = true", "always-allow-substitutes = no"])+          `andThen` assertEqual+            "typo"+            (Left "Boolean setting 'always-allow-substitutes' has invalid value 'ture'")+            (alwaysAllowSubstitutes ["always-allow-substitutes = ture"]),+      runTest "an unknown setting is ignored, not an error" $+        assertEqual "unknown" (Right ["https://a"]) (subs ["cores = 4\nsubstituters = https://a"]),+      runTest "blank and comment-only lines are skipped" $+        assertEqual "blanks" (Right ["https://a"]) (subs ["# a comment\n\nsubstituters = https://a\n"]),+      runTest "a line missing = is a syntax error quoting the line as truncated, untrimmed" $+        let expected = "nix.conf: syntax error in configuration line '   substituters https://a ' in '" <> T.pack (root </> "src" </> "1.conf") <> "'"+         in assertEqual "syntax" (Left expected) (resolveTexts ["   substituters https://a # comment"]),+      runTest "the default config is empty" $+        assertEqual "default" (Right []) (subs []),+      -- Tokens, as upstream's tokenizeString splits them: on space, tab,+      -- CR and LF only, which nix config show 2.33.2 agrees with.+      runTest "a value splits on space, tab and CR, and not on other spaces" $+        assertEqual+          "separators"+          (Right ["https://a\xA0https://b\vhttps://c\fhttps://d", "https://e", "https://f", "https://g"])+          (uris ["allowed-uris = https://a\xC2\xA0https://b\vhttps://c\fhttps://d https://e\rhttps://f\thttps://g"]),+      runTest "a CRLF line ends where its LF does" $+        assertEqual "crlf" (Right ["https://a"]) (subs ["substituters = https://a\r\n"]),+      runTest "a Boolean value ending in a no-break space is upstream's invalid-value error" $+        assertEqual "nbsp-bool" (Left "Boolean setting 'pure-eval' has invalid value 'true\xA0'") (ncPureEval <$> resolveTexts ["pure-eval = true\xC2\xA0"]),+      -- Bytes with no UTF-8 reading in a setting.+      runTest "a comment and an unknown setting holding a byte with no UTF-8 reading are never decoded" $+        assertEqual "bytes-ignored" (Right ["https://a"]) (substitutersOf Map.empty [] (Just ("max-jobs = " <> latin1 <> "\nsubstituters = https://a # " <> latin1))),+      runTest "a list setting holding a byte with no UTF-8 reading is refused under its own name" $+        let expected = "setting 'substituters' has invalid value 'https://caf\xFFFD.example': not valid UTF-8"+         in assertEqual "list-bytes" (Left expected) (substitutersOf Map.empty [] (Just ("extra-binary-caches = https://" <> latin1 <> ".example"))),+      runTest "the daemon's lists of users keep a byte with no UTF-8 reading, and extra- adds to them" $+        assertEqual+          "users"+          (Right ["root", "caf\xE9", "@wheel"])+          (Config.ncTrustedUsers <$> Config.resolveConfig [Config.ConfigAssignment "trusted-users" "root caf\xE9", Config.ConfigAssignment "extra-trusted-users" "@wheel"]),+      runTest "trusted-users defaults to root, and on Windows, which has no root, to the machine's administrators by their SID" $+        assertEqual+          "trusted-users"+          (Right (if SI.os == "mingw32" then ["@S-1-5-32-544"] else ["root"]))+          (Config.ncTrustedUsers <$> Config.resolveConfig []),+      runTest "a Boolean or integer setting holding such a byte is upstream's invalid-value error" $+        assertEqual+          "scalar-bytes"+          (Left "Boolean setting 'pure-eval' has invalid value 'true\xFFFD'", Left "setting 'max-call-depth' has invalid value '5\xFFFD'")+          (ncPureEval <$> resolveTexts ["pure-eval = true\xE9"], depthOf "5\xE9"),+      -- max-call-depth: a scalar under upstream's unsigned-integer grammar.+      runTest "max-call-depth defaults to upstream's 10000" $+        assertEqual "depth-default" (Right 10000) (depth []),+      runTest "max-call-depth parses a decimal" $+        assertEqual "depth-decimal" (Right 5) (depthOf "5"),+      runTest "a higher source replaces max-call-depth" $+        assertEqual "depth-replace" (Right 7) (depth ["max-call-depth = 5", "max-call-depth = 7"]),+      runTest "max-call-depth takes a binary unit suffix in either case" $+        assertEqual "depth-unit" (Right [10240, 5120, 1048576]) (traverse depthOf ["10K", "5k", "1M"]),+      runTest "max-call-depth takes a leading plus and leading zeros" $+        assertEqual "depth-plus" (Right [5, 7]) (traverse depthOf ["+5", "007"]),+      runTest "max-call-depth accepts the top of unsigned int" $+        assertEqual "depth-top" (Right 4294967295) (depthOf "4294967295"),+      runTest "an invalid max-call-depth is refused with upstream's words" $+        assertEqual "depth-invalid" (Left "setting 'max-call-depth' has invalid value 'abc'") (depthOf "abc"),+      runTest "max-call-depth refuses a sign, a fraction, hex, an unknown unit, an empty value and a second token" $+        assertEqual "depth-refused" (True, 6) (all refused rejects, length rejects),+      runTest "max-call-depth refuses a value past unsigned int, a unit product included" $+        assertEqual "depth-range" True (refused "4294967296" && refused "5G"),+      runTest "extra-max-call-depth is an unknown name, not an append" $+        assertEqual "depth-extra" (Right 10000) (depth ["extra-max-call-depth = 5"]),+      -- cores: a scalar under the same grammar, unset until a source sets+      -- it, since its default is the machine's.+      runTest "cores is unset when no source sets it" $+        assertEqual "cores-unset" (Right Nothing) (cores []),+      runTest "cores and its alias build-cores set it, 0 included" $+        assertEqual "cores-set" (Right [Just 4, Just 6, Just 0, Just 2048]) (traverse (cores . pure) ["cores = 4", "build-cores = 6", "cores = 0", "cores = 2K"]),+      runTest "a higher source replaces cores, whichever name each uses" $+        assertEqual "cores-replace" (Right (Just 2)) (cores ["cores = 8", "build-cores = 2"]),+      runTest "an invalid cores is refused in upstream's words, which name the setting and not the alias" $+        assertEqual+          "cores-invalid"+          (Left "setting 'cores' has invalid value 'all'", Left "setting 'cores' has invalid value '-1'")+          (cores ["cores = all"], cores ["build-cores = -1"]),+      runTest "extra-cores and extra-build-cores are unknown names, not appends" $+        assertEqual "cores-extra" (Right Nothing) (cores ["extra-cores = 4", "extra-build-cores = 4"]),+      -- filetransfer-retry-attempts: a scalar under the same grammar, whose+      -- older name download-attempts is its alias.+      runTest "the download attempts are upstream's 5 until a source sets them by either name, 0 included" $+        assertEqual+          "attempts-set"+          (Right [5, 3, 1, 0, 2])+          (traverse attempts [[], ["download-attempts = 3"], ["filetransfer-retry-attempts = 1"], ["download-attempts = 0"], ["filetransfer-retry-attempts = 9", "download-attempts = 2"]]),+      runTest "an invalid download-attempts is refused in upstream's words, which name the setting and not the alias" $+        assertEqual "attempts-invalid" (Left "setting 'filetransfer-retry-attempts' has invalid value 'many'") (attempts ["download-attempts = many"]),+      -- Includes.+      runTest "an include is spliced in at its line, resolved against the including file's directory" $+        let files =+              fileMap+                [ (systemConf, "substituters = https://a\ninclude site.conf\nextra-substituters = https://c"),+                  (etcNix </> "site.conf", "extra-substituters = https://b")+                ]+         in assertEqual "inline" (Right ["https://a", "https://b", "https://c"]) (substitutersOf files [asciiOsPath systemConf] Nothing),+      runTest "a nested include resolves against the nested file, with .. collapsed" $+        let files =+              fileMap+                [ (systemConf, "include sub/one.conf"),+                  (etcNix </> "sub" </> "one.conf", "include ../two.conf"),+                  (etcNix </> "two.conf", "substituters = https://two")+                ]+         in assertEqual "nested" (Right ["https://two"]) (substitutersOf files [asciiOsPath systemConf] Nothing),+      runTest "!include of a file that cannot be read is skipped" $+        let files = fileMap [(systemConf, "substituters = https://a\n!include missing.conf\nextra-substituters = https://b")]+         in assertEqual "optional" (Right ["https://a", "https://b"]) (substitutersOf files [asciiOsPath systemConf] Nothing),+      runTest "include of a missing file is an error in upstream's words, naming both files" $+        let files = fileMap [(systemConf, "include missing.conf")]+            expected = "nix.conf: file '" <> T.pack (etcNix </> "missing.conf") <> "' included from '" <> T.pack systemConf <> "' not found"+         in assertEqual "required" (Left expected) (substitutersOf files [asciiOsPath systemConf] Nothing),+      -- A file that exists but will not open: upstream drops it, here a+      -- required include of it is an error in its own words.+      runTest "include of a file that exists but cannot be read is an error, not a silent drop" $+        let locked = etcNix </> "locked.conf"+            readLocked path = Identity (if path == asciiOsPath locked then Left Config.ConfigFileUnreadable else Right "include locked.conf")+            expected = "nix.conf: file '" <> T.pack locked <> "' included from '" <> T.pack systemConf <> "' cannot be read"+         in assertEqual "unreadable" (Left expected) (ncSubstituters <$> runIdentity (Config.loadConfig readLocked [asciiOsPath systemConf] Nothing)),+      runTest "!include of a file that exists but cannot be read is skipped" $+        let locked = etcNix </> "locked.conf"+            readLocked path = Identity (if path == asciiOsPath locked then Left Config.ConfigFileUnreadable else Right "!include locked.conf\nsubstituters = https://a")+         in assertEqual "unreadable-optional" (Right ["https://a"]) (ncSubstituters <$> runIdentity (Config.loadConfig readLocked [asciiOsPath systemConf] Nothing)),+      runTest "an include cycle is refused rather than followed" $+        let files = fileMap [(systemConf, "include site.conf"), (etcNix </> "site.conf", "include nix.conf")]+         in assertLeft "cycle" (substitutersOf files [asciiOsPath systemConf] Nothing),+      runTest "an include with no path or two paths is a syntax error" $+        assertEqual "arity" [True, True, True] (map (either (const True) (const False) . resolveTexts . pure) ["include", "include a b", "!include"]),+      runTest "a relative include from NIX_CONFIG is refused as not absolute" $+        let expected = "nix.conf: not an absolute path: '" <> T.pack ("." </> "rel.conf") <> "'"+         in assertEqual "env-relative" (Left expected) (substitutersOf Map.empty [] (Just "include rel.conf")),+      runTest "an absolute include from NIX_CONFIG is expanded" $+        let files = fileMap [(etcNix </> "x.conf", "substituters = https://x")]+         in assertEqual "env-absolute" (Right ["https://x"]) (substitutersOf files [] (Just ("include " <> BS8.pack (etcNix </> "x.conf")))),+      -- An include target is bytes from the line to the open: the+      -- file its bytes name is read, never the one a lossy decode names.+      runTest "an include target with no UTF-8 reading opens the file its bytes name" $+        let target = latin1 <> ".conf"+            including = fileMap [(systemConf, "include " <> target)]+            decoy = maybe including (\name -> Map.insert (asciiOsPath etcNix OP.</> name) "substituters = https://replacement" including) (hostPathFromBytes (replaced <> ".conf"))+         in case hostPathFromBytes target of+              Just name ->+                let files = Map.insert (asciiOsPath etcNix OP.</> name) "substituters = https://latin1" decoy+                 in assertEqual "include-bytes" (Right ["https://latin1"]) (substitutersOf files [asciiOsPath systemConf] Nothing)+              Nothing ->+                let expected = "nix.conf: file 'caf\xFFFD.conf' included from '" <> T.pack systemConf <> "' is not valid UTF-8, so it names no Windows file"+                 in assertEqual "include-bytes-windows" (Left expected) (substitutersOf decoy [asciiOsPath systemConf] Nothing),+      runTest "!include of a target with no UTF-8 reading that names nothing goes on without it" $+        let files = fileMap [(systemConf, "!include " <> latin1 <> ".conf\nsubstituters = https://a")]+         in assertEqual "optional-bytes" (Right ["https://a"]) (substitutersOf files [asciiOsPath systemConf] Nothing),+      -- The directories a cascade names keep their bytes too, so the+      -- system file under such a NIX_CONF_DIR, and an include beside a+      -- file under such a config home, are the files those bytes name.+      runTest "NIX_CONF_DIR holding a byte with no UTF-8 reading names the system file by its bytes" $+        let confDir = BS8.pack (etcNix ++ "-") <> latin1+            located = cascade {Config.clConfDir = Just confDir, Config.clUserConfFiles = Just ""}+         in case hostPathFromBytes confDir of+              Just dir ->+                let files = Map.fromList [(dir OP.</> nixConfName, "include site.conf"), (dir OP.</> asciiOsPath "site.conf", "substituters = https://conf-dir")]+                 in assertEqual "conf-dir-bytes" (Right (Just (dir OP.</> nixConfName)), Right ["https://conf-dir"]) (firstPathOf located, substitutersAt files located Nothing)+              Nothing -> assertLeft "conf-dir-bytes-windows" (firstPathOf located),+      runTest "an include beside a user file under a config home holding such a byte resolves beneath it" $+        case hostPathFromBytes (BS8.pack (configHome ++ "-") <> latin1) of+          Just home ->+            let located = cascade {Config.clSystemConfDir = Nothing, Config.clConfigHome = home, Config.clConfigDirs = []}+                userDir = home OP.</> asciiOsPath "nix"+                files = Map.fromList [(userDir OP.</> nixConfName, "include more.conf"), (userDir OP.</> asciiOsPath "more.conf", "substituters = https://home-bytes")]+             in assertEqual "home-bytes" (Right ["https://home-bytes"]) (substitutersAt files located Nothing)+          Nothing -> assertEqual "home-bytes-windows" "mingw32" SI.os,+      -- The cascade: which files, in which order, and who wins.+      runTest "the cascade is the system file, XDG_CONFIG_DIRS back to front, then the config home" $+        assertEqual "order" (Right (map asciiOsPath [systemConf, xdgConf etcXdgLocal, xdgConf etcXdg, xdgConf configHome])) (Config.configFilePaths cascade),+      runTest "the config home beats XDG_CONFIG_DIRS beats the system file" $+        assertEqual "home-wins" (Right ["https://home"]) (substitutersAt cascadeFiles cascade Nothing),+      runTest "the first XDG_CONFIG_DIRS entry beats the later ones" $+        assertEqual "xdg-first" (Right ["https://xdg"]) (substitutersAt (Map.delete (asciiOsPath (xdgConf configHome)) cascadeFiles) cascade Nothing),+      runTest "a listed file that cannot be read is absent, not an error" $+        assertEqual "absent" (Right ["https://system"]) (substitutersAt (Map.filterWithKey (\path _ -> path == asciiOsPath systemConf) cascadeFiles) cascade Nothing),+      runTest "extra- in a stronger file widens what a weaker file set" $+        let files = fileMap [(systemConf, "trusted-public-keys = k1"), (xdgConf configHome, "extra-trusted-public-keys = k2")]+         in assertEqual "widen-across-files" (Right ["k1", "k2"]) (fmap ncTrustedPublicKeys (Config.configFilePaths cascade >>= \paths -> resolveWith files paths Nothing)),+      runTest "NIX_CONFIG beats every file" $+        assertEqual "env-wins" (Right ["https://env"]) (substitutersAt cascadeFiles cascade (Just "substituters = https://env")),+      runTest "NIX_USER_CONF_FILES replaces the XDG files, first listed strongest" $+        let listed = cascade {Config.clUserConfFiles = Just (listVar [etcNix </> "a.conf", etcNix </> "b.conf"])}+         in assertEqual "listed" (Right (map asciiOsPath [systemConf, etcNix </> "b.conf", etcNix </> "a.conf"])) (Config.configFilePaths listed),+      runTest "NIX_CONFIG_HOME holds the config home's nix.conf itself, ahead of XDG_CONFIG_DIRS" $+        assertEqual+          "nix-config-home"+          (Right (map asciiOsPath [systemConf, xdgConf etcXdgLocal, xdgConf etcXdg, nixConfigHome </> "nix.conf"]))+          (Config.configFilePaths cascade {Config.clNixConfigHome = Just (BS8.pack nixConfigHome)}),+      runTest "NIX_CONFIG_HOME's nix.conf beats XDG_CONFIG_DIRS, and the XDG config home's is not read" $+        let files = Map.insert (asciiOsPath (nixConfigHome </> "nix.conf")) "substituters = https://nix-config-home" cascadeFiles+         in assertEqual "nix-config-home-wins" (Right ["https://nix-config-home"]) (substitutersAt files cascade {Config.clNixConfigHome = Just (BS8.pack nixConfigHome)} Nothing),+      runTest "an empty NIX_CONFIG_HOME is set, and names nix.conf in the working directory" $+        assertEqual+          "nix-config-home-empty"+          (Right (map asciiOsPath [systemConf, xdgConf etcXdgLocal, xdgConf etcXdg, "nix.conf"]))+          (Config.configFilePaths cascade {Config.clNixConfigHome = Just ""}),+      runTest "NIX_USER_CONF_FILES replaces NIX_CONFIG_HOME's file with the rest" $+        let listed = cascade {Config.clUserConfFiles = Just (listVar [etcNix </> "a.conf"]), Config.clNixConfigHome = Just (BS8.pack nixConfigHome)}+         in assertEqual "listed-over-home" (Right (map asciiOsPath [systemConf, etcNix </> "a.conf"])) (Config.configFilePaths listed),+      runTest "an empty NIX_USER_CONF_FILES names no user files" $+        assertEqual "none" (Right [asciiOsPath systemConf]) (Config.configFilePaths cascade {Config.clUserConfFiles = Just ""}),+      runTest "empty NIX_USER_CONF_FILES entries are dropped" $+        assertEqual "empties" (Right (map asciiOsPath [systemConf, etcNix </> "a.conf"])) (Config.configFilePaths cascade {Config.clUserConfFiles = Just (listVar ["", etcNix </> "a.conf", ""])}),+      runTest "NIX_CONF_DIR moves the system file" $+        assertEqual "conf-dir" (Right (Just (asciiOsPath (etcXdg </> "nix.conf")))) (firstPathOf cascade {Config.clConfDir = Just (BS8.pack etcXdg)}),+      runTest "an empty NIX_CONF_DIR is unset" $+        assertEqual "conf-dir-empty" (Right (Just (asciiOsPath systemConf))) (firstPathOf cascade {Config.clConfDir = Just ""}),+      runTest "a relative NIX_CONF_DIR is refused with upstream's complaint" $+        assertEqual "conf-dir-relative" (Left "nix.conf: not an absolute path: 'rel'") (firstPathOf cascade {Config.clConfDir = Just "rel"}),+      runTest "dot and dot-dot in NIX_CONF_DIR collapse, so the system file is named canonically" $+        assertEqual "conf-dir-canonical" (Right (Just (asciiOsPath systemConf))) (firstPathOf cascade {Config.clConfDir = Just (BS8.pack (root </> "etc" </> "x" </> ".." </> "." </> "nix"))}),+      -- A UNC directory keeps its server on Windows, where System.FilePath+      -- and std::filesystem both read it as the drive; a doubled POSIX+      -- root is one root, as upstream's canonPath folds it.+      runTest "a UNC NIX_CONF_DIR keeps its root, and its include resolves beneath it" $+        let (dir, expected) =+              if SI.os == "mingw32"+                then ("\\\\server\\share", "\\\\server\\share\\nix.conf")+                else ("//server/share", "/server/share/nix.conf")+            uncConf = takeDirectory expected </> "site.conf"+            files = fileMap [(expected, "include site.conf"), (uncConf, "substituters = https://unc")]+            unc = cascade {Config.clConfDir = Just (BS8.pack dir), Config.clUserConfFiles = Just ""}+         in assertEqual "unc" (Right (Just (asciiOsPath expected)), Right ["https://unc"]) (firstPathOf unc, substitutersAt files unc Nothing),+      runTest "a platform with no machine-wide directory has no system file" $+        assertEqual "no-system-dir" (Right (map asciiOsPath [xdgConf etcXdgLocal, xdgConf etcXdg, xdgConf configHome])) (Config.configFilePaths cascade {Config.clSystemConfDir = Nothing}),+      runTest "NIX_CONF_DIR names a system file even where the platform has no directory for one" $+        assertEqual "conf-dir-no-default" (Right (Just (asciiOsPath (etcXdg </> "nix.conf")))) (firstPathOf cascade {Config.clSystemConfDir = Nothing, Config.clConfDir = Just (BS8.pack etcXdg)}),+      runTest "a setting set through an alias or extra- counts as the setting, and a name no setting has counts as none" $+        let assigned = Config.assignedSettings . map (uncurry Config.ConfigAssignment)+         in assertEqual+              "substituters"+              (assignedHow [("substituters", Config.Replaced)])+              (assigned [("binary-caches", "https://a"), ("extra-substituters", "https://b"), ("no-such-setting", "x"), ("extra-no-such-setting", "x")])+              `andThen` assertEqual+                "aliases"+                (assignedHow [("cores", Config.Replaced), ("filetransfer-retry-attempts", Config.Replaced), ("sandbox", Config.Replaced), ("sandbox-paths", Config.ExtendedOnly), ("trusted-public-keys", Config.ExtendedOnly)])+                (assigned [("build-cores", "2"), ("download-attempts", "3"), ("build-use-chroot", "false"), ("extra-build-chroot-dirs", "/bin"), ("extra-binary-cache-public-keys", "k")])+              `andThen` assertEqual "extra- on a setting that has no list is no setting" (assignedHow []) (assigned [("extra-max-call-depth", "5"), ("extra-sandbox", "true")]),+      runTest "a setting is replaced when any assignment of it is plain, before the extra- ones or after, and extended only when every one is extra-" $+        let assigned = Config.assignedSettings . map (uncurry Config.ConfigAssignment)+         in assertEqual "extra- alone" (assignedHow [("substituters", Config.ExtendedOnly)]) (assigned [("extra-substituters", "https://a"), ("extra-binary-caches", "https://b")])+              `andThen` assertEqual "plain, then extra-" (assignedHow [("substituters", Config.Replaced)]) (assigned [("substituters", "https://a"), ("extra-substituters", "https://b")])+              `andThen` assertEqual "extra-, then plain" (assignedHow [("substituters", Config.Replaced)]) (assigned [("extra-substituters", "https://a"), ("binary-caches", "https://b")])+              `andThen` assertEqual "each setting by itself" (assignedHow [("substituters", Config.Replaced), ("trusted-public-keys", Config.ExtendedOnly)]) (assigned [("substituters", "https://a"), ("extra-trusted-public-keys", "k")]),+      runTest "the settings the sources set are told with the configuration they make, whichever source sets them, and a value no setting takes fails as it does without them" $+        let files = Map.fromList [(asciiOsPath (root </> "a.conf"), "binary-caches = https://a\nbuild-cores = 2"), (asciiOsPath (root </> "b.conf"), "restrict-eval = yes")]+            paths = map asciiOsPath [root </> "a.conf", root </> "b.conf"]+            loaded = runIdentity (Config.loadConfigAssigned (readFrom files) paths (Just "extra-substituters = https://b"))+            plain = runIdentity (Config.loadConfig (readFrom files) paths (Just "extra-substituters = https://b"))+            broken = Map.insert (asciiOsPath (root </> "b.conf")) "restrict-eval = maybe" files+         in assertEqual "assigned" (Right (assignedHow [("substituters", Config.Replaced), ("cores", Config.Replaced), ("restrict-eval", Config.Replaced)])) (snd <$> loaded)+              `andThen` assertEqual "configuration" plain (fst <$> loaded)+              `andThen` assertEqual "refused" (runIdentity (Config.loadConfig (readFrom broken) paths Nothing)) (fst <$> runIdentity (Config.loadConfigAssigned (readFrom broken) paths Nothing)),+      runTest "only the store settings a source set are sent, each spelled as nix.conf spells it" $+        let sent =+              overridesOf+                [ ("binary-caches", "https://a https://b"),+                  ("sandbox", "relaxed"),+                  ("restrict-eval", "true"),+                  ("keep-failed", "true"),+                  ("extra-sandbox-paths", "/bin/sh=/bin/sh /usr"),+                  ("secret-key-files", "/k1 /k2"),+                  ("require-sigs", "no")+                ]+         in assertEqual+              "sent"+              ( Right+                  ( Map.fromList+                      [ ("substituters", "https://a https://b"),+                        ("sandbox", "relaxed"),+                        ("extra-sandbox-paths", "/bin/sh=/bin/sh /usr"),+                        ("secret-key-files", "/k1 /k2"),+                        ("require-sigs", "false")+                      ]+                  )+              )+              sent,+      runTest "each kind of store setting is spelled as nix.conf spells it, and the settings that are not the store's, or that travel in the options message, are not sent" $+        let sent =+              overridesOf+                [ ("trusted-public-keys", "k1 k2"),+                  ("trusted-substituters", "https://t"),+                  ("always-allow-substitutes", "yes"),+                  ("sandbox-fallback", "0"),+                  ("sandbox", "true"),+                  ("sandbox-paths", "/b /a"),+                  ("allowed-impure-host-deps", "/lib"),+                  ("ssl-cert-file", "/ca.pem"),+                  ("build-users-group", "nixbld"),+                  ("download-attempts", "4"),+                  ("cores", "3"),+                  ("fallback", "true"),+                  ("experimental-features", "nix-command"),+                  ("use-xdg-base-directories", "true"),+                  ("max-call-depth", "7"),+                  ("allowed-uris", "https://u"),+                  ("pure-eval", "true"),+                  ("trace-verbose", "true"),+                  ("allow-import-from-derivation", "false"),+                  ("trace-import-from-derivation", "true"),+                  ("bash-prompt", "p"),+                  ("bash-prompt-prefix", "p"),+                  ("bash-prompt-suffix", "p"),+                  ("trusted-users", "root"),+                  ("allowed-users", "*")+                ]+         in assertEqual+              "sent"+              ( Right+                  ( Map.fromList+                      [ ("trusted-public-keys", "k1 k2"),+                        ("trusted-substituters", "https://t"),+                        ("always-allow-substitutes", "true"),+                        ("sandbox-fallback", "false"),+                        ("sandbox", "true"),+                        ("sandbox-paths", "/a /b"),+                        ("allowed-impure-host-deps", "/lib"),+                        ("ssl-cert-file", "/ca.pem"),+                        ("build-users-group", "nixbld"),+                        ("filetransfer-retry-attempts", "4")+                      ]+                  )+              )+              sent,+      runTest "a setting no source set is not sent, nor one a source set whose value only the machine can tell and the configuration holds none of, nor a set of paths that keeps its default and adds none" $+        let config = Config.defaultNixConfig {ncSubstituters = ["https://a"], ncKeepFailed = True}+            assigned names = assignedHow [(name, Config.Replaced) | name <- names]+         in assertEqual "none assigned" Map.empty (Config.storeSettingOverrides (assigned []) config)+              `andThen` assertEqual "no value" Map.empty (Config.storeSettingOverrides (assigned ["sandbox", "require-drop-supplementary-groups", "ssl-cert-file", "build-users-group", "sandbox-paths", "allowed-impure-host-deps"]) config)+              `andThen` assertEqual "unknown" Map.empty (Config.storeSettingOverrides (assigned ["no-such-setting"]) config),+      -- The defaults are what upstream's client holds: its substituters+      -- default rendered with the trailing slash, and its trusted key.+      runTest "a list that only extra- assignments built is sent under its name with upstream's default before its entries, none merged, and one a plain assignment replaced is sent as it resolved" $+        let cache = "https://cache.nixos.org/"+            key = "cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY="+         in assertEqual+              "extra- alone"+              (Right (Map.fromList [("substituters", cache <> " https://a https://b"), ("trusted-public-keys", key <> " k1 k2")]))+              (overridesOf [("extra-substituters", "https://a"), ("extra-binary-caches", "https://b"), ("extra-trusted-public-keys", "k1"), ("extra-binary-cache-public-keys", "k2")])+              `andThen` assertEqual "extra- of the default's own entry" (Right (Map.fromList [("substituters", cache <> " " <> cache), ("trusted-public-keys", key <> " " <> key)])) (overridesOf [("extra-substituters", cache), ("extra-trusted-public-keys", key)])+              `andThen` assertEqual "extra- and empty" (Right (Map.fromList [("substituters", cache), ("trusted-public-keys", key)])) (overridesOf [("extra-substituters", ""), ("extra-trusted-public-keys", "")])+              `andThen` assertEqual "plain" (Right (Map.fromList [("substituters", "https://a"), ("trusted-public-keys", "k1")])) (overridesOf [("binary-caches", "https://a"), ("trusted-public-keys", "k1")])+              `andThen` assertEqual "plain, then extra-" (Right (Map.fromList [("substituters", "https://a https://b")])) (overridesOf [("substituters", "https://a"), ("extra-substituters", "https://b")])+              `andThen` assertEqual "extra-, then plain" (Right (Map.fromList [("substituters", "https://b")])) (overridesOf [("extra-substituters", "https://a"), ("substituters", "https://b")])+              `andThen` assertEqual "plain and empty" (Right (Map.fromList [("substituters", "")])) (overridesOf [("substituters", "")])+              `andThen` assertEqual "neither" (Right Map.empty) (overridesOf []),+      runTest "a list whose default is empty in upstream's client too, and a list of words, are sent as they resolved whether an extra- assignment built them or not" $+        assertEqual+          "sent"+          (Right (Map.fromList [("trusted-substituters", "https://t"), ("secret-key-files", "/k1 /k2")]))+          (overridesOf [("extra-trusted-substituters", "https://t"), ("extra-secret-key-files", "/k1"), ("extra-secret-key-files", "/k2")])+          `andThen` assertEqual "extra- and empty" (Right (Map.fromList [("trusted-substituters", ""), ("secret-key-files", "")])) (overridesOf [("extra-trusted-substituters", ""), ("extra-secret-key-files", "")]),+      runTest "a setting upstream declares on some systems only is sent from those alone" $+        let platformOnly = [("sandbox-dev-shm-size", "25%"), ("sandbox-build-dir", "/build2"), ("darwin-log-sandbox-violations", "1"), ("require-drop-supplementary-groups", "no")]+            -- Upstream declares sandbox-dev-shm-size on Linux, sandbox-build-dir+            -- on Linux and FreeBSD, darwin-log-sandbox-violations on macOS and+            -- require-drop-supplementary-groups everywhere but Windows.+            declaredHere = case SI.os of+              "linux" -> [("sandbox-dev-shm-size", "25%"), ("sandbox-build-dir", "/build2"), ("require-drop-supplementary-groups", "false")]+              "freebsd" -> [("sandbox-build-dir", "/build2"), ("require-drop-supplementary-groups", "false")]+              "darwin" -> [("darwin-log-sandbox-violations", "true"), ("require-drop-supplementary-groups", "false")]+              "mingw32" -> []+              _ -> [("require-drop-supplementary-groups", "false")]+         in assertEqual (T.pack SI.os) (Right (Map.fromList declaredHere)) (overridesOf platformOnly),+      runTest "store = daemon sets the store setting and the last source wins, and the configuration leaves sending it to the client" $+        let stored = fmap ncStore . Config.resolveConfig . map (uncurry Config.ConfigAssignment)+         in allFailures+              [ assertEqual "default" Nothing (ncStore Config.defaultNixConfig),+                assertEqual "set" (Right (Just "daemon")) (stored [("store", "daemon")]),+                assertEqual "the last wins" (Right (Just "local")) (stored [("store", "daemon"), ("store", "local")]),+                assertEqual "set to nothing" (Right (Just "")) (stored [("store", "")]),+                assertEqual "not among the overrides" (Right False) (Map.member "store" <$> overridesOf [("store", "daemon")]),+                assertEqual "nor when set to nothing" (Right False) (Map.member "store" <$> overridesOf [("store", "")]),+                assertEqual "extra- has no list to extend" (assignedHow []) (Config.assignedSettings [Config.ConfigAssignment "extra-store" "daemon"])+              ],+      runTest "the records of two sets of assignments make the record of both, a setting that either replaced being replaced" $+        let assigned = Config.assignedSettings . map (uncurry Config.ConfigAssignment)+            appended = assigned [("extra-substituters", "https://a")]+            overridden = assigned [("substituters", "https://b")]+         in allFailures+              [ assertEqual "a plain assignment after an extra- one" overridden (appended <> overridden),+                assertEqual "an extra- assignment after a plain one" overridden (overridden <> appended),+                assertEqual "extra- twice" appended (appended <> appended),+                assertEqual "different settings" (assignedHow [("substituters", Config.ExtendedOnly), ("sandbox", Config.Replaced)]) (appended <> assigned [("sandbox", "true")]),+                assertEqual "nothing" appended (appended <> assigned [])+              ],+      runTestM "recording assignments one set after another is recording each and combining the records" $ do+        result <-+          QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} $+            QC.forAll ((,,) <$> QC.listOf genStoreAssignment <*> QC.listOf genStoreAssignment <*> QC.listOf genStoreAssignment) $ \(first, second, third) ->+              let record = Config.assignedSettings+               in record (first ++ second) QC.=== record first <> record second+                    QC..&&. (record first <> record second) <> record third QC.=== record first <> (record second <> record third)+        pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result))),+      runTestM "what a daemon reads from the overrides makes the same overrides" $ do+        result <-+          QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} $+            QC.forAll (QC.listOf genStoreAssignment) $ \assignments ->+              let overrides = overridesFrom assignments+                  reread = overridesFrom [Config.ConfigAssignment name value | (name, value) <- foldMap Map.toAscList overrides]+               in reread QC.=== overrides+        pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))+    ]+  where+    rejects = ["-1", "1.5", "0x10", "5X", "", "5 6"]+    assignedHow = Config.AssignedSettings . Map.fromList+    -- The overrides a client sends for assignments, or why they make no+    -- configuration.+    overridesFrom assignments = Config.storeSettingOverrides (Config.assignedSettings assignments) <$> Config.resolveConfig assignments+    overridesOf = overridesFrom . map (uncurry Config.ConfigAssignment)++-- ---------------------------------------------------------------------------+-- Tests: download attempts+-- ---------------------------------------------------------------------------++-- | A fetch through the binary is tried as often as nix.conf says: once+-- under @download-attempts = 1@, so a server that fails the first request+-- fails the fetch, and under upstream's default otherwise, so the second+-- request is made and its file is the result.+testFetchRetryCLI :: IO [Bool]+testFetchRetryCLI = do+  putStrLn "cli/fetch-retry"+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-cli-fetch-retry"+  ambient <- isolatedStoreEnvironment root+  let isolate extraConfig =+        ("NIX_CONFIG", "substituters =\ntrusted-public-keys =\n" <> extraConfig)+          : ("XDG_CONFIG_HOME", root </> "config")+          : ("XDG_CACHE_HOME", root </> "cache")+          : filter (\(key, _) -> key `notElem` ["NIX_CONFIG", "NIX_CONFIG_HOME", "XDG_CONFIG_HOME", "XDG_CACHE_HOME"]) ambient+      fetchUnder extraConfig url =+        Proc.readCreateProcessWithExitCode+          ((Proc.proc "cabal" ["run", "-v0", "exe:nova-nix", "--", "eval", "--store", root </> "store", "--expr", "builtins.fetchurl \"" <> T.unpack url <> "\""]) {Proc.env = Just (isolate extraConfig)})+          ""+      -- Each path fails its first request and serves the file after.+      route _ earlier+        | earlier == 0 = Send (httpResponse "503 Service Unavailable" "busy")+        | otherwise = Send (httpResponse "200 OK" "served\n")+  expected <- either (fail . show) pure (makeFixedOutputPath "twice" "sha256" FlatIngestion (sha256Digest "served\n"))+  bracket_ (forceRemoveIfExists root) (forceRemoveIfExists root) $+    withHttpServer route $ \base requests _ -> do+      (onceCode, _, onceErr) <- fetchUnder "download-attempts = 1\n" (base <> "/once")+      (twiceCode, twiceOut, twiceErr) <- fetchUnder "" (base <> "/twice")+      seen <- requests+      sequence+        [ runTest "download-attempts = 1 makes one attempt, and its failure is the fetch's" $+            case onceCode of+              ExitFailure _ | ("HTTP 503 fetching " <> T.unpack base <> "/once") `isInfixOf` onceErr, length (filter (== "/once") seen) == 1 -> Pass+              _ -> Fail ("expected one failed attempt, got: " <> T.pack (show (onceCode, onceErr, seen))),+          runTest "with no setting a failed first attempt is tried again" $+            case twiceCode of+              ExitSuccess | T.strip (T.pack twiceOut) == "\"" <> storePathToText defaultStoreDir expected <> "\"", length (filter (== "/twice") seen) == 2 -> Pass+              _ -> Fail ("expected the second attempt's file, got: " <> T.pack (show (twiceCode, twiceOut, twiceErr, seen)))+        ]++-- ---------------------------------------------------------------------------+-- Tests: evaluation policy - restricted and pure modes+-- ---------------------------------------------------------------------------++-- | The flags and settings through the binary: the modes and+-- @trace-verbose@ select themselves from the command line and from+-- NIX_CONFIG, and a refusal surfaces as the eval error it is.  Under+-- @trace-verbose@, @builtins.traceVerbose@ is upstream's @prim_trace@+-- (primops.cc at 2.24.9).+testEvalPolicyCLI :: IO [Bool]+testEvalPolicyCLI = do+  putStrLn "cli/eval-policy"+  tmpBase <- getTemporaryDirectory >>= Dir.canonicalizePath+  cwd <- Dir.getCurrentDirectory+  let root = tmpBase </> "nova-nix-test-cli-policy"+  ambient <- isolatedStoreEnvironment root+  let -- Where a channel: entry would land if it were taken for a path.+      cwdChannelEntry = T.unpack (canonPathValue (T.pack (cwd </> "channel:nova-probe")))+      allowed = root </> "allowed"+      -- A string, since a drive-letter path (C:/...) is a URI token and+      -- a native spelling (C:\...) is no token at all; an absolute+      -- string is coerced to a path on every platform.+      outsideFile = T.unpack (canonPathValue (T.pack (root </> "outside.txt")))+      helpFirstLine = maybe "" T.unpack (listToMaybe Ref.helpLines)+      isolate extraConfig =+        ("NIX_CONFIG", "substituters =\ntrusted-public-keys =\n" <> extraConfig)+          : ("XDG_CONFIG_HOME", root </> "config")+          : filter (\(key, _) -> key `notElem` ["NIX_CONFIG", "NIX_CONFIG_HOME", "XDG_CONFIG_HOME", "NIX_PATH"]) ambient+      runCLI extraConfig args =+        Proc.readCreateProcessWithExitCode+          ((Proc.proc "cabal" (["run", "-v0", "exe:nova-nix", "--"] ++ args)) {Proc.env = Just (isolate extraConfig)})+          ""+      expectOut label extraConfig args expected =+        runTestM ("CLI " <> label) $ do+          (code, out, err) <- runCLI extraConfig args+          pure $ case (code, lines out) of+            (ExitSuccess, line : _) -> assertEqual label expected line+            _ -> Fail ("CLI: " <> T.pack (show code) <> "; stdout=" <> T.pack out <> "; stderr=" <> T.pack err)+      expectErr label extraConfig args needle =+        runTestM ("CLI " <> label) $ do+          (code, _, err) <- runCLI extraConfig args+          pure $+            if code /= ExitSuccess && needle `T.isInfixOf` T.pack err+              then Pass+              else Fail ("expected a failure mentioning " <> needle <> ", got " <> T.pack (show (code, err)))+      -- The whole run: the exit code, then stdout and stderr line by line.+      expectRun label extraConfig args expected =+        runTestM ("CLI " <> label) $ do+          (code, out, err) <- runCLI extraConfig args+          pure (assertEqual label expected (code, lines out, lines err))+      traceVerboseHi = ["eval", "--expr", "builtins.traceVerbose \"hi\" 1"]+  bracket_+    ( do+        forceRemoveIfExists root+        createDirectoryIfMissing True allowed+        BS.writeFile (allowed </> "data.txt") "hello\n"+        BS.writeFile (root </> "outside.txt") "no\n"+    )+    (forceRemoveIfExists root)+    $ sequence+      [ expectOut "--pure-eval hides currentTime" "" ["eval", "--pure-eval", "--expr", "builtins ? currentTime"] "false",+        expectOut "--restrict-eval empties getEnv" "" ["eval", "--restrict-eval", "--expr", "builtins.getEnv \"HOME\""] "\"\"",+        expectOut "pure-eval from NIX_CONFIG" "pure-eval = true\n" ["eval", "--expr", "builtins ? currentSystem"] "false",+        expectOut "a --nix-path root is readable under --restrict-eval" "" ["eval", "--restrict-eval", "--nix-path", "allowed=" ++ allowed, "--expr", "builtins.readFile <allowed/data.txt>"] "\"hello\\n\"",+        expectErr "a read outside the roots fails the command" "" ["eval", "--restrict-eval", "--expr", "builtins.readFile \"" ++ outsideFile ++ "\""] "is forbidden in restricted mode",+        expectErr "a channel: search path entry allows nothing" "" ["eval", "--restrict-eval", "--nix-path", "nixpkgs=channel:nova-probe", "--expr", "builtins.readFile \"" ++ cwdChannelEntry ++ "\""] "is forbidden in restricted mode",+        expectOut "build accepts the flag before its target" "" ["build", "--pure-eval", "--help"] helpFirstLine,+        expectRun "traceVerbose prints nothing by default" "" traceVerboseHi (ExitSuccess, ["1"], []),+        expectRun "--trace-verbose makes traceVerbose trace" "" ("--trace-verbose" : traceVerboseHi) (ExitSuccess, ["1"], ["trace: hi"]),+        expectRun "trace-verbose from NIX_CONFIG makes traceVerbose trace" "trace-verbose = true\n" traceVerboseHi (ExitSuccess, ["1"], ["trace: hi"]),+        expectRun "under --trace-verbose traceVerbose forces its first argument" "" ["eval", "--trace-verbose", "--expr", "builtins.traceVerbose (throw \"a\") 1"] (ExitFailure 1, [], ["error: a"]),+        expectRun "under --trace-verbose traceVerbose prints before its second argument fails" "" ["eval", "--trace-verbose", "--expr", "builtins.traceVerbose \"hi\" (throw \"b\")"] (ExitFailure 1, [], ["trace: hi", "error: b"]),+        -- prim_trace runs only once it has both arguments (callFunction,+        -- eval.cc at 2.24.9), so a partial application forces nothing.+        expectRun "under --trace-verbose a partial traceVerbose leaves its argument unforced" "" ["eval", "--trace-verbose", "--expr", "builtins.seq (builtins.traceVerbose (throw \"a\")) 1"] (ExitSuccess, ["1"], []),+        expectOut "build accepts --trace-verbose before its target" "" ["build", "--trace-verbose", "--help"] helpFirstLine,+        expectOut "build accepts --no-allow-import-from-derivation before its target" "" ["build", "--no-allow-import-from-derivation", "--help"] helpFirstLine,+        expectOut "trust accepts --no-allow-import-from-derivation before its target" "" ["trust", "--no-allow-import-from-derivation", "--help"] helpFirstLine,+        expectOut "eval accepts --no-allow-import-from-derivation" "" ["eval", "--no-allow-import-from-derivation", "--expr", "1"] "1",+        -- A flag only moves a setting from its default, so none turns an+        -- import from derivation the configuration refuses back on.+        expectErr "there is no --allow-import-from-derivation to undo the configuration's refusal" "" ["eval", "--allow-import-from-derivation", "--expr", "1"] "unknown eval flag"+      ]++-- | The eval result through the binary: stdout carries the printer's bytes+-- and a bare newline, with no text encoding or newline translation between.+testResultPrinterCLI :: IO [Bool]+testResultPrinterCLI = do+  putStrLn "cli/eval-result"+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-cli-result"+  ambient <- isolatedStoreEnvironment root+  let file = root </> "latin1"+      notUtf8 = "a" <> BS.singleton 0xfc <> "b"+      -- A string, as in testEvalPolicyCLI: a drive-letter path is no+      -- path literal.+      fileString = T.unpack (canonPathValue (T.pack file))+      isolated =+        ("XDG_CONFIG_HOME", root </> "config")+          : filter (\(key, _) -> key `notElem` ["NIX_CONFIG", "NIX_CONFIG_HOME", "XDG_CONFIG_HOME"]) ambient+      cliProcess args = (Proc.proc "cabal" (["run", "-v0", "exe:nova-nix", "--"] ++ args)) {Proc.env = Just isolated, Proc.std_out = Proc.CreatePipe}+      printsThrough label args expected = runTestM label (Proc.withCreateProcess (cliProcess args) (checkPrinted label expected))+      checkPrinted label expected _ stdoutPipe _ process = case stdoutPipe of+        Nothing -> pure (Fail "no stdout pipe")+        Just out -> do+          printed <- BS.hGetContents out+          code <- Proc.waitForProcess process+          pure $ case code of+            ExitSuccess -> assertEqual label expected printed+            ExitFailure _ -> Fail ("CLI: " <> T.pack (show code))+      -- The binary's heap is capped for a derivation, which holds itself:+      -- an eval that forgets what it has entered then exhausts the cap+      -- and fails, where it would run until the machine had no memory+      -- left.  The eval needs a few megabytes.+      heapCapped args = ["+RTS", "-M64m", "-RTS"] ++ args+  bracket_+    (forceRemoveIfExists root >> createDirectoryIfMissing True root >> BS.writeFile file notUtf8)+    (forceRemoveIfExists root)+    $ sequence+      [ printsThrough "CLI eval writes a string's bytes and a bare newline" ["eval", "--expr", "builtins.readFile \"" ++ fileString ++ "\""] ("\"" <> notUtf8 <> "\"\n"),+        printsThrough+          "CLI eval prints a derivation once and its output as repeated"+          (heapCapped ["eval", "--expr", T.unpack selfHoldingDerivation])+          (TE.encodeUtf8 selfHoldingPrinted <> "\n"),+        printsThrough+          "CLI eval --strict prints a derivation, its outputs in all and out as repeated"+          (heapCapped ["eval", "--strict", "--expr", T.unpack selfHoldingDerivation])+          (TE.encodeUtf8 selfHoldingPrintedStrict <> "\n")+      ]++-- | The user's @nix.conf@ in @NIX_CONFIG_HOME@, as upstream 2.36.0 reads+-- it: the file there is read in place of the XDG config home's, the XDG+-- config home's is read when the variable is unset, and an empty one+-- names @nix.conf@ in the working directory.  @pure-eval@ in the file read+-- is what each run sees.  Every place a run reads a config file from is+-- under the test's root, the home and @ZDOTDIR@ included, so the binary is+-- found by @cabal@ first and run by its path.+testNixConfigHomeCLI :: IO [Bool]+testNixConfigHomeCLI = do+  putStrLn "cli/nix-config-home"+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-cli-nix-config-home"+  ambient <- isolatedStoreEnvironment root+  _ <- Proc.readCreateProcessWithExitCode (Proc.proc "cabal" ["run", "-v0", "exe:nova-nix", "--", "--version"]) ""+  (_, listed, _) <- Proc.readCreateProcessWithExitCode (Proc.proc "cabal" ["list-bin", "-v0", "exe:nova-nix"]) ""+  let exe = fromMaybe "nova-nix" (listToMaybe (reverse (filter (not . null) (lines (filter (/= '\r') listed)))))+      home = root </> "home"+      pureConf dir = createDirectoryIfMissing True dir >> BS.writeFile (dir </> "nix.conf") "pure-eval = true\n"+      isolatedNames = ["NIX_CONFIG", "NIX_CONF_DIR", "NIX_USER_CONF_FILES", "NIX_CONFIG_HOME", "XDG_CONFIG_HOME", "XDG_CONFIG_DIRS", "HOME", "USERPROFILE", "APPDATA", "ZDOTDIR"]+      environment configHome nixConfigHome =+        [ ("HOME", home),+          ("USERPROFILE", home),+          ("ZDOTDIR", home),+          ("APPDATA", configHome),+          ("XDG_CONFIG_HOME", configHome),+          ("XDG_CONFIG_DIRS", root </> "xdg-dirs"),+          ("NIX_CONF_DIR", root </> "system")+        ]+          ++ [("NIX_CONFIG_HOME", dir) | Just dir <- [nixConfigHome]]+          ++ filter ((`notElem` isolatedNames) . fst) ambient+      -- What @builtins ? currentSystem@ prints: false under pure-eval.+      expect label expected cwd configHome nixConfigHome = runTestM label $ do+        (code, out, err) <-+          Proc.readCreateProcessWithExitCode+            ((Proc.proc exe ["eval", "--expr", "builtins ? currentSystem"]) {Proc.env = Just (environment configHome nixConfigHome), Proc.cwd = Just cwd})+            ""+        pure $ case (code, lines out) of+          (ExitSuccess, line : _) -> assertEqual label expected line+          _ -> Fail ("CLI: " <> T.pack (show code) <> "; stdout=" <> T.pack out <> "; stderr=" <> T.pack err)+      work = root </> "work"+      plainHome = root </> "xdg-plain"+      pureHome = root </> "xdg-pure"+      nixHome = root </> "nix-home"+      emptyNixHome = root </> "nix-home-empty"+      pureWork = root </> "pure-work"+  bracket_+    ( do+        forceRemoveIfExists root+        mapM_ (createDirectoryIfMissing True) [home, work, plainHome, emptyNixHome]+        pureConf nixHome+        pureConf (pureHome </> "nix")+        pureConf pureWork+    )+    (forceRemoveIfExists root)+    $ sequence+      [ expect "NIX_CONFIG_HOME's nix.conf is read" "false" work plainHome (Just nixHome),+        expect "with NIX_CONFIG_HOME unset, a nix.conf in the directory it would name is not read" "true" work plainHome Nothing,+        expect "with NIX_CONFIG_HOME unset, the XDG config home's nix.conf is read" "false" work pureHome Nothing,+        expect "NIX_CONFIG_HOME takes the XDG config home's place" "true" work pureHome (Just emptyNixHome),+        expect "an empty NIX_CONFIG_HOME names nix.conf in the working directory" "false" pureWork plainHome (Just "")+      ]++-- | nix.conf bytes through the binary: an include target, the+-- system directory and NIX_CONFIG reach the file system and the settings+-- as the bytes they hold.  Each case reads whether pure-eval came on,+-- which hides currentSystem.  A name that is not UTF-8 exists only on a+-- volume that holds one, so a case needing such a name makes it first+-- and skips, with the reason, where the temp volume refuses it: APFS+-- refuses the name, and HFS+ holds it but opens no path beneath a+-- directory so named.  A Windows name or variable is UTF-16 and holds no+-- such byte at all.  The decoy cases need no such name: a file named by+-- U+FFFD's UTF-8, which a lossy decode of the byte would open instead,+-- must stay unread, as it does under nix-instantiate 2.33.2.+testConfigBytesCLI :: IO [Bool]+testConfigBytesCLI = do+  putStrLn "cli/config-bytes"+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-cli-config-bytes"+  ambient <- isolatedStoreEnvironment root+  let confDir = root </> "etc"+      noConfDir = root </> "none"+      configVars = ["NIX_CONFIG", "NIX_CONF_DIR", "NIX_USER_CONF_FILES", "XDG_CONFIG_DIRS"]+      -- An empty NIX_USER_CONF_FILES names no user files, so only the+      -- system file under NIX_CONF_DIR and NIX_CONFIG are read.+      runCLI dir nixConfig =+        Proc.readCreateProcessWithExitCode+          ( (Proc.proc "cabal" ["run", "-v0", "exe:nova-nix", "--", "eval", "--expr", "builtins ? currentSystem"])+              { Proc.env = Just (("NIX_CONF_DIR", dir) : ("NIX_USER_CONF_FILES", "") : ("NIX_CONFIG", nixConfig) : filter ((`notElem` configVars) . fst) ambient)+              }+          )+          ""+      expectAnswer label expected dir nixConfig = do+        (code, out, err) <- runCLI dir nixConfig+        pure $ case (code, lines out) of+          (ExitSuccess, line : _) -> assertEqual label expected line+          _ -> Fail ("CLI: " <> T.pack (show code) <> "; stdout=" <> T.pack out <> "; stderr=" <> T.pack err)+      expectPure label = expectAnswer label "false"+      expectImpure label = expectAnswer label "true"+      expectRefusal nixConfig needle = do+        (code, _, err) <- runCLI noConfDir nixConfig+        pure $+          if code /= ExitSuccess && needle `T.isInfixOf` T.pack err+            then Pass+            else Fail ("expected a failure mentioning " <> needle <> ", got " <> T.pack (show (code, err)))+      -- A case whose name or value holds bytes, spelled as the+      -- platform's strings carry them.+      spelledCase label bytes check = do+        spelled <- envSpelling bytes+        case spelled of+          Nothing -> True <$ putStrLn ("  SKIP  " <> T.unpack label <> ": a Windows name or variable cannot hold a byte with no UTF-8 reading")+          Just spelling -> check spelling+      envCase label bytes check = spelledCase label bytes (runTestM label . check)+      -- A case over a file whose name holds bytes, made before the case+      -- runs and skipped where the temp volume refuses it.+      -- A decoy's name is UTF-8, which every volume holds.+      decoyCase label bytes make check = spelledCase label bytes $ \name -> make name >> runTestM label (check name)+      fileCase label bytes make check = spelledCase label bytes $ \name -> do+        made <- try (make name)+        case made of+          -- The error string alone: the path in the full message holds+          -- the very byte stdout's encoding cannot write.+          Left (err :: IOException) -> True <$ putStrLn ("  SKIP  " <> T.unpack label <> ": the temp volume cannot hold a name that is not UTF-8 (" <> ioeGetErrorString err <> ")")+          Right () -> runTestM label (check name)+      latin1 = "caf\xE9" :: BS.ByteString+      -- The name a lossy decode of latin1 spells: U+FFFD's UTF-8.+      decoy = "caf\xEF\xBF\xBD" :: BS.ByteString+      decoyDir = root </> "decoy"+  bracket_+    (forceRemoveIfExists root >> createDirectoryIfMissing True confDir >> createDirectoryIfMissing True decoyDir)+    (forceRemoveIfExists root)+    $ sequence+      [ fileCase+          "CLI an include target with no UTF-8 reading opens the file it names"+          (latin1 <> ".conf")+          ( \name -> do+              BS.writeFile (confDir </> name) "pure-eval = true\n"+              BS.writeFile (confDir </> "nix.conf") ("include " <> latin1 <> ".conf\n")+          )+          (const (expectPure "include-bytes" confDir "")),+        fileCase+          "CLI a NIX_CONF_DIR holding a byte with no UTF-8 reading names the system file"+          latin1+          ( \name -> do+              createDirectoryIfMissing True (root </> name)+              BS.writeFile (root </> name </> "nix.conf") "pure-eval = true\n"+          )+          (\name -> expectPure "conf-dir-bytes" (root </> name) ""),+        decoyCase+          "CLI an !include target with no UTF-8 reading leaves the U+FFFD-named file unread"+          (decoy <> ".conf")+          ( \name -> do+              BS.writeFile (decoyDir </> name) "pure-eval = true\n"+              BS.writeFile (decoyDir </> "nix.conf") ("!include " <> latin1 <> ".conf\n")+          )+          (const (expectImpure "include-decoy" decoyDir "")),+        spelledCase "CLI a NIX_CONF_DIR holding such a byte leaves the U+FFFD-named directory unread" latin1 $ \confName ->+          decoyCase+            "CLI a NIX_CONF_DIR holding such a byte leaves the U+FFFD-named directory unread"+            decoy+            ( \name -> do+                createDirectoryIfMissing True (decoyDir </> name)+                BS.writeFile (decoyDir </> name </> "nix.conf") "pure-eval = true\n"+            )+            (const (expectImpure "conf-dir-decoy" (decoyDir </> confName) "")),+        envCase+          "CLI NIX_CONFIG holding such a byte in a comment and an unknown setting applies the rest"+          ("max-jobs = " <> latin1 <> "\npure-eval = true # " <> latin1 <> "\n")+          (expectPure "env-bytes-ignored" noConfDir),+        envCase+          "CLI NIX_CONFIG holding such a byte in a list setting is refused"+          ("pure-eval = true\nextra-substituters = https://" <> latin1 <> ".example\n")+          (`expectRefusal` "setting 'substituters' has invalid value"),+        envCase+          "CLI a Boolean ending in a no-break space is invalid, as upstream splits the line"+          "pure-eval = true\xC2\xA0\n"+          (`expectRefusal` "Boolean setting 'pure-eval' has invalid value")+      ]++-- ---------------------------------------------------------------------------+-- Tests: which store a command uses+-- ---------------------------------------------------------------------------++-- | A daemon the suite's binary runs for a test, serving a store of its+-- own in the directory it is given, trusting every client or none as the+-- flag says, until the test is done.  The test is given the address the+-- daemon listens at; a daemon that does not listen is a failure, with+-- what it said.+withDaemonProcess :: FilePath -> [(String, String)] -> FilePath -> String -> (String -> IO a) -> IO (Either Text a)+withDaemonProcess exe environment dir trustFlag test = do+  createDirectoryIfMissing True dir+  address <- daemonAddress dir+  case address of+    Nothing -> pure (Left "the daemon's address has no spelling as bytes")+    Just bytes ->+      withBinaryFile logFile WriteMode $ \logHandle ->+        Proc.withCreateProcess (daemonProcess (BS8.unpack bytes) logHandle) $ \_ _ _ daemon -> do+          _ <- waitUntilWithin startWaitMicros (settled daemon bytes)+          listening <- (== AddressPresent) <$> addressPresence bytes+          if listening+            then do+              result <- test (BS8.unpack bytes)+              Proc.terminateProcess daemon+              _ <- Proc.waitForProcess daemon+              pure (Right result)+            else do+              said <- BS.readFile logFile+              pure (Left ("the daemon did not listen: " <> TE.decodeUtf8Lenient said))+  where+    logFile = dir </> "daemon.log"+    daemonProcess address logHandle =+      (Proc.proc exe ["daemon", "--store", dir </> "store", "--socket-path", address, trustFlag])+        { Proc.env = Just environment,+          Proc.std_out = Proc.UseHandle logHandle,+          Proc.std_err = Proc.UseHandle logHandle+        }+    -- Listening, or gone: either ends the wait.+    settled daemon bytes = do+      exited <- isJust <$> Proc.getProcessExitCode daemon+      present <- (== AddressPresent) <$> addressPresence bytes+      pure (exited || present)++-- | Which store a command uses, through the real CLI.  What each command+-- needs of the store is refused where the store is reached through a+-- daemon and that cannot be done there yet, in words that say how to get+-- on; a command that never asks the store does not connect to the daemon,+-- and one that does fails in upstream's words when it is not there; the+-- @store@ setting overrides @NIX_REMOTE@ and @--store@ overrides both; and+-- a command given a running daemon's address adds and builds into that+-- daemon's store, the flags that set a setting reaching it as the settings+-- they stand for.+testStoreChoiceCLI :: IO [Bool]+testStoreChoiceCLI = do+  putStrLn "cli/store-choice"+  shell <- findTestShell+  tmpBase <- getTemporaryDirectory+  -- Short, as a socket's path may not be long.+  let root = tmpBase </> "nn-sc"+  ambient <- isolatedStoreEnvironment root+  _ <- Proc.readCreateProcessWithExitCode (Proc.proc "cabal" ["run", "-v0", "exe:nova-nix", "--", "--version"]) ""+  (_, listed, _) <- Proc.readCreateProcessWithExitCode (Proc.proc "cabal" ["list-bin", "-v0", "exe:nova-nix"]) ""+  let exe = fromMaybe "nova-nix" (listToMaybe (reverse (filter (not . null) (lines (filter (/= '\r') listed)))))+      noDaemon = fromMaybe "" (lookup "NIX_DAEMON_SOCKET_PATH" ambient)+      isolatedNames = ["NIX_CONFIG", "NIX_CONF_DIR", "NIX_USER_CONF_FILES", "NIX_CONFIG_HOME", "XDG_CONFIG_HOME", "XDG_CONFIG_DIRS"]+      environment config additions =+        additions+          ++ [ ("NIX_CONFIG", config),+               ("NIX_CONF_DIR", root </> "system"),+               ("NIX_USER_CONF_FILES", ""),+               ("XDG_CONFIG_HOME", root </> "config"),+               ("XDG_CONFIG_DIRS", root </> "config-dirs")+             ]+          ++ filter ((`notElem` (isolatedNames ++ map fst additions)) . fst) ambient+      quiet = "substituters =\ntrusted-public-keys =\nsandbox = false\n"+      run config additions args = do+        (code, out, err) <- Proc.readCreateProcessWithExitCode ((Proc.proc exe args) {Proc.env = Just (environment config additions)}) ""+        pure (code, filter (/= '\r') out, filter (/= '\r') err)+      toFileExpression = "builtins.toFile \"a\" \"b\""+      buildExpression =+        T.unpack+          ( "derivation { name = \"through-the-daemon\"; system = builtins.currentSystem; builder = "+              <> nixQuotedPath (T.unpack shell)+              <> "; args = [ \"-c\" \"echo built > $out\" ]; }"+          )+      fixedOutputExpression =+        "derivation { name = \"fetched\"; system = \"builtin\"; builder = \"builtin:fetchurl\"; url = \"http://127.0.0.1:9/fetched\"; "+          <> "outputHashMode = \"flat\"; outputHashAlgo = \"sha256\"; outputHash = \"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\"; }"+      -- The last line a command printed, a string's quotes taken off, as+      -- the base name of the store path it names.+      printedName out = takeFileName . filter (/= '"') <$> listToMaybe (reverse (filter (not . null) (lines out)))+      refused label args expected =+        runTestM label $ do+          (code, out, err) <- run quiet [] args+          pure (assertEqual "status, stdout and stderr" (ExitFailure 1, "", expected <> "\n") (code, out, err))+      refusedThroughDaemon doing command =+        command <> ": nova-nix does not " <> doing <> " through the daemon yet; give --store local where the store can be written"+      daemonRefusal = "daemon: --store names a store reached through a daemon; the daemon serves a store it opens itself"+      noSuchSocket = root </> "none"+      -- A store path the daemon holds nothing at.+      absentStorePath = "/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-gone"+      connectReason = "cannot connect to socket at \"" <> noSuchSocket <> "\": No such file or directory\n"+      connectFailure = "error: " <> connectReason+      posixOnly tests = if SI.os == "mingw32" then [] else tests+      daemonEnvironment config = environment config [("NIX_REMOTE", "daemon")]+      expectWarning err phrase = T.pack phrase `T.isInfixOf` T.pack err+      -- The settings an untrusted daemon says it ignored, of the three+      -- flags that set one and of the store setting.+      ignoredSetting name = "ignoring the client-specified setting '" <> name <> "', because it is a restricted setting and you are not a trusted user"+  bracket_+    (forceRemoveIfExists root >> createDirectoryIfMissing True root)+    (forceRemoveIfExists root)+    ( sequence $+        [ refused "store gc through the daemon is refused, saying why" ["store", "gc", "--store", "daemon"] (refusedThroughDaemon "collect garbage" "store gc"),+          refused "store delete through the daemon is refused, saying why" ["store", "delete", "--store", "daemon", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-gone"] (refusedThroughDaemon "delete paths" "store delete"),+          refused+            "--exec-wrapper through the daemon is refused, saying why"+            ["build", "--store", "daemon", "--exec-wrapper", T.unpack (platformToText currentPlatform) <> "=" <> T.unpack shell, "--no-out-link", "--expr", "1"]+            "error: --exec-wrapper needs a store nova-nix builds in itself; give --store local, or a store directory",+          refused "the daemon refuses a store reached through a daemon" ["daemon", "--store", "daemon"] daemonRefusal,+          refused "the daemon refuses a socket's address as its store" ["daemon", "--store", "unix://" <> noDaemon] daemonRefusal,+          runTestM "a command that never asks the store does not connect to the daemon" $ do+            (code, out, err) <- run quiet [] ["eval", "--store", "daemon", "--expr", "1 + 1"]+            pure (assertEqual "status, stdout and stderr" (ExitSuccess, "2\n", "") (code, out, err))+        ]+          ++ posixOnly+            [ runTestM "a daemon that is not there fails in upstream's words, whether --store or NIX_REMOTE names it" $ do+                named <- run quiet [] ["build", "--no-out-link", "--store", "unix://" <> noSuchSocket, "--expr", buildExpression]+                environmental <- run quiet [("NIX_REMOTE", "daemon"), ("NIX_DAEMON_SOCKET_PATH", noSuchSocket)] ["build", "--no-out-link", "--expr", buildExpression]+                pure $+                  allFailures+                    [ assertEqual "--store" (ExitFailure 1, "", connectFailure) named,+                      assertEqual "NIX_REMOTE" (ExitFailure 1, "", connectFailure) environmental+                    ],+              runTestM "push and trust through a daemon that is not there fail with the connection failure, each going to the daemon" $ do+                let store = ["--store", "unix://" <> noSuchSocket]+                    cache = ["--cache", "https://cache.invalid"]+                pushedAll <- run quiet [] (["push"] ++ store ++ cache ++ ["--all"])+                pushedNamed <- run quiet [] (["push"] ++ store ++ cache ++ [absentStorePath])+                trusted <- run quiet [] (["trust"] ++ store ++ ["--expr", fixedOutputExpression])+                pure $+                  allFailures+                    [ assertEqual "push --all" (ExitFailure 1, "", "push failed: " <> connectReason) pushedAll,+                      assertEqual "push of a named path" (ExitFailure 1, "", "push failed: " <> connectReason) pushedNamed,+                      assertEqual "trust" (ExitFailure 1, "", "trust: " <> connectReason) trusted+                    ],+              runTestM "the store setting overrides NIX_REMOTE, and --store overrides both" $ do+                let additions = [("NIX_REMOTE", "daemon"), ("NIX_DAEMON_SOCKET_PATH", noSuchSocket)]+                    configured = quiet <> "store = " <> root </> "store\n"+                setting <- run configured additions ["eval", "--read-write-mode", "--expr", toFileExpression]+                flagged <- run configured additions ["eval", "--read-write-mode", "--store", "unix://" <> noSuchSocket, "--expr", toFileExpression]+                let (settingCode, settingOut, settingErr) = setting+                written <- traverse (\name -> BS.readFile (root </> "store" </> name)) (printedName settingOut)+                pure $+                  assertEqual "the setting names a directory, which is written to" (ExitSuccess, Just "b", "") (settingCode, written, settingErr)+                    `andThen` assertEqual "the flag names a daemon that is not there" (ExitFailure 1, "", connectFailure) flagged,+              runTestM "--store sets the store setting for a command that models upstream's nix command, and for one that models nix-build it only gives the setting a value" $ do+                outcome <- withDaemonProcess exe (environment "substituters = https://cache.nixos.org/\n" []) (root </> "v") "--force-untrusted" $ \address -> do+                  let store = ["--store", "unix://" <> address]+                  built <- run "" [] (["build", "--no-out-link"] ++ store ++ ["--expr", buildExpression])+                  added <- run "" [] (["profile", "add", "--profile", root </> "v" </> "profile"] ++ store ++ [absentStorePath])+                  pure (built, added)+                pure $ case outcome of+                  Left problem -> Fail problem+                  Right ((builtCode, _, builtErr), (addedCode, _, addedErr)) ->+                    allFailures+                      [ assertEqual "build, as nix-build, sends nothing for --store" (ExitSuccess, False) (builtCode, expectWarning builtErr (ignoredSetting "store")),+                        assertEqual "profile add, as nix profile add, sends the setting" (ExitFailure 1, True) (addedCode, expectWarning addedErr (ignoredSetting "store"))+                      ]+            ]+          ++ [ runTestM "a command through a running daemon adds and builds into the daemon's store, which --store names whatever NIX_REMOTE and the store setting say" $ do+                 outcome <- withDaemonProcess exe (daemonEnvironment ("store = daemon\n" <> quiet)) (root </> "t") "--force-trusted" $ \address -> do+                   written <- run quiet [] ["eval", "--read-write-mode", "--store", "unix://" <> address, "--expr", toFileExpression]+                   built <- run quiet [] ["build", "--no-out-link", "--store", "unix://" <> address, "--expr", buildExpression]+                   pure (written, built)+                 case outcome of+                   Left problem -> pure (Fail problem)+                   Right ((writtenCode, writtenOut, writtenErr), (builtCode, builtOut, _)) -> do+                     let names = catMaybes [printedName writtenOut, printedName builtOut]+                         parsed = traverse (parseStorePathBaseName . T.pack) names+                     store <- openStore testLogger (StoreDir (root </> "t" </> "store"))+                     valid <- traverse (traverse (isValid store)) parsed+                     closeStore store+                     built <- traverse (\name -> BS.readFile (root </> "t" </> "store" </> name)) (printedName builtOut)+                     pure $+                       assertEqual "toFile" (ExitSuccess, "") (writtenCode, writtenErr)+                         `andThen` assertEqual "build" ExitSuccess builtCode+                         `andThen` assertEqual "both paths are valid in the daemon's store" (Just [True, True]) valid+                         `andThen` assertEqual "the build's output" (Just "built\n") (BS8.filter (/= '\r') <$> built),+               runTestM "the flags that set a setting reach an untrusted daemon as the settings they stand for, and --store is not one" $ do+                 outcome <- withDaemonProcess exe (environment "substituters = https://cache.nixos.org/\n" []) (root </> "u") "--force-untrusted" $ \address -> do+                   let eval config flags = run config [] (["eval", "--read-write-mode", "--store", "unix://" <> address] ++ flags ++ ["--expr", toFileExpression])+                       reported (code, _, err) = (code, err)+                   plain <- reported <$> eval "" []+                   substituter <- reported <$> eval "" ["--substituter", "http://example.invalid"]+                   key <- reported <$> eval "" ["--trusted-key", "example.invalid-1:AAAA"]+                   sandbox <- reported <$> eval "" ["--no-sandbox"]+                   configured <- reported <$> run ("store = unix://" <> address <> "\n") [] ["eval", "--read-write-mode", "--expr", toFileExpression]+                   overSetting <- reported <$> run "store = local\n" [] ["eval", "--read-write-mode", "--store", "unix://" <> address, "--expr", toFileExpression]+                   pure (plain, substituter, key, sandbox, configured, overSetting)+                 pure $ case outcome of+                   Left problem -> Fail problem+                   Right ((plainCode, plainErr), (substituterCode, substituterErr), (keyCode, keyErr), (sandboxCode, sandboxErr), (configuredCode, configuredErr), (overSettingCode, overSettingErr)) ->+                     allFailures+                       [ assertEqual "nothing is sent for what no flag set" (ExitSuccess, "") (plainCode, plainErr),+                         assertEqual "--substituter" (ExitSuccess, True) (substituterCode, expectWarning substituterErr "ignoring untrusted substituter 'http://example.invalid'"),+                         assertEqual "--trusted-key" (ExitSuccess, True) (keyCode, expectWarning keyErr (ignoredSetting "trusted-public-keys")),+                         assertEqual "--no-sandbox" (ExitSuccess, True) (sandboxCode, expectWarning sandboxErr (ignoredSetting "sandbox")),+                         assertEqual "the store setting is sent" (ExitSuccess, True) (configuredCode, expectWarning configuredErr (ignoredSetting "store")),+                         assertEqual "--store over a store setting, which is the setting that is sent" (ExitSuccess, True) (overSettingCode, expectWarning overSettingErr (ignoredSetting "store"))+                       ]+             ]+    )
+ test/Test/Daemon.hs view
@@ -0,0 +1,3267 @@+{-# LANGUAGE LambdaCase #-}++-- | Tests of the daemon's wire format, its protocol, its side of a+-- connection, scripted byte by byte against a store in memory, who may+-- connect to it, the daemon itself on a socket, or on Windows its pipe,+-- over a store on disk, and what a client adds to a store on disk+-- through it.+module Test.Daemon+  ( testDaemonWire,+    testDaemonProtocol,+    testDaemonFixtures,+    testDaemonServer,+    testDaemonAuth,+    testDaemonSocketIO,+    testDaemonBuilds,+    testDaemonAdds,++    -- * A daemon on disk, for the pipe's tests+    withSocketDaemon,+    socketTestMicros,+    helloOver,+    defaultStoreDir,+    fooPath,+  )+where++import Control.Concurrent (forkFinally, killThread)+import Control.Concurrent.MVar (MVar, newEmptyMVar, putMVar, takeMVar)+import Control.Exception (IOException, bracket, onException, try)+import Control.Monad (replicateM, void, when)+import Control.Monad.State.Strict (State, gets, modify', runState, state)+import DaemonLink (DaemonLink (..), connectDaemon, daemonAddress, listenerOpenToUsers)+import qualified Data.Bifunctor as Bifunctor+import Data.Bits (shiftR)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Builder as BB+import qualified Data.ByteString.Char8 as BS8+import qualified Data.ByteString.Lazy as BL+import Data.Foldable (traverse_)+import Data.Functor.Identity (Identity, runIdentity)+import Data.IORef (atomicModifyIORef', newIORef, readIORef)+import Data.Int (Int64)+import Data.List (isPrefixOf, isSuffixOf, sort)+import Data.List.NonEmpty (NonEmpty (..))+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe, mapMaybe)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Time.Clock.POSIX (getPOSIXTime)+import Data.Word (Word32, Word64, Word8)+import Foreign.C.Types (CInt (..))+import Nix.Builder (BuildConfig (..))+import Nix.Builder.BuildUser (ProcessPrivilege (..))+import Nix.Builder.Sandbox (SandboxMode (..))+import Nix.Builder.Settings (MachineDefaults (..), settingsBuildConfig)+import Nix.CacheDirectory (cacheInfoFileName, cacheInfoText, directoryUrl)+import Nix.Config (NixConfig (..), defaultNixConfig)+import qualified Nix.Daemon.Auth as Auth+import qualified Nix.Daemon.Connection as Conn+import qualified Nix.Daemon.Listen as Listen+import Nix.Daemon.LocalStore (ServedStore, newServedStore, serveLocal)+import qualified Nix.Daemon.Ops as Ops+import qualified Nix.Daemon.Protocol as Proto+import qualified Nix.Daemon.Wire as Wire+import Nix.Derivation (Derivation (..), DerivationOutput (..), DrvFile, Platform (..), drvFileATerm, drvFileDerivation, drvFilePath, inputAddressed, toATerm)+import Nix.Environment (argumentBytes)+import Nix.Hash (FileIngestionMethod (..), makeFixedOutputPath, makeSourcePath, sha256Digest)+import qualified Nix.Hash as Hash+import Nix.Http (FetchRetryPolicy (..), defaultDownloadAttempts)+import Nix.Logger (ActivityStart (..), Logger, plainLogger)+import Nix.Push (storePathBasename)+import qualified Nix.Realise as Realise+import Nix.Store (Store (..), closeStore, isValid, openStore)+import Nix.Store.Access (Sid, novaNixServiceSid, serviceSid, sidFromText, sidText)+import Nix.Store.DB (PathInfo (..), PathRegistration (..), RegistrationTime (..), StoreDB, Ultimate (..), closeStoreDB, openStoreDB, queryPathInfo, queryReferences, registerPath)+import qualified Nix.Store.ExecBit as ExecBit+import Nix.Store.Path (StoreDir (..), StorePath, defaultStoreDir, parseStorePath, storePathHashLen, storePathToFilePath, storePathToText)+import Nix.Store.Path.Internal (StorePath (..))+import qualified NovaCache.Base32 as Nix32+import qualified NovaCache.Base64 as B64+import qualified NovaCache.Hash as CHash+import qualified NovaCache.NAR as NAR+import qualified NovaCache.NarInfo as NarInfo+import qualified NovaCache.Signing as Signing+import qualified System.Directory as Dir+import System.Environment (lookupEnv)+import System.FilePath ((</>))+import System.IO.Error (mkIOError, resourceVanishedErrorType)+import qualified System.Info as SI+import System.Timeout (timeout)+import Test.Harness (TestResult (..), andThen, assertEqual, assertRight, findTestShell, forceRemoveIfExists, genContentAddress, genFixturePath, genSignatures, mkTestBuildDrv, runTest, runTestM, servedNar, sigTestKeyText, sigTestSecretKeyFile, signedTestNarInfo, symlinksAvailable)+import qualified Test.QuickCheck as QC++-- ---------------------------------------------------------------------------+-- Tests: the daemon's wire codec+-- ---------------------------------------------------------------------------++-- | The bytes a builder writes.+builtBytes :: BB.Builder -> BS.ByteString+builtBytes = BL.toStrict . BB.toLazyByteString++-- | A value decoded from all of its input, or why not: a decode that+-- leaves bytes over did not read what was written.+decodeWhole :: Wire.Decoder a -> BS.ByteString -> Either Text a+decodeWhole reader input = case Wire.runDecoder reader input of+  Left err -> Left (T.pack (show err))+  Right (value, rest)+    | BS.null rest -> Right value+    | otherwise -> Left (T.pack (show (BS.length rest)) <> " bytes left over")++-- | Upstream's refusal of bytes, as 'decodeWhole' reports it.+wireRefusal :: Text -> Either Text a+wireRefusal message = Left (T.pack (show (Wire.Malformed message)))++-- | A QuickCheck property as a test result.+codecProperty :: (QC.Testable prop) => prop -> IO TestResult+codecProperty prop = do+  result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} prop+  pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))++-- | What the store starts an activity for: a build or a check of a+-- derivation, or a substitution of a path from a cache.+genActivityStart :: QC.Gen ActivityStart+genActivityStart =+  QC.oneof+    [ Building <$> genFixturePath ".drv",+      Checking <$> genFixturePath ".drv",+      Substituting <$> genFixturePath "" <*> (T.pack <$> QC.arbitrary)+    ]++-- | Upstream's framing: numbers and their ranges, strings and their+-- padding, lists, and framed streams however their input arrives.+testDaemonWire :: IO [Bool]+testDaemonWire = do+  putStrLn "daemon/wire"+  sequence+    [ runTestM "a word reads back as itself" $+        codecProperty $ \n ->+          decodeWhole Wire.getWord64 (builtBytes (Wire.putNum (n :: Word64))) QC.=== Right n,+      runTestM "a number reads back up to its type's largest value and is refused above it, naming the type as upstream does" $+        codecProperty $+          QC.forAll genWord $ \n ->+            let encoded = builtBytes (Wire.putNum n)+                bounded :: (Integral a) => Text -> Word64 -> Either Text a+                bounded typeCode bound+                  | n <= bound = Right (fromIntegral n)+                  | otherwise = wireRefusal ("serialised integer " <> T.pack (show n) <> " is too large for type '" <> typeCode <> "'")+             in QC.conjoin+                  [ decodeWhole Wire.getWord8 encoded QC.=== bounded "h" 255,+                    decodeWhole Wire.getWord32 encoded QC.=== bounded "j" 4294967295,+                    decodeWhole Wire.getInt64 encoded QC.=== bounded "l" 9223372036854775807,+                    decodeWhole Wire.getBool encoded QC.=== fmap (/= (0 :: Word64)) (bounded "b" 1)+                  ],+      runTest "a negative number is written as its two's complement, which upstream's int64_t read refuses" $+        assertEqual "read" (wireRefusal "serialised integer 18446744073709551615 is too large for type 'l'") (decodeWhole Wire.getInt64 (builtBytes (Wire.putNum (-1 :: Int64)))),+      runTestM "a string reads back as itself, padded with zeros to a multiple of eight" $+        codecProperty $+          QC.forAll genWireBytes $ \bytes ->+            let encoded = builtBytes (Wire.putBytes bytes)+                padding = BS.drop (8 + BS.length bytes) encoded+             in QC.conjoin+                  [ decodeWhole Wire.getBytes encoded QC.=== Right bytes,+                    BS.length encoded `mod` 8 QC.=== 0,+                    QC.property (BS.length padding < 8 && BS.all (== 0) padding)+                  ],+      runTestM "a string with a byte of its padding set is refused" $+        codecProperty $+          QC.forAll (genWireBytes `QC.suchThat` ((/= 0) . (`mod` 8) . BS.length)) $ \bytes ->+            let encoded = builtBytes (Wire.putBytes bytes)+                paddingStart = 8 + BS.length bytes+             in QC.forAll ((,) <$> QC.choose (paddingStart, BS.length encoded - 1) <*> QC.choose (1, 255)) $ \(at, byte) ->+                  let corrupted = BS.take at encoded <> BS.singleton byte <> BS.drop (at + 1) encoded+                   in decodeWhole Wire.getBytes corrupted QC.=== wireRefusal "non-zero padding",+      runTestM "a string cut short asks for more input, and fails when the input ends" $+        codecProperty $+          QC.forAll genWireBytes $ \bytes ->+            let encoded = builtBytes (Wire.putBytes bytes)+             in QC.forAll (QC.choose (0, BS.length encoded - 1)) $ \cut ->+                  let prefix = BS.take cut encoded+                      waiting = case Wire.feedInput (Just prefix) (Wire.startDecoding Wire.getBytes) of+                        Wire.NeedInput _ -> True+                        _ -> False+                   in QC.conjoin [QC.property waiting, fmap fst (Wire.runDecoder Wire.getBytes prefix) QC.=== Left Wire.InputEnded],+      runTestM "a list reads back as itself" $+        codecProperty $+          QC.forAll (QC.listOf genWireBytes) $ \items ->+            decodeWhole (Wire.getList Wire.getBytes) (builtBytes (Wire.putList Wire.putBytes items)) QC.=== Right items,+      runTestM "a framed stream reads back as its bytes however its input is split, and stops at the chunk that ends it" $+        codecProperty $+          QC.forAll ((,) <$> QC.listOf genWireBytes <*> genWireBytes) $ \(chunks, after) ->+            let encoded = builtBytes (foldMap Wire.putFrame chunks <> Wire.putFrameEnd) <> after+             in QC.forAll (genSplit encoded) $ \pieces ->+                  readFrames pieces QC.=== Right (BS.concat chunks, after),+      runTest "a decode that needs no input keeps all it is given as what follows" $+        assertEqual "rest" (Right ((), "rest")) (Wire.runDecoder (pure ()) "rest"),+      runTest "a frame is its length and its bytes, unpadded, and an empty one ends the stream" $+        assertEqual+          "frames"+          ("\3\0\0\0\0\0\0\0abc\0\0\0\0\0\0\0\0" :: BS.ByteString)+          (builtBytes (Wire.putFrame "abc" <> Wire.putFrame "" <> Wire.putFrameEnd)),+      runTest "a refused read leaves the input after the bytes it read, where upstream's source is left" $+        case Wire.feedInput (Just (builtBytes (Wire.putNum (4294967296 :: Word64)) <> "rest")) (Wire.startDecoding Wire.getWord32) of+          Wire.DecodeFailed (Wire.Malformed _) rest -> assertEqual "rest" "rest" rest+          _ -> Fail "expected a refusal",+      runTest "a frame's length is read as upstream's unsigned int" $+        assertEqual "read" (wireRefusal "serialised integer 4294967296 is too large for type 'j'") (decodeWhole Wire.getFrame (builtBytes (Wire.putNum (4294967296 :: Word64))))+    ]+  where+    genWord = QC.oneof [QC.arbitrary, QC.choose (0, 300), QC.choose (4294967200, 4294967400), QC.choose (9223372036854775800, maxBound), QC.choose (0, 2)]++-- | Bytes of any length, short ones most.+genWireBytes :: QC.Gen BS.ByteString+genWireBytes = BS.pack <$> QC.resize 40 (QC.listOf QC.arbitrary)++-- | Bytes cut at random places into pieces, as reads from a socket might+-- deliver them.+genSplit :: BS.ByteString -> QC.Gen [BS.ByteString]+genSplit bytes = do+  cuts <- sort <$> QC.listOf (QC.choose (0, BS.length bytes))+  pure (zipWith slice (0 : cuts) (cuts ++ [BS.length bytes]))+  where+    slice from to = BS.take (to - from) (BS.drop from bytes)++-- | A framed stream read a chunk at a time from input that arrives in+-- pieces: the bytes it carries, and the input after its end.+readFrames :: [BS.ByteString] -> Either Wire.DecodeError (BS.ByteString, BS.ByteString)+readFrames = go [] (Wire.startDecoding Wire.getFrame)+  where+    go chunks decoding pieces = case decoding of+      Wire.NeedInput _ -> case pieces of+        piece : rest -> go chunks (Wire.feedInput (Just piece) decoding) rest+        [] -> go chunks (Wire.feedInput Nothing decoding) []+      Wire.DecodeFailed err _ -> Left err+      Wire.Decoded Nothing rest -> Right (BS.concat (reverse chunks), BS.concat (rest : pieces))+      Wire.Decoded (Just chunk) rest -> go (chunk : chunks) (Wire.feedInput (Just rest) (Wire.startDecoding Wire.getFrame)) pieces++-- | Every version the codec's gates distinguish, from upstream's oldest+-- tested to its newest, each with and without the feature that changes+-- how realisations travel.+gateVersions :: [Proto.Version]+gateVersions =+  [ Proto.Version (Proto.VersionNumber 1 minor) features+  | minor <- [10 .. Proto.vnMinor Proto.latestVersionNumber],+    features <- [Set.empty, Set.singleton Proto.featureRealisationWithPath]+  ]++-- | The version at a minor number, with no features.+protoVersion :: Word8 -> Proto.Version+protoVersion minor = Proto.Version (Proto.VersionNumber 1 minor) Set.empty++-- | The newest version, with the feature that carries realisations.+realisationVersion :: Proto.Version+realisationVersion = Proto.Version Proto.latestVersionNumber (Set.singleton Proto.featureRealisationWithPath)++-- | Whether a version's number is at least 1.@minor@.+versionAtLeast :: Proto.Version -> Word8 -> Bool+versionAtLeast version minor = Proto.versionNumber version >= Proto.VersionNumber 1 minor++-- | Whether a version carries realisations.+carriesRealisations :: Proto.Version -> Bool+carriesRealisations = Set.member Proto.featureRealisationWithPath . Proto.versionFeatures++-- | The law every serialiser keeps: at every version, what is written+-- reads back as what that version carries of it, and nothing is left over.+-- @carried@ is this suite's own account of each gate, so a gate dropped+-- from both the reader and the writer still fails it.+roundTripsAtEveryVersion ::+  (Eq a, Show a) =>+  (Proto.Version -> QC.Gen a) ->+  (Proto.Version -> a -> a) ->+  (Proto.Version -> Wire.Decoder a) ->+  (Proto.Version -> a -> BB.Builder) ->+  QC.Property+roundTripsAtEveryVersion gen carried reader writer =+  QC.conjoin+    [ QC.counterexample (show version) $+        QC.forAll (gen version) $ \value ->+          decodeWhole (reader version) (builtBytes (writer version value)) QC.=== Right (carried version value)+    | version <- gateVersions+    ]++-- | The store directory the codec's properties name paths under.+wireStoreDir :: StoreDir+wireStoreDir = defaultStoreDir++-- | A store path: a nix-base32 hash and a name, some of them derivations.+genWireStorePath :: QC.Gen StorePath+genWireStorePath = do+  hashPart <- QC.vectorOf storePathHashLen (QC.elements "0123456789abcdfghijklmnpqrsvwxyz")+  first <- QC.elements ['a' .. 'z']+  rest <- QC.resize 12 (QC.listOf (QC.elements (['a' .. 'z'] ++ ['A' .. 'Z'] ++ ['0' .. '9'] ++ "+-._?=")))+  suffix <- QC.elements ["", ".drv"]+  pure (StorePath (T.pack hashPart) (T.pack (first : rest) <> suffix))++genOutputName :: QC.Gen Proto.OutputName+genOutputName = Proto.OutputName . T.pack <$> ((:) <$> QC.elements ['a' .. 'z'] <*> QC.resize 6 (QC.listOf (QC.elements (['a' .. 'z'] ++ ['0' .. '9'] ++ "-_"))))++genOutputsSpec :: QC.Gen Proto.OutputsSpec+genOutputsSpec = QC.oneof [pure Proto.AllOutputs, QC.suchThatMap (Set.fromList <$> QC.resize 3 (QC.listOf1 genOutputName)) Proto.namedOutputs]++genDerivedPath :: QC.Gen Proto.DerivedPath+genDerivedPath = QC.oneof [Proto.DerivedOpaque <$> genWireStorePath, Proto.DerivedBuilt <$> genWireStorePath <*> genOutputsSpec]++genNarHash :: QC.Gen Proto.NarHash+genNarHash = QC.suchThatMap (BS.pack <$> QC.vectorOf 32 QC.arbitrary) Proto.narHashFromDigest++genPathInfo :: QC.Gen Proto.UnkeyedValidPathInfo+genPathInfo =+  Proto.UnkeyedValidPathInfo+    <$> QC.oneof [pure Nothing, Just <$> genWireStorePath]+    <*> genNarHash+    <*> (Set.fromList <$> QC.resize 3 (QC.listOf genWireStorePath))+    <*> QC.choose (0, maxBound)+    <*> QC.arbitrary+    <*> QC.arbitrary+    <*> genSignatures+    <*> QC.oneof [pure Nothing, Just <$> genContentAddress]++-- | What a version carries of a path's info: its trust fields from 1.16.+carriedPathInfo :: Proto.Version -> Proto.UnkeyedValidPathInfo -> Proto.UnkeyedValidPathInfo+carriedPathInfo version info+  | versionAtLeast version 16 = info+  | otherwise = info {Proto.upiUltimate = False, Proto.upiSignatures = Set.empty, Proto.upiContentAddress = Nothing}++genUnkeyedRealisation :: QC.Gen Proto.UnkeyedRealisation+genUnkeyedRealisation = Proto.UnkeyedRealisation <$> genWireStorePath <*> genSignatures++genBuildResult :: QC.Gen Proto.BuildResult+genBuildResult = do+  outcome <-+    QC.oneof+      [ Proto.Succeeded <$> (Proto.Success <$> QC.elements [minBound .. maxBound] <*> (Map.fromList <$> QC.resize 3 (QC.listOf ((,) <$> genOutputName <*> genUnkeyedRealisation)))),+        Proto.Failed <$> (Proto.Failure <$> QC.elements [minBound .. maxBound] <*> genWireBytes <*> QC.arbitrary)+      ]+  Proto.BuildResult outcome+    <$> QC.arbitrary+    <*> QC.choose (0, maxBound)+    <*> QC.choose (0, maxBound)+    <*> QC.oneof [pure Nothing, Just <$> QC.choose (0, maxBound)]+    <*> QC.oneof [pure Nothing, Just <$> QC.choose (0, maxBound)]++-- | What a version carries of a build result: how often and when it built+-- from 1.29, its CPU times from 1.37, and its outputs from 1.28, their+-- signatures only with the realisation feature.+carriedBuildResult :: Proto.Version -> Proto.BuildResult -> Proto.BuildResult+carriedBuildResult version result = withCpu (withTimes (result {Proto.brOutcome = outcome}))+  where+    withTimes r+      | versionAtLeast version 29 = r+      | otherwise = r {Proto.brTimesBuilt = 0, Proto.brStartTime = 0, Proto.brStopTime = 0}+    withCpu r+      | versionAtLeast version 37 = r+      | otherwise = r {Proto.brCpuUser = Nothing, Proto.brCpuSystem = Nothing}+    outcome = case Proto.brOutcome result of+      Proto.Succeeded (Proto.Success status outputs) -> Proto.Succeeded (Proto.Success status (carriedOutputs outputs))+      Proto.Failed (Proto.Failure status message nonDeterministic) ->+        Proto.Failed (Proto.Failure status message (nonDeterministic && versionAtLeast version 29))+    carriedOutputs outputs+      | carriesRealisations version = outputs+      | versionAtLeast version 28 = Map.map (\realisation -> realisation {Proto.urSignatures = Set.empty}) outputs+      | otherwise = Map.empty++-- | Whether a store path is a derivation's.+isDrvPath :: StorePath -> Bool+isDrvPath path = ".drv" `T.isSuffixOf` spName path++-- | What a version carries of a derived path: before 1.30 all of a path's+-- outputs are spelled as the bare path, which reads back as the path+-- itself unless it is a derivation's.+carriedDerivedPath :: Proto.Version -> Proto.DerivedPath -> Proto.DerivedPath+carriedDerivedPath version derived = case derived of+  Proto.DerivedBuilt path Proto.AllOutputs+    | not (versionAtLeast version 30) && not (isDrvPath path) -> Proto.DerivedOpaque path+  _ -> derived++-- | Whether a version can spell a derived path: before 1.30 a derivation+-- file itself cannot be asked for.+spellable :: Proto.Version -> Proto.DerivedPath -> Bool+spellable version derived = case derived of+  Proto.DerivedOpaque path -> versionAtLeast version 30 || not (isDrvPath path)+  Proto.DerivedBuilt _ _ -> True++genDaemonError :: QC.Gen Proto.DaemonError+genDaemonError =+  (Proto.DaemonError . Proto.Verbosity <$> QC.arbitrary)+    <*> genWireBytes+    <*> QC.resize 3 (QC.listOf genWireBytes)+    <*> QC.arbitrary++genFields :: QC.Gen [Proto.Field]+genFields = QC.resize 4 (QC.listOf (QC.oneof [Proto.FieldInt <$> QC.arbitrary, Proto.FieldString <$> genWireBytes]))++genStderrMessage :: QC.Gen Proto.StderrMessage+genStderrMessage =+  QC.oneof+    [ Proto.StderrNext <$> genWireBytes,+      Proto.StderrRead <$> QC.arbitrary,+      Proto.StderrWrite <$> genWireBytes,+      pure Proto.StderrLast,+      Proto.StderrError <$> genDaemonError,+      Proto.StderrStartActivity+        <$> ( (Proto.Activity . Proto.ActivityId <$> QC.arbitrary)+                <*> (Proto.Verbosity <$> QC.arbitrary)+                <*> (Proto.ActivityType <$> QC.arbitrary)+                <*> genWireBytes+                <*> genFields+                <*> (Proto.ActivityId <$> QC.arbitrary)+            ),+      Proto.StderrStopActivity . Proto.ActivityId <$> QC.arbitrary,+      (Proto.StderrResult . Proto.ActivityId <$> QC.arbitrary) <*> (Proto.ResultType <$> QC.arbitrary) <*> genFields+    ]++-- | What a version carries of a message: from 1.26 an error goes as a+-- record without its exit status, which reads back as 1; before, as its+-- message and exit status, which read back at the error level with no+-- traces.+carriedStderrMessage :: Proto.Version -> Proto.StderrMessage -> Proto.StderrMessage+carriedStderrMessage version message = case message of+  Proto.StderrError err+    | versionAtLeast version 26 -> Proto.StderrError err {Proto.errExitStatus = 1}+    | otherwise -> Proto.StderrError err {Proto.errLevel = Proto.errorVerbosity, Proto.errTraces = []}+  _ -> message++-- | Every version a request's form changes at, with each combination of+-- the two features that change what one carries.+requestVersions :: [Proto.Version]+requestVersions =+  [ Proto.Version (Proto.VersionNumber 1 minor) (Set.fromList features)+  | minor <- [10 .. Proto.vnMinor Proto.latestVersionNumber],+    features <- [[], [Proto.featureRealisationWithPath], [Proto.featureDeleteDeadSpecificReferrers], [Proto.featureRealisationWithPath, Proto.featureDeleteDeadSpecificReferrers]]+  ]++-- | A request a client may send at a version, its derived paths ones+-- the version can spell.+genRequest :: Proto.Version -> QC.Gen Ops.Request+genRequest version =+  QC.oneof+    [ Ops.SetOptions <$> genClientSettings,+      Ops.IsValidPath <$> genWireStorePath,+      Ops.QueryValidPaths <$> genPathSet <*> QC.elements [Ops.NoSubstitute, Ops.Substitute],+      Ops.QuerySubstitutablePaths <$> genPathSet,+      Ops.QueryReferrers <$> genWireStorePath,+      Ops.QueryValidDerivers <$> genWireStorePath,+      Ops.QueryDerivationOutputMap <$> genWireStorePath,+      pure Ops.QueryAllValidPaths,+      Ops.QueryPathInfo <$> genWireStorePath,+      Ops.QueryMissing <$> targets,+      Ops.AddToStore <$> (Ops.AddToStoreRequest <$> genWireBytes <*> genWireBytes <*> genPathSet <*> repair),+      Ops.AddToStoreNar <$> (Proto.ValidPathInfo <$> genWireStorePath <*> genPathInfo) <*> repair <*> QC.elements [Ops.CheckSigs, Ops.NoCheckSigs],+      Ops.AddMultipleToStore <$> repair <*> QC.elements [Ops.CheckSigs, Ops.NoCheckSigs],+      Ops.BuildPaths <$> targets <*> mode,+      Ops.BuildPathsWithResults <$> targets <*> mode,+      Ops.EnsurePath <$> genWireStorePath,+      Ops.AddTempRoot <$> genWireStorePath,+      Ops.AddIndirectRoot . canonicalLink <$> QC.resize 3 (QC.listOf1 (BS8.pack <$> QC.listOf1 (QC.elements (['a' .. 'z'] ++ "-_")))),+      pure Ops.FindRoots,+      Ops.CollectGarbage+        <$> ( Ops.GCRequest+                <$> QC.elements [Proto.ReturnLive, Proto.ReturnDead, Proto.DeleteDead, Proto.DeleteSpecific]+                <*> QC.oneof [pure Proto.WholeStore, Proto.SpecificPaths <$> genPathSet <*> QC.arbitrary]+                <*> QC.arbitrary+            )+        <*> QC.elements [Ops.KeepLiveness, Ops.IgnoreLiveness],+      pure Ops.OptimiseStore,+      Ops.VerifyStore <$> QC.elements [Ops.SkipContents, Ops.CheckContents] <*> repair,+      Ops.AddSignatures <$> genWireStorePath <*> genSignatures,+      Ops.NarFromPath <$> genWireStorePath+    ]+  where+    targets = QC.resize 3 (QC.listOf (genDerivedPath `QC.suchThat` spellable version))+    repair = QC.elements [Ops.NoRepair, Ops.Repair]+    mode = QC.elements [Proto.BuildNormal, Proto.BuildRepair, Proto.BuildCheck]++genPathSet :: QC.Gen (Set.Set StorePath)+genPathSet = Set.fromList <$> QC.resize 3 (QC.listOf genWireStorePath)++-- | The absolute link in canonical form, as the host spells it, whose+-- components are given: one that a daemon reads back as it was sent.+canonicalLink :: [BS.ByteString] -> BS.ByteString+canonicalLink components+  | SI.os == "mingw32" = "C:\\" <> BS8.intercalate "\\" components+  | otherwise = "/" <> BS8.intercalate "/" components++-- | What a version carries of a request: below 1.27 no substitute flag,+-- derived paths as the version spells them, and without the+-- delete-specific feature a collection's paths as a bare set, so the+-- whole store for a specific deletion reads back as no paths.+carriedRequest :: Proto.Version -> Ops.Request -> Ops.Request+carriedRequest version = \case+  Ops.QueryValidPaths paths _ | not (versionAtLeast version 27) -> Ops.QueryValidPaths paths Ops.NoSubstitute+  Ops.QueryMissing targets -> Ops.QueryMissing (map (carriedDerivedPath version) targets)+  Ops.BuildPaths targets mode -> Ops.BuildPaths (map (carriedDerivedPath version) targets) mode+  Ops.BuildPathsWithResults targets mode -> Ops.BuildPathsWithResults (map (carriedDerivedPath version) targets) mode+  Ops.CollectGarbage (Ops.GCRequest action paths maxFreed) liveness+    | not (Set.member Proto.featureDeleteDeadSpecificReferrers (Proto.versionFeatures version)) ->+        let bare = case paths of+              Proto.WholeStore | action == Proto.DeleteSpecific -> Proto.SpecificPaths Set.empty False+              _ -> paths+         in Ops.CollectGarbage (Ops.GCRequest action bare maxFreed) liveness+  request -> request++-- | Upstream's refusal of a request a version cannot carry, or 'Nothing'+-- where it can carry it.+refusalFor :: Proto.Version -> Ops.Request -> Maybe Text+refusalFor version = \case+  Ops.AddToStore _ | not (versionAtLeast version 25) -> Just "AddToStore before protocol 1.25 is not supported by this daemon"+  Ops.AddToStoreNar {} | not (versionAtLeast version 23) -> Just "AddToStoreNar before protocol 1.23 is not supported by this daemon"+  Ops.CollectGarbage (Ops.GCRequest action (Proto.SpecificPaths _ referrers) _) _+    | not (Set.member Proto.featureDeleteDeadSpecificReferrers (Proto.versionFeatures version)) ->+        if action /= Proto.DeleteSpecific+          then Just "Your daemon version is too old to support garbage collecting a specific set of paths"+          else if referrers then Just "Your daemon version is too old to support deleting referrers." else Nothing+  _ -> Nothing++-- | A request as a daemon reads one: its code, then what that names.+requestReader :: Proto.Version -> Wire.Decoder Ops.Request+requestReader version = Wire.getWord32 >>= \code -> fromMaybe (Wire.malformed ("no request has code " <> T.pack (show code))) (Ops.getRequest wireStoreDir version code)++-- | A client's settings: its verbosity at most upstream's loudest, as a+-- daemon reads it.+genClientSettings :: QC.Gen Ops.ClientSettings+genClientSettings =+  Ops.ClientSettings+    <$> QC.arbitrary+    <*> QC.arbitrary+    <*> QC.arbitrary+    <*> (Proto.Verbosity <$> QC.choose (0, 7))+    <*> QC.arbitrary+    <*> QC.arbitrary+    <*> QC.arbitrary+    <*> QC.arbitrary+    <*> QC.arbitrary+    <*> (Map.fromList <$> QC.resize 3 (QC.listOf ((,) <$> genWireBytes <*> genWireBytes)))++genMissing :: QC.Gen Proto.Missing+genMissing = Proto.Missing <$> genPathSet <*> genPathSet <*> genPathSet <*> QC.arbitrary <*> QC.arbitrary++genGCResult :: QC.Gen Proto.GCResult+genGCResult = Proto.GCResult . Set.fromList <$> QC.resize 3 (QC.listOf genWireBytes) <*> QC.arbitrary++genOutputMap :: QC.Gen (Map.Map Proto.OutputName (Maybe StorePath))+genOutputMap = Map.fromList <$> QC.resize 3 (QC.listOf ((,) <$> genOutputName <*> QC.oneof [pure Nothing, Just <$> genWireStorePath]))++-- | Roots, each kept by at least one link, as a listing gives them.+genRoots :: QC.Gen (Map.Map StorePath (Set.Set BS.ByteString))+genRoots = Map.fromList <$> QC.resize 3 (QC.listOf ((,) <$> genWireStorePath <*> (Set.fromList <$> QC.resize 2 (QC.listOf1 genWireBytes))))++-- | Every value the protocol carries, written and read back at every+-- version gate, and the refusals upstream makes of bytes it does not+-- accept.+testDaemonProtocol :: IO [Bool]+testDaemonProtocol = do+  putStrLn "daemon/protocol"+  sequence+    [ runTestM "a version number reads back as itself" $+        codecProperty $ \major minor ->+          let number = Proto.VersionNumber major minor+           in decodeWhole Proto.getVersionNumber (builtBytes (Proto.putVersionNumber number)) QC.=== Right number,+      runTest "a version number is the major number in the second byte and the minor in the first" $+        assertEqual "1.38" ("\x26\x01\0\0\0\0\0\0" :: BS.ByteString) (builtBytes (Proto.putVersionNumber Proto.latestVersionNumber)),+      runTestM "a feature list reads back as its set" $+        codecProperty $+          QC.forAll (QC.listOf genWireBytes) $ \names ->+            let features = Set.fromList (map Proto.Feature names)+             in decodeWhole Proto.getFeatures (builtBytes (Wire.putList Wire.putBytes names)) QC.=== Right features+                  QC..&&. decodeWhole Proto.getFeatures (builtBytes (Proto.putFeatures features)) QC.=== Right features,+      runTestM "what a daemon tells its client after the handshake reads back as far as each version carries it"+        $ codecProperty+        $ roundTripsAtEveryVersion+          (const ((Proto.HandshakeInfo . Just <$> genWireBytes) <*> QC.elements [Nothing, Just Proto.Trusted, Just Proto.NotTrusted]))+          ( \version (Proto.HandshakeInfo daemonVersion trust) ->+              Proto.HandshakeInfo (if versionAtLeast version 33 then daemonVersion else Nothing) (if versionAtLeast version 35 then trust else Nothing)+          )+          Proto.getHandshakeInfo+          (\version (Proto.HandshakeInfo daemonVersion trust) -> Proto.putHandshakeInfo version (fromMaybe BS.empty daemonVersion) trust),+      runTestM "a client's obsolete fields are read whole at every version"+        $ codecProperty+        $ QC.conjoin [decodeWhole (Proto.getClientObsoleteFields version) (builtBytes (Proto.putClientObsoleteFields version)) QC.=== Right () | version <- gateVersions],+      runTest "a client's CPU affinity, when set, is followed by a number" $+        assertEqual "read" (Right ()) (decodeWhole (Proto.getClientObsoleteFields (protoVersion 14)) (builtBytes (Wire.putNum (1 :: Word64) <> Wire.putNum (7 :: Word64) <> Wire.putBool False))),+      runTest "a handshake that opens with another word is refused" $+        assertEqual "client" (wireRefusal "protocol mismatch") (decodeWhole Proto.getClientMagic (builtBytes Proto.putServerMagic))+          `andThen` assertEqual "server" (wireRefusal "nix-daemon protocol mismatch from") (decodeWhole Proto.getServerMagic (builtBytes Proto.putClientMagic)),+      runTestM "a store path, a store path or none, and a set of them read back as themselves" $+        codecProperty $+          QC.forAll ((,,) <$> genWireStorePath <*> QC.oneof [pure Nothing, Just <$> genWireStorePath] <*> (Set.fromList <$> QC.listOf genWireStorePath)) $ \(path, optional, paths) ->+            QC.conjoin+              [ decodeWhole (Proto.getStorePath wireStoreDir) (builtBytes (Proto.putStorePath wireStoreDir path)) QC.=== Right path,+                decodeWhole (Proto.getStorePath (StoreDir "/tmp/nova-store")) (builtBytes (Proto.putStorePath (StoreDir "/tmp/nova-store") path)) QC.=== Right path,+                decodeWhole (Proto.getOptionalStorePath wireStoreDir) (builtBytes (Proto.putOptionalStorePath wireStoreDir optional)) QC.=== Right optional,+                decodeWhole (Proto.getStorePathSet wireStoreDir) (builtBytes (Proto.putStorePathSet wireStoreDir paths)) QC.=== Right paths+              ],+      runTestM "a store path spelled with empty, . and .. components reads as the path it names, as upstream's canonPath makes it" $+        codecProperty $+          QC.forAll ((,) <$> genWireStorePath <*> QC.elements ["/nix/store//", "/nix/./store/", "/nix/x/../store/", "//nix/store/", "/../nix/store/"]) $ \(path, prefix) ->+            readStorePath (prefix <> storePathBasename path <> "/") QC.=== Right path,+      runTest "a store path is refused in upstream's words" $+        assertEqual "empty" (wireRefusal "empty path is not a valid store path") (readStorePath "")+          `andThen` assertEqual "relative" (wireRefusal "not an absolute path: \"nix/store/x\"") (readStorePath "nix/store/x")+          `andThen` assertEqual "the store itself" (wireRefusal "path \"/nix/store\" is not in the Nix store") (readStorePath "/nix/store/.")+          `andThen` assertEqual "elsewhere" (wireRefusal "path \"/tmp/g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-foo\" is not in the Nix store") (readStorePath "/tmp/g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-foo")+          `andThen` assertEqual "beneath one" (wireRefusal "path \"/nix/store/g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-foo/bin\" is not in the Nix store") (readStorePath "/nix/store/g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-foo/bin")+          `andThen` assertEqual "short" (wireRefusal "'g1w7-foo' is too short to be a valid store path") (readStorePath "/nix/store/g1w7-foo")+          `andThen` assertEqual "no dash" (wireRefusal "'g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q_foo' can't name a store path because the hash part is not followed by a '-'") (readStorePath "/nix/store/g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q_foo")+          `andThen` assertEqual "hash" (wireRefusal "store path 'e1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-foo' contains illegal base-32 character 'e'") (readStorePath "/nix/store/e1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-foo")+          `andThen` assertEqual "name" (wireRefusal "path 'g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-f$o' is not a valid store path: name 'f$o' contains illegal character '$'") (readStorePath "/nix/store/g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-f$o"),+      runTestM "a signature set, a NAR hash and a content address read back as themselves" $+        codecProperty $+          QC.forAll ((,,) <$> genSignatures <*> genNarHash <*> QC.oneof [pure Nothing, Just <$> genContentAddress]) $ \(sigs, narHash, ca) ->+            QC.conjoin+              [ decodeWhole Proto.getSignatureSet (builtBytes (Proto.putSignatureSet sigs)) QC.=== Right sigs,+                decodeWhole Proto.getNarHash (builtBytes (Proto.putNarHash narHash)) QC.=== Right narHash,+                decodeWhole Proto.getOptionalContentAddress (builtBytes (Proto.putOptionalContentAddress ca)) QC.=== Right ca+              ],+      runTest "a NAR hash reads in any spelling of a SHA-256 hash" $+        let digest = sha256Digest "nar"+         in assertEqual "nix32" (Proto.narHashFromDigest digest) (either (const Nothing) Just (decodeWhole Proto.getNarHash (builtBytes (Wire.putBytes (TE.encodeUtf8 ("sha256:" <> Nix32.encode digest))))))+              `andThen` assertEqual "other algorithm" (wireRefusal "hash 'sha1:0000000000000000000000000000000000000000' should have type 'sha256'") (decodeWhole Proto.getNarHash (builtBytes (Wire.putBytes "sha1:0000000000000000000000000000000000000000"))),+      runTest "a signature is refused in upstream's words" $+        let readSignatures spelled = decodeWhole Proto.getSignatureSet (builtBytes (Wire.putList Wire.putBytes [spelled]))+         in assertEqual "no colon" (wireRefusal "signature is corrupt") (readSignatures "key")+              `andThen` assertEqual "no name" (wireRefusal "signature is corrupt") (readSignatures ":AAAA")+              `andThen` assertEqual "no bytes" (wireRefusal "signature is corrupt") (readSignatures "key:")+              `andThen` assertEqual "not base64" (wireRefusal "invalid character in Base64 string: '@'") (readSignatures "key:AA@A"),+      runTest "a content address is refused in upstream's words" $+        let readCa spelled = decodeWhole Proto.getContentAddress (builtBytes (Wire.putBytes spelled))+         in assertEqual "no prefix" (wireRefusal "not a content address because it is not in the form '<prefix>:<rest>': sha256") (readCa "sha256")+              `andThen` assertEqual "prefix" (wireRefusal "content address prefix 'flat' is unrecognized. Recogonized prefixes are 'text' or 'fixed'") (readCa "flat:sha256:x")+              `andThen` assertEqual "no hash" (wireRefusal "content address hash must be in form '<algo>:<hash>', but found: text:sha256") (readCa "text:sha256")+              `andThen` assertEqual "git" (wireRefusal "experimental Nix feature 'git-hashing' is disabled; add '--extra-experimental-features git-hashing' to enable it") (readCa "fixed:git:sha1:x")+              `andThen` assertEqual "algorithm" (wireRefusal "unknown hash algorithm 'sha3', expect 'md5', 'sha1', 'sha256', or 'sha512'") (readCa "fixed:r:sha3:x"),+      runTest "an upload's method and algorithm are read as upstream reads them, a refusal quoting the colon they are read with" $+        assertEqual "text" (Right (Proto.TextMethod, "sha256")) (Proto.parseContentAddressMethod "text:sha256")+          `andThen` assertEqual "recursive" (Right (Proto.FixedMethod NarIngestion, "sha256")) (Proto.parseContentAddressMethod "fixed:r:sha256")+          `andThen` assertEqual "flat, what follows ignored" (Right (Proto.FixedMethod FlatIngestion, "md5")) (Proto.parseContentAddressMethod "fixed:md5:ignored")+          `andThen` assertEqual "git" (Left "experimental Nix feature 'git-hashing' is disabled; add '--extra-experimental-features git-hashing' to enable it") (Proto.parseContentAddressMethod "fixed:git:sha1")+          `andThen` assertEqual "no algorithm" (Left "content address hash must be in form '<algo>:<hash>', but found: text:") (Proto.parseContentAddressMethod "text")+          `andThen` assertEqual "algorithm" (Left "unknown hash algorithm 'sha3', expect 'md5', 'sha1', 'sha256', or 'sha512'") (Proto.parseContentAddressMethod "text:sha3")+          `andThen` assertEqual "prefix" (Left "content address prefix 'bogus' is unrecognized. Recogonized prefixes are 'text' or 'fixed'") (Proto.parseContentAddressMethod "bogus:sha256"),+      runTest "a content address's base64 digest ends at its padding, whatever bytes follow it, as upstream reads it" $+        assertEqual+          "read"+          (maybe (Left "no expected value") Right (Proto.contentAddressFromParts (Proto.FixedMethod FlatIngestion) "md5" (BS.replicate 16 0)))+          (decodeWhole Proto.getContentAddress (builtBytes (Wire.putBytes ("fixed:md5:" <> BS8.replicate 22 'A' <> "=\xff")))),+      runTestM "a path's info reads back as far as each version carries it"+        $ codecProperty+        $ roundTripsAtEveryVersion+          (const genPathInfo)+          carriedPathInfo+          (Proto.getUnkeyedValidPathInfo wireStoreDir)+          (Proto.putUnkeyedValidPathInfo wireStoreDir),+      runTestM "a path and its info read back as far as each version carries it"+        $ codecProperty+        $ roundTripsAtEveryVersion+          (const (Proto.ValidPathInfo <$> genWireStorePath <*> genPathInfo))+          (\version (Proto.ValidPathInfo path info) -> Proto.ValidPathInfo path (carriedPathInfo version info))+          (Proto.getValidPathInfo wireStoreDir)+          (Proto.putValidPathInfo wireStoreDir),+      runTestM "a derived path reads back as far as each version spells it, and one it cannot spell is refused"+        $ codecProperty+        $ QC.conjoin+          [ QC.counterexample (show version) $+              QC.forAll genDerivedPath $ \derived ->+                case Proto.putDerivedPath wireStoreDir version derived of+                  Right builder ->+                    QC.counterexample "written" (QC.property (spellable version derived))+                      QC..&&. decodeWhole (Proto.getDerivedPath wireStoreDir version) (builtBytes builder) QC.=== Right (carriedDerivedPath version derived)+                  Left _ -> QC.counterexample "refused" (QC.property (not (spellable version derived)))+          | version <- gateVersions+          ],+      runTest "a derivation file is refused before 1.30 in upstream's words" $+        assertEqual+          "refusal"+          (Left "trying to request '/nix/store/g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-bar.drv', but daemon protocol 1.29 is too old (< 1.29) to request a derivation file")+          (builtBytes <$> Proto.putDerivedPath wireStoreDir (protoVersion 29) (Proto.DerivedOpaque (g1w7 "bar.drv"))),+      runTest "a derived path is refused in upstream's words" $+        let readDerived minor spelled = decodeWhole (Proto.getDerivedPath wireStoreDir (protoVersion minor)) (builtBytes (Wire.putBytes spelled))+            bar = "/nix/store/g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-bar.drv"+         in assertEqual+              "dynamic"+              (wireRefusal "experimental Nix feature 'dynamic-derivations' is disabled (building output 'out' of 'g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-bar.drv'); add '--extra-experimental-features dynamic-derivations' to enable it")+              (readDerived 30 (bar <> "!out!lib"))+              `andThen` assertEqual "no names" (wireRefusal "name must not be empty") (readDerived 30 (bar <> "!"))+              `andThen` assertEqual "empty name" (wireRefusal "name must not be empty") (readDerived 30 (bar <> "!out,,lib"))+              `andThen` assertEqual "bad name" (wireRefusal "name 'a$' contains illegal character '$'") (readDerived 30 (bar <> "!z$,a$"))+              `andThen` assertEqual "unchecked before 1.30" (Right (Proto.DerivedBuilt (g1w7 "bar.drv") (fromMaybe Proto.AllOutputs (Proto.namedOutputs (Set.fromList [Proto.OutputName "a$", Proto.OutputName "out!x"]))))) (readDerived 29 (bar <> "!a$,,out!x"))+              `andThen` assertEqual "a bare derivation before 1.30" (Right (Proto.DerivedBuilt (g1w7 "bar.drv") Proto.AllOutputs)) (readDerived 29 (bar <> "!,")),+      runTestM "realisations read back with the feature that carries them, and are refused without it"+        $ codecProperty+        $ QC.conjoin+          [ QC.counterexample (show version) $+              QC.forAll ((,,) <$> genUnkeyedRealisation <*> (Proto.DrvOutput <$> genWireStorePath <*> genOutputName) <*> QC.oneof [pure Nothing, Just <$> genUnkeyedRealisation]) $ \(unkeyed, output, optional) ->+                let readBack reader = fmap (decodeWhole (reader wireStoreDir version) . builtBytes)+                    buildTrace = "the daemon is missing the 'realisation-with-path-not-hash' protocol feature, needed to understand build trace"+                    contentAddressing = "the daemon is missing the 'realisation-with-path-not-hash' protocol feature, needed to support content-addressing derivations"+                    pathBytes path = Wire.putBytes (TE.encodeUtf8 (storePathToText wireStoreDir path))+                 in if carriesRealisations version+                      then+                        QC.conjoin+                          [ readBack Proto.getUnkeyedRealisation (Proto.putUnkeyedRealisation wireStoreDir version unkeyed) QC.=== Right (Right unkeyed),+                            readBack Proto.getDrvOutput (Proto.putDrvOutput wireStoreDir version output) QC.=== Right (Right output),+                            readBack Proto.getRealisation (Proto.putRealisation wireStoreDir version (Proto.Realisation output unkeyed)) QC.=== Right (Right (Proto.Realisation output unkeyed)),+                            readBack Proto.getOptionalUnkeyedRealisation (Proto.putOptionalUnkeyedRealisation wireStoreDir version optional) QC.=== Right (Right optional)+                          ]+                      else+                        QC.conjoin+                          [ fmap builtBytes (Proto.putUnkeyedRealisation wireStoreDir version unkeyed) QC.=== Left buildTrace,+                            fmap builtBytes (Proto.putDrvOutput wireStoreDir version output) QC.=== Left contentAddressing,+                            fmap builtBytes (Proto.putRealisation wireStoreDir version (Proto.Realisation output unkeyed)) QC.=== Left contentAddressing,+                            fmap builtBytes (Proto.putOptionalUnkeyedRealisation wireStoreDir version (Just unkeyed)) QC.=== Left buildTrace,+                            decodeWhole (Proto.getUnkeyedRealisation wireStoreDir version) (builtBytes (pathBytes (Proto.urOutPath unkeyed) <> Wire.putList Wire.putBytes [])) QC.=== wireRefusal buildTrace,+                            decodeWhole (Proto.getDrvOutput wireStoreDir version) (builtBytes (pathBytes (Proto.doDrvPath output) <> Proto.putOutputName (Proto.doOutputName output))) QC.=== wireRefusal contentAddressing,+                            readBack Proto.getOptionalUnkeyedRealisation (Proto.putOptionalUnkeyedRealisation wireStoreDir version Nothing) QC.=== Right (Right Nothing)+                          ]+          | version <- gateVersions+          ],+      runTestM "a build result reads back as far as each version carries it"+        $ codecProperty+        $ roundTripsAtEveryVersion (const genBuildResult) carriedBuildResult (Proto.getBuildResult wireStoreDir) (Proto.putBuildResult wireStoreDir),+      runTestM "a keyed build result reads back as far as each version carries it"+        $ codecProperty+        $ QC.conjoin+          [ QC.counterexample (show version) $+              QC.forAll ((,) <$> (genDerivedPath `QC.suchThat` spellable version) <*> genBuildResult) $ \(derived, result) ->+                fmap (decodeWhole (Proto.getKeyedBuildResult wireStoreDir version) . builtBytes) (Proto.putKeyedBuildResult wireStoreDir version (Proto.KeyedBuildResult derived result))+                  QC.=== Right (Right (Proto.KeyedBuildResult (carriedDerivedPath version derived) (carriedBuildResult version result)))+          | version <- gateVersions+          ],+      runTest "a build's outputs in the older JSON form are refused in upstream's words" $+        let readOutputs pairs = decodeWhole (Proto.getBuildResult wireStoreDir (protoVersion 28)) (builtBytes (Wire.putNum (0 :: Word64) <> Wire.putBytes "" <> Wire.putList (\(k, v) -> Wire.putBytes k <> Wire.putBytes v) pairs))+         in assertEqual "id" (wireRefusal "Invalid derivation output id out") (readOutputs [("out", "{}")])+              `andThen` assertEqual "object" (wireRefusal "Expected JSON value to be of type 'object' but it is of type 'array': []") (readOutputs [("x!out", "[]")])+              `andThen` assertEqual "key" (wireRefusal "Expected JSON object to contain key 'outPath' but it doesn't: {\"id\":\"x\"}") (readOutputs [("x!out", "{\"id\":\"x\"}")])+              `andThen` assertEqual "string" (wireRefusal "Expected JSON value to be of type 'string' but it is of type 'number': 5") (readOutputs [("x!out", "{\"outPath\":5}")]),+      runTest "a build mode, a status, a trust flag, a collection's action and paths, and a tag are each refused out of range" $+        let readByte reader byte = decodeWhole reader (builtBytes (Wire.putNum (byte :: Word64)))+         in assertEqual "mode" (wireRefusal "Invalid build mode") (readByte Proto.getBuildMode 3)+              `andThen` assertEqual "status" (wireRefusal "Invalid BuildResult status 15 from remote") (void (decodeWhole (Proto.getBuildResult wireStoreDir (protoVersion 27)) (builtBytes (Wire.putNum (15 :: Word64) <> Wire.putBytes ""))))+              `andThen` assertEqual "trust" (wireRefusal "Invalid trusted status from remote") (readByte Proto.getTrust 3)+              `andThen` assertEqual "action" (wireRefusal "Invalid GC action") (readByte Proto.getGCAction 4)+              `andThen` assertEqual "paths" (wireRefusal "Invalid whole store indicator from remote") (readByte (Proto.getGCPaths wireStoreDir) 2)+              `andThen` assertEqual "realisation" (wireRefusal "Invalid optional build trace from remote") (readByte (Proto.getOptionalUnkeyedRealisation wireStoreDir realisationVersion) 2)+              `andThen` assertEqual+                "duration"+                (wireRefusal "Invalid optional tag from remote")+                (void (decodeWhole (Proto.getBuildResult wireStoreDir (protoVersion 37)) (builtBytes (Wire.putNum (0 :: Word64) <> Wire.putBytes "" <> foldMap Wire.putNum [0, 0, 0, 0 :: Word64] <> Wire.putNum (2 :: Word64))))),+      runTestM "a build mode, a trust flag, a collection's action and its paths read back as themselves"+        $ codecProperty+        $ QC.forAll+          ( (,,,)+              <$> QC.elements [Proto.BuildNormal, Proto.BuildRepair, Proto.BuildCheck]+              <*> QC.elements [Nothing, Just Proto.Trusted, Just Proto.NotTrusted]+              <*> QC.elements [Proto.ReturnLive, Proto.ReturnDead, Proto.DeleteDead, Proto.DeleteSpecific]+              <*> QC.oneof [pure Proto.WholeStore, (Proto.SpecificPaths . Set.fromList <$> QC.listOf genWireStorePath) <*> QC.arbitrary]+          )+        $ \(mode, trust, action, paths) ->+          QC.conjoin+            [ decodeWhole Proto.getBuildMode (builtBytes (Proto.putBuildMode mode)) QC.=== Right mode,+              decodeWhole Proto.getTrust (builtBytes (Proto.putTrust trust)) QC.=== Right trust,+              decodeWhole Proto.getGCAction (builtBytes (Proto.putGCAction action)) QC.=== Right action,+              decodeWhole (Proto.getGCPaths wireStoreDir) (builtBytes (Proto.putGCPaths wireStoreDir paths)) QC.=== Right paths+            ],+      runTestM "a request reads back, at every version and with every feature, as what the version carries of it, and one it cannot carry is refused in upstream's words" $+        codecProperty $+          QC.forAll (QC.elements requestVersions) $+            \version -> QC.forAll (genRequest version) $ \request ->+              QC.counterexample (show version) $ case Ops.putRequest wireStoreDir version request of+                Right bytes -> decodeWhole (requestReader version) (builtBytes bytes) QC.=== Right (carriedRequest version request)+                Left refusal -> refusalFor version request QC.=== Just refusal,+      -- Only a Windows host spells a path the Windows way, so the rule is+      -- held there alone.+      runTestM "on Windows an indirect root's link is kept when absolute, collapsed over the host's separators and roots, and refused when no drive or share makes it absolute" $+        if SI.os /= "mingw32"+          then Pass <$ putStrLn "  SKIP  a Windows link is read by a Windows host alone"+          else+            let rootedLink link = decodeWhole (requestReader (protoVersion 38)) (builtBytes (Wire.putNum (12 :: Word64) <> Wire.putBytes link))+                recorded = Right . Ops.AddIndirectRoot+                refused link = wireRefusal ("the link '" <> TE.decodeUtf8Lenient link <> "' is not an absolute Windows path: it needs a drive and a backslash, as in C:\\result, or a UNC share")+             in pure $+                  assertEqual "absolute and canonical" (recorded "C:\\home\\user\\result") (rootedLink "C:\\home\\user\\result")+                    `andThen` assertEqual "dots" (recorded "C:\\home\\user\\result2") (rootedLink "C:\\home\\user\\..\\user\\.\\result2\\")+                    `andThen` assertEqual "a drive's root" (recorded "C:\\result") (rootedLink "C:\\home\\..\\..\\result")+                    `andThen` assertEqual "a share" (recorded "\\\\server\\share\\result") (rootedLink "\\\\server\\share\\dir\\..\\result")+                    `andThen` assertEqual "relative" (refused "home\\user\\result") (rootedLink "home\\user\\result")+                    `andThen` assertEqual "a drive's relative directory" (refused "C:result") (rootedLink "C:result")+                    `andThen` assertEqual "rooted without a drive" (refused "\\home\\user\\result") (rootedLink "\\home\\user\\result")+                    `andThen` assertEqual "POSIX" (refused "/home/user/result") (rootedLink "/home/user/result")+                    `andThen` assertEqual "no UTF-8 reading" (refused "C:\\\xff") (rootedLink "C:\\\xff"),+      runTestM "a client's settings read back as themselves" $+        codecProperty $+          QC.forAll genClientSettings $ \settings ->+            decodeWhole Ops.getClientSettings (builtBytes (Ops.putClientSettings settings)) QC.=== Right settings,+      runTestM "what realising paths would take, a collection's result, a derivation's outputs and the roots read back as themselves" $+        codecProperty $+          QC.forAll ((,,,) <$> genMissing <*> genGCResult <*> genOutputMap <*> genRoots) $ \(missing, collected, outputs, roots) ->+            QC.conjoin+              [ decodeWhole (Proto.getMissing wireStoreDir) (builtBytes (Proto.putMissing wireStoreDir missing)) QC.=== Right missing,+                decodeWhole Proto.getGCResult (builtBytes (Proto.putGCResult collected)) QC.=== Right collected,+                decodeWhole (Proto.getOutputMap wireStoreDir) (builtBytes (Proto.putOutputMap wireStoreDir outputs)) QC.=== Right outputs,+                decodeWhole (Proto.getRoots wireStoreDir) (builtBytes (Proto.putRoots wireStoreDir roots)) QC.=== Right roots+              ],+      runTestM "build results with the paths they answer read back as far as each version carries them"+        $ codecProperty+        $ QC.conjoin+          [ QC.counterexample (show version) $+              QC.forAll (QC.resize 3 (QC.listOf (Proto.KeyedBuildResult <$> (genDerivedPath `QC.suchThat` spellable version) <*> genBuildResult))) $ \results ->+                let (bytes, refusal) = Proto.putKeyedBuildResults wireStoreDir version results+                 in refusal QC.=== Nothing+                      QC..&&. decodeWhole (Proto.getKeyedBuildResults wireStoreDir version) (builtBytes bytes)+                        QC.=== Right [Proto.KeyedBuildResult (carriedDerivedPath version path) (carriedBuildResult version result) | Proto.KeyedBuildResult path result <- results]+          | version <- gateVersions+          ],+      runTestM "a daemon's message to its client reads back as far as each version carries it"+        $ codecProperty+        $ roundTripsAtEveryVersion (const genStderrMessage) carriedStderrMessage Proto.getStderrMessage Proto.putStderrMessage,+      runTest "a daemon's messages, its errors and a collection's paths are laid out as upstream writes them" $+        let word = Wire.putNum :: Word64 -> BB.Builder+            failure = Proto.DaemonError (Proto.Verbosity 3) "msg" ["outer", "inner"] 7+            activity = Proto.Activity (Proto.ActivityId 5) (Proto.Verbosity 4) (Proto.ActivityType 105) "text" [Proto.FieldInt 9, Proto.FieldString "s"] (Proto.ActivityId 2)+            written version message = builtBytes (Proto.putStderrMessage (protoVersion version) message)+         in assertEqual+              "error record"+              (builtBytes (word 0x63787470 <> Wire.putBytes "Error" <> word 3 <> Wire.putBytes "Error" <> Wire.putBytes "msg" <> word 0 <> word 2 <> word 0 <> Wire.putBytes "outer" <> word 0 <> Wire.putBytes "inner"))+              (written 26 (Proto.StderrError failure))+              `andThen` assertEqual "error before 1.26" (builtBytes (word 0x63787470 <> Wire.putBytes "msg" <> word 7)) (written 25 (Proto.StderrError failure))+              `andThen` assertEqual+                "activity"+                (builtBytes (word 0x53545254 <> word 5 <> word 4 <> word 105 <> Wire.putBytes "text" <> word 2 <> word 0 <> word 9 <> word 1 <> Wire.putBytes "s" <> word 2))+                (written 38 (Proto.StderrStartActivity activity))+              `andThen` assertEqual "result" (builtBytes (word 0x52534c54 <> word 5 <> word 101 <> word 1 <> word 1 <> Wire.putBytes "s")) (written 38 (Proto.StderrResult (Proto.ActivityId 5) (Proto.ResultType 101) [Proto.FieldString "s"]))+              `andThen` assertEqual "stop" (builtBytes (word 0x53544f50 <> word 5)) (written 38 (Proto.StderrStopActivity (Proto.ActivityId 5)))+              `andThen` assertEqual "read" (builtBytes (word 0x64617461 <> word 4096)) (written 38 (Proto.StderrRead 4096))+              `andThen` assertEqual "action" (builtBytes (word 3)) (builtBytes (Proto.putGCAction Proto.DeleteSpecific))+              `andThen` assertEqual+                "specific paths"+                (builtBytes (word 0 <> word 1 <> Wire.putBytes "/nix/store/g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-foo" <> word 1))+                (builtBytes (Proto.putGCPaths wireStoreDir (Proto.SpecificPaths (Set.singleton (g1w7 "foo")) True)))+              `andThen` assertEqual "whole store" (builtBytes (word 1)) (builtBytes (Proto.putGCPaths wireStoreDir Proto.WholeStore))+              `andThen` assertEqual "features" (builtBytes (word 2 <> Wire.putBytes "a" <> Wire.putBytes "b")) (builtBytes (Proto.putFeatures (Set.fromList [Proto.Feature "b", Proto.Feature "a"]))),+      runTest "a daemon's message is refused in upstream's words" $+        let version = protoVersion 38+            readMessage builder = decodeWhole (Proto.getStderrMessage version) (builtBytes builder)+         in assertEqual "message" (wireRefusal "got unknown message type 1234 from Nix daemon") (readMessage (Wire.putNum (0x1234 :: Word64)))+              `andThen` assertEqual "error type" (wireRefusal "unexpected error type 'Oops'") (readMessage (Wire.putNum (0x63787470 :: Word64) <> Wire.putBytes "Oops"))+              `andThen` assertEqual+                "position"+                (wireRefusal "deserializing error positions is not supported")+                (readMessage (Wire.putNum (0x63787470 :: Word64) <> Wire.putBytes "Error" <> Wire.putNum (0 :: Word64) <> Wire.putBytes "Error" <> Wire.putBytes "msg" <> Wire.putNum (1 :: Word64)))+              `andThen` assertEqual+                "field"+                (wireRefusal "got unsupported field type 2 from Nix daemon")+                (readMessage (Wire.putNum (0x52534c54 :: Word64) <> Wire.putNum (1 :: Word64) <> Wire.putNum (0 :: Word64) <> Wire.putNum (1 :: Word64) <> Wire.putNum (2 :: Word64)))+    ]+  where+    readStorePath spelled = decodeWhole (Proto.getStorePath wireStoreDir) (builtBytes (Wire.putBytes (TE.encodeUtf8 spelled)))++-- | A store path under upstream's fixtures' hash.+g1w7 :: Text -> StorePath+g1w7 = StorePath "g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q"++-- | The environment variable naming a directory holding upstream's+-- worker-protocol fixtures (@src/libstore-tests/data/worker-protocol@ at+-- the tag CI fetches).  Unset, the group skips; set, every fixture must be+-- there.+workerProtocolDirVar :: String+workerProtocolDirVar = "NOVA_NIX_TEST_WORKER_PROTOCOL_DIR"++-- | One of upstream's fixtures and what reading it must give: the value+-- its own test gives at the version it reads at, and, where upstream+-- writes the value back too, the same bytes from writing what was read.+wireFixture :: (Eq a, Show a) => FilePath -> Wire.Decoder a -> Maybe a -> Maybe (a -> Either Text BB.Builder) -> (FilePath, BS.ByteString -> TestResult)+wireFixture stem reader expected writer = (stem <> ".bin", check)+  where+    check bytes = case (decodeWhole reader bytes, expected) of+      (Left err, _) -> Fail ("read: " <> err)+      (Right _, Nothing) -> Fail "the expected value does not build"+      (Right value, Just wanted) ->+        assertEqual "read" wanted value `andThen` case writer of+          Nothing -> Pass+          Just write -> assertRight "write" (write value) (assertEqual "written" bytes . builtBytes)++-- | A writer that cannot refuse.+totalWriter :: (a -> BB.Builder) -> Maybe (a -> Either Text BB.Builder)+totalWriter writer = Just (Right . writer)++-- | Upstream 2.35.4's worker-protocol fixtures, each as its+-- @worker-protocol.cc@ reads it.  @build-result-1.28@, @-1.29@ and @-1.37@+-- hold outputs in the older JSON form with a real derivation hash, which+-- upstream reads but writes back with 'dummy' hashes, so it reads them only+-- (@build-result-1.29-compat@ is the form it writes).+upstreamWireFixtures :: [(FilePath, BS.ByteString -> TestResult)]+upstreamWireFixtures =+  [ -- Upstream's last string is the C literal "oh no \0\0\0 what was that!",+    -- which becomes a std::string at its first NUL.+    wireFixture "string" (replicateM 5 Wire.getBytes) (Just ["", "hi", "white rabbit", BS.pack [0xe5, 0xa4, 0xa7, 0xe7, 0x99, 0xbd, 0xe5, 0x85, 0x94], "oh no "]) (totalWriter (foldMap Wire.putBytes)),+    wireFixture "store-path" (replicateM 2 (Proto.getStorePath defaultStoreDir)) (Just [g1w7 "foo", g1w7 "foo-bar"]) (totalWriter (foldMap (Proto.putStorePath defaultStoreDir))),+    wireFixture "content-address" (replicateM 3 Proto.getContentAddress) (sequence [textDerive, flatBlob, narParens]) (totalWriter (foldMap Proto.putContentAddress)),+    wireFixture "derived-path-1.29" (derivedPaths 29 3) (Just [Proto.DerivedOpaque (g1w7 "foo"), Proto.DerivedBuilt (g1w7 "bar.drv") Proto.AllOutputs, builtXY]) (derivedWriter 29),+    wireFixture "derived-path-1.30" (derivedPaths 30 4) (Just [Proto.DerivedOpaque (g1w7 "foo"), Proto.DerivedOpaque (g1w7 "foo.drv"), Proto.DerivedBuilt (g1w7 "bar.drv") Proto.AllOutputs, builtXY]) (derivedWriter 30),+    wireFixture+      "drv-output-realisation-with-path-not-hash"+      (replicateM 2 (Proto.getDrvOutput defaultStoreDir realisationVersion))+      (Just [Proto.DrvOutput (g1w7 "foo.drv") (Proto.OutputName "baz"), Proto.DrvOutput (g1w7 "foo.drv") (Proto.OutputName "quux")])+      (Just (fmap mconcat . traverse (Proto.putDrvOutput defaultStoreDir realisationVersion))),+    wireFixture "unkeyed-realisation-realisation-with-path-not-hash" (Proto.getUnkeyedRealisation defaultStoreDir realisationVersion) (Proto.UnkeyedRealisation (g1w7 "foo") <$> zeroSignatures ["asdf", "qwer"]) (Just (Proto.putUnkeyedRealisation defaultStoreDir realisationVersion)),+    wireFixture+      "realisation-realisation-with-path-not-hash"+      (Proto.getRealisation defaultStoreDir realisationVersion)+      (Proto.Realisation (Proto.DrvOutput (g1w7 "foo.drv") (Proto.OutputName "baz")) . Proto.UnkeyedRealisation (g1w7 "foo") <$> zeroSignatures ["asdf", "qwer"])+      (Just (Proto.putRealisation defaultStoreDir realisationVersion)),+    wireFixture "build-result-1.27" (buildResults (protoVersion 27)) (Just [rejected, notDeterministic False 0, built Map.empty 0 Nothing]) (buildWriter (protoVersion 27)),+    wireFixture "build-result-1.28" (buildResults (protoVersion 28)) (Just [rejected, notDeterministic False 0, built fooBar 0 Nothing]) Nothing,+    wireFixture "build-result-1.29" (buildResults (protoVersion 29)) (Just [rejected, notDeterministic True 3, built fooBar 1 Nothing]) Nothing,+    wireFixture "build-result-1.29-compat" (buildResults (protoVersion 29)) (Just [rejected, notDeterministic True 3, built fooBar 1 Nothing]) (buildWriter (protoVersion 29)),+    wireFixture "build-result-1.37" (buildResults (protoVersion 37)) (Just [rejected, notDeterministic True 3, built fooBar 1 cpuTimes]) Nothing,+    wireFixture "build-result-realisation-with-path-not-hash" (buildResults realisationVersion) (Just [rejected, notDeterministic True 3, built fooBar 1 cpuTimes]) (buildWriter realisationVersion),+    wireFixture+      "keyed-build-result-1.29"+      (replicateM 2 (Proto.getKeyedBuildResult defaultStoreDir (protoVersion 29)))+      ( Just+          [ Proto.KeyedBuildResult (Proto.DerivedOpaque (g1w7 "xxx")) rejected,+            Proto.KeyedBuildResult (Proto.DerivedBuilt (g1w7 "bar.drv") (fromMaybe Proto.AllOutputs (Proto.namedOutputs (Set.singleton (Proto.OutputName "out"))))) (notDeterministic True 3)+          ]+      )+      (Just (fmap mconcat . traverse (Proto.putKeyedBuildResult defaultStoreDir (protoVersion 29)))),+    wireFixture+      "unkeyed-valid-path-info-1.15"+      (replicateM 2 (Proto.getUnkeyedValidPathInfo defaultStoreDir (protoVersion 15)))+      (sequence [pathInfo Nothing [], pathInfo (Just (g1w7 "bar.drv")) [StorePath "g1w7hyyyy1w7hy3qg1w7hy3qgqqqqy3q" "foo.drv"]])+      (totalWriter (foldMap (Proto.putUnkeyedValidPathInfo defaultStoreDir (protoVersion 15)))),+    wireFixture+      "valid-path-info-1.15"+      (replicateM 2 (Proto.getValidPathInfo defaultStoreDir (protoVersion 15)))+      (sequence [Proto.ValidPathInfo (g1w7 "bar") <$> pathInfo Nothing [], Proto.ValidPathInfo (g1w7 "bar") <$> pathInfo (Just (g1w7 "bar.drv")) [yyyyFoo, g1w7 "bar"]])+      (totalWriter (foldMap (Proto.putValidPathInfo defaultStoreDir (protoVersion 15)))),+    wireFixture+      "valid-path-info-1.16"+      (replicateM 3 (Proto.getValidPathInfo defaultStoreDir (protoVersion 16)))+      ( sequence+          [ Proto.ValidPathInfo (g1w7 "bar") . (\info -> info {Proto.upiUltimate = True}) <$> pathInfo Nothing [],+            Proto.ValidPathInfo (g1w7 "bar") <$> ((\info sigs -> info {Proto.upiSignatures = sigs}) <$> pathInfo (Just (g1w7 "bar.drv")) [yyyyFoo, g1w7 "bar"] <*> zeroSignatures ["fake-sig-1", "fake-sig-2"]),+            fixedFoo >>= \path -> Proto.ValidPathInfo path <$> ((\info ca -> info {Proto.upiContentAddress = Just ca}) <$> pathInfo Nothing [g1w7 "bar", path] <*> narParens)+          ]+      )+      (totalWriter (foldMap (Proto.putValidPathInfo defaultStoreDir (protoVersion 16)))),+    wireFixture "build-mode" (replicateM 3 Proto.getBuildMode) (Just [Proto.BuildNormal, Proto.BuildRepair, Proto.BuildCheck]) (totalWriter (foldMap Proto.putBuildMode)),+    wireFixture "optional-trusted-flag" (replicateM 3 Proto.getTrust) (Just [Nothing, Just Proto.Trusted, Just Proto.NotTrusted]) (totalWriter (foldMap Proto.putTrust)),+    wireFixture+      "vector"+      ((,) <$> replicateM 3 (Wire.getList Wire.getBytes) <*> Wire.getList (Wire.getList Wire.getBytes))+      (Just ([[], [""], ["", "foo", "bar"]], [[], [""], ["", "1", "2"]]))+      (totalWriter (\(vectors, nested) -> foldMap (Wire.putList Wire.putBytes) vectors <> Wire.putList (Wire.putList Wire.putBytes) nested)),+    wireFixture+      "set"+      ((,) <$> replicateM 3 stringSet <*> (Set.fromList <$> Wire.getList stringSet))+      (Just ([Set.empty, Set.singleton "", Set.fromList ["", "foo", "bar"]], Set.fromList [Set.empty, Set.singleton "", Set.fromList ["", "1", "2"]]))+      (totalWriter (\(sets, nested) -> foldMap putStringSet sets <> Wire.putList putStringSet (Set.toAscList nested))),+    wireFixture "optional-store-path" (replicateM 2 (Proto.getOptionalStorePath defaultStoreDir)) (Just [Nothing, Just (g1w7 "foo-bar")]) (totalWriter (foldMap (Proto.putOptionalStorePath defaultStoreDir))),+    wireFixture "optional-content-address" (replicateM 2 Proto.getOptionalContentAddress) (sequence [Just Nothing, Just <$> flatBlob]) (totalWriter (foldMap Proto.putOptionalContentAddress)),+    wireFixture "client-handshake-info_1_30" (replicateM 1 (Proto.getHandshakeInfo (protoVersion 30))) (Just [Proto.HandshakeInfo Nothing Nothing]) (handshakeWriter 30),+    wireFixture "client-handshake-info_1_33" (replicateM 2 (Proto.getHandshakeInfo (protoVersion 33))) (Just [Proto.HandshakeInfo (Just "foo") Nothing, Proto.HandshakeInfo (Just "bar") Nothing]) (handshakeWriter 33),+    wireFixture+      "client-handshake-info_1_35"+      (replicateM 2 (Proto.getHandshakeInfo (protoVersion 35)))+      (Just [Proto.HandshakeInfo (Just "foo") (Just Proto.NotTrusted), Proto.HandshakeInfo (Just "bar") (Just Proto.Trusted)])+      (handshakeWriter 35),+    alsoWrittenByTheDaemon (wireFixture "handshake-to-client" (Proto.getServerMagic *> Proto.getVersionNumber) (Just (Proto.VersionNumber 1 10)) (totalWriter (\number -> Proto.putServerMagic <> Proto.putVersionNumber number)))+  ]+  where+    derivedPaths minor count = replicateM count (Proto.getDerivedPath defaultStoreDir (protoVersion minor))+    derivedWriter minor = Just (fmap mconcat . traverse (Proto.putDerivedPath defaultStoreDir (protoVersion minor)))+    builtXY = Proto.DerivedBuilt (g1w7 "bar.drv") (fromMaybe Proto.AllOutputs (Proto.namedOutputs (Set.fromList [Proto.OutputName "x", Proto.OutputName "y"])))+    buildResults version = replicateM 3 (Proto.getBuildResult defaultStoreDir version)+    buildWriter version = totalWriter (foldMap (Proto.putBuildResult defaultStoreDir version))+    result outcome timesBuilt cpu = Proto.BuildResult outcome timesBuilt (if timesBuilt == 0 then 0 else 30) (if timesBuilt == 0 then 0 else 50) (fst <$> cpu) (snd <$> cpu)+    rejected = result (Proto.Failed (Proto.Failure Proto.OutputRejected "no idea why" False)) 0 Nothing+    notDeterministic nonDeterministic timesBuilt = result (Proto.Failed (Proto.Failure Proto.NotDeterministic "no idea why" nonDeterministic)) timesBuilt Nothing+    built outputs = result (Proto.Succeeded (Proto.Success Proto.Built outputs))+    fooBar = Map.fromList [(Proto.OutputName name, Proto.UnkeyedRealisation (g1w7 name) Set.empty) | name <- ["foo", "bar"]]+    cpuTimes = Just (500000000, 604000000)+    zeroSignatures names = Set.fromList <$> traverse (\name -> Proto.signatureFromParts name (BS.replicate 64 0)) names+    contentAddress method algo input = Hash.rawHashWithAlgo algo input >>= Proto.contentAddressFromParts method algo+    textDerive = contentAddress Proto.TextMethod "sha256" "Derive(...)"+    flatBlob = contentAddress (Proto.FixedMethod FlatIngestion) "sha1" "blob blob..."+    narParens = contentAddress (Proto.FixedMethod NarIngestion) "sha256" "(...)"+    narHash = Hash.base64ToBytes "FePFYIlMuycIXPZbWi7LGEiMmZSX9FMbaQenWBzm1Sc=" >>= Proto.narHashFromDigest+    pathInfo deriver references = (\hash -> Proto.UnkeyedValidPathInfo deriver hash (Set.fromList references) 23423 34878 False Set.empty Nothing) <$> narHash+    yyyyFoo = StorePath "g1w7hyyyy1w7hy3qg1w7hy3qgqqqqy3q" "foo"+    -- The path upstream's makeFromCA gives "foo" with that content+    -- address, referring to bar and to itself.+    fixedFoo = either (const Nothing) Just (Hash.makeStorePath defaultStoreDir "source:/nix/store/g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-bar:self" (sha256Digest "(...)") "foo")+    stringSet = Set.fromList <$> Wire.getList Wire.getBytes+    putStringSet strings = Wire.putList Wire.putBytes (Set.toAscList strings)+    handshakeWriter minor = totalWriter (foldMap (\(Proto.HandshakeInfo daemonVersion trust) -> Proto.putHandshakeInfo (protoVersion minor) (fromMaybe BS.empty daemonVersion) trust))++-- | Fixtures upstream 2.35.4 keeps that no test of its reads: realisations+-- keyed by a derivation's hash, the form 2.35.4 stopped speaking.  Read as+-- 2.35.4 reads a realisation, each is refused.+orphanedWireFixtures :: [(FilePath, BS.ByteString -> TestResult)]+orphanedWireFixtures =+  [ ("drv-output.bin", refused (Proto.getDrvOutput defaultStoreDir realisationVersion)),+    ("realisation.bin", refused (Proto.getRealisation defaultStoreDir realisationVersion)),+    ("realisation-with-deps.bin", refused (Proto.getRealisation defaultStoreDir realisationVersion))+  ]+  where+    refused reader bytes = case Wire.runDecoder reader bytes of+      Left (Wire.Malformed _) -> Pass+      other -> Fail ("expected a refusal, got " <> T.pack (show (fmap snd other)))++-- | Upstream's worker-protocol fixtures read, and written back where+-- upstream writes them, byte for byte.  Every @.bin@ in the directory+-- must have a case, so a fixture a newer tag adds fails here until it is+-- read.+testDaemonFixtures :: IO [Bool]+testDaemonFixtures = do+  putStrLn "daemon/fixtures"+  named <- lookupEnv workerProtocolDirVar+  case named of+    Nothing -> do+      putStrLn ("  SKIP  needs " ++ workerProtocolDirVar)+      pure []+    Just dir -> do+      present <- Dir.doesDirectoryExist dir+      if not present+        then (: []) <$> runTest (T.pack workerProtocolDirVar <> " names a directory") (Fail (T.pack dir))+        else do+          let cases = upstreamWireFixtures ++ orphanedWireFixtures+          listed <- filter (".bin" `isSuffixOf`) <$> Dir.listDirectory dir+          let unread = filter (`notElem` map fst cases) listed+          checked <- mapM (readFixture dir) cases+          complete <- runTest "every fixture has a case" (assertEqual "fixtures with no case" [] (sort unread))+          pure (checked ++ [complete])+  where+    readFixture dir (file, check) =+      runTestM (T.pack file) $ do+        exists <- Dir.doesFileExist (dir </> file)+        if exists then check <$> BS.readFile (dir </> file) else pure (Fail "missing")++-- ---------------------------------------------------------------------------+-- Tests: the daemon's side of a connection+-- ---------------------------------------------------------------------------++-- Wire bytes spelled out by hand, apart from the codec, so a script holds+-- what the connection writes to upstream's layout rather than to the+-- codec's own idea of it.++-- | A number as upstream writes every one: eight bytes, little-endian.+le64 :: Word64 -> BS.ByteString+le64 n = BS.pack [fromIntegral (n `shiftR` (8 * i)) | i <- [0 .. 7]]++-- | A string: its length, its bytes, and zeros to a multiple of eight.+wstr :: BS.ByteString -> BS.ByteString+wstr bytes = le64 (fromIntegral (BS.length bytes)) <> bytes <> BS.replicate ((8 - BS.length bytes `mod` 8) `mod` 8) 0++-- | A list of strings.+wstrs :: [BS.ByteString] -> BS.ByteString+wstrs items = le64 (fromIntegral (length items)) <> BS.concat (map wstr items)++-- | A chunk of a framed stream, and the empty one that ends it.+wframe :: BS.ByteString -> BS.ByteString+wframe chunk = le64 (fromIntegral (BS.length chunk)) <> chunk++frameEnd :: BS.ByteString+frameEnd = le64 0++-- | The words that open the daemon's messages, and its handshake's.+nextWord, lastWord, errorWord, startWord, stopWord, resultWord, clientMagicWord, serverMagicWord :: Word64+nextWord = 0x6f6c6d67+lastWord = 0x616c7473+errorWord = 0x63787470+startWord = 0x53545254+stopWord = 0x53544f50+resultWord = 0x52534c54+clientMagicWord = 0x6e697863+serverMagicWord = 0x6478696f++-- | A line, the end of an operation's work, and an error as a record+-- (from 1.26) and as its message and exit status (before).+msgNext :: BS.ByteString -> BS.ByteString+msgNext line = le64 nextWord <> wstr line++msgLast :: BS.ByteString+msgLast = le64 lastWord++msgError :: BS.ByteString -> BS.ByteString+msgError message = le64 errorWord <> wstr "Error" <> le64 0 <> wstr "Error" <> wstr message <> le64 0 <> le64 0++msgErrorBefore126 :: BS.ByteString -> BS.ByteString+msgErrorBefore126 message = le64 errorWord <> wstr message <> le64 1++-- | A path as the wire names it.+pathOnWire :: StorePath -> BS.ByteString+pathOnWire = TE.encodeUtf8 . storePathToText defaultStoreDir++-- | A set of paths, in order.+wpaths :: [StorePath] -> BS.ByteString+wpaths = wstrs . map pathOnWire . Set.toAscList . Set.fromList++-- | A signature as the wire spells it.+sigBytes :: Proto.Signature -> BS.ByteString+sigBytes sig = Proto.sigKeyName sig <> ":" <> TE.encodeUtf8 (B64.encode (Proto.sigBytes sig))++-- | A path's info as a version from 1.16 writes it.+winfo :: Proto.UnkeyedValidPathInfo -> BS.ByteString+winfo info =+  wstr (maybe "" pathOnWire (Proto.upiDeriver info))+    <> wstr (TE.encodeUtf8 (Hash.bytesToHexText (Proto.narHashDigest (Proto.upiNarHash info))))+    <> wpaths (Set.toList (Proto.upiReferences info))+    <> le64 (fromIntegral (Proto.upiRegistrationTime info))+    <> le64 (Proto.upiNarSize info)+    <> le64 (if Proto.upiUltimate info then 1 else 0)+    <> wstrs (map sigBytes (Set.toAscList (Proto.upiSignatures info)))+    <> wstr ""++-- | The features the scripts' daemon offers, as it lists them.+serverFeatures :: [BS.ByteString]+serverFeatures = ["delete-dead-specific-referrers", "realisation-with-path-not-hash"]++-- | The Nix version the scripts' daemon names itself by.+serverNixVersion :: BS.ByteString+serverNixVersion = "nova-nix (test)"++-- | The substituter the scripts' daemon uses, and the one it trusts for+-- its clients.+daemonSubstituter, trustedSubstituter :: Text+daemonSubstituter = "https://cache.example.org/"+trustedSubstituter = "https://trusted.example.org/"++serverConfigAt :: Proto.Version -> Conn.ServerConfig+serverConfigAt version =+  Conn.ServerConfig+    { Conn.scStoreDir = defaultStoreDir,+      Conn.scVersion = version,+      Conn.scNixVersion = serverNixVersion,+      Conn.scVerbosity = Proto.Verbosity 3,+      Conn.scConfig = defaultNixConfig {ncSubstituters = [daemonSubstituter], ncTrustedSubstituters = [trustedSubstituter]}+    }++serverConfig :: Conn.ServerConfig+serverConfig = serverConfigAt (Proto.Version Proto.latestVersionNumber (Set.fromList (map Proto.Feature serverFeatures)))++-- | What a client at a minor version opens a connection with: the magic+-- word, its version, its features from 1.38 (one the daemon does not+-- offer among them), and its obsolete fields.+clientHello :: Word8 -> BS.ByteString+clientHello minor =+  le64 clientMagicWord+    <> le64 (0x100 + fromIntegral minor)+    <> (if minor >= 38 then wstrs ["realisation-with-path-not-hash", "some-other-feature", "delete-dead-specific-referrers"] else "")+    <> (if minor >= 14 then le64 0 else "")+    <> (if minor >= 11 then le64 0 else "")++-- | What the daemon answers a client's opening with: its magic word and+-- version, its features from 1.38, its Nix version from 1.33, its trust+-- from 1.35, and the end of its startup work.+serverHello :: Word8 -> Proto.Trust -> BS.ByteString+serverHello minor trust =+  le64 serverMagicWord+    <> le64 0x126+    <> (if minor >= 38 then wstrs serverFeatures else "")+    <> (if minor >= 33 then wstr serverNixVersion else "")+    <> (if minor >= 35 then le64 (if trust == Proto.Trusted then 1 else 2) else "")+    <> msgLast++-- | Paths the scripts name: valid ones, one that refers to another, a+-- derivation, one a substituter offers, one nothing knows, one whose+-- query reports as it works, two uploads, and a dump's.+fooPath, barPath, drvPath, offeredPath, missingPath, noisyPath, newPath, refusedPath, dumpPath :: StorePath+fooPath = StorePath "00000000000000000000000000000001" "foo"+barPath = StorePath "00000000000000000000000000000002" "bar"+drvPath = StorePath "00000000000000000000000000000003" "foo.drv"+offeredPath = StorePath "00000000000000000000000000000004" "offered"+missingPath = StorePath "00000000000000000000000000000005" "missing"+noisyPath = StorePath "00000000000000000000000000000006" "noisy"+newPath = StorePath "00000000000000000000000000000007" "new"+refusedPath = StorePath "00000000000000000000000000000008" "refused"+dumpPath = StorePath "00000000000000000000000000000009" "dump"++-- | A path's NAR in the scripts.+narOf :: StorePath -> BS.ByteString+narOf path = "nar of " <> TE.encodeUtf8 (spName path)++-- | A path's info whose NAR is 'narOf' the path.+infoFor :: StorePath -> [StorePath] -> Maybe StorePath -> Maybe Proto.UnkeyedValidPathInfo+infoFor path references deriver = withNar <$> Proto.narHashFromDigest (sha256Digest (narOf path))+  where+    withNar narHash =+      Proto.UnkeyedValidPathInfo+        { Proto.upiDeriver = deriver,+          Proto.upiNarHash = narHash,+          Proto.upiReferences = Set.fromList references,+          Proto.upiRegistrationTime = 1700000000,+          Proto.upiNarSize = fromIntegral (BS.length (narOf path)),+          Proto.upiUltimate = False,+          Proto.upiSignatures = Set.empty,+          Proto.upiContentAddress = Nothing+        }++-- | The infos the scripts' store and uploads hold.+data Fixtures = Fixtures+  { fooInfo :: !Proto.UnkeyedValidPathInfo,+    barInfo :: !Proto.UnkeyedValidPathInfo,+    drvInfo :: !Proto.UnkeyedValidPathInfo,+    noisyInfo :: !Proto.UnkeyedValidPathInfo,+    newInfo :: !Proto.UnkeyedValidPathInfo,+    refusedInfo :: !Proto.UnkeyedValidPathInfo+  }++fixtures :: Maybe Fixtures+fixtures =+  Fixtures+    <$> infoFor fooPath [] (Just drvPath)+    <*> infoFor barPath [fooPath] Nothing+    <*> infoFor drvPath [] Nothing+    <*> infoFor noisyPath [] Nothing+    <*> infoFor newPath [fooPath] Nothing+    <*> infoFor refusedPath [] Nothing++-- | A script's test, given the fixtures.+scriptTest :: Text -> (Fixtures -> TestResult) -> IO Bool+scriptTest name check = runTest name (maybe (Fail "the fixtures do not build") check fixtures)++-- | The scripts' store: the valid paths and their infos, what it was+-- asked in order, latest first, the NARs it imported, and the settings+-- its latest call ran under.+data Fake = Fake+  { fakeValid :: !(Map.Map StorePath Proto.UnkeyedValidPathInfo),+    fakeCalls :: ![Text],+    fakeImports :: ![(StorePath, BS.ByteString)],+    fakeSettings :: !(Maybe Ops.ConnectionSettings)+  }++-- | The store every script starts with.+startingStore :: Fixtures -> Fake+startingStore fx =+  Fake (Map.fromList [(fooPath, fooInfo fx), (barPath, barInfo fx), (drvPath, drvInfo fx), (noisyPath, noisyInfo fx)]) [] [] Nothing++-- | What a script runs over: the client's input still to come, what the+-- daemon has written, latest first, and the store.+data World = World+  { worldInput :: ![BS.ByteString],+    worldOutput :: ![BS.ByteString],+    worldFake :: !Fake+  }++type Scripted = State World++scriptTransport :: Conn.Transport Scripted+scriptTransport =+  Conn.Transport+    { Conn.transportReceive =+        state $ \world -> case worldInput world of+          [] -> (Nothing, world)+          chunk : rest -> (Just chunk, world {worldInput = rest}),+      Conn.transportSend = \bytes -> modify' (\world -> world {worldOutput = builtBytes bytes : worldOutput world})+    }++onFake :: (Fake -> Fake) -> Scripted ()+onFake change = modify' (\world -> world {worldFake = change (worldFake world)})++validPaths :: Scripted (Map.Map StorePath Proto.UnkeyedValidPathInfo)+validPaths = gets (fakeValid . worldFake)++-- | Record a call, and the settings it ran under.+asked :: Ops.Work Scripted -> Text -> Scripted ()+asked w call = onFake (\fake -> fake {fakeCalls = call : fakeCalls fake, fakeSettings = Just (Ops.workSettings w)})++-- | An intake that keeps what it is fed and acts on all of it at its end,+-- recording an upload that broke off.+collecting :: BS.ByteString -> (BS.ByteString -> Scripted (Either Proto.DaemonError a)) -> Ops.Intake Scripted a+collecting held atEnd = Ops.Taking (\chunk -> pure (collecting (held <> chunk) atEnd)) (atEnd held) (onFake (\fake -> fake {fakeCalls = "broken off" : fakeCalls fake}))++-- | What a build reports: its activity's start (a build's, type 105), a+-- line its builder wrote (a result of type 101), and its stop.+buildEvents :: [Ops.LogEvent]+buildEvents =+  [ Ops.ActivityStarted (Proto.Activity (Proto.ActivityId 7) (Proto.Verbosity 3) (Proto.ActivityType 105) "building noisy" [Proto.FieldString "noisy.drv", Proto.FieldInt 1] (Proto.ActivityId 0)),+    Ops.ActivityResult (Proto.ActivityId 7) (Proto.ResultType 101) [Proto.FieldString "a build line"],+    Ops.ActivityStopped (Proto.ActivityId 7)+  ]++-- | Those reports as upstream's daemon sends them from 1.20.+buildBytes :: BS.ByteString+buildBytes =+  (le64 startWord <> le64 7 <> le64 3 <> le64 105 <> wstr "building noisy" <> le64 2 <> le64 1 <> wstr "noisy.drv" <> le64 0 <> le64 1 <> le64 0)+    <> (le64 resultWord <> le64 7 <> le64 101 <> le64 1 <> le64 1 <> wstr "a build line")+    <> (le64 stopWord <> le64 7)++-- | What querying 'noisyPath' reports as it works: a line at the info+-- level, one at a level above it, and a build.+noisyEvents :: [Ops.LogEvent]+noisyEvents = Ops.LogLine (Proto.Verbosity 3) "checking noisy" : Ops.LogLine (Proto.Verbosity 5) "too quiet to hear" : buildEvents++-- | A build's result in the scripts: built once, its output at 'fooPath'.+builtResult :: Proto.BuildResult+builtResult =+  Proto.BuildResult+    (Proto.Succeeded (Proto.Success Proto.Built (Map.singleton (Proto.OutputName "out") (Proto.UnkeyedRealisation fooPath Set.empty))))+    1+    10+    20+    Nothing+    Nothing++-- | The roots the scripts' store holds, as a client is shown them.+rootsShown :: Ops.RootCensoring -> Map.Map StorePath (Set.Set BS.ByteString)+rootsShown censoring = Map.singleton fooPath (Set.singleton link)+  where+    link = case censoring of+      Ops.ShowRoots -> "/home/user/result"+      Ops.CensorRoots -> "{censored}"++-- | Two links a scripted client asks the daemon to root, each as the client+-- spells it and as the daemon makes it absolute.  A POSIX daemon takes a+-- relative link from @/@ and collapses the path; a Windows daemon takes an+-- absolute link alone, so there both links are absolute.+firstLink, secondLink :: (BS.ByteString, BS.ByteString)+firstLink+  | SI.os == "mingw32" = ("C:\\home\\user\\result", "C:\\home\\user\\result")+  | otherwise = ("home/user/./result", "/home/user/result")+secondLink+  | SI.os == "mingw32" = ("C:\\home\\user\\..\\user\\.\\result2\\", "C:\\home\\user\\result2")+  | otherwise = ("/home/user/../user//result2/", "/home/user/result2")++-- | What the fake store notes of a link it is asked to root.+askedRoot :: BS.ByteString -> Text+askedRoot link = "AddIndirectRoot " <> TE.decodeLatin1 link++-- | Upstream's refusal of a path that is not valid.+notValid :: StorePath -> Proto.DaemonError+notValid path = Ops.daemonError ("path '" <> storePathToText defaultStoreDir path <> "' is not valid")++fakeStore :: Ops.DaemonStore Scripted+fakeStore =+  Ops.DaemonStore+    { Ops.dsIsValidPath = \w path -> do+        asked w ("IsValidPath " <> spName path)+        when (path == noisyPath) (traverse_ (Ops.workReport w) noisyEvents)+        Right . Map.member path <$> validPaths,+      Ops.dsQueryValidPaths = \w substitute paths -> do+        asked w ("QueryValidPaths " <> T.pack (show substitute))+        Right . (\known -> Set.filter (`Map.member` known) paths) <$> validPaths,+      Ops.dsQuerySubstitutablePaths = \w paths -> Right (Set.filter (== offeredPath) paths) <$ asked w "QuerySubstitutablePaths",+      Ops.dsQueryReferrers = \w path -> do+        asked w "QueryReferrers"+        Right . Map.keysSet . Map.filter (Set.member path . Proto.upiReferences) <$> validPaths,+      Ops.dsQueryValidDerivers = \w path -> do+        asked w "QueryValidDerivers"+        Right . maybe Set.empty (maybe Set.empty Set.singleton . Proto.upiDeriver) . Map.lookup path <$> validPaths,+      Ops.dsQueryDerivationOutputMap = \w _ ->+        Right (Map.fromList [(Proto.OutputName "out", Just fooPath), (Proto.OutputName "dev", Nothing)]) <$ asked w "QueryDerivationOutputMap",+      Ops.dsQueryAllValidPaths = \w -> asked w "QueryAllValidPaths" >> (Right . Map.keysSet <$> validPaths),+      Ops.dsQueryPathInfo = \w path -> asked w "QueryPathInfo" >> (Right . Map.lookup path <$> validPaths),+      Ops.dsQueryMissing = \w _ -> Right (Proto.Missing (Set.singleton drvPath) (Set.singleton offeredPath) Set.empty 10 20) <$ asked w "QueryMissing",+      Ops.dsAddToStore = \w upload -> do+        asked w ("AddToStore " <> TE.decodeLatin1 (Ops.duName upload) <> " " <> T.pack (show (Ops.duMethod upload)) <> " " <> Ops.duAlgo upload)+        pure . collecting BS.empty $ \dump -> do+          onFake (\fake -> fake {fakeImports = (dumpPath, dump) : fakeImports fake})+          pure $ case Proto.narHashFromDigest (sha256Digest dump) of+            Nothing -> Left (Ops.daemonError "no hash")+            Just narHash -> Right (Proto.ValidPathInfo dumpPath (Proto.UnkeyedValidPathInfo Nothing narHash (Ops.duReferences upload) 1700000000 (fromIntegral (BS.length dump)) True Set.empty Nothing)),+      Ops.dsAddToStoreNar = \w (Proto.ValidPathInfo path info) repair checkSigs -> do+        asked w ("AddToStoreNar " <> spName path <> " " <> T.pack (show repair) <> " " <> T.pack (show checkSigs) <> " ultimate " <> T.pack (show (Proto.upiUltimate info)))+        importing path info repair <$> validPaths,+      Ops.dsBuildPaths = \w _ mode -> do+        asked w ("BuildPaths " <> T.pack (show mode))+        Right () <$ traverse_ (Ops.workReport w) buildEvents,+      Ops.dsBuildPathsWithResults = \w targets mode -> Right [Proto.KeyedBuildResult target builtResult | target <- targets] <$ asked w ("BuildPathsWithResults " <> T.pack (show mode)),+      Ops.dsEnsurePath = \w path -> do+        asked w ("EnsurePath " <> spName path)+        (\known -> if Map.member path known then Right () else Left (notValid path)) <$> validPaths,+      Ops.dsAddTempRoot = \w path -> Right () <$ asked w ("AddTempRoot " <> spName path),+      Ops.dsAddIndirectRoot = \w link -> Right () <$ asked w ("AddIndirectRoot " <> TE.decodeLatin1 link),+      Ops.dsFindRoots = \w censoring -> Right (rootsShown censoring) <$ asked w ("FindRoots " <> T.pack (show censoring)),+      Ops.dsCollectGarbage = \w request ->+        Right (Proto.GCResult (Set.singleton (pathOnWire (StorePath "0000000000000000000000000000000a" "dead"))) 4096) <$ asked w ("CollectGarbage " <> T.pack (show request)),+      Ops.dsOptimiseStore = \w -> Right () <$ asked w "OptimiseStore",+      Ops.dsVerifyStore = \w contents repair -> Right False <$ asked w ("VerifyStore " <> T.pack (show contents) <> " " <> T.pack (show repair)),+      Ops.dsAddSignatures = \w path sigs -> Right () <$ asked w ("AddSignatures " <> spName path <> " " <> T.pack (show (Set.size sigs))),+      Ops.dsNarFromPath = \path sink -> do+        onFake (\fake -> fake {fakeCalls = ("NarFromPath " <> spName path) : fakeCalls fake})+        known <- validPaths+        if Map.member path known+          then Right () <$ traverse_ sink [BS.take 4 (narOf path), BS.drop 4 (narOf path)]+          else Left (notValid path) <$ sink "partial"+    }++-- | How the scripts' store imports a NAR: 'refusedPath' is refused before+-- a byte is read, as upstream refuses an unsigned path; a valid path is+-- left as it is without its NAR being read, unless it is repaired; any+-- other is held to its info's hash and size.+importing :: StorePath -> Proto.UnkeyedValidPathInfo -> Ops.Repair -> Map.Map StorePath Proto.UnkeyedValidPathInfo -> Ops.Intake Scripted ()+importing path info repair known+  | path == refusedPath = Ops.Taken (Left (Ops.daemonError ("cannot add path '" <> storePathToText defaultStoreDir path <> "' because it lacks a signature by a trusted key")))+  | Map.member path known && repair == Ops.NoRepair = Ops.Taken (Right ())+  | otherwise = collecting BS.empty imported+  where+    imported nar+      | Proto.narHashFromDigest (sha256Digest nar) == Just (Proto.upiNarHash info) && fromIntegral (BS.length nar) == Proto.upiNarSize info =+          Right () <$ onFake (\fake -> fake {fakeValid = Map.insert path info (fakeValid fake), fakeImports = (path, nar) : fakeImports fake})+      | otherwise = pure (Left (Ops.daemonError ("hash mismatch importing path '" <> storePathToText defaultStoreDir path <> "'")))++-- | Run a client's bytes against the scripts' store: how the connection+-- ended, every byte the daemon wrote, and the store after.+runScript :: Conn.ServerConfig -> Proto.Trust -> Fake -> [BS.ByteString] -> (Conn.ConnectionEnd, BS.ByteString, Fake)+runScript config trust fake input = (ended, BS.concat (reverse (worldOutput world)), worldFake world)+  where+    (ended, world) = runState (Conn.serveConnection config trust fakeStore scriptTransport) (World (filter (not . BS.null) input) [] fake)++-- | A session at a minor version: what the daemon writes after its+-- handshake, how the connection ends, and a check of the store after.+assertSession :: Proto.Trust -> Word8 -> Fake -> [BS.ByteString] -> BS.ByteString -> Conn.ConnectionEnd -> (Fake -> TestResult) -> TestResult+assertSession trust minor fake ops expected end check =+  let (ended, written, after) = runScript serverConfig trust fake (clientHello minor : ops)+   in assertEqual "written" (serverHello minor trust <> expected) written+        `andThen` assertEqual "end" end ended+        `andThen` check after++-- | The store was asked exactly these, in order.+askedOnly :: [Text] -> Fake -> TestResult+askedOnly calls fake = assertEqual "calls" calls (reverse (fakeCalls fake))++-- | A request naming one path.+reqPath :: Word64 -> StorePath -> BS.ByteString+reqPath code path = le64 code <> wstr (pathOnWire path)++-- | Settings as upstream's client sends them, at a verbosity, with the+-- other settings given.+setOptionsAt :: Word64 -> [(BS.ByteString, BS.ByteString)] -> BS.ByteString+setOptionsAt verbosity overrides =+  le64 19+    <> foldMap le64 [1, 0, 1, verbosity, 1, 0, 1, 7, 0, 0, 4, 1]+    <> le64 (fromIntegral (length overrides))+    <> foldMap (\(name, value) -> wstr name <> wstr value) overrides++-- | A path's info as an upload sends it.+uploadInfo :: StorePath -> Proto.UnkeyedValidPathInfo -> BS.ByteString+uploadInfo path info = wstr (pathOnWire path) <> winfo info++-- | A path derived from 'drvPath', its output @out@.+drvOut :: BS.ByteString+drvOut = pathOnWire drvPath <> "!out"++-- | The scripted connections: a client's bytes against a fake store, and+-- every byte the daemon writes back, spelled out by hand.+testDaemonServer :: IO [Bool]+testDaemonServer = do+  putStrLn "daemon/server"+  sequence+    [ scriptTest "a trusted client's queries are each answered after the end of their work, as upstream's daemon answers them" $ \fx ->+        assertSession+          Proto.Trusted+          38+          (startingStore fx)+          [ setOptionsAt 3 [],+            reqPath 1 fooPath,+            reqPath 1 missingPath,+            reqPath 26 fooPath,+            reqPath 26 missingPath,+            le64 31 <> wpaths [fooPath, missingPath] <> le64 1,+            le64 32 <> wpaths [offeredPath, missingPath],+            reqPath 6 fooPath,+            reqPath 33 fooPath,+            reqPath 41 drvPath,+            le64 23,+            le64 40 <> wstrs [drvOut],+            reqPath 10 fooPath,+            reqPath 11 fooPath,+            le64 12 <> wstr (fst firstLink),+            le64 12 <> wstr (fst secondLink),+            le64 14,+            le64 20 <> le64 2 <> le64 1 <> le64 0 <> le64 100 <> le64 0 <> le64 0 <> le64 0,+            le64 34,+            le64 35 <> le64 1 <> le64 0,+            le64 37 <> wstr (pathOnWire fooPath) <> wstrs ["key:" <> TE.encodeUtf8 (B64.encode (BS.replicate 64 0))],+            reqPath 38 fooPath+          ]+          ( msgLast+              <> (msgLast <> le64 1)+              <> (msgLast <> le64 0)+              <> (msgLast <> le64 1 <> winfo (fooInfo fx))+              <> (msgLast <> le64 0)+              <> (msgLast <> wpaths [fooPath])+              <> (msgLast <> wpaths [offeredPath])+              <> (msgLast <> wpaths [barPath])+              <> (msgLast <> wpaths [drvPath])+              <> (msgLast <> le64 2 <> wstr "dev" <> wstr "" <> wstr "out" <> wstr (pathOnWire fooPath))+              <> (msgLast <> wpaths [fooPath, barPath, drvPath, noisyPath])+              <> (msgLast <> wpaths [drvPath] <> wpaths [offeredPath] <> wpaths [] <> le64 10 <> le64 20)+              <> (msgLast <> le64 1)+              <> (msgLast <> le64 1)+              <> (msgLast <> le64 1)+              <> (msgLast <> le64 1)+              <> (msgLast <> le64 1 <> wstr "/home/user/result" <> wstr (pathOnWire fooPath))+              <> (msgLast <> wstrs ["/nix/store/0000000000000000000000000000000a-dead"] <> le64 4096 <> le64 0)+              <> (msgLast <> le64 1)+              <> (msgLast <> le64 0)+              <> (msgLast <> le64 1)+              <> (msgLast <> narOf fooPath)+          )+          Conn.ClientClosed+          ( askedOnly+              [ "IsValidPath foo",+                "IsValidPath missing",+                "QueryPathInfo",+                "QueryPathInfo",+                "QueryValidPaths Substitute",+                "QuerySubstitutablePaths",+                "QueryReferrers",+                "QueryValidDerivers",+                "QueryDerivationOutputMap",+                "QueryAllValidPaths",+                "QueryMissing",+                "EnsurePath foo",+                "AddTempRoot foo",+                askedRoot (snd firstLink),+                askedRoot (snd secondLink),+                "FindRoots ShowRoots",+                "CollectGarbage " <> T.pack (show (Ops.GCRequest Proto.DeleteDead Proto.WholeStore 100)),+                "OptimiseStore",+                "VerifyStore CheckContents NoRepair",+                "AddSignatures foo 1",+                "NarFromPath foo"+              ]+          ),+      scriptTest "a build's activity and its log line reach the client as it runs, and its results are keyed by the paths asked for" $ \fx ->+        assertSession+          Proto.Trusted+          38+          (startingStore fx)+          [le64 9 <> wstrs [drvOut] <> le64 0, le64 46 <> wstrs [drvOut] <> le64 2]+          ( buildBytes+              <> (msgLast <> le64 1)+              <> msgLast+              <> le64 1+              <> wstr drvOut+              <> (le64 0 <> wstr "" <> le64 1 <> le64 0 <> le64 10 <> le64 20 <> le64 0 <> le64 0)+              <> (le64 1 <> wstr "out" <> wstr (pathOnWire fooPath) <> le64 0)+          )+          Conn.ClientClosed+          (askedOnly ["BuildPaths BuildNormal", "BuildPathsWithResults BuildCheck"]),+      scriptTest "a message and an activity the store reports mid-operation reach the client as upstream's daemon forwards them" $ \fx ->+        assertSession Proto.Trusted 38 (startingStore fx) [reqPath 1 noisyPath] (msgNext "checking noisy\n" <> buildBytes <> msgLast <> le64 1) Conn.ClientClosed (const Pass),+      scriptTest "before 1.20 an activity's start reaches the client as a line, and the rest of what it reports does not" $ \fx ->+        assertSession+          Proto.Trusted+          19+          (startingStore fx)+          [reqPath 1 noisyPath]+          (msgNext "checking noisy\n" <> msgNext "building noisy...\n" <> msgLast <> le64 1)+          Conn.ClientClosed+          (const Pass),+      scriptTest "a client's verbosity decides which of the store's lines reach it" $ \fx ->+        assertSession+          Proto.Trusted+          38+          (startingStore fx)+          [setOptionsAt 5 [], reqPath 1 noisyPath, setOptionsAt 0 [], reqPath 1 noisyPath]+          ( msgLast+              <> msgNext "checking noisy\n"+              <> msgNext "too quiet to hear\n"+              <> buildBytes+              <> (msgLast <> le64 1)+              <> msgLast+              <> buildBytes+              <> (msgLast <> le64 1)+          )+          Conn.ClientClosed+          (const Pass),+      scriptTest "an operation that fails in its work is sent upstream's error record, and the connection goes on" $ \fx ->+        assertSession+          Proto.Trusted+          38+          (startingStore fx)+          [reqPath 10 missingPath, reqPath 1 fooPath]+          (msgError "path '/nix/store/00000000000000000000000000000005-missing' is not valid" <> msgLast <> le64 1)+          Conn.ClientClosed+          (const Pass),+      scriptTest "before 1.26 a failure is sent as its message and exit status" $ \fx ->+        assertSession+          Proto.Trusted+          25+          (startingStore fx)+          [reqPath 10 missingPath, reqPath 1 fooPath]+          (msgErrorBefore126 "path '/nix/store/00000000000000000000000000000005-missing' is not valid" <> msgLast <> le64 1)+          Conn.ClientClosed+          (const Pass),+      scriptTest "a failure before an operation's work is sent twice and closes the connection, as upstream's daemon closes it" $ \fx ->+        let closed message ops =+              assertSession Proto.Trusted 38 (startingStore fx) (ops ++ [reqPath 1 fooPath]) (msgError message <> msgError message) (Conn.ClosedOnError (Ops.daemonError (TE.decodeUtf8 message))) (askedOnly [])+         in closed "invalid operation 99" [le64 99]+              `andThen` closed "path \"/tmp/x\" is not in the Nix store" [le64 1 <> wstr "/tmp/x"]+              `andThen` closed "Invalid build mode" [le64 9 <> wstrs [drvOut] <> le64 3],+      scriptTest "an operation's code too large to read is sent once and closes the connection, and input ending inside a request is sent twice" $ \fx ->+        assertSession+          Proto.Trusted+          38+          (startingStore fx)+          [le64 4294967296]+          (msgError "serialised integer 4294967296 is too large for type 'j'")+          (Conn.ClosedOnError (Ops.daemonError "serialised integer 4294967296 is too large for type 'j'"))+          (askedOnly [])+          `andThen` assertSession+            Proto.Trusted+            38+            (startingStore fx)+            [le64 1 <> le64 64 <> "/nix/store"]+            (msgError "unexpected end-of-file" <> msgError "unexpected end-of-file")+            (Conn.ClosedOnError (Ops.daemonError "unexpected end-of-file"))+            (askedOnly []),+      runTest "a client whose input ends between operations closes the connection, with nothing more sent" $+        let (ended, written, _) = runScript serverConfig Proto.Trusted emptyFake [clientHello 38, BS.take 3 (le64 1)]+         in assertEqual "end" Conn.ClientClosed ended `andThen` assertEqual "written" (serverHello 38 Proto.Trusted) written,+      scriptTest "an untrusted client is refused what upstream's daemon refuses it, and a trusted one is not" $ \fx ->+        let store = startingStore fx+            narUpload repair dontCheck = le64 39 <> uploadInfo newPath ((newInfo fx) {Proto.upiUltimate = True}) <> le64 repair <> le64 dontCheck <> wframe (narOf newPath) <> frameEnd+            refusedBefore message request =+              assertSession Proto.NotTrusted 38 store [request, reqPath 1 fooPath] (msgError message <> msgError message) (Conn.ClosedOnError (Ops.daemonError (TE.decodeUtf8 message))) (askedOnly [])+            refusedInWork message request =+              assertSession Proto.NotTrusted 38 store [request, reqPath 1 fooPath] (msgError message <> msgLast <> le64 1) Conn.ClientClosed (askedOnly ["IsValidPath foo"])+            served trust request reply calls = assertSession trust 38 store [request] reply Conn.ClientClosed (askedOnly calls)+         in refusedBefore "you are not privileged to repair paths" (le64 7 <> wstr "dump" <> wstr "text:sha256" <> wpaths [] <> le64 1)+              `andThen` refusedBefore "you are not privileged to repair store paths" (narUpload 1 0)+              `andThen` refusedBefore "you are not privileged to repair store paths" (le64 44 <> le64 1 <> le64 0)+              `andThen` refusedBefore "repairing is not allowed because you are not in 'trusted-users'" (le64 9 <> wstrs [drvOut] <> le64 1)+              `andThen` refusedBefore "repairing is not allowed because you are not in 'trusted-users'" (le64 46 <> wstrs [drvOut] <> le64 1)+              `andThen` refusedInWork "you are not privileged to repair paths" (le64 35 <> le64 0 <> le64 1)+              `andThen` served Proto.Trusted (le64 9 <> wstrs [drvOut] <> le64 1) (buildBytes <> msgLast <> le64 1) ["BuildPaths BuildRepair"]+              `andThen` served Proto.Trusted (le64 35 <> le64 0 <> le64 1) (msgLast <> le64 0) ["VerifyStore SkipContents Repair"]+              `andThen` served Proto.Trusted (narUpload 1 1) msgLast ["AddToStoreNar new Repair NoCheckSigs ultimate True"]+              `andThen` served Proto.NotTrusted (narUpload 0 1) msgLast ["AddToStoreNar new NoRepair CheckSigs ultimate False"]+              `andThen` served+                Proto.NotTrusted+                (le64 44 <> le64 0 <> le64 1 <> wframe (le64 1 <> uploadInfo newPath ((newInfo fx) {Proto.upiUltimate = True}) <> narOf newPath) <> frameEnd)+                msgLast+                ["AddToStoreNar new NoRepair CheckSigs ultimate False"]+              `andThen` served Proto.NotTrusted (le64 14) (msgLast <> le64 1 <> wstr "{censored}" <> wstr (pathOnWire fooPath)) ["FindRoots CensorRoots"],+      scriptTest "no client may have a collection ignore liveness, and the refusal leaves the connection open" $ \fx ->+        let ignoring = le64 20 <> le64 2 <> le64 1 <> le64 1 <> le64 0 <> le64 0 <> le64 0 <> le64 0+            refused trust =+              assertSession trust 38 (startingStore fx) [ignoring, reqPath 1 fooPath] (msgError "you are not allowed to ignore liveness" <> msgLast <> le64 1) Conn.ClientClosed (askedOnly ["IsValidPath foo"])+         in refused Proto.Trusted `andThen` refused Proto.NotTrusted,+      scriptTest "a collection's paths are a set with a referrers flag under the delete-specific feature and a bare set without it, where a collection of the dead limited to some is refused" $ \fx ->+        let tail3 = le64 0 <> le64 0 <> le64 0+            bare action paths = le64 20 <> le64 action <> wpaths paths <> le64 0 <> le64 0 <> tail3+            reply = msgLast <> wstrs ["/nix/store/0000000000000000000000000000000a-dead"] <> le64 4096 <> le64 0+            asks request = "CollectGarbage " <> T.pack (show request)+            message = "Garbage collecting specific paths requested but it is not supported by the negotiated protocol"+         in assertSession+              Proto.Trusted+              38+              (startingStore fx)+              [le64 20 <> le64 2 <> le64 0 <> wpaths [fooPath] <> le64 1 <> le64 0 <> le64 7 <> tail3]+              reply+              Conn.ClientClosed+              (askedOnly [asks (Ops.GCRequest Proto.DeleteDead (Proto.SpecificPaths (Set.singleton fooPath) True) 7)])+              `andThen` assertSession+                Proto.Trusted+                37+                (startingStore fx)+                [bare 3 [fooPath], bare 0 []]+                (reply <> reply)+                Conn.ClientClosed+                (askedOnly [asks (Ops.GCRequest Proto.DeleteSpecific (Proto.SpecificPaths (Set.singleton fooPath) False) 0), asks (Ops.GCRequest Proto.ReturnLive Proto.WholeStore 0)])+              `andThen` assertSession Proto.Trusted 37 (startingStore fx) [bare 2 [fooPath]] (msgError message <> msgError message) (Conn.ClosedOnError (Ops.daemonError (TE.decodeUtf8 message))) (askedOnly []),+      scriptTest "a NAR upload is fed to the store up to its declared size, and the rest of its frames are read past" $ \fx ->+        let nar = narOf newPath+            upload = le64 39 <> uploadInfo newPath (newInfo fx) <> le64 0 <> le64 0 <> foldMap wframe [BS.take 3 nar, BS.drop 3 nar <> "trailing", "more"] <> frameEnd+         in assertSession+              Proto.Trusted+              38+              (startingStore fx)+              [upload, reqPath 1 newPath]+              (msgLast <> msgLast <> le64 1)+              Conn.ClientClosed+              (assertEqual "imported" [(newPath, nar)] . fakeImports),+      scriptTest "a store that fails an upload, or needs none of it, has the rest read past before the reply, and the connection goes on" $ \fx ->+        let upload path info nar = le64 39 <> uploadInfo path info <> le64 0 <> le64 0 <> wframe nar <> wframe "more" <> frameEnd+            unsigned = "cannot add path '/nix/store/00000000000000000000000000000008-refused' because it lacks a signature by a trusted key"+            mismatch = "hash mismatch importing path '/nix/store/00000000000000000000000000000007-new'"+            session request reply = assertSession Proto.Trusted 38 (startingStore fx) [request, reqPath 1 fooPath] (reply <> msgLast <> le64 1) Conn.ClientClosed+         in session (upload refusedPath (refusedInfo fx) (narOf refusedPath)) (msgError unsigned) (assertEqual "imported" [] . fakeImports)+              `andThen` session (upload newPath (newInfo fx) "not the nar of new") (msgError mismatch) (assertEqual "imported" [] . fakeImports)+              `andThen` session (upload fooPath (fooInfo fx) (narOf fooPath)) msgLast (assertEqual "imported" [] . fakeImports),+      scriptTest "a frame too long to read fails its upload, and reading past the upload goes on from the bytes after the length, as upstream's does" $ \fx ->+        assertSession+          Proto.Trusted+          38+          (startingStore fx)+          [le64 39 <> uploadInfo newPath (newInfo fx) <> le64 0 <> le64 0 <> le64 4294967296 <> wframe "x" <> frameEnd, reqPath 1 fooPath]+          (msgError "serialised integer 4294967296 is too large for type 'j'" <> msgLast <> le64 1)+          Conn.ClientClosed+          (askedOnly ["AddToStoreNar new NoRepair CheckSigs ultimate False", "broken off", "IsValidPath foo"]),+      scriptTest "input that ends inside an upload fails it once, and the connection then closes as the client's input has ended" $ \fx ->+        assertSession+          Proto.Trusted+          38+          (startingStore fx)+          [le64 39 <> uploadInfo newPath (newInfo fx) <> le64 0 <> le64 0 <> wframe "abc"]+          (msgError "unexpected end-of-file")+          Conn.ClientClosed+          (askedOnly ["AddToStoreNar new NoRepair CheckSigs ultimate False", "broken off"]),+      scriptTest "AddMultipleToStore imports each path in turn from one framed stream, reading past the NAR of one already valid, and none is ultimate" $ \fx ->+        let payload =+              le64 2+                <> uploadInfo fooPath ((fooInfo fx) {Proto.upiUltimate = True})+                <> narOf fooPath+                <> uploadInfo newPath ((newInfo fx) {Proto.upiUltimate = True})+                <> narOf newPath+            request = le64 44 <> le64 0 <> le64 0 <> foldMap wframe [BS.take 5 payload, BS.take 100 (BS.drop 5 payload), BS.drop 105 payload] <> frameEnd+         in assertSession+              Proto.Trusted+              38+              (startingStore fx)+              [request, reqPath 1 newPath]+              (msgLast <> msgLast <> le64 1)+              Conn.ClientClosed+              ( \after ->+                  askedOnly ["AddToStoreNar foo NoRepair CheckSigs ultimate False", "AddToStoreNar new NoRepair CheckSigs ultimate False", "IsValidPath new"] after+                    `andThen` assertEqual "imported" [(newPath, narOf newPath)] (fakeImports after)+              ),+      scriptTest "AddMultipleToStore stops at the first path the store refuses, and an upload that ends before its count does fails it" $ \fx ->+        let failing = wframe (le64 2 <> uploadInfo refusedPath (refusedInfo fx) <> narOf refusedPath <> uploadInfo newPath (newInfo fx) <> narOf newPath)+            short = wframe (le64 2 <> uploadInfo newPath (newInfo fx) <> narOf newPath)+            session frames reply calls = assertSession Proto.Trusted 38 (startingStore fx) [le64 44 <> le64 0 <> le64 0 <> frames <> frameEnd, reqPath 1 fooPath] (reply <> msgLast <> le64 1) Conn.ClientClosed (askedOnly (calls ++ ["IsValidPath foo"]))+         in session failing (msgError "cannot add path '/nix/store/00000000000000000000000000000008-refused' because it lacks a signature by a trusted key") ["AddToStoreNar refused NoRepair CheckSigs ultimate False"]+              `andThen` session short (msgError "reached end of FramedSource") ["AddToStoreNar new NoRepair CheckSigs ultimate False"],+      scriptTest "AddToStore makes a path from its framed dump and replies with the path's info" $ \fx ->+        case Proto.narHashFromDigest (sha256Digest "hello") of+          Nothing -> Fail "no hash"+          Just narHash ->+            assertSession+              Proto.Trusted+              38+              (startingStore fx)+              [le64 7 <> wstr "dump" <> wstr "fixed:r:sha256" <> wpaths [fooPath] <> le64 0 <> wframe "hel" <> wframe "lo" <> frameEnd]+              (msgLast <> wstr (pathOnWire dumpPath) <> winfo (Proto.UnkeyedValidPathInfo Nothing narHash (Set.singleton fooPath) 1700000000 5 True Set.empty Nothing))+              Conn.ClientClosed+              (askedOnly ["AddToStore dump FixedMethod NarIngestion sha256"]),+      scriptTest "an upload's method is read before its dump, so a method refused leaves the dump to be read as the next operation, as upstream leaves it" $ \fx ->+        assertSession+          Proto.Trusted+          38+          (startingStore fx)+          [le64 7 <> wstr "dump" <> wstr "bogus:sha256" <> wpaths [] <> le64 0 <> wframe "hello" <> frameEnd]+          ( msgError "content address prefix 'bogus' is unrecognized. Recogonized prefixes are 'text' or 'fixed'"+              <> msgError "invalid operation 5"+              <> msgError "invalid operation 5"+          )+          (Conn.ClosedOnError (Ops.daemonError "invalid operation 5"))+          (askedOnly []),+      scriptTest "an upload in a form older than a framed one is refused as its request begins" $ \fx ->+        let refused minor message ops =+              assertSession Proto.Trusted minor (startingStore fx) ops (msgErrorBefore126 message <> msgErrorBefore126 message) (Conn.ClosedOnError (Ops.daemonError (TE.decodeUtf8 message))) (askedOnly [])+         in refused 24 "AddToStore before protocol 1.25 is not supported by this daemon" [le64 7, wstr "dump"]+              `andThen` refused 22 "AddToStoreNar before protocol 1.23 is not supported by this daemon" [le64 39]+              `andThen` assertSession Proto.Trusted 26 (startingStore fx) [le64 31 <> wpaths [fooPath]] (msgLast <> wpaths [fooPath]) Conn.ClientClosed (askedOnly ["QueryValidPaths NoSubstitute"]),+      scriptTest "an untrusted client's settings apply as far as upstream's daemon lets them, with its warnings in the settings' order" $ \fx ->+        let overrides =+              [ ("substituters", "https://trusted.example.org https://evil.example.org " <> TE.encodeUtf8 daemonSubstituter),+                ("plugin-files", "/x.so"),+                ("keep-going", "true"),+                ("build-poll-interval", "3"),+                ("ssh-auth-sock", "/tmp/agent"),+                ("experimental-features", "nix-command")+              ]+            warnings =+              msgNext "warning: ignoring the client-specified setting 'keep-going', because it is a restricted setting and you are not a trusted user\n"+                <> msgNext "warning: Ignoring the client-specified plugin-files.\nThe client specifying plugins to the daemon never made sense, and was removed in Nix >=2.14.\n"+                <> msgNext "warning: ignoring untrusted substituter 'https://evil.example.org', you are not a trusted user.\nRun `man nix.conf` for more information on the `substituters` configuration option.\n"+         in assertSession+              Proto.NotTrusted+              38+              (startingStore fx)+              [setOptionsAt 3 overrides, reqPath 1 fooPath]+              (warnings <> msgLast <> msgLast <> le64 1)+              Conn.ClientClosed+              ( \after -> case fakeSettings after of+                  Nothing -> Fail "the store saw no settings"+                  Just settings ->+                    assertEqual "substituters" [trustedSubstituter, daemonSubstituter] (ncSubstituters (Ops.connConfig settings))+                      `andThen` assertEqual "keep-failed" True (ncKeepFailed (Ops.connConfig settings))+                      `andThen` assertEqual "fallback" True (ncFallback (Ops.connConfig settings))+                      `andThen` assertEqual "cores" (Just 4) (ncCores (Ops.connConfig settings))+                      `andThen` assertEqual "verbosity" (Proto.Verbosity 3) (Ops.connVerbosity settings)+              )+              `andThen` assertSession Proto.NotTrusted 38 (startingStore fx) [setOptionsAt 0 [("keep-going", "true")]] msgLast Conn.ClientClosed (const Pass),+      scriptTest "a trusted client's settings apply as a nix.conf's lines would, a value refused warned of as upstream warns of it" $ \fx ->+        assertSession+          Proto.Trusted+          38+          (startingStore fx)+          [setOptionsAt 3 [("fallback", "maybe"), ("substituters", "https://any.example.org"), ("max-jobs", "8")], reqPath 1 fooPath]+          (msgNext "warning: Boolean setting 'fallback' has invalid value 'maybe'" <> msgLast <> msgLast <> le64 1)+          Conn.ClientClosed+          ( \after -> case fakeSettings after of+              Nothing -> Fail "the store saw no settings"+              Just settings ->+                assertEqual "substituters" ["https://any.example.org"] (ncSubstituters (Ops.connConfig settings))+                  `andThen` assertEqual "fallback" True (ncFallback (Ops.connConfig settings))+          ),+      scriptTest "a NAR that cannot be written closes the connection, its error following the end of the work" $ \fx ->+        assertSession+          Proto.Trusted+          38+          (startingStore fx)+          [reqPath 38 missingPath, reqPath 1 fooPath]+          (msgLast <> "partial" <> msgError "path '/nix/store/00000000000000000000000000000005-missing' is not valid" <> msgError "path '/nix/store/00000000000000000000000000000005-missing' is not valid")+          (Conn.ClosedOnError (notValid missingPath))+          (askedOnly ["NarFromPath missing"]),+      runTest "a handshake that opens with another word is refused with nothing sent" $+        let (ended, written, _) = runScript serverConfig Proto.Trusted emptyFake [le64 serverMagicWord]+         in assertEqual "end" (Conn.HandshakeFailed "protocol mismatch") ended `andThen` assertEqual "written" "" written,+      runTest "a client older than 1.18 is refused once the versions are exchanged, and sent nothing more" $+        let (ended, written, _) = runScript serverConfig Proto.Trusted emptyFake [clientHello 17, reqPath 1 fooPath]+         in assertEqual "end" (Conn.HandshakeFailed "the Nix client version is too old") ended `andThen` assertEqual "written" (le64 serverMagicWord <> le64 0x126) written,+      scriptTest "a client newer than the daemon is served at the daemon's version, and one below 1.38 exchanges no features" $ \fx ->+        assertSession Proto.Trusted 40 (startingStore fx) [reqPath 1 fooPath] (msgLast <> le64 1) Conn.ClientClosed (const Pass)+          `andThen` assertSession Proto.NotTrusted 37 (startingStore fx) [reqPath 1 fooPath] (msgLast <> le64 1) Conn.ClientClosed (const Pass),+      runTestM "however a client's bytes are split into reads, the daemon writes the same bytes, and each reply reads back as what the store answered" $+        codecProperty $+          QC.forAll genQuerySession $ \(known, queries) ->+            let input = clientHello 38 <> foldMap queryBytes queries+                fake = Fake known [] [] Nothing+                (_, whole, _) = runScript serverConfig Proto.Trusted fake [input]+                hello = serverHello 38 Proto.Trusted+             in QC.forAll (genSplit input) $ \pieces ->+                  let (_, split, _) = runScript serverConfig Proto.Trusted fake pieces+                   in QC.conjoin+                        [ split QC.=== whole,+                          BS.take (BS.length hello) whole QC.=== hello,+                          decodeWhole (traverse replyReader queries) (BS.drop (BS.length hello) whole) QC.=== Right (map (answerFrom known) queries)+                        ]+    ]++-- | No paths at all.+emptyFake :: Fake+emptyFake = Fake Map.empty [] [] Nothing++-- | A query the property sends, and the answers it reads back.+data Query+  = AskValid !StorePath+  | AskInfo !StorePath+  | AskValidAmong !(Set.Set StorePath)+  | AskReferrers !StorePath+  | AskAll+  deriving (Show)++data Answer+  = Valid !Bool+  | Info !(Maybe Proto.UnkeyedValidPathInfo)+  | Paths !(Set.Set StorePath)+  deriving (Eq, Show)++-- | A store of up to four paths, some referring to others, and queries+-- about them and about paths it does not hold.+genQuerySession :: QC.Gen (Map.Map StorePath Proto.UnkeyedValidPathInfo, [Query])+genQuerySession = do+  paths <- QC.resize 4 (QC.listOf genWireStorePath)+  infos <- traverse (\_ -> withReferences paths =<< genPathInfo) paths+  let known = Map.fromList (zip paths infos)+      anyPath = QC.oneof (genWireStorePath : [QC.elements paths | not (null paths)])+  queries <-+    QC.resize 8 . QC.listOf $+      QC.oneof+        [ AskValid <$> anyPath,+          AskInfo <$> anyPath,+          AskValidAmong . Set.fromList <$> QC.resize 3 (QC.listOf anyPath),+          AskReferrers <$> anyPath,+          pure AskAll+        ]+  pure (known, queries)+  where+    withReferences paths info = (\refs -> info {Proto.upiReferences = Set.fromList refs}) <$> QC.sublistOf paths++-- | A query as a client sends it.+queryBytes :: Query -> BS.ByteString+queryBytes = \case+  AskValid path -> reqPath 1 path+  AskInfo path -> reqPath 26 path+  AskValidAmong paths -> le64 31 <> wpaths (Set.toList paths) <> le64 0+  AskReferrers path -> reqPath 6 path+  AskAll -> le64 23++-- | What the scripts' store answers a query, from its paths alone.+answerFrom :: Map.Map StorePath Proto.UnkeyedValidPathInfo -> Query -> Answer+answerFrom known = \case+  AskValid path -> Valid (Map.member path known)+  AskInfo path -> Info (Map.lookup path known)+  AskValidAmong paths -> Paths (Set.filter (`Map.member` known) paths)+  AskReferrers path -> Paths (Map.keysSet (Map.filter (Set.member path . Proto.upiReferences) known))+  AskAll -> Paths (Map.keysSet known)++-- | A query's reply as the protocol's own readers read it: the end of+-- the work, then the answer.+replyReader :: Query -> Wire.Decoder Answer+replyReader query =+  Proto.getStderrMessage replyVersion >>= \case+    Proto.StderrLast -> case query of+      AskValid _ -> Valid <$> Wire.getBool+      AskInfo _ -> Wire.getBool >>= \valid -> Info <$> if valid then Just <$> Proto.getUnkeyedValidPathInfo defaultStoreDir replyVersion else pure Nothing+      AskValidAmong _ -> Paths <$> Proto.getStorePathSet defaultStoreDir+      AskReferrers _ -> Paths <$> Proto.getStorePathSet defaultStoreDir+      AskAll -> Paths <$> Proto.getStorePathSet defaultStoreDir+    other -> Wire.malformed ("expected the end of the work, got " <> T.pack (show other))+  where+    replyVersion = Proto.Version Proto.latestVersionNumber (Set.fromList (map Proto.Feature serverFeatures))++-- | Upstream's handshake fixture is what its daemon writes when it and its+-- client both offer 1.10, and what this daemon writes offering 1.10, as it+-- then refuses a client below the oldest it serves.+alsoWrittenByTheDaemon :: (FilePath, BS.ByteString -> TestResult) -> (FilePath, BS.ByteString -> TestResult)+alsoWrittenByTheDaemon (file, check) = (file, \bytes -> check bytes `andThen` daemonWrites bytes)+  where+    daemonWrites bytes =+      let (ended, written, _) = runScript (serverConfigAt (Proto.Version (Proto.VersionNumber 1 10) Set.empty)) Proto.Trusted emptyFake [le64 clientMagicWord <> le64 0x10a]+       in assertEqual "the daemon's handshake" bytes written `andThen` assertEqual "end" (Conn.HandshakeFailed "the Nix client version is too old") ended++-- ---------------------------------------------------------------------------+-- Tests: who may connect+-- ---------------------------------------------------------------------------++-- | A user database with two users, three groups, and a directory that+-- counts @alice@ in @staff@ though the group lists no one.+fakeUsers :: Auth.UserDatabase Identity+fakeUsers =+  Auth.UserDatabase+    { Auth.udUserName = \uid -> pure (Map.lookup uid (Map.fromList [(1000, "alice"), (1001, "bob")])),+      Auth.udGroupName = \gid -> pure (Map.lookup gid (Map.fromList [(100, "users"), (200, "wheel"), (300, "staff")])),+      Auth.udGroup = \name -> pure (Map.lookup name (Map.fromList [("users", Auth.GroupEntry 100 []), ("wheel", Auth.GroupEntry 200 ["bob"]), ("staff", Auth.GroupEntry 300 [])])),+      Auth.udMembership = \uid gid -> pure (if (uid, gid) == (1000, 300) then Just True else Nothing)+    }++-- | Upstream's refusal of a user.+notAllowed :: Text -> Auth.Admission+notAllowed user = Auth.Refused ("user '" <> user <> "' is not allowed to connect to the Nix daemon")++-- | Admission decided as upstream's daemon decides it, over a user+-- database of the test's own.+testDaemonAuth :: IO [Bool]+testDaemonAuth = do+  putStrLn "daemon/auth"+  sequence+    [ runTest "a peer is trusted and admitted as trusted-users and allowed-users name it, by user, group or everyone" $+        let admit trusted allowed buildGroup peer = runIdentity (Auth.admitPeer fakeUsers (Auth.AuthSettings trusted allowed buildGroup) peer)+            alice = Auth.Peer (Just 7) (Just 1000) (Just 100)+            bob = Auth.Peer Nothing (Just 1001) (Just 100)+         in assertEqual "allowed" (Auth.Admitted Proto.NotTrusted (Just "alice")) (admit ["root"] ["*"] "" alice)+              `andThen` assertEqual "by name" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["alice"] [] "" alice)+              `andThen` assertEqual "everyone" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["*"] [] "" alice)+              `andThen` assertEqual "a group's member list" (Auth.Admitted Proto.Trusted (Just "bob")) (admit ["@wheel"] [] "" bob)+              `andThen` assertEqual "the peer's own group" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["@users"] [] "" alice)+              `andThen` assertEqual "the directory's membership" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["@staff"] [] "" alice)+              `andThen` assertEqual "no such group, not named" (notAllowed "alice") (admit ["@nosuch"] ["bob"] "" alice)+              `andThen` assertEqual "a trusted user always may" (Auth.Admitted Proto.Trusted (Just "bob")) (admit ["bob"] [] "" bob)+              `andThen` assertEqual "a user with no entry is its number" (Auth.Admitted Proto.NotTrusted (Just "4242")) (admit [] ["4242"] "" (Auth.Peer Nothing (Just 4242) (Just 4243)))+              `andThen` assertEqual "a peer with no user" (Auth.Admitted Proto.NotTrusted Nothing) (admit [] ["*"] "" Auth.unknownPeer)+              `andThen` assertEqual "a peer with no user, not allowed" (notAllowed "<unknown>") (admit [] ["alice"] "" Auth.unknownPeer)+              `andThen` assertEqual "the build users' group, trusted or not" (notAllowed "alice") (admit ["*"] ["*"] "users" alice),+      runTest "a Windows account is trusted and admitted by SID: its user's, or a group's its token holds, named by SID or by a name the system resolves, or everyone" $+        case traverse sidFromText ["S-1-5-21-1-2-3-1000", "S-1-5-21-1-2-3-1001", "S-1-5-21-1-2-3-3000", "S-1-5-32-545", "S-1-5-21-1-2-3-2000"] of+          Just [alice, bob, unnamed, users, builders] ->+            let userNames = [("alice", alice), ("HOST\\alice", alice), ("bob", bob)]+                groupNames = [("Users", users), ("nixbld", builders)]+                accounts = windowsAccounts userNames groupNames [(alice, [users]), (bob, [builders])]+                admit trusted allowed buildGroup peer = runIdentity (Auth.admitAccount accounts (Auth.AuthSettings trusted allowed buildGroup) peer)+                asAlice = Auth.AccountPeer (Just 7) alice [users]+             in assertEqual "allowed" (Auth.Admitted Proto.NotTrusted (Just "alice")) (admit ["root"] ["*"] "" asAlice)+                  `andThen` assertEqual "by name" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["alice"] [] "" asAlice)+                  `andThen` assertEqual "by domain and name" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["HOST\\alice"] [] "" asAlice)+                  `andThen` assertEqual "by SID" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["S-1-5-21-1-2-3-1000"] [] "" asAlice)+                  `andThen` assertEqual "everyone" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["*"] [] "" asAlice)+                  `andThen` assertEqual "a group the token holds, by SID" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["@S-1-5-32-545"] [] "" asAlice)+                  `andThen` assertEqual "a group the token holds, by name" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["@Users"] [] "" asAlice)+                  `andThen` assertEqual "a group the token does not hold" (Auth.Admitted Proto.NotTrusted (Just "alice")) (admit ["@nixbld"] ["*"] "" asAlice)+                  `andThen` assertEqual "a group's SID names no user" (notAllowed "alice") (admit ["S-1-5-32-545"] [] "" asAlice)+                  `andThen` assertEqual "a group's name is no user's" (Auth.Admitted Proto.NotTrusted (Just "alice")) (admit ["Users"] ["*"] "" asAlice)+                  `andThen` assertEqual "another user" (notAllowed "alice") (admit ["bob"] ["@nosuch"] "" asAlice)+                  `andThen` assertEqual "an account with no name is its SID" (Auth.Admitted Proto.NotTrusted (Just "S-1-5-21-1-2-3-3000")) (admit [] ["*"] "" (Auth.AccountPeer Nothing unnamed []))+                  `andThen` assertEqual "the build users' group, by the account's groups, whatever the token shows" (notAllowed "bob") (admit ["*"] ["*"] "nixbld" (Auth.AccountPeer Nothing bob []))+                  `andThen` assertEqual "the build users' group, trusted or not" (notAllowed "bob") (admit ["*"] ["*"] "nixbld" (Auth.AccountPeer Nothing bob [builders]))+                  `andThen` assertEqual "a group the token shows is not the account's" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["*"] [] "nixbld" (Auth.AccountPeer (Just 7) alice [builders]))+                  `andThen` assertEqual "the build users' group, not held" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["*"] [] "nixbld" asAlice)+                  `andThen` assertEqual "a build users' group no account has holds no one" (Auth.Admitted Proto.Trusted (Just "alice")) (admit ["*"] [] "nosuchgroup" asAlice)+          _ -> Fail "the tests' SIDs do not read as SIDs",+      runTest "a client the daemon cannot place in the build users' group is refused, and an entry it cannot look up only withholds trust" $+        case traverse sidFromText ["S-1-5-21-1-2-3-1000", "S-1-5-32-545", "S-1-5-21-1-2-3-2000"] of+          Just [alice, users, builders] ->+            let healthy = windowsAccounts [("alice", alice)] [("Users", users), ("nixbld", builders)] [(alice, [users])]+                groupsFail = healthy {Auth.adAccountGroups = const (pure (Left "the groups cannot be read"))}+                groupLookupFails = healthy {Auth.adAccountSid = \kind name -> if kind == Auth.GroupAccount && name == "nixbld" then pure (Left "the lookup failed") else Auth.adAccountSid healthy kind name}+                entryLookupFails = healthy {Auth.adAccountSid = \kind name -> if kind == Auth.UserAccount && name == "carol" then pure (Left "the lookup failed") else Auth.adAccountSid healthy kind name}+                admit db trusted buildGroup = runIdentity (Auth.admitAccount db (Auth.AuthSettings trusted ["*"] buildGroup) (Auth.AccountPeer (Just 7) alice [users]))+             in assertEqual "healthy" (Auth.Admitted Proto.NotTrusted (Just "alice")) (admit healthy [] "nixbld")+                  `andThen` assertEqual "the account's groups cannot be read" (Auth.Refused "user 'alice' is not allowed to connect to the Nix daemon: cannot tell the groups of the account: the groups cannot be read") (admit groupsFail [] "nixbld")+                  `andThen` assertEqual "the group cannot be looked up" (Auth.Refused "user 'alice' is not allowed to connect to the Nix daemon: cannot look up build-users-group 'nixbld': the lookup failed") (admit groupLookupFails [] "nixbld")+                  `andThen` assertEqual "no build users' group, no question" (Auth.Admitted Proto.NotTrusted (Just "alice")) (admit groupsFail [] "")+                  `andThen` assertEqual "a trusted-users entry that cannot be looked up trusts no one" (Auth.Admitted Proto.NotTrusted (Just "alice")) (admit entryLookupFails ["carol"] "")+          _ -> Fail "the tests' SIDs do not read as SIDs",+      runTest "a service's SID is derived from its name as Windows derives it" $+        assertEqual "TrustedInstaller" (sidFromText "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464") (Just (serviceSid "TrustedInstaller"))+          `andThen` assertEqual "ALG" (sidFromText "S-1-5-80-2387347252-3645287876-2469496166-3824418187-3586569773") (Just (serviceSid "ALG"))+          `andThen` assertEqual "nova-nix" (sidFromText "S-1-5-80-3559003300-525236055-3252912499-3879747958-1619201019") (Just novaNixServiceSid)+          `andThen` assertEqual "the name's case does not matter" (serviceSid "Nova-Nix") (serviceSid "NOVA-NIX"),+      runTest "a client trusts a pipe its own account, SYSTEM, Administrators or the nova-nix service owns, and no other account" $+        case traverse sidFromText [clientSid, otherUserSid, "S-1-5-18", "S-1-5-19", "S-1-5-20", "S-1-5-32-544", "S-1-5-32-545", "S-1-1-0", "S-1-5-11", "S-1-5-80-0", "S-1-5-80-1-2", trustedInstallerSid] of+          Just [client, other, system, localService, networkService, administrators, users, everyone, authenticated, allServices, shortService, trustedInstaller] ->+            let trusts = Auth.trustsPipeOwner client+             in assertEqual "its own account" True (trusts client)+                  `andThen` assertEqual "SYSTEM" True (trusts system)+                  `andThen` assertEqual "Administrators, the owner of what an elevated administrator makes" True (trusts administrators)+                  `andThen` assertEqual "the nova-nix service" True (trusts novaNixServiceSid)+                  `andThen` assertEqual "LOCAL SERVICE, which other services share" False (trusts localService)+                  `andThen` assertEqual "NETWORK SERVICE, which other services share" False (trusts networkService)+                  `andThen` assertEqual "another service's SID" False (trusts trustedInstaller)+                  `andThen` assertEqual "another user, an administrator that is not elevated among them, whose pipes it owns as itself" False (trusts other)+                  `andThen` assertEqual "the Users group" False (trusts users)+                  `andThen` assertEqual "Everyone" False (trusts everyone)+                  `andThen` assertEqual "Authenticated Users" False (trusts authenticated)+                  `andThen` assertEqual "ALL SERVICES, a group every service's token holds" False (trusts allServices)+                  `andThen` assertEqual "a SID that only starts as a service's does" False (trusts shortService)+                  `andThen` assertEqual "any other client trusts its own account too" True (Auth.trustsPipeOwner other other)+          _ -> Fail "the tests' SIDs do not read as SIDs",+      runTestM "a client trusts a pipe's owner exactly when it is its own account, among the accounts of users" $+        codecProperty $+          QC.forAll genUserSidText $ \(clientText, ownerText) ->+            case (sidFromText clientText, sidFromText ownerText) of+              (Just client, Just owner) -> Auth.trustsPipeOwner client owner QC.=== (client == owner) QC..&&. Auth.trustsPipeOwner client client QC.=== True+              _ -> QC.counterexample "a generated SID does not read as one" False,+      runTestM "a service's SID reads as a SID of five subauthorities after S-1-5-80, whatever its name" $+        codecProperty $+          QC.forAll (QC.listOf1 (QC.elements (['A' .. 'Z'] <> ['a' .. 'z'] <> ['0' .. '9'] <> "-_"))) $ \name ->+            case T.splitOn "-" (sidText (serviceSid (T.pack name))) of+              "S" : "1" : "5" : "80" : rest -> QC.counterexample (show rest) (length rest == 5)+              other -> QC.counterexample (show other) False,+      runTest "an admitted connection is logged as upstream's daemon logs it" $+        assertEqual "trusted" "accepted connection from pid 7, user alice (trusted)" (Auth.acceptedMessage (Just 7) (Auth.Admitted Proto.Trusted (Just "alice")))+          `andThen` assertEqual "not trusted, nothing known" "accepted connection from pid <unknown>, user <unknown>" (Auth.acceptedMessage Nothing (Auth.Admitted Proto.NotTrusted Nothing))+    ]++-- | The SIDs of the client in the pipe-owner tests and of another user,+-- and a service's SID, as Windows writes the one of TrustedInstaller.+clientSid, otherUserSid, trustedInstallerSid :: Text+clientSid = "S-1-5-21-1-2-3-1000"+otherUserSid = "S-1-5-21-1-2-3-1001"+trustedInstallerSid = "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464"++-- | Windows' accounts as a test supplies them: the users and the groups+-- by name, and the groups each account belongs to.  A name with no account+-- is found to have none, and an account with no entry has no groups.+windowsAccounts :: [(BS.ByteString, Sid)] -> [(BS.ByteString, Sid)] -> [(Sid, [Sid])] -> Auth.AccountDatabase Identity+windowsAccounts users groups memberships =+  Auth.AccountDatabase+    { Auth.adAccountSid = \kind name -> pure (Right (lookup name (case kind of Auth.UserAccount -> users; Auth.GroupAccount -> groups))),+      Auth.adAccountName = \sid -> pure (lookup sid [(named, spelled) | (spelled, named) <- users <> groups]),+      Auth.adAccountGroups = \sid -> pure (Right (fromMaybe [] (lookup sid memberships)))+    }++-- | Two SIDs of the accounts of users, a machine's or a domain's, which+-- Windows numbers @S-1-5-21@, three subauthorities that name the machine+-- or domain, and the account's RID.  Drawn from a few values, so a pair is+-- often equal as well as different.+genUserSidText :: QC.Gen (Text, Text)+genUserSidText = (,) <$> userSid <*> userSid+  where+    userSid = (\machine rid -> "S-1-5-21-" <> T.pack (show machine) <> "-2-3-" <> T.pack (show rid)) <$> few <*> few+    few = QC.elements [1, 2, 1000, 1001 :: Word32]++-- ---------------------------------------------------------------------------+-- Tests: the daemon on a socket+-- ---------------------------------------------------------------------------++-- | How long a socket test may take before it fails: well past what any+-- of them takes, so only a daemon that stopped answering reaches it.+socketTestMicros :: Int+socketTestMicros = 60 * 1000 * 1000++-- | A store of its own in a directory of its own, served as a daemon+-- serves one, holding 'fooPath', valid, and a logger keeping what is+-- logged, which the test is given in order; the directory is removed+-- after.+withServedStore :: (FilePath -> Store -> ServedStore -> Logger -> IO [Text] -> IO TestResult) -> IO TestResult+withServedStore body = do+  tmp <- Dir.getTemporaryDirectory+  let root = tmp </> "nn-daemon"+  forceRemoveIfExists root+  Dir.createDirectoryIfMissing True (root </> "store")+  logged <- newIORef []+  let logger = plainLogger (\_ message -> atomicModifyIORef' logged (\messages -> (message : messages, ()))) (const (pure ()))+  result <- bracket (openStore logger (StoreDir (root </> "store"))) closeStore $ \store -> do+    registerPath (stDB store) (PathRegistration fooPath (Hash.formatNixHash (Hash.hashBytes (narOf fooPath))) (BS.length (narOf fooPath)) Nothing [] NotUltimate Set.empty Nothing RegisteredNow)+    served <- newServedStore testDefaults store+    body root store served logger (reverse <$> readIORef logged)+  forceRemoveIfExists root+  pure result++-- | The scripts' daemon configuration, for a store a test serves.+servedConfig :: NixConfig -> Conn.ServerConfig+servedConfig config = serverConfig {Conn.scConfig = config}++-- | A daemon serving a store of its own, on a socket beside it or on+-- Windows a pipe of its own ("DaemonLink"), on a thread stopped once the+-- test is done, with what it logged.  The test is given the directory the+-- store keeps its files in and the address the daemon listens at.  A+-- daemon that does not stop is a failure, as a stop that waits forever+-- would otherwise hang the suite.+withSocketDaemon :: Listen.TrustOverride -> (NixConfig -> NixConfig) -> (StoreDir -> BS.ByteString -> IO [Text] -> IO TestResult) -> IO TestResult+withSocketDaemon trust configure body =+  withServedStore $ \root store served logger logged -> do+    let config = configure defaultNixConfig+    auth <- Listen.authSettingsFor config+    daemonAddress root >>= \case+      Nothing -> pure (Fail "the socket path has no spelling as bytes")+      Just address ->+        Listen.openListener address >>= \case+          Left refusal -> pure (Fail refusal)+          Right listener -> do+            stopped <- newEmptyMVar+            let options = Listen.DaemonOptions trust auth (serveLocal served (servedConfig config))+            thread <- forkFinally (Listen.serveListener logger options listener) (\_ -> putMVar stopped ())+            ran <- timeout socketTestMicros (body (stDir store) address logged) `onException` stop thread stopped listener+            stoppedInTime <- stop thread stopped listener+            pure $ case (ran, stoppedInTime) of+              (Nothing, _) -> Fail "the daemon stopped answering"+              (_, Nothing) -> Fail "the daemon did not stop"+              (Just result, Just ()) -> result+  where+    stop thread stopped listener = timeout socketTestMicros (killThread thread >> takeMVar stopped) <* Listen.closeListener listener++-- | A transport over a client's input, given in chunks, and what the+-- daemon wrote to it.+memoryTransport :: [BS.ByteString] -> IO (Conn.Transport IO, IO BS.ByteString)+memoryTransport input = do+  pending <- newIORef (filter (not . BS.null) input)+  written <- newIORef []+  let receive = atomicModifyIORef' pending (\case [] -> ([], Nothing); chunk : rest -> (rest, Just chunk))+      send bytes = atomicModifyIORef' written (\chunks -> (builtBytes bytes : chunks, ()))+  pure (Conn.Transport receive send, BS.concat . reverse <$> readIORef written)++-- | Send bytes, and read back as many as are expected, or what the+-- daemon wrote before it closed the connection.+exchange :: DaemonLink -> BS.ByteString -> Int -> IO BS.ByteString+exchange link request count = linkSend link request >> receiveCount link count++receiveCount :: DaemonLink -> Int -> IO BS.ByteString+receiveCount link count = go [] 0+  where+    go chunks got+      | got >= count = pure (BS.concat (reverse chunks))+      | otherwise =+          linkReceive link (count - got) >>= \chunk ->+            if BS.null chunk then pure (BS.concat (reverse chunks)) else go (chunk : chunks) (got + BS.length chunk)++-- | Everything the daemon writes until it closes the connection.+receiveToEnd :: DaemonLink -> IO BS.ByteString+receiveToEnd link = go []+  where+    go chunks =+      linkReceive link receiveSize >>= \chunk ->+        if BS.null chunk then pure (BS.concat (reverse chunks)) else go (chunk : chunks)+    receiveSize = 4096++-- | A client's opening, and what the daemon answers it with.+helloOver :: DaemonLink -> Proto.Trust -> IO TestResult+helloOver link trust =+  assertEqual "handshake" (serverHello 38 trust) <$> exchange link (clientHello 38) (BS.length (serverHello 38 trust))++-- | The daemon's socket tests, which on Windows run over its pipe: a+-- client served over it, two at once, an untrusted one refused what it+-- may not ask, and one refused outright.+testDaemonSocketIO :: IO [Bool]+testDaemonSocketIO = do+  putStrLn "daemon/socket"+  sequence+    [ runTestM "a client is served over a socket every user may write, or a pipe Users may read and write, its paths' info read from the store" $+        withSocketDaemon Listen.DefaultTrust (\config -> config {ncTrustedUsers = ["*"]}) $ \_ address logged ->+          bracket (connectDaemon address) linkClose $ \link -> do+            hello <- helloOver link Proto.Trusted+            valid <- exchange link (reqPath 1 fooPath <> reqPath 1 missingPath) (2 * BS.length (msgLast <> le64 1))+            info <- exchange link (reqPath 26 fooPath) infoReplySize+            messages <- logged+            open <- listenerOpenToUsers address+            pure $+              open+                `andThen` hello+                `andThen` assertEqual "valid" (msgLast <> le64 1 <> msgLast <> le64 0) valid+                `andThen` assertEqual+                  "info"+                  (Right (Just (fromIntegral (BS.length (narOf fooPath)), False, Proto.narHashFromDigest (sha256Digest (narOf fooPath)))))+                  (fmap (\i -> (Proto.upiNarSize i, Proto.upiUltimate i, Just (Proto.upiNarHash i))) <$> decodeWhole pathInfoReply info)+                `andThen` assertEqual "logged" [True] (map (\message -> "accepted connection from pid " `T.isPrefixOf` message && " (trusted)" `T.isSuffixOf` message) messages),+      runTestM "two clients are served at once, one shown the temporary root the other holds" $+        withSocketDaemon Listen.DefaultTrust (\config -> config {ncTrustedUsers = ["*"]}) $ \_ address _ ->+          bracket (connectDaemon address) linkClose $ \first -> do+            firstHello <- helloOver first Proto.Trusted+            rooted <- exchange first (reqPath 11 fooPath) (BS.length (msgLast <> le64 1))+            bracket (connectDaemon address) linkClose $ \second -> do+              secondHello <- helloOver second Proto.Trusted+              shown <- exchange second (le64 14) (BS.length (rootsHeldBy 0))+              firstValid <- exchange first (reqPath 1 fooPath) (BS.length (msgLast <> le64 1))+              pure $+                firstHello+                  `andThen` assertEqual "rooted" (msgLast <> le64 1) rooted+                  `andThen` secondHello+                  `andThen` assertEqual "the first's root, shown to the second" (rootsHeldBy 0) shown+                  `andThen` assertEqual "the first, served after the second" (msgLast <> le64 1) firstValid,+      runTestM "a connection's temporary roots go with it, and a client the daemon does not trust is not told who holds one" $+        withServedStore $ \_ _ served _ _ -> do+          let serveOne trust input = do+                (transport, written) <- memoryTransport input+                ended <- serveLocal served (servedConfig defaultNixConfig) trust transport+                (,) ended <$> written+          first <- serveOne Proto.Trusted [clientHello 38, reqPath 11 fooPath, le64 14]+          second <- serveOne Proto.NotTrusted [clientHello 38, le64 14]+          pure $+            assertEqual "first" (Conn.ClientClosed, serverHello 38 Proto.Trusted <> msgLast <> le64 1 <> rootsHeldBy 0) first+              `andThen` assertEqual "second" (Conn.ClientClosed, serverHello 38 Proto.NotTrusted <> rootsWithNone) second,+      runTestM "a client trusted-users does not name is not trusted, and is refused a repair as upstream's daemon refuses it" $+        withSocketDaemon Listen.DefaultTrust (\config -> config {ncTrustedUsers = []}) $ \_ address logged ->+          bracket (connectDaemon address) linkClose $ \link -> do+            hello <- helloOver link Proto.NotTrusted+            linkSend link (le64 9 <> wstrs [pathOnWire drvPath <> "!out"] <> le64 1)+            refused <- receiveToEnd link+            messages <- logged+            let message = "repairing is not allowed because you are not in 'trusted-users'"+            pure $+              hello+                `andThen` assertEqual "refused" (msgError message <> msgError message) refused+                `andThen` assertEqual "logged" [False] (map (" (trusted)" `T.isSuffixOf`) messages),+      runTestM "a client allowed-users does not name is sent nothing and the connection closed, and the daemon says why" $+        withSocketDaemon Listen.DefaultTrust (\config -> config {ncTrustedUsers = [], ncAllowedUsers = []}) $ \_ address logged ->+          bracket (connectDaemon address) linkClose $ \link -> do+            written <- receiveToEnd link+            messages <- logged+            pure $+              assertEqual "written" "" written+                `andThen` assertEqual+                  "logged"+                  [True]+                  (map (\message -> "error: while processing connection: user '" `T.isPrefixOf` message && "' is not allowed to connect to the Nix daemon" `T.isSuffixOf` message) messages),+      runTestM "a daemon told to trust every client trusts one no setting names, without asking who it is" $+        withSocketDaemon Listen.ForceTrusted (\config -> config {ncTrustedUsers = [], ncAllowedUsers = []}) $ \_ address logged ->+          bracket (connectDaemon address) linkClose $ \link -> do+            hello <- helloOver link Proto.Trusted+            messages <- logged+            pure (hello `andThen` assertEqual "logged" ["accepted connection from pid <unknown>, user <unknown> (trusted)"] messages)+    ]+  where+    -- A path's info, answered: the end of the work, the flag, the info.+    pathInfoReply =+      Proto.getStderrMessage replyVersion >>= \case+        Proto.StderrLast -> Wire.getBool >>= \found -> if found then Just <$> Proto.getUnkeyedValidPathInfo defaultStoreDir replyVersion else pure Nothing+        other -> Wire.malformed ("expected the end of the work, got " <> T.pack (show other))+    replyVersion = Proto.Version Proto.latestVersionNumber (Set.fromList (map Proto.Feature serverFeatures))+    infoReplySize = BS.length (msgLast <> le64 1) + BS.length (winfoSized (narOf fooPath))+    -- A path's info with no deriver, references or signatures: its size+    -- on the wire, whatever its registration time.+    winfoSized nar = wstr "" <> wstr (BS.replicate 64 0x30) <> wpaths [] <> le64 0 <> le64 (fromIntegral (BS.length nar)) <> le64 0 <> wstrs [] <> wstr ""+    rootsHeldBy holder = msgLast <> le64 1 <> wstr ("{temp:" <> BS8.pack (show (holder :: Int)) <> "}") <> wstr (pathOnWire fooPath)+    rootsWithNone = msgLast <> le64 0++-- ---------------------------------------------------------------------------+-- Tests: builds and substitution through the daemon+-- ---------------------------------------------------------------------------++testDaemonBuilds :: IO [Bool]+testDaemonBuilds = do+  putStrLn "daemon/builds"+  basics <-+    sequence+      [ runTest "a build is the activity upstream's derivation goal starts, and a check says it checks" $+          assertEqual+            "activities"+            [ Proto.Activity (Proto.ActivityId 7) (Proto.Verbosity 3) Proto.actBuild ("building '" <> spelled builtDrvPath <> "'") [Proto.FieldString (spelled builtDrvPath), Proto.FieldString "", Proto.FieldInt 1, Proto.FieldInt 1] (Proto.ActivityId 0),+              Proto.Activity (Proto.ActivityId 8) (Proto.Verbosity 3) Proto.actBuild ("checking outputs of '" <> spelled builtDrvPath <> "'") [Proto.FieldString (spelled builtDrvPath), Proto.FieldString "", Proto.FieldInt 1, Proto.FieldInt 1] (Proto.ActivityId 0)+            ]+            [ Ops.storeActivity defaultStoreDir (Proto.ActivityId 7) (Building builtDrvPath),+              Ops.storeActivity defaultStoreDir (Proto.ActivityId 8) (Checking builtDrvPath)+            ],+        runTestM "the activity a store starts reads back from what the daemon sends of it" $+          codecProperty $+            QC.forAll ((,) <$> genActivityStart <*> QC.arbitrary) $ \(start, number) ->+              Ops.activityStart defaultStoreDir (Ops.storeActivity defaultStoreDir (Proto.ActivityId number) start) QC.=== Just start,+        runTest "an upstream daemon's build on a machine, and a repair, read as a build, and an activity of another kind, or that names nothing the store holds, reads as none" $+          let activity text fields kind = Proto.Activity (Proto.ActivityId 3) (Proto.Verbosity 3) kind text fields (Proto.ActivityId 0)+              derivationFields = [Proto.FieldString (spelled builtDrvPath), Proto.FieldString "", Proto.FieldInt 1, Proto.FieldInt 1]+              building text fields = activity text fields Proto.actBuild+              startOf = Ops.activityStart defaultStoreDir+           in assertEqual "on a machine" (Just (Building builtDrvPath)) (startOf (building ("building '" <> spelled builtDrvPath <> "' on 'ssh://builder'") [Proto.FieldString (spelled builtDrvPath), Proto.FieldString "ssh://builder", Proto.FieldInt 1, Proto.FieldInt 1]))+                `andThen` assertEqual "repair" (Just (Building builtDrvPath)) (startOf (building ("repairing outputs of '" <> spelled builtDrvPath <> "'") derivationFields))+                `andThen` assertEqual "check" (Just (Checking builtDrvPath)) (startOf (building ("checking outputs of '" <> spelled builtDrvPath <> "'") derivationFields))+                `andThen` assertEqual "another kind" Nothing (startOf (activity "copying" derivationFields (Proto.ActivityType 100)))+                `andThen` assertEqual "no fields" Nothing (startOf (building "building 'x'" []))+                `andThen` assertEqual "a number first" Nothing (startOf (building "building 'x'" [Proto.FieldInt 1]))+                `andThen` assertEqual "no store path" Nothing (startOf (building "building 'x'" [Proto.FieldString "/not/a/store/path"]))+                `andThen` assertEqual "a path elsewhere" Nothing (startOf (building "building 'x'" [Proto.FieldString (BS8.pack (storePathToFilePath (StoreDir "/elsewhere/store") builtDrvPath))]))+                `andThen` assertEqual "substitution without a cache" Nothing (startOf (activity "" [Proto.FieldString (spelled builtPath)] Proto.actSubstitute))+                `andThen` assertEqual "a cache that is not UTF-8" Nothing (startOf (activity "" [Proto.FieldString (spelled builtPath), Proto.FieldString "\xFF"] Proto.actSubstitute)),+        runTest "a substitution is the activity upstream's substitution goal starts, with no text, naming the path and the cache" $+          assertEqual+            "activity"+            (Proto.Activity (Proto.ActivityId 9) (Proto.Verbosity 0) Proto.actSubstitute "" [Proto.FieldString (spelled builtPath), Proto.FieldString "https://cache.example"] (Proto.ActivityId 0))+            (Ops.storeActivity defaultStoreDir (Proto.ActivityId 9) (Substituting builtPath "https://cache.example")),+        runTest "a connection's download-attempts sets how many times each of its downloads is tried, upstream's number when it sets none" $+          let attempts config = frpAttempts (bcFetchRetry (settingsBuildConfig testDefaults config defaultStoreDir))+           in assertEqual "default" defaultDownloadAttempts (attempts defaultNixConfig)+                `andThen` assertEqual "set" 2 (attempts defaultNixConfig {ncDownloadAttempts = 2}),+        runTest "settings give a build the cores they name, and the machine's count where cores is 0 or nothing sets it" $+          let buildCores cores = bcCores (settingsBuildConfig testDefaults {mdCores = 5} defaultNixConfig {ncCores = cores} defaultStoreDir)+           in assertEqual "unset" 5 (buildCores Nothing)+                `andThen` assertEqual "zero" 5 (buildCores (Just 0))+                `andThen` assertEqual "set" 3 (buildCores (Just 3)),+        runTestM "for any machine count, 0 and nothing give it and a positive count is the build's" $+          codecProperty $ \machine (QC.Positive count) ->+            let buildCores cores = bcCores (settingsBuildConfig testDefaults {mdCores = machine} defaultNixConfig {ncCores = cores} defaultStoreDir)+             in QC.conjoin [buildCores Nothing QC.=== machine, buildCores (Just 0) QC.=== machine, buildCores (Just count) QC.=== count],+        runTest "a client's cores of 0 replaces the daemon's own count, so a build takes the machine's default as upstream's does, and a count it sends is the build's" $+          let current = Ops.ConnectionSettings (Proto.Verbosity 3) defaultNixConfig {ncCores = Just 6} Nothing+              client cores = Ops.ClientSettings False False False (Proto.Verbosity 3) 1 0 True cores True Map.empty+              buildCores cores =+                let (applied, _) = Ops.applyClientSettings Proto.Trusted (client cores) current+                 in bcCores (settingsBuildConfig testDefaults {mdCores = 5} (Ops.connConfig applied) defaultStoreDir)+           in assertEqual "zero" 5 (buildCores Ops.unsetCores)+                `andThen` assertEqual "set" 3 (buildCores 3)+      ]+  shell <- findTestShell+  served <-+    sequence+      [ runTestM "a build through the daemon is an activity the client is sent, its builder's line a result of it, and its output is valid after" $+          withBuildable shell $ \store serve -> do+            (ended, reply) <- serve [le64 9 <> wstrs [pathOnWire builtDrvPath <> "!*"] <> le64 0]+            valid <- isValid store builtPath+            pure $+              assertEqual "ended" Conn.ClientClosed ended+                `andThen` assertEqual "valid" True valid+                `andThen` assertEqual+                  "reported, then answered"+                  (Right ([builtStart, Proto.StderrResult (Proto.ActivityId 1) Proto.resBuildLogLine [Proto.FieldString "hi"], Proto.StderrStopActivity (Proto.ActivityId 1)], True))+                  (decodeWhole (workThenReply Wire.getBool) reply),+        runTestM "a build with results says it was built, and where its output is" $+          withBuildable shell $ \_ serve -> do+            let requested = Proto.DerivedBuilt builtDrvPath Proto.AllOutputs+                outputs = Map.singleton (Proto.OutputName "out") (Proto.UnkeyedRealisation builtPath Set.empty)+            (_, reply) <- serve [le64 46 <> wstrs [pathOnWire builtDrvPath <> "!*"] <> le64 0]+            pure $+              assertEqual+                "results"+                (Right [Proto.KeyedBuildResult requested (Proto.BuildResult (Proto.Succeeded (Proto.Success Proto.Built outputs)) 1 0 0 Nothing Nothing)])+                (snd <$> decodeWhole (workThenReply (Proto.getKeyedBuildResults defaultStoreDir builtVersion)) reply),+        runTestM "what realising a derivation and a path would take: a build of the one, and the other unknown" $+          withBuildable shell $ \_ serve -> do+            (_, reply) <- serve [le64 40 <> wstrs [pathOnWire builtDrvPath <> "!*", pathOnWire missingPath]]+            pure $+              assertEqual+                "missing"+                (Right (Proto.Missing (Set.singleton builtDrvPath) Set.empty (Set.singleton missingPath) 0 0))+                (snd <$> decodeWhole (workThenReply (Proto.getMissing defaultStoreDir)) reply),+        runTestM "a derivation the store does not hold and no cache gives fails its request, in upstream's words" $+          withServedStore $ \_ _ served _ _ -> do+            let message = "failed to obtain derivation of '" <> pathOnWire builtDrvPath <> "'"+                serve request = do+                  (transport, written) <- memoryTransport [clientHello 38, request]+                  _ <- serveLocal served (servedConfig buildableConfig) Proto.Trusted transport+                  BS.drop (BS.length (serverHello 38 Proto.Trusted)) <$> written+            withResults <- serve (le64 46 <> wstrs [pathOnWire builtDrvPath <> "!*"] <> le64 0)+            built <- serve (le64 9 <> wstrs [pathOnWire builtDrvPath <> "!*"] <> le64 0)+            pure $+              assertEqual+                "results"+                (Right [Proto.KeyedBuildResult (Proto.DerivedBuilt builtDrvPath Proto.AllOutputs) (Proto.BuildResult (Proto.Failed (Proto.Failure Proto.DependencyFailed message False)) 0 0 0 Nothing Nothing)])+                (snd <$> decodeWhole (workThenReply (Proto.getKeyedBuildResults defaultStoreDir builtVersion)) withResults)+                `andThen` assertEqual "built" (msgError message) built,+        runTestM "a fixed output with other contents than its derivation fixes is rejected, as upstream reports a hash mismatch" $+          withServedStore $ \_ store served _ _ -> do+            let dir = stDir store+                fixed = (mkTestBuildDrv shell builtPath "printf other > $out") {drvOutputs = [DerivationOutput "out" builtPath "sha256" (T.replicate 64 "0")]}+            holdDerivation (stDB store) dir builtDrvPath fixed+            (transport, written) <- memoryTransport [clientHello 38, le64 46 <> wstrs [pathOnWire builtDrvPath <> "!*"] <> le64 0]+            _ <- serveLocal served (servedConfig buildableConfig) Proto.Trusted transport+            reply <- BS.drop (BS.length (serverHello 38 Proto.Trusted)) <$> written+            pure $ case snd <$> decodeWhole (workThenReply (Proto.getKeyedBuildResults defaultStoreDir builtVersion)) reply of+              Right [Proto.KeyedBuildResult _ (Proto.BuildResult (Proto.Failed (Proto.Failure Proto.OutputRejected message _)) _ _ _ _ _)]+                | "hash mismatch" `BS.isInfixOf` message -> Pass+              other -> Fail ("expected the output rejected for its hash, got " <> T.pack (show other)),+        runTestM "results asked for an output a derivation does not have are refused, as upstream's goal throws" $+          withBuildable shell $ \store serve -> do+            let dir = stDir store+                refusal = Realise.realiseFailureMessage dir (Realise.MissingOutputs builtDrvPath ("absent" :| []))+            (_, reply) <- serve [le64 46 <> wstrs [pathOnWire builtDrvPath <> "!absent"] <> le64 0]+            pure (assertEqual "refused" (msgError (TE.encodeUtf8 refusal)) reply),+        runTestM "a repair is refused before anything is substituted or built" $+          withBuildable shell $ \_ serve -> do+            (_, reply) <- serve [le64 9 <> wstrs [pathOnWire missingPath] <> le64 1]+            pure (assertEqual "refused" (msgError "repairing is not available in nova-nix") reply),+        runTestM "a path no cache holds has no substituter in the results, in upstream's words" $+          withBuildable shell $ \_ serve -> do+            let message = "path '" <> pathOnWire missingPath <> "' is required, but there is no substituter that can build it"+            (_, reply) <- serve [le64 46 <> wstrs [pathOnWire missingPath] <> le64 0]+            pure $+              assertEqual+                "results"+                (Right [Proto.KeyedBuildResult (Proto.DerivedOpaque missingPath) (Proto.BuildResult (Proto.Failed (Proto.Failure Proto.NoSubstituters message False)) 0 0 0 Nothing Nothing)])+                (snd <$> decodeWhole (workThenReply (Proto.getKeyedBuildResults defaultStoreDir builtVersion)) reply),+        -- Every send after the request has been read fails, as one to a+        -- client that went away does: the build's reports are dropped,+        -- and the build still makes its output.+        runTestM "a build whose client can no longer be sent anything still builds" $+          withServedStore $ \_ store served _ _ -> do+            let dir = stDir store+            holdDerivation (stDB store) dir builtDrvPath (mkTestBuildDrv shell builtPath "echo hi; echo built > $out")+            transport <- goneAfterInput [clientHello 38, le64 9 <> wstrs [pathOnWire builtDrvPath <> "!*"] <> le64 0]+            _ <- try (serveLocal served (servedConfig buildableConfig) Proto.Trusted transport) :: IO (Either IOException Conn.ConnectionEnd)+            assertEqual "built" True <$> isValid store builtPath,+        -- The builder says which process it started in the background,+        -- and the test waits for that process to end once it hangs up.+        runTestM "a client that hangs up during a build has the build stopped, and every process its builder started killed" $+          if SI.os == "mingw32"+            then Pass <$ putStrLn "  SKIP  the daemon does not watch a Windows client for its hangup"+            else withSocketDaemon Listen.DefaultTrust (\config -> config {ncTrustedUsers = ["*"], ncSandbox = Just SandboxDisabled, ncSubstituters = []}) $ \dir address _ -> do+              bracket (openStoreDB dir) closeStoreDB $ \db -> holdDerivation db dir builtDrvPath (mkTestBuildDrv shell builtPath "sleep 1000 & echo \"started $!\"; wait")+              bracket (connectDaemon address) linkClose $ \link -> do+                hello <- helloOver link Proto.Trusted+                linkSend link (le64 9 <> wstrs [pathOnWire builtDrvPath <> "!*"] <> le64 0)+                started <- receiveResultLine link startedPrefix+                case BS8.readInt =<< BS.stripPrefix startedPrefix =<< started of+                  Nothing -> pure (Fail ("the builder did not say which process it started: " <> T.pack (show started)))+                  Just (background, _) -> do+                    linkClose link+                    ended <- c_await_exit (fromIntegral background) (fromIntegral killWaitMillis)+                    pure $ case ended of+                      0 -> hello+                      1 -> Fail "a process the builder started outlived the client's hangup"+                      _ -> Fail "the process the builder started could not be watched",+        runTestM+          "a path no cache holds cannot be ensured, in upstream's words, and the connection goes on"+          $ withBuildable shell+          $ \_ serve -> do+            (_, reply) <- serve [reqPath 10 missingPath, reqPath 1 missingPath]+            pure $+              assertEqual+                "refused, then answered"+                (msgError ("path '" <> pathOnWire missingPath <> "' is required, but there is no substituter that can build it") <> msgLast <> le64 0)+                reply,+        runTestM "a path a file:// cache holds is ensured through the daemon, as a substitution activity naming the path and the cache, and is valid after with the cache's NAR hash" $+          withServedStore $ \root _ served _ _ -> do+            let cache = root </> "cache"+                url = directoryUrl cache+            holdInFileCache cache cachedPath >>= \case+              Left err -> pure (Fail ("the cache could not be written: " <> T.pack err))+              Right publicKey -> do+                let config = buildableConfig {ncSubstituters = [url], ncTrustedPublicKeys = [publicKey]}+                    substituted = Proto.Activity (Proto.ActivityId 1) (Proto.Verbosity 0) Proto.actSubstitute "" [Proto.FieldString (pathOnWire cachedPath), Proto.FieldString (TE.encodeUtf8 url)] (Proto.ActivityId 0)+                    infoReply = Wire.getBool >>= \found -> if found then Just . Proto.narHashDigest . Proto.upiNarHash <$> Proto.getUnkeyedValidPathInfo defaultStoreDir builtVersion else pure Nothing+                (transport, written) <- memoryTransport [clientHello 38, reqPath 10 cachedPath, reqPath 26 cachedPath]+                _ <- serveLocal served (servedConfig config) Proto.Trusted transport+                reply <- BS.drop (BS.length (serverHello 38 Proto.Trusted)) <$> written+                pure $+                  assertEqual+                    "substituted, then its info"+                    (Right (([Proto.StderrStartActivity substituted, Proto.StderrStopActivity (Proto.ActivityId 1)], True), ([], Just (sha256Digest (servedNar cachedPath)))))+                    (decodeWhole ((,) <$> workThenReply Wire.getBool <*> workThenReply infoReply) reply),+        -- Upstream's store reads require-sigs as it opens, before a+        -- client's settings arrive, so the daemon's setting holds a+        -- substitution to a signature whatever a trusted client sets.+        runTestM "a trusted client that turns require-sigs off does not have a path substituted that no key the daemon trusts signed" $+          withServedStore $ \root store served _ _ -> do+            let cache = root </> "cache"+                config = buildableConfig {ncSubstituters = [directoryUrl cache]}+                refusal = msgError ("path '" <> pathOnWire cachedPath <> "' is required, but there is no substituter that can build it")+            holdInFileCache cache cachedPath >>= \case+              Left err -> pure (Fail ("the cache could not be written: " <> T.pack err))+              Right _ -> do+                (_, reply) <- serveAdding served config Proto.Trusted [setOptionsAt 3 [("require-sigs", "false")], reqPath 10 cachedPath]+                valid <- isValid store cachedPath+                pure (assertEqual "valid" False valid `andThen` assertEqual "refused" refusal (BS.takeEnd (BS.length refusal) reply)),+        runTestM "a trusted client that turns require-sigs on does not have a path refused that the daemon takes unsigned by any key it trusts" $+          withServedStore $ \root store served _ _ -> do+            let cache = root </> "cache"+                config = buildableConfig {ncSubstituters = [directoryUrl cache], ncRequireSigs = False}+            holdInFileCache cache cachedPath >>= \case+              Left err -> pure (Fail ("the cache could not be written: " <> T.pack err))+              Right _ -> do+                (_, reply) <- serveAdding served config Proto.Trusted [setOptionsAt 3 [("require-sigs", "true")], reqPath 10 cachedPath]+                valid <- isValid store cachedPath+                pure (assertEqual "valid" True valid `andThen` assertEqual "answered" (le64 1) (BS.takeEnd 8 reply))+      ]+  pure (basics ++ served)+  where+    spelled = TE.encodeUtf8 . storePathToText defaultStoreDir+    builtVersion = Proto.Version Proto.latestVersionNumber (Set.fromList (map Proto.Feature serverFeatures))+    builtStart =+      Proto.StderrStartActivity+        (Proto.Activity (Proto.ActivityId 1) (Proto.Verbosity 3) Proto.actBuild ("building '" <> pathOnWire builtDrvPath <> "'") [Proto.FieldString (pathOnWire builtDrvPath), Proto.FieldString "", Proto.FieldInt 1, Proto.FieldInt 1] (Proto.ActivityId 0))+    -- The work's reports other than its lines, then the reply.+    workThenReply reply = go []+      where+        go seen =+          Proto.getStderrMessage builtVersion >>= \case+            Proto.StderrLast -> (,) (reverse seen) <$> reply+            Proto.StderrNext _ -> go seen+            message -> go (message : seen)++-- | Read a daemon's messages from a socket until a build's line that+-- starts with the bytes arrives: that line, or 'Nothing' when the input+-- ends or does not read as messages first.+receiveResultLine :: DaemonLink -> BS.ByteString -> IO (Maybe BS.ByteString)+receiveResultLine link prefix = go BS.empty+  where+    version = Proto.Version Proto.latestVersionNumber (Set.fromList (map Proto.Feature serverFeatures))+    go arrived = case Wire.runDecoder (Proto.getStderrMessage version) arrived of+      Right (Proto.StderrResult _ kind [Proto.FieldString line], _)+        | kind == Proto.resBuildLogLine && prefix `BS.isPrefixOf` line -> pure (Just line)+      Right (_, rest) -> go rest+      Left Wire.InputEnded -> linkReceive link receiveSize >>= \chunk -> if BS.null chunk then pure Nothing else go (arrived <> chunk)+      Left (Wire.Malformed _) -> pure Nothing+    receiveSize = 4096++-- | What the hangup test's builder says before the process it started.+startedPrefix :: BS.ByteString+startedPrefix = "started "++-- | How long a hangup test waits for the process a builder started to be+-- gone, within the time the whole socket test has.+killWaitMillis :: Int+killWaitMillis = socketTestMicros `div` 2000++-- | Wait up to the milliseconds given for a process to end, not only a+-- child ("process_wait.c"): 0 once it has, 1 when it still runs, -1 on+-- failure.+foreign import ccall safe "nova_test_await_exit" c_await_exit :: CInt -> CInt -> IO CInt++-- | Write a derivation into a store and register it, as a client's+-- AddToStore would leave it.+holdDerivation :: StoreDB -> StoreDir -> StorePath -> Derivation -> IO ()+holdDerivation db dir path drv = do+  let aterm = toATerm drv+  BS.writeFile (storePathToFilePath dir path) aterm+  registerPath db (PathRegistration path (Hash.formatNixHash (Hash.hashBytes aterm)) (BS.length aterm) Nothing [] NotUltimate Set.empty Nothing RegisteredNow)++-- | A transport over input given whose sends fail once the last of the+-- input has been read, as they do to a client that went away.+goneAfterInput :: [BS.ByteString] -> IO (Conn.Transport IO)+goneAfterInput input = do+  pending <- newIORef (filter (not . BS.null) input)+  let receive = atomicModifyIORef' pending (\case [] -> ([], Nothing); chunk : rest -> (rest, Just chunk))+      send _ =+        readIORef pending >>= \case+          [] -> ioError (mkIOError resourceVanishedErrorType "the client went away" Nothing Nothing)+          _ -> pure ()+  pure (Conn.Transport receive send)++-- | The settings a daemon test's builds run under: unsandboxed, and with+-- no cache to ask.+buildableConfig :: NixConfig+buildableConfig = defaultNixConfig {ncSandbox = Just SandboxDisabled, ncSubstituters = []}++-- | A served store holding a derivation whose builder, run by the shell+-- given, writes one line, and a way to serve a trusted client at 1.38 that sends requests: how+-- its connection ended and what it was sent after the handshake.  Builds+-- run unsandboxed and nothing is substituted, so the test asks no cache.+withBuildable :: Text -> (Store -> ([BS.ByteString] -> IO (Conn.ConnectionEnd, BS.ByteString)) -> IO TestResult) -> IO TestResult+withBuildable shell body =+  withServedStore $ \_ store served _ _ -> do+    holdDerivation (stDB store) (stDir store) builtDrvPath (mkTestBuildDrv shell builtPath "echo hi; echo built > $out")+    let config = buildableConfig+        serve requests = do+          (transport, written) <- memoryTransport (clientHello 38 : requests)+          ended <- serveLocal served (servedConfig config) Proto.Trusted transport+          (,) ended . BS.drop (BS.length (serverHello 38 Proto.Trusted)) <$> written+    body store serve++-- | The derivation a daemon test builds, and its output.+builtDrvPath, builtPath :: StorePath+builtDrvPath = StorePath "0000000000000000000000000000000b" "built.drv"+builtPath = StorePath "0000000000000000000000000000000c" "built"++-- | The path a daemon test substitutes from a file:// cache.+cachedPath :: StorePath+cachedPath = StorePath "0000000000000000000000000000000d" "cached"++-- | Write a file:// cache holding a path, uncompressed, as the NAR+-- 'servedNar' gives it, with its narinfo signed by 'sigTestKeyText': the+-- public key that verifies it, or why it could not be signed.+holdInFileCache :: FilePath -> StorePath -> IO (Either String Text)+holdInFileCache cache path = case signedTestNarInfo path [] (T.pack narFile) (servedNar path) of+  Left err -> pure (Left err)+  Right (publicKey, narInfo) -> do+    Dir.createDirectoryIfMissing True (cache </> "nar")+    BS.writeFile (cache </> cacheInfoFileName) cacheInfoText+    BS.writeFile (cache </> T.unpack (spHash path) <> ".narinfo") (TE.encodeUtf8 narInfo)+    BS.writeFile (cache </> narFile) (servedNar path)+    pure (Right publicKey)+  where+    narFile = "nar/" <> T.unpack (spName path) <> ".nar"++-- | Machine defaults a served store's builds fall back on, the same on+-- every machine: one core, no sandbox helper or bundled shell, not root,+-- so no build users, and no certificate bundle.+testDefaults :: MachineDefaults+testDefaults =+  MachineDefaults+    { mdCores = 1,+      mdSandboxHelper = Nothing,+      mdSandboxShell = Set.empty,+      mdPrivilege = RunsUnprivileged,+      mdUserPool = "/nix/var/nix/userpool",+      mdCaFile = Nothing+    }++-- ---------------------------------------------------------------------------+-- Tests: adding paths through the daemon+-- ---------------------------------------------------------------------------++-- | Derivations, dumps and NARs a client adds to a served store through+-- the daemon, over a transport in memory, so they run wherever the store+-- does: each is valid after with what it was added with, or refused in+-- upstream's words with nothing left behind.+testDaemonAdds :: IO [Bool]+testDaemonAdds = do+  putStrLn "daemon/adds"+  linked <- symlinksAvailable+  sequence+    [ runTestM "a client the daemon does not trust adds a derivation as a text, and is answered upstream's path for it" $+        withServedStore $ \_ store served _ _ -> case upstreamDrv of+          Left err -> pure (Fail err)+          Right (aterm, drvFile)+            | drvFile /= StorePath "wwk71dy0w17kn5spjd8hbsrk6520xs11" "d.drv" -> pure (Fail ("the derivation's own path is not upstream's: " <> T.pack (show drvFile)))+            | otherwise -> do+                let dir = stDir store+                    expected = addedFrom drvFile (regularNar aterm) [] (textAddress aterm)+                (ended, reply) <- serveAdding served defaultNixConfig Proto.NotTrusted [dumpRequest "d.drv" "text:sha256" [] <> framedIn 7 aterm]+                held <- addedAs store drvFile+                contents <- BS.readFile (storePathToFilePath dir drvFile)+                pure $+                  assertEqual "ended" Conn.ClientClosed ended+                    `andThen` assertEqual "answered" (Right (Right expected)) (decodeWhole (answerOf (answeredAs <$> Proto.getValidPathInfo defaultStoreDir addVersion)) reply)+                    `andThen` assertEqual "registered" (Just expected) held+                    `andThen` assertEqual "contents" aterm contents,+      runTestM "a source tree is added as a recursive dump, arriving in frames that split its archive anywhere, with the paths it references" $+        withServedStore $ \_ store served _ _ -> do+          let dir = stDir store+              nar =+                NAR.serialise+                  ( NAR.NarDirectory+                      [ ("bin", NAR.NarDirectory [("run", NAR.NarRegular True "#!/bin/sh\n")]),+                        ("data", NAR.NarRegular False ("refers to " <> pathOnWire fooPath))+                      ]+                  )+          case makeSourcePath "source" (sha256Digest nar) (Set.singleton fooPath) of+            Left err -> pure (Fail (T.pack (show err)))+            Right sourcePath -> do+              let expected = addedFrom sourcePath nar [fooPath] (Proto.contentAddressFromParts (Proto.FixedMethod NarIngestion) "sha256" (sha256Digest nar))+              (_, reply) <- serveAdding served defaultNixConfig Proto.Trusted [dumpRequest "source" "fixed:r:sha256" [fooPath] <> framedIn 13 nar]+              held <- addedAs store sourcePath+              executable <- ExecBit.isExecutable (storePathToFilePath dir sourcePath </> "bin" </> "run")+              staged <- stagingLeft store+              pure $+                assertEqual "answered" (Right (Right expected)) (decodeWhole (answerOf (answeredAs <$> Proto.getValidPathInfo defaultStoreDir addVersion)) reply)+                  `andThen` assertEqual "registered" (Just expected) held+                  `andThen` assertEqual "executable" True executable+                  `andThen` assertEqual "staging left" [] staged,+      runTestM "a fixed output is added from a flat dump hashed with the algorithm it names" $+        withServedStore $ \_ store served _ _ -> do+          let dir = stDir store+              contents = "hello\n"+          case Hash.rawHashWithAlgo "sha1" contents of+            Nothing -> pure (Fail "no SHA-1")+            Just digest -> case makeFixedOutputPath "hello.txt" "sha1" FlatIngestion digest of+              Left err -> pure (Fail (T.pack (show err)))+              Right flatPath -> do+                let expected = addedFrom flatPath (regularNar contents) [] (Proto.contentAddressFromParts (Proto.FixedMethod FlatIngestion) "sha1" digest)+                (_, reply) <- serveAdding served defaultNixConfig Proto.NotTrusted [dumpRequest "hello.txt" "fixed:sha1" [] <> framedIn 4 contents]+                held <- addedAs store flatPath+                onDisk <- BS.readFile (storePathToFilePath dir flatPath)+                pure $+                  assertEqual "answered" (Right (Right expected)) (decodeWhole (answerOf (answeredAs <$> Proto.getValidPathInfo defaultStoreDir addVersion)) reply)+                    `andThen` assertEqual "registered" (Just expected) held+                    `andThen` assertEqual "contents" contents onDisk,+      runTestM "what a dump's address cannot make is refused in upstream's words, the dump read past, and the connection goes on" $+        withServedStore $ \_ store served _ _ -> do+          (ended, reply) <-+            serveAdding+              served+              defaultNixConfig+              Proto.NotTrusted+              [ dumpRequest "refused" "fixed:sha256" [fooPath] <> framedIn 4 "contents",+                dumpRequest "refused" "text:sha1" [] <> framedIn 4 "contents",+                reqPath 1 fooPath+              ]+          staged <- stagingLeft store+          pure $+            assertEqual "ended" Conn.ClientClosed ended+              `andThen` assertEqual+                "refused, then answered"+                ( msgError "fixed output derivation 'refused' is not allowed to refer to other store paths.\nYou may need to use the 'unsafeDiscardReferences' derivation attribute, see the manual for more details."+                    <> msgError "cannot add 'refused' as a text hashed with sha1: a text's content address is its sha256 hash"+                    <> msgLast+                    <> le64 1+                )+                reply+              `andThen` assertEqual "staging left" [] staged,+      runTestM "a dump whose archive goes on past its end is refused, and nothing is left of it" $+        withServedStore $ \_ store served _ _ -> do+          (_, reply) <- serveAdding served defaultNixConfig Proto.NotTrusted [dumpRequest "trailing" "fixed:r:sha256" [] <> framedIn 16 (regularNar "contents" <> "more")]+          staged <- stagingLeft store+          pure (assertEqual "refused" (msgError "trailing bytes after NAR root node") reply `andThen` assertEqual "staging left" [] staged),+      runTestM "the git-hashing method is refused as upstream refuses it without the experimental feature, before the dump is read" $+        withServedStore $ \_ _ served _ _ -> do+          (_, reply) <- serveAdding served defaultNixConfig Proto.Trusted [dumpRequest "git" "fixed:git:sha1" [], reqPath 1 fooPath]+          pure (assertEqual "refused, then answered" (msgError "experimental Nix feature 'git-hashing' is disabled; add '--extra-experimental-features git-hashing' to enable it" <> msgLast <> le64 1) reply),+      runTestM "a NAR a trusted client sends unchecked is imported with its deriver, references and signatures, and its path is a root of the connection" $+        withServedStore $ \_ store served _ _ -> do+          let dir = stDir store+              nar = regularNar "imported"+          case (narInfoOf nar [fooPath] (Just builtDrvPath), Proto.parseSignature ("other-key:" <> TE.encodeUtf8 (B64.encode (BS.replicate 64 7)))) of+            (Just info, Right sig) -> do+              let sent = info {Proto.upiSignatures = Set.singleton sig, Proto.upiUltimate = True}+              (_, reply) <- serveAdding served defaultNixConfig Proto.Trusted [narRequest importedPath sent NoCheck <> framedIn 9 nar, le64 14]+              held <- addedAs store importedPath+              row <- queryPathInfo (stDB store) importedPath+              pure $+                assertEqual+                  "imported, then the roots"+                  (Right (Right (), Right [(importedPath, ["{temp:0}"])]))+                  (decodeWhole ((,) <$> answerOf (pure ()) <*> answerOf (rootsListed <$> Proto.getRoots defaultStoreDir)) reply)+                  `andThen` assertEqual "registered" (Just (addedFrom importedPath nar [fooPath] Nothing)) held+                  `andThen` assertEqual+                    "deriver, signatures, ultimate"+                    (Just (Just (T.pack (storePathToFilePath dir builtDrvPath)), Set.singleton sig, Ultimate))+                    ((\found -> (piDeriver found, piSignatures found, piUltimate found)) <$> row)+            other -> pure (Fail ("no info to send: " <> T.pack (show other))),+      runTestM "a NAR signed by a key trusted-public-keys names is imported from a client the daemon does not trust, which cannot ask that it not be checked" $+        withServedStore $ \_ store served _ _ -> do+          let nar = regularNar "signed"+          case (narInfoOf nar [fooPath] Nothing, testPublicKey) of+            (Just info, Right publicKey) -> case signedFor signedPath info of+              Left err -> pure (Fail (T.pack err))+              Right sig -> do+                let sent = info {Proto.upiSignatures = Set.singleton sig}+                (_, reply) <- serveAdding served defaultNixConfig {ncTrustedPublicKeys = [publicKey]} Proto.NotTrusted [narRequest signedPath sent NoCheck <> framedIn 64 nar]+                held <- addedAs store signedPath+                row <- queryPathInfo (stDB store) signedPath+                pure $+                  assertEqual "imported" msgLast reply+                    `andThen` assertEqual "registered" (Just (addedFrom signedPath nar [fooPath] Nothing)) held+                    `andThen` assertEqual "signatures" (Just (Set.singleton sig)) (piSignatures <$> row)+            other -> pure (Fail ("no info or key: " <> T.pack (show other))),+      runTestM "an unsigned NAR of a path that is not content-addressed is refused a client the daemon does not trust, in upstream's words, and nothing of it is kept" $+        withServedStore $ \_ store served _ _ -> do+          let dir = stDir store+              nar = regularNar "unsigned"+          case narInfoOf nar [] Nothing of+            Nothing -> pure (Fail "no info to send")+            Just info -> do+              (ended, reply) <- serveAdding served defaultNixConfig Proto.NotTrusted [narRequest unsignedPath info NoCheck <> framedIn 8 nar, le64 14, reqPath 1 unsignedPath]+              written <- Dir.doesPathExist (storePathToFilePath dir unsignedPath)+              staged <- stagingLeft store+              pure $+                assertEqual "ended" Conn.ClientClosed ended+                  `andThen` assertEqual+                    "refused, no root kept for it, and not valid"+                    (msgError ("cannot add path '" <> pathOnWire unsignedPath <> "' because it lacks a signature by a trusted key") <> msgLast <> le64 0 <> msgLast <> le64 0)+                    reply+                  `andThen` assertEqual "written" False written+                  `andThen` assertEqual "staging left" [] staged,+      runTestM "a NAR whose hash or size is not its info's is refused in upstream's words, and nothing of it is kept" $+        withServedStore $ \_ store served _ _ -> do+          let dir = stDir store+              nar = regularNar "mismatch"+              sri bytes = "sha256-" <> TE.encodeUtf8 (B64.encode bytes)+          case (narInfoOf nar [] Nothing, Proto.narHashFromDigest (sha256Digest "not the nar")) of+            (Just info, Just otherHash) -> do+              let wrongHash = info {Proto.upiNarHash = otherHash}+                  wrongSize = info {Proto.upiNarSize = Proto.upiNarSize info + 8}+              (_, reply) <- serveAdding served defaultNixConfig Proto.Trusted [narRequest mismatchPath wrongHash NoCheck <> framedIn 16 nar, narRequest mismatchPath wrongSize NoCheck <> framedIn 16 nar]+              written <- Dir.doesPathExist (storePathToFilePath dir mismatchPath)+              valid <- isValid store mismatchPath+              staged <- stagingLeft store+              let spelled = pathOnWire mismatchPath+              pure $+                assertEqual+                  "refused"+                  ( msgError ("hash mismatch importing path '" <> spelled <> "';\n  specified: " <> sri (sha256Digest "not the nar") <> "\n  got:       " <> sri (sha256Digest nar))+                      <> msgError ("size mismatch importing path '" <> spelled <> "';\n  specified: " <> BS8.pack (show (BS.length nar + 8)) <> "\n  got:       " <> BS8.pack (show (BS.length nar)))+                  )+                  reply+                  `andThen` assertEqual "written, valid" (False, False) (written, valid)+                  `andThen` assertEqual "staging left" [] staged+            other -> pure (Fail ("no info to send: " <> T.pack (show other))),+      -- The daemon reads a NAR to the size its info states, where upstream+      -- reads it to its root node's close and then holds it to that size.+      runTestM "a NAR longer than the size its info states is refused as an archive cut short there, and nothing of it is kept" $+        withServedStore $ \_ store served _ _ -> do+          let dir = stDir store+              nar = regularNar "longer"+          case narInfoOf nar [] Nothing of+            Nothing -> pure (Fail "no info to send")+            Just info -> do+              (ended, reply) <- serveAdding served defaultNixConfig Proto.Trusted [narRequest mismatchPath info {Proto.upiNarSize = Proto.upiNarSize info - 8} NoCheck <> framedIn 16 nar, reqPath 1 mismatchPath]+              written <- Dir.doesPathExist (storePathToFilePath dir mismatchPath)+              staged <- stagingLeft store+              pure $+                assertEqual "ended" Conn.ClientClosed ended+                  `andThen` assertEqual "refused, then not valid" (msgError "unexpected end of NAR: node closing" <> msgLast <> le64 0) reply+                  `andThen` assertEqual "written, staging left" (False, []) (written, staged),+      runTestM "a path already valid is answered as added without its NAR or dump being written, and its registration is kept" $+        withServedStore $ \_ store served _ _ -> do+          let dir = stDir store+              otherNar = regularNar "other contents"+              contents = "flat\n"+          case (narInfoOf otherNar [] Nothing, makeFixedOutputPath "kept" "sha256" FlatIngestion (sha256Digest contents)) of+            (Just info, Right keptPath) -> do+              -- Registered with a NAR that is not its dump's, which the+              -- answer names only if it comes from the registration.+              let registeredNar = regularNar "what was there"+              BS.writeFile (storePathToFilePath dir keptPath) "what was there"+              registerPath (stDB store) (PathRegistration keptPath (Hash.formatNixHash (Hash.hashBytes registeredNar)) (BS.length registeredNar) Nothing [] NotUltimate Set.empty Nothing RegisteredNow)+              (_, reply) <- serveAdding served defaultNixConfig Proto.Trusted [narRequest fooPath info NoCheck <> framedIn 8 otherNar, dumpRequest "kept" "fixed:sha256" [] <> framedIn 8 contents]+              fooWritten <- Dir.doesPathExist (storePathToFilePath dir fooPath)+              fooHeld <- addedAs store fooPath+              keptContents <- BS.readFile (storePathToFilePath dir keptPath)+              pure $+                assertEqual+                  "answered, the dump from its registration"+                  (Right (Right (), Right (addedFrom keptPath registeredNar [] Nothing)))+                  (decodeWhole ((,) <$> answerOf (pure ()) <*> answerOf (answeredAs <$> Proto.getValidPathInfo defaultStoreDir addVersion)) reply)+                  `andThen` assertEqual "foo written" False fooWritten+                  `andThen` assertEqual "foo kept" (Just (addedFrom fooPath (narOf fooPath) [] Nothing)) fooHeld+                  `andThen` assertEqual "kept contents" "what was there" keptContents+            other -> pure (Fail ("no info to send: " <> T.pack (show other))),+      runTestM "several NARs sent together are each imported, one already valid passed over" $+        withServedStore $ \_ store served _ _ -> do+          let fooNar = narOf fooPath+              newNar = NAR.serialise (NAR.NarDirectory [("file", NAR.NarRegular False "new")])+          case (narInfoOf fooNar [] Nothing, narInfoOf newNar [fooPath] Nothing) of+            (Just fooSent, Just newSent) -> do+              let upload = le64 2 <> addressedUploadInfo fooPath fooSent <> fooNar <> addressedUploadInfo importedPath newSent <> newNar+              (_, reply) <- serveAdding served defaultNixConfig Proto.Trusted [le64 44 <> le64 0 <> le64 1 <> framedIn 24 upload, reqPath 1 importedPath]+              held <- addedAs store importedPath+              pure $+                assertEqual "imported, then valid" (msgLast <> msgLast <> le64 1) reply+                  `andThen` assertEqual "registered" (Just (addedFrom importedPath newNar [fooPath] Nothing)) held+            other -> pure (Fail ("no info to send: " <> T.pack (show other))),+      runTestM "a trusted key that does not read refuses a checked import in upstream's words" $+        withServedStore $ \_ _ served _ _ -> do+          let nar = regularNar "keyed"+              importWith keys = case narInfoOf nar [] Nothing of+                Nothing -> pure (Left "no info to send")+                Just info -> do+                  (_, reply) <- serveAdding served defaultNixConfig {ncTrustedPublicKeys = keys} Proto.NotTrusted [narRequest signedPath info Check <> framedIn 8 nar]+                  pure (decodeWhole (answerOf (pure ())) reply)+              refusal message traces = Right (Left ((Ops.daemonError message) {Proto.errTraces = traces}))+          corrupt <- importWith ["not a key"]+          short <- importWith ["k:AAAA"]+          pure $+            assertEqual "corrupt" (refusal "key is corrupt" ["while decoding key named '' with raw value 'not a key'"]) corrupt+              `andThen` assertEqual "short" (refusal "public key is not valid" []) short,+      runTestM "a secret key file that does not read refuses a checked import in upstream's words, which keep its contents out of the trace" $+        withServedStore $ \root _ served _ _ -> do+          let nar = regularNar "keyed"+              keyFile = root </> "corrupt-key"+          BS.writeFile keyFile "not a key\n"+          spelled <- argumentBytes keyFile+          case (narInfoOf nar [] Nothing, spelled) of+            (Nothing, _) -> pure (Fail "no info to send")+            (_, Nothing) -> pure (Fail "the key file's path has no spelling as bytes")+            (Just info, Just file) -> do+              (_, reply) <- serveAdding served defaultNixConfig {ncSecretKeyFiles = [file]} Proto.NotTrusted [narRequest signedPath info Check <> framedIn 8 nar]+              pure (assertEqual "refused" (Right (Left ((Ops.daemonError "key is corrupt") {Proto.errTraces = ["while decoding key named ''"]}))) (decodeWhole (answerOf (pure ())) reply)),+      runTestM "a NAR signed by the key in a file secret-key-files names is imported from a client the daemon does not trust, and a file that cannot be read is passed over" $+        withServedStore $ \root store served _ _ -> do+          let nar = regularNar "signed by a secret key"+              keyFile = root </> "secret-key"+          case (narInfoOf nar [] Nothing, sigTestSecretKeyFile) of+            (Just info, Right keyBytes) -> case signedFor signedPath info of+              Left err -> pure (Fail (T.pack err))+              Right sig -> do+                BS.writeFile keyFile keyBytes+                spelled <- sequence <$> traverse argumentBytes [root </> "missing-key", keyFile]+                case spelled of+                  Nothing -> pure (Fail "a key file's path has no spelling as bytes")+                  Just files -> do+                    (_, reply) <- serveAdding served defaultNixConfig {ncSecretKeyFiles = files} Proto.NotTrusted [narRequest signedPath info {Proto.upiSignatures = Set.singleton sig} Check <> framedIn 16 nar]+                    held <- addedAs store signedPath+                    pure (assertEqual "imported" msgLast reply `andThen` assertEqual "registered" (Just (addedFrom signedPath nar [] Nothing)) held)+            other -> pure (Fail ("no info or key: " <> T.pack (show other))),+      runTestM "under require-sigs off an unsigned NAR is imported from a client the daemon does not trust, and no key is read" $+        withServedStore $ \_ store served _ _ -> do+          let nar = regularNar "unsigned, unchecked"+          case narInfoOf nar [] Nothing of+            Nothing -> pure (Fail "no info to send")+            Just info -> do+              (_, reply) <- serveAdding served defaultNixConfig {ncRequireSigs = False, ncTrustedPublicKeys = ["not a key"]} Proto.NotTrusted [narRequest unsignedPath info Check <> framedIn 16 nar]+              held <- addedAs store unsignedPath+              pure (assertEqual "imported" msgLast reply `andThen` assertEqual "registered" (Just (addedFrom unsignedPath nar [] Nothing)) held),+      -- Upstream's store reads require-sigs as it opens, before a client's+      -- settings arrive.+      runTestM "a trusted client that turns require-sigs off still has a checked import held to the daemon's" $+        withServedStore $ \_ store served _ _ -> do+          let nar = regularNar "checked anyway"+          case narInfoOf nar [] Nothing of+            Nothing -> pure (Fail "no info to send")+            Just info -> do+              (_, reply) <- serveAdding served defaultNixConfig Proto.Trusted [setOptionsAt 3 [("require-sigs", "false")], narRequest unsignedPath info Check <> framedIn 16 nar]+              valid <- isValid store unsignedPath+              pure $+                assertEqual "refused" (msgLast <> msgError ("cannot add path '" <> pathOnWire unsignedPath <> "' because it lacks a signature by a trusted key")) reply+                  `andThen` assertEqual "valid" False valid,+      -- Upstream prints the warning at its error level, so a client that+      -- asks to hear errors alone hears it.+      runTestM "a content address that does not make its path is warned of at the error level, which a client hearing only errors is sent" $+        withServedStore $ \_ _ served _ _ -> do+          let nar = regularNar "misaddressed"+          case narInfoOf nar [] Nothing of+            Nothing -> pure (Fail "no info to send")+            Just info -> do+              let claimed = info {Proto.upiContentAddress = Proto.contentAddressFromParts (Proto.FixedMethod NarIngestion) "sha256" (sha256Digest nar)}+                  spelled = pathOnWire unsignedPath+              (_, reply) <- serveAdding served defaultNixConfig Proto.NotTrusted [setOptionsAt 0 [], narRequest unsignedPath claimed Check <> framedIn 16 nar]+              pure $+                assertEqual+                  "warned, then refused"+                  ( msgLast+                      <> msgNext ("warning: path '" <> spelled <> "' claims to be content-addressed but isn't\n")+                      <> msgError ("cannot add path '" <> spelled <> "' because it lacks a signature by a trusted key")+                  )+                  reply,+      runTestM "a NAR's path is registered at the time its info states, sent alone or with others, and at the time of its import where its info states 0" $+        withServedStore $ \_ store served _ _ -> do+          let stated = 1234567890+              aloneNar = regularNar "stated alone"+              togetherNar = regularNar "stated together"+              unstatedNar = regularNar "unstated"+          case (narInfoOf aloneNar [] Nothing, narInfoOf togetherNar [] Nothing, narInfoOf unstatedNar [] Nothing) of+            (Just alone, Just together, Just unstated) -> do+              let upload = le64 1 <> addressedUploadInfo signedPath together {Proto.upiRegistrationTime = stated} <> togetherNar+              before <- floor <$> getPOSIXTime+              (_, reply) <-+                serveAdding+                  served+                  defaultNixConfig+                  Proto.Trusted+                  [ narRequest importedPath alone {Proto.upiRegistrationTime = stated} NoCheck <> framedIn 16 aloneNar,+                    le64 44 <> le64 0 <> le64 1 <> framedIn 24 upload,+                    narRequest unsignedPath unstated NoCheck <> framedIn 16 unstatedNar+                  ]+              after <- ceiling <$> getPOSIXTime+              times <- traverse (fmap (fmap piRegTime) . queryPathInfo (stDB store)) [importedPath, signedPath, unsignedPath]+              pure $+                assertEqual "imported" (msgLast <> msgLast <> msgLast) reply+                  `andThen` case times of+                    [Just aloneTime, Just togetherTime, Just importTime]+                      | (aloneTime, togetherTime) == (fromIntegral stated, fromIntegral stated) && before <= importTime && importTime <= after -> Pass+                    other -> Fail ("registration times: " <> T.pack (show other) <> ", imported between " <> T.pack (show (before :: Int, after)))+            other -> pure (Fail ("no info to send: " <> T.pack (show other))),+      runTestM "an upload that breaks off, or whose client is stopped between two of its chunks, leaves nothing behind" $+        withServedStore $ \_ store served _ _ -> do+          let nar = NAR.serialise (NAR.NarDirectory [("a", NAR.NarRegular False (BS.replicate 64 1)), ("b", NAR.NarRegular False "b")])+              opening = dumpRequest "cut" "fixed:r:sha256" [] <> wframe (BS.take 100 nar)+          (transport, written) <- memoryTransport [clientHello 38, opening]+          broken <- serveLocal served (servedConfig defaultNixConfig) Proto.Trusted transport+          told <- BS.drop (BS.length (serverHello 38 Proto.Trusted)) <$> written+          brokenLeft <- stagingLeft store+          reached <- newEmptyMVar+          stopped <- newEmptyMVar+          block <- newEmptyMVar+          stalling <- stallingTransport [clientHello 38, opening] (putMVar reached ()) block+          thread <- forkFinally (serveLocal served (servedConfig defaultNixConfig) Proto.Trusted stalling) (\_ -> putMVar stopped ())+          takeMVar reached+          stalledLeft <- stagingLeft store+          killThread thread+          takeMVar stopped+          putMVar block ()+          killedLeft <- stagingLeft store+          pure $+            assertEqual "broken off" (Conn.ClientClosed, msgError "unexpected end-of-file") (broken, told)+              `andThen` assertEqual "left once broken off" [] brokenLeft+              `andThen` assertEqual "staged while it stalls" 1 (length stalledLeft)+              `andThen` assertEqual "left once stopped" [] killedLeft,+      runTestM "a NAR whose root is a symlink is imported where the host makes links" $+        if not linked+          then Pass <$ putStrLn "  SKIP  this host does not make symlinks"+          else withServedStore $ \_ store served _ _ -> do+            let dir = stDir store+                nar = NAR.serialise (NAR.NarSymlink "target")+            case narInfoOf nar [] Nothing of+              Nothing -> pure (Fail "no info to send")+              Just info -> do+                (_, reply) <- serveAdding served defaultNixConfig Proto.Trusted [narRequest importedPath info NoCheck <> framedIn 8 nar]+                target <- Dir.getSymbolicLinkTarget (storePathToFilePath dir importedPath)+                held <- addedAs store importedPath+                pure (assertEqual "imported" msgLast reply `andThen` assertEqual "target" "target" target `andThen` assertEqual "registered" (Just (addedFrom importedPath nar [] Nothing)) held),+      -- A link's Windows flavour is read off what its target reaches from+      -- where the link is made, so a link made before its tree is moved+      -- to its path reaches one directory too deep.+      runTestM "a link that an imported NAR or a recursive dump makes to a directory of a sibling path reaches it as a directory" $+        if not linked+          then Pass <$ putStrLn "  SKIP  this host does not make symlinks"+          else withServedStore $ \_ store served _ _ -> do+            let dir = stDir store+                depLib = storePathToFilePath dir siblingPath </> "lib"+                nar = NAR.serialise (NAR.NarDirectory [("lib", NAR.NarSymlink ("../" <> TE.encodeUtf8 (storePathBasename siblingPath) <> "/lib"))])+                digest = sha256Digest nar+            Dir.createDirectoryIfMissing True depLib+            BS.writeFile (depLib </> "hello") "hello"+            case (narInfoOf nar [] Nothing, makeSourcePath "linked" digest Set.empty) of+              (Just info, Right dumpedPath) -> do+                (_, reply) <- serveAdding served defaultNixConfig Proto.Trusted [narRequest importedPath info NoCheck <> framedIn 16 nar, dumpRequest "linked" "fixed:r:sha256" [] <> framedIn 16 nar]+                reached <- traverse (\path -> let lib = storePathToFilePath dir path </> "lib" in (,) <$> Dir.doesDirectoryExist lib <*> Dir.doesFileExist (lib </> "hello")) [importedPath, dumpedPath]+                pure $+                  assertEqual+                    "imported, then added"+                    (Right (Right (), Right (addedFrom dumpedPath nar [] (Proto.contentAddressFromParts (Proto.FixedMethod NarIngestion) "sha256" digest))))+                    (decodeWhole ((,) <$> answerOf (pure ()) <*> answerOf (answeredAs <$> Proto.getValidPathInfo defaultStoreDir addVersion)) reply)+                    `andThen` assertEqual "a directory, and its file, through each link" [(True, True), (True, True)] reached+              other -> pure (Fail ("no info to send: " <> T.pack (show other))),+      runTestM "an unsigned NAR whose content address makes its path is imported from a client the daemon does not trust" $+        withServedStore $ \_ store served _ _ -> do+          let nar = NAR.serialise (NAR.NarDirectory [("file", NAR.NarRegular False ("refers to " <> pathOnWire fooPath))])+              digest = sha256Digest nar+              address = Proto.contentAddressFromParts (Proto.FixedMethod NarIngestion) "sha256" digest+          case (narInfoOf nar [fooPath] Nothing, makeSourcePath "addressed" digest (Set.singleton fooPath)) of+            (Just info, Right addressedPath) -> do+              (_, reply) <- serveAdding served defaultNixConfig Proto.NotTrusted [narRequest addressedPath info {Proto.upiContentAddress = address} Check <> framedIn 16 nar]+              held <- addedAs store addressedPath+              pure (assertEqual "imported" msgLast reply `andThen` assertEqual "registered" (Just (addedFrom addressedPath nar [fooPath] address)) held)+            other -> pure (Fail ("no info to send: " <> T.pack (show other))),+      -- Upstream refuses to make a path from such an address, which it+      -- does while it counts a path's signatures, before it reads the NAR,+      -- and again as it registers the path.+      runTestM "a fixed address other than a NAR's SHA-256 stated with references is refused in upstream's words: before the NAR is read where signatures are checked, and as the path is registered where they are not" $+        withServedStore $ \_ store served _ _ -> do+          let dir = stDir store+              contents = "fixed contents"+              nar = regularNar contents+              digest = sha256Digest contents+              refusal = msgError "fixed output derivation 'fixed' is not allowed to refer to other store paths.\nYou may need to use the 'unsafeDiscardReferences' derivation attribute, see the manual for more details."+          case (narInfoOf nar [fooPath] Nothing, makeFixedOutputPath "fixed" "sha256" FlatIngestion digest) of+            (Just info, Right fixedPath) -> do+              let sent = info {Proto.upiContentAddress = Proto.contentAddressFromParts (Proto.FixedMethod FlatIngestion) "sha256" digest}+                  -- Bytes no archive begins with, which a read would+                  -- refuse in other words.+                  notArchive = BS.replicate (BS.length nar) 0+              (_, checked) <- serveAdding served defaultNixConfig Proto.NotTrusted [narRequest fixedPath sent Check <> framedIn 16 notArchive, reqPath 1 fixedPath]+              checkedStaged <- stagingLeft store+              (_, unchecked) <- serveAdding served defaultNixConfig Proto.Trusted [narRequest fixedPath sent NoCheck <> framedIn 16 nar, reqPath 1 fixedPath]+              written <- Dir.doesPathExist (storePathToFilePath dir fixedPath)+              staged <- stagingLeft store+              pure $+                assertEqual "checked, then not valid" (refusal <> msgLast <> le64 0) checked+                  `andThen` assertEqual "staged where checked" [] checkedStaged+                  `andThen` assertEqual "unchecked, then not valid" (refusal <> msgLast <> le64 0) unchecked+                  `andThen` assertEqual "written, staging left" (False, []) (written, staged)+            other -> pure (Fail ("no info to send: " <> T.pack (show other))),+      runTestM "a reference that is not valid is refused in upstream's words, a NAR's or a dump's, and nothing of either is kept" $+        withServedStore $ \_ store served _ _ -> do+          let dir = stDir store+              nar = regularNar "refers"+              dumped = regularNar "dumped"+              refusedReference = msgError ("path '" <> pathOnWire missingPath <> "' is not valid")+          case (narInfoOf nar [missingPath] Nothing, makeSourcePath "dumped" (sha256Digest dumped) (Set.singleton missingPath)) of+            (Just info, Right dumpedPath) -> do+              (_, reply) <- serveAdding served defaultNixConfig Proto.Trusted [narRequest importedPath info NoCheck <> framedIn 16 nar, dumpRequest "dumped" "fixed:r:sha256" [missingPath] <> framedIn 16 dumped]+              written <- traverse (Dir.doesPathExist . storePathToFilePath dir) [importedPath, dumpedPath]+              valid <- traverse (isValid store) [importedPath, dumpedPath]+              staged <- stagingLeft store+              pure $+                assertEqual "refused" (refusedReference <> refusedReference) reply+                  `andThen` assertEqual "written, valid" ([False, False], [False, False]) (written, valid)+                  `andThen` assertEqual "staging left" [] staged+            other -> pure (Fail ("no info to send: " <> T.pack (show other))),+      runTestM "a derivation sent as a text whose output is not the path its inputs make is refused in upstream's words, and nothing of it is kept" $+        withServedStore $ \_ store served _ _ -> case upstreamMade of+          Left err -> pure (Fail err)+          Right made -> case drvOutputs (drvFileDerivation made) of+            [out] -> do+              let dir = stDir store+                  wrongOut = StorePath (T.replicate 32 "1") "d"+                  wrongDrv = (drvFileDerivation made) {drvOutputs = [out {doPath = wrongOut}], drvEnv = Map.insert "out" (pathOnWire wrongOut) (drvEnv (drvFileDerivation made))}+                  aterm = toATerm wrongDrv+              (_, reply) <- serveAdding served defaultNixConfig Proto.NotTrusted [dumpRequest "d.drv" "text:sha256" [] <> framedIn 7 aterm]+              left <- filter (".drv" `isSuffixOf`) <$> Dir.listDirectory (unStoreDir dir)+              staged <- stagingLeft store+              pure $+                assertEqual "refused" (msgError ("derivation has incorrect output '" <> pathOnWire wrongOut <> "', should be '" <> pathOnWire (doPath out) <> "'")) reply+                  `andThen` assertEqual "derivations, staging left" ([], []) (left, staged)+            outputs -> pure (Fail ("expected one output, got: " <> T.pack (show outputs)))+    ]+  where+    rootsListed = map (fmap Set.toList) . Map.toList++-- | Paths the add tests import, and a path beside them that one links to.+importedPath, signedPath, unsignedPath, mismatchPath, siblingPath :: StorePath+importedPath = StorePath "0000000000000000000000000000000f" "imported"+signedPath = StorePath "0000000000000000000000000000000g" "signed"+unsignedPath = StorePath "0000000000000000000000000000000h" "unsigned"+mismatchPath = StorePath "0000000000000000000000000000000i" "mismatch"+siblingPath = StorePath "0000000000000000000000000000000j" "dep"++-- | The derivation upstream writes for+-- @derivation { name = "d"; system = "x"; builder = "/bin/sh"; }@, whose+-- path the evaluator's tests hold to upstream's: its file's contents and+-- its path.+upstreamDrv :: Either Text (BS.ByteString, StorePath)+upstreamDrv = (\made -> (drvFileATerm made, drvFilePath made)) <$> upstreamMade++-- | That derivation as made from its inputs.+upstreamMade :: Either Text DrvFile+upstreamMade = Bifunctor.first (T.pack . show) (inputAddressed "d" [] drv)+  where+    drv =+      Derivation+        { drvOutputs = [DerivationOutput "out" (StorePath (T.replicate 32 "0") "d") "" ""],+          drvInputDrvs = Map.empty,+          drvInputSrcs = [],+          drvPlatform = OtherPlatform "x",+          drvBuilder = "/bin/sh",+          drvArgs = [],+          drvEnv = Map.fromList [("builder", "/bin/sh"), ("name", "d"), ("system", "x")]+        }++-- | The version an add test's client and the daemon agree, a client at+-- 1.38 sending the features 'clientHello' sends.+addVersion :: Proto.Version+addVersion = Proto.Version Proto.latestVersionNumber (Set.fromList (map Proto.Feature serverFeatures))++-- | Serve one connection over a served store, under the settings given,+-- to a client at 1.38 sending the requests: how it ended, and what it was+-- sent after the handshake.+serveAdding :: ServedStore -> NixConfig -> Proto.Trust -> [BS.ByteString] -> IO (Conn.ConnectionEnd, BS.ByteString)+serveAdding served config trust requests = do+  (transport, written) <- memoryTransport (clientHello 38 : requests)+  ended <- serveLocal served (servedConfig config) trust transport+  (,) ended . BS.drop (BS.length (serverHello 38 trust)) <$> written++-- | A transport over a client's input, given in chunks, that once it has+-- given them signals, then waits on the variable given, as one whose+-- client went quiet mid-upload; what is sent to it is dropped.+stallingTransport :: [BS.ByteString] -> IO () -> MVar () -> IO (Conn.Transport IO)+stallingTransport input signal block = do+  pending <- newIORef (filter (not . BS.null) input)+  let receive =+        atomicModifyIORef' pending (\case [] -> ([], Nothing); chunk : rest -> (rest, Just chunk)) >>= \case+          Just chunk -> pure (Just chunk)+          Nothing -> signal >> takeMVar block >> pure Nothing+  pure (Conn.Transport receive (const (pure ())))++-- | The staging directories a store holds, by name.+stagingLeft :: Store -> IO [FilePath]+stagingLeft store = filter ("tmp-" `isPrefixOf`) <$> Dir.listDirectory (unStoreDir (stDir store))++-- | An operation's answer: its reply once its work ends, or the error that+-- ended it, what it reports on the way passed over.+answerOf :: Wire.Decoder a -> Wire.Decoder (Either Proto.DaemonError a)+answerOf reply =+  Proto.getStderrMessage addVersion >>= \case+    Proto.StderrLast -> Right <$> reply+    Proto.StderrError err -> pure (Left err)+    _ -> answerOf reply++-- | Bytes as an upload sends them: in frames of at most the size given,+-- then the frame that ends the upload.+framedIn :: Int -> BS.ByteString -> BS.ByteString+framedIn size bytes+  | BS.null bytes = frameEnd+  | otherwise = wframe (BS.take size bytes) <> framedIn size (BS.drop size bytes)++-- | A dump's request, not repairing: its name, its method and algorithm,+-- and the paths it refers to.  The dump follows.+dumpRequest :: BS.ByteString -> BS.ByteString -> [StorePath] -> BS.ByteString+dumpRequest name method refs = le64 7 <> wstr name <> wstr method <> wstrs (map pathOnWire refs) <> le64 0++-- | Whether an import asks that its signatures be checked.+data Checking = Check | NoCheck++-- | An import of a path from its NAR, not repairing.  The NAR follows.+narRequest :: StorePath -> Proto.UnkeyedValidPathInfo -> Checking -> BS.ByteString+narRequest path info checking = le64 39 <> addressedUploadInfo path info <> le64 0 <> le64 (case checking of Check -> 0; NoCheck -> 1)++-- | A path's info as an upload sends it, its content address with it.+addressedUploadInfo :: StorePath -> Proto.UnkeyedValidPathInfo -> BS.ByteString+addressedUploadInfo path info =+  wstr (pathOnWire path)+    <> wstr (maybe "" pathOnWire (Proto.upiDeriver info))+    <> wstr (TE.encodeUtf8 (Hash.bytesToHexText (Proto.narHashDigest (Proto.upiNarHash info))))+    <> wstrs (map pathOnWire (Set.toAscList (Proto.upiReferences info)))+    <> le64 (fromIntegral (Proto.upiRegistrationTime info))+    <> le64 (Proto.upiNarSize info)+    <> le64 (if Proto.upiUltimate info then 1 else 0)+    <> wstrs (map sigBytes (Set.toAscList (Proto.upiSignatures info)))+    <> wstr (maybe "" (TE.encodeUtf8 . Proto.renderContentAddress) (Proto.upiContentAddress info))++-- | The info a NAR is sent with: its hash and size, the references and+-- deriver given, unsigned, not ultimate, with no content address.+narInfoOf :: BS.ByteString -> [StorePath] -> Maybe StorePath -> Maybe Proto.UnkeyedValidPathInfo+narInfoOf nar references deriver =+  (\narHash -> Proto.UnkeyedValidPathInfo deriver narHash (Set.fromList references) 0 (fromIntegral (BS.length nar)) False Set.empty Nothing)+    <$> Proto.narHashFromDigest (sha256Digest nar)++-- | The public key 'sigTestKeyText' makes, as @trusted-public-keys@+-- spells it.+testPublicKey :: Either String Text+testPublicKey = Signing.renderPublicKey <$> (Signing.parseSecretKey sigTestKeyText >>= Signing.toPublicKey)++-- | A signature by 'sigTestKeyText' of a path's info: of the fingerprint+-- upstream signs, its path under the logical store directory.+signedFor :: StorePath -> Proto.UnkeyedValidPathInfo -> Either String Proto.Signature+signedFor path info = do+  secretKey <- Signing.parseSecretKey sigTestKeyText+  sig <- Signing.sign secretKey fingerprinted+  either (Left . T.unpack) Right (Proto.parseSignature (TE.encodeUtf8 sig))+  where+    fingerprinted =+      NarInfo.NarInfo+        { NarInfo.niStorePath = storePathToText defaultStoreDir path,+          NarInfo.niUrl = "",+          NarInfo.niCompression = "",+          NarInfo.niFileHash = Nothing,+          NarInfo.niFileSize = Nothing,+          NarInfo.niNarHash = Hash.formatNixHash (CHash.NixHash (Proto.narHashDigest (Proto.upiNarHash info))),+          NarInfo.niNarSize = toInteger (Proto.upiNarSize info),+          NarInfo.niReferences = map storePathBasename (Set.toAscList (Proto.upiReferences info)),+          NarInfo.niDeriver = Nothing,+          NarInfo.niSigs = [],+          NarInfo.niCA = Nothing+        }++-- | The NAR of a regular file that is not executable.+regularNar :: BS.ByteString -> BS.ByteString+regularNar contents = NAR.serialise (NAR.NarRegular False contents)++-- | A text's content address.+textAddress :: BS.ByteString -> Maybe Proto.ContentAddress+textAddress contents = Proto.contentAddressFromParts Proto.TextMethod "sha256" (sha256Digest contents)++-- | What an add test holds a path's info to: the path, its NAR's hash and+-- size, its references and its content address.+data Added = Added !StorePath !(Maybe Proto.NarHash) !Word64 ![StorePath] !(Maybe Proto.ContentAddress)+  deriving (Eq, Show)++-- | A path added from a NAR, with the references and the address given.+addedFrom :: StorePath -> BS.ByteString -> [StorePath] -> Maybe Proto.ContentAddress -> Added+addedFrom path nar = Added path (Proto.narHashFromDigest (sha256Digest nar)) (fromIntegral (BS.length nar))++-- | An answered path's info, as an add test holds it.+answeredAs :: Proto.ValidPathInfo -> Added+answeredAs (Proto.ValidPathInfo path info) =+  Added path (Just (Proto.upiNarHash info)) (Proto.upiNarSize info) (Set.toAscList (Proto.upiReferences info)) (Proto.upiContentAddress info)++-- | A path's registration, as an add test holds it, if the path is valid.+-- A reference the store spells as no path is left out, which a test sees+-- as a reference missing.+addedAs :: Store -> StorePath -> IO (Maybe Added)+addedAs store path = do+  row <- queryPathInfo (stDB store) path+  references <- queryReferences (stDB store) path+  pure (registered references <$> row)+  where+    registered references row =+      Added+        path+        (either (const Nothing) (\(CHash.NixHash digest) -> Proto.narHashFromDigest digest) (CHash.parseNixHash (piNarHash row)))+        (fromIntegral (piNarSize row))+        (mapMaybe (parseStorePath (stDir store)) references)+        (piContentAddress row)
+ test/Test/DaemonClient.hs view
@@ -0,0 +1,635 @@+{-# LANGUAGE LambdaCase #-}++-- | Tests of the daemon's client ("Nix.Daemon.Client"): sessions run in+-- memory against the daemon's side of a connection+-- ("Nix.Daemon.Connection") over a store held in memory, the operations+-- an older daemon is not sent, and the daemon's messages given to a logger.+module Test.DaemonClient+  ( testDaemonClient,+    testDaemonClientIO,+    Logged (..),+    eventLogger,+    Standing (..),+    standing,+    channelTransport,+    sampleInfo,+    serverConfigAt,+    withNarHash,+    fooPath,+    barPath,+    missingPath,+  )+where++import Control.Concurrent (ThreadId, throwTo, yield)+import Control.Concurrent.Async (async, asyncThreadId, wait, withAsync)+import Control.Concurrent.Chan (Chan, newChan, readChan, writeChan)+import Control.Concurrent.MVar (MVar, newEmptyMVar, putMVar, takeMVar, tryPutMVar)+import Control.Exception (Exception, finally, try, uninterruptibleMask_)+import Control.Monad (void)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Builder as BB+import qualified Data.ByteString.Lazy as BL+import Data.IORef (IORef, atomicModifyIORef', modifyIORef', newIORef, readIORef, writeIORef)+import qualified Data.Map.Strict as Map+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import GHC.Conc (ThreadStatus (..), threadStatus)+import Nix.Config (defaultNixConfig)+import qualified Nix.Daemon.Client as Client+import qualified Nix.Daemon.Connection as Conn+import qualified Nix.Daemon.Ops as Ops+import qualified Nix.Daemon.Protocol as Proto+import Nix.Hash (sha256Digest)+import Nix.Logger (ActivityStart (..), Level (..), Logger (..), plainLogger)+import Nix.Store.Path (StoreDir, defaultStoreDir)+import Nix.Store.Path.Internal (StorePath (..))+import qualified System.Info as SI+import System.Timeout (timeout)+import Test.Harness (TestResult (..), andThen, assertEqual, runTest, runTestM)++-- ---------------------------------------------------------------------------+-- Without a connection+-- ---------------------------------------------------------------------------++-- | The daemon's messages, without a connection.+testDaemonClient :: IO [Bool]+testDaemonClient = do+  putStrLn "daemon/client"+  sequence+    [ runTestM "the daemon's messages reach a logger as the local store's own calls" $ do+        (logger, events) <- eventLogger+        relay <- Client.newRelay defaultStoreDir logger+        let building = Building fooPath+            started = Ops.storeActivity defaultStoreDir (Proto.ActivityId 7) building+            unknown = Proto.ActivityId 99+        mapM_+          (Client.relayMessage relay)+          [ Proto.StderrNext "warning: x\n",+            Proto.StderrStartActivity started,+            Proto.StderrStartActivity started {Proto.actId = Proto.ActivityId 8, Proto.actType = Proto.ActivityType 100},+            Proto.StderrResult (Proto.ActivityId 7) Proto.resBuildLogLine [Proto.FieldString "built a line"],+            Proto.StderrResult unknown Proto.resBuildLogLine [Proto.FieldString "an unknown activity's line"],+            Proto.StderrResult (Proto.ActivityId 7) Proto.resPostBuildLogLine [Proto.FieldString "hooked"],+            Proto.StderrResult (Proto.ActivityId 7) (Proto.ResultType 105) [Proto.FieldInt 1],+            Proto.StderrStopActivity (Proto.ActivityId 8),+            Proto.StderrStopActivity (Proto.ActivityId 7),+            Proto.StderrResult (Proto.ActivityId 7) Proto.resBuildLogLine [Proto.FieldString "after the stop"]+          ]+        assertEqual+          "logged"+          [ LoggedMessage LevelError "warning: x",+            LoggedStart building,+            LoggedActivityLine building "built a line",+            LoggedBuildLine "an unknown activity's line",+            LoggedMessage LevelInfo "post-build-hook: hooked",+            LoggedStop building,+            LoggedBuildLine "after the stop"+          ]+          <$> events,+      runTest "a message of the daemon's is what a logger takes of it, and a line is shown without its trailing whitespace and with any byte that is not UTF-8 replaced" $+        let started = Ops.storeActivity defaultStoreDir (Proto.ActivityId 3) (Substituting fooPath "https://cache.example")+            relayedAs = Client.relayed defaultStoreDir+         in assertEqual "message" (Client.RelayedMessage "caf\xFFFD") (relayedAs (Proto.StderrNext "caf\xE9 \t\r\n  "))+              `andThen` assertEqual "start" (Client.RelayedStart 3 (Substituting fooPath "https://cache.example")) (relayedAs (Proto.StderrStartActivity started))+              `andThen` assertEqual "another kind" Client.RelayedNothing (relayedAs (Proto.StderrStartActivity started {Proto.actType = Proto.ActivityType 100}))+              `andThen` assertEqual "result of another kind" Client.RelayedNothing (relayedAs (Proto.StderrResult (Proto.ActivityId 3) (Proto.ResultType 105) [Proto.FieldInt 1]))+              `andThen` assertEqual "result with no line" Client.RelayedNothing (relayedAs (Proto.StderrResult (Proto.ActivityId 3) Proto.resBuildLogLine []))+              `andThen` assertEqual "stop" (Client.RelayedStop 3) (relayedAs (Proto.StderrStopActivity (Proto.ActivityId 3)))+              `andThen` assertEqual "end of the work" Client.RelayedNothing (relayedAs Proto.StderrLast),+      runTestM "activities a failed operation left open are stopped, latest first, once, and an activity started under a number already open stops the one it replaces" $ do+        (logger, events) <- eventLogger+        relay <- Client.newRelay defaultStoreDir logger+        let start number target = Proto.StderrStartActivity (Ops.storeActivity defaultStoreDir (Proto.ActivityId number) target)+        mapM_ (Client.relayMessage relay) [start 1 (Building fooPath), start 2 (Checking barPath), start 1 (Building missingPath)]+        Client.stopOpenActivities relay+        Client.stopOpenActivities relay+        Client.relayMessage relay (Proto.StderrStopActivity (Proto.ActivityId 2))+        assertEqual+          "logged"+          [ LoggedStart (Building fooPath),+            LoggedStart (Checking barPath),+            LoggedStart (Building missingPath),+            LoggedStop (Building fooPath),+            LoggedStop (Checking barPath),+            LoggedStop (Building missingPath)+          ]+          <$> events,+      runTestM "an exception that arrives as the daemon's start of an activity is kept leaves the activity kept, so that it is stopped" $ do+        -- The logger's start call cannot be interrupted until its last+        -- step, so the exception thrown while it runs is delivered the+        -- moment the call lets it, which is where the call is only+        -- masked by the relay.+        inLogger <- newEmptyMVar+        proceed <- newEmptyMVar+        stops <- newIORef (0 :: Int)+        let logger =+              (plainLogger (\_ _ -> pure ()) (\_ -> pure ()))+                { logActivity = \_ -> do+                    putMVar inLogger ()+                    uninterruptibleMask_ (takeMVar proceed)+                    pure (\_ -> pure (), modifyIORef' stops (+ 1))+                }+            start = Proto.StderrStartActivity (Ops.storeActivity defaultStoreDir (Proto.ActivityId 1) (Building fooPath))+        relay <- Client.newRelay defaultStoreDir logger+        reader <- async (try (Client.relayMessage relay start))+        takeMVar inLogger+        thrower <- async (throwTo (asyncThreadId reader) Interrupted)+        throwing <- standing (asyncThreadId thrower)+        putMVar proceed ()+        interrupted <- wait reader+        wait thrower+        Client.stopOpenActivities relay+        stopped <- readIORef stops+        pure $+          assertEqual "the exception waits for the reader" Waiting throwing+            `andThen` assertEqual "the reader was interrupted when the start was kept" (Left Interrupted) interrupted+            `andThen` assertEqual "the activity was kept, so it is stopped" 1 stopped+    ]++-- ---------------------------------------------------------------------------+-- Sessions+-- ---------------------------------------------------------------------------++-- | Sessions run in memory against the daemon's side of a connection.+testDaemonClientIO :: IO [Bool]+testDaemonClientIO = do+  putStrLn "daemon/client-sessions"+  withNarHash "daemon/client-sessions" $ \narHash -> sessionTests narHash++-- | The sessions, given the NAR hash the store's infos carry.+sessionTests :: Proto.NarHash -> IO [Bool]+sessionTests narHash =+  sequence+    [ runTestM "the handshake agrees the newest version and the three features, and hears the daemon's version and trust" $ do+        (outcome, end) <- session narHash Proto.Trusted latest $ (,) <$> Client.agreedVersion <*> Client.daemonInfo+        pure $+          assertEqual "outcome" (Right (Client.offeredVersion, Just (Proto.HandshakeInfo (Just nixVersion) (Just Proto.Trusted)))) outcome+            `andThen` assertEqual "end" Conn.ClientClosed end,+      runTestM "an older daemon's version is agreed, with no features and none of what it tells from later versions, and a request it does not carry is not sent while the session goes on" $ do+        let older = Proto.Version (Proto.VersionNumber 1 30) Set.empty+        (outcome, _) <- session narHash Proto.NotTrusted older $ do+          version <- Client.agreedVersion+          refused <- Client.attempt (Client.buildPathsWithResults [] Proto.BuildNormal)+          valid <- Client.isValidPath fooPath+          info <- Client.daemonInfo+          pure (version, refused, valid, info)+        pure $+          assertEqual+            "outcome"+            (Right (older, Left (Client.NotSent "BuildPathsWithResults needs protocol 1.34, which the daemon does not speak"), True, Just (Proto.HandshakeInfo Nothing Nothing)))+            outcome,+      runTestM "a daemon older than an operation is not sent it, saying which version it needs, and a query's substitute flag is left out below 1.27, as upstream's client leaves it out" $ do+        let oldest = Proto.Version Proto.minimumVersionNumber Set.empty+        (outcome, _) <- session narHash Proto.Trusted oldest $ do+          missing <- Client.attempt (Client.queryMissing [Proto.DerivedOpaque fooPath])+          outputs <- Client.attempt (Client.queryDerivationOutputMap drvPath)+          results <- Client.attempt (Client.buildPathsWithResults [Proto.DerivedOpaque fooPath] Proto.BuildNormal)+          valid <- Client.queryValidPaths (Set.fromList [fooPath, missingPath]) Ops.Substitute+          after <- Client.isValidPath fooPath+          pure (missing, outputs, results, valid, after)+        let notSent operation minor = Left (Client.NotSent (operation <> " needs protocol 1." <> minor <> ", which the daemon does not speak"))+        pure $ case outcome of+          Right (missing, outputs, results, valid, after) ->+            assertEqual "missing" (notSent "QueryMissing" "19") (void missing)+              `andThen` assertEqual "outputs" (notSent "QueryDerivationOutputMap" "22") (void outputs)+              `andThen` assertEqual "results" (notSent "BuildPathsWithResults" "34") (void results)+              `andThen` assertEqual "valid" (Set.singleton fooPath) valid+              `andThen` assertEqual "after" True after+          Left failure -> Fail (T.pack (show failure)),+      runTestM "the queries answer what the store holds" $ do+        (outcome, _) <- session narHash Proto.Trusted latest $ do+          valid <- Client.isValidPath fooPath+          invalid <- Client.isValidPath missingPath+          validAmong <- Client.queryValidPaths (Set.fromList [fooPath, missingPath]) Ops.NoSubstitute+          everything <- Client.queryAllValidPaths+          referrers <- Client.queryReferrers barPath+          info <- Client.queryPathInfo fooPath+          noInfo <- Client.queryPathInfo missingPath+          outputs <- Client.queryDerivationOutputMap drvPath+          missing <- Client.queryMissing [Proto.DerivedOpaque missingPath]+          pure (valid, invalid, validAmong, everything, referrers, info, noInfo, outputs, missing)+        pure $ case outcome of+          Right (valid, invalid, validAmong, everything, referrers, info, noInfo, outputs, missing) ->+            assertEqual "valid" True valid+              `andThen` assertEqual "invalid" False invalid+              `andThen` assertEqual "valid among" (Set.singleton fooPath) validAmong+              `andThen` assertEqual "everything" (Set.fromList [fooPath, barPath, drvPath]) everything+              `andThen` assertEqual "referrers" (Set.singleton fooPath) referrers+              `andThen` assertEqual "info" (Just (sampleInfo narHash (Set.singleton barPath))) info+              `andThen` assertEqual "no info" Nothing noInfo+              `andThen` assertEqual "outputs" (Map.fromList [(Proto.OutputName "out", Just fooPath)]) outputs+              `andThen` assertEqual "missing" (Proto.Missing Set.empty Set.empty (Set.singleton missingPath) 0 0) missing+          Left failure -> Fail (T.pack (show failure)),+      runTestM "settings sent reach the store's work, and roots and paths asked for reach the store" $ do+        (outcome, _, fake) <-+          sessionWith narHash Proto.Trusted latest $ do+            Client.setOptions sampleSettings+            Client.addTempRoot fooPath+            Client.addIndirectRoot rootedLink+            Client.ensurePath barPath+        pure $+          assertEqual "outcome" (Right ()) outcome+            `andThen` assertEqual "settings" (Just sampleSettings) (fakeSettings fake)+            `andThen` assertEqual "temporary roots" (Set.singleton fooPath) (fakeTempRoots fake)+            `andThen` assertEqual "indirect roots" (Set.singleton rootedLink) (fakeIndirectRoots fake)+            `andThen` assertEqual "ensured" [barPath] (fakeEnsured fake),+      runTestM "a NAR uploaded in chunks reaches the store whole, and its path is valid after" $ do+        chunks <- newIORef ["nar of ", "new", ""]+        let source = atomicModifyIORef' chunks (\case (chunk : rest) -> (rest, chunk); [] -> ([], BS.empty))+            info = Proto.ValidPathInfo newPath (sampleInfo narHash Set.empty)+        (outcome, _, fake) <- sessionWith narHash Proto.Trusted latest $ do+          Client.addToStoreNar info Ops.NoRepair Ops.CheckSigs source+          Client.isValidPath newPath+        pure $+          assertEqual "outcome" (Right True) outcome+            `andThen` assertEqual "uploaded" ["nar of new"] (fakeUploads fake),+      runTestM "a dump uploaded makes a path, whose info the client is given" $ do+        chunks <- newIORef ["the ", "dump", ""]+        let source = atomicModifyIORef' chunks (\case (chunk : rest) -> (rest, chunk); [] -> ([], BS.empty))+        (outcome, _, fake) <- sessionWith narHash Proto.Trusted latest (Client.addToStore (Ops.AddToStoreRequest "dump" "text:sha256" Set.empty Ops.NoRepair) source)+        pure $+          assertEqual "outcome" (Right (Proto.ValidPathInfo dumpPath (sampleInfo narHash Set.empty))) outcome+            `andThen` assertEqual "uploaded" ["the dump"] (fakeUploads fake),+      runTestM "an upload the daemon answers with more output than the connection holds is not stuck, the daemon's messages being read while the frames are sent" $ do+        state <- newIORef (startingFake narHash)+        toDaemon <- newEmptyMVar+        toClient <- newEmptyMVar+        daemonTransport <- boundedTransport toDaemon toClient+        clientTransport <- boundedTransport toClient toDaemon+        heard <- newIORef (0 :: Int)+        chunks <- newIORef (replicate uploadChunkCount "chunk;" <> [BS.empty])+        let source = atomicModifyIORef' chunks (\case (chunk : rest) -> (rest, chunk); [] -> ([], BS.empty))+            request = Ops.AddToStoreRequest "dump" "text:sha256" Set.empty Ops.NoRepair+            store = (fakeStore narHash state) {Ops.dsAddToStore = \work _ -> pure (reportingEachChunk work state narHash)}+            daemon = Conn.serveConnection (serverConfigAt latest) Proto.Trusted store daemonTransport `finally` tryPutMVar toClient Nothing+            countLines = \case Proto.StderrNext _ -> modifyIORef' heard (+ 1); _ -> pure ()+        finished <- withAsync daemon $ \_ ->+          timeout uploadDeadlockMicros (Client.runClient storeDir Client.offeredVersion clientTransport countLines (Client.addToStore request source) `finally` tryPutMVar toDaemon Nothing)+        linesHeard <- readIORef heard+        fake <- readIORef state+        pure $ case finished of+          Nothing -> Fail "the upload did not finish: the daemon's output was not read while the frames were sent"+          Just outcome ->+            assertEqual "outcome" (Right (Proto.ValidPathInfo dumpPath (sampleInfo narHash Set.empty))) outcome+              `andThen` assertEqual "uploaded" [BS.concat (replicate uploadChunkCount "chunk;")] (fakeUploads fake)+              `andThen` assertEqual "lines heard" uploadChunkCount linesHeard,+      runTestM "a build's messages reach the report as they come, then its results" $ do+        reported <- newIORef []+        (outcome, _, _) <- sessionReporting (\message -> modifyIORef' reported (message :)) narHash Proto.Trusted latest $ do+          results <- Client.buildPathsWithResults [Proto.DerivedOpaque fooPath] Proto.BuildNormal+          Client.buildPaths [Proto.DerivedOpaque fooPath] Proto.BuildNormal+          pure results+        messages <- reverse <$> readIORef reported+        pure $+          assertEqual "outcome" (Right [Proto.KeyedBuildResult (Proto.DerivedOpaque fooPath) sampleBuildResult]) outcome+            `andThen` assertEqual "messages" (concat (replicate 2 buildMessages)) messages,+      runTestM "a daemon's error fails the operation, and the session goes on" $ do+        (outcome, _) <- session narHash Proto.Trusted latest $ do+          failed <- Client.attempt (Client.queryReferrers refusedPath)+          valid <- Client.isValidPath fooPath+          pure (failed, valid)+        pure (assertEqual "outcome" (Right (Left (Client.DaemonFailed (Ops.daemonError refusalMessage)), True)) outcome),+      runTestM "a request the daemon refuses before its work fails, and the connection it closes is lost" $ do+        (outcome, end) <- session narHash Proto.NotTrusted latest $ do+          refused <- Client.attempt (Client.addToStoreNar (Proto.ValidPathInfo newPath (sampleInfo narHash Set.empty)) Ops.Repair Ops.CheckSigs (pure BS.empty))+          after <- Client.attempt (Client.isValidPath fooPath)+          final <- Client.attempt (Client.isValidPath fooPath)+          pure (refused, isLeft after, final)+        pure $+          assertEqual "outcome" (Right (Left (Client.DaemonFailed (Ops.daemonError "you are not privileged to repair store paths")), True, Left (Client.ConnectionLost Client.disconnectedMessage))) outcome+            `andThen` assertEqual "end" (Conn.ClosedOnError (Ops.daemonError "you are not privileged to repair store paths")) end,+      runTestM "a daemon that is gone fails the handshake in upstream's words" $ do+        let gone = Conn.Transport (pure Nothing) (\_ -> pure ())+        outcome <- Client.runClient storeDir Client.offeredVersion gone (\_ -> pure ()) (pure ())+        pure (assertEqual "outcome" (Left (Client.ConnectionLost Client.disconnectedMessage)) outcome),+      runTestM "a session opened once serves operations run one after another, the daemon's bytes carried between them" $ do+        state <- newIORef (startingFake narHash)+        toDaemon <- newChan+        toClient <- newChan+        daemonTransport <- channelTransport toDaemon toClient+        clientTransport <- channelTransport toClient toDaemon+        let daemon = Conn.serveConnection (serverConfigAt latest) Proto.Trusted (fakeStore narHash state) daemonTransport `finally` writeChan toClient Nothing+            report _ = pure ()+            continued = Client.continueSession storeDir clientTransport report+        withAsync daemon $ \running -> do+          opened <- Client.openSession storeDir Client.offeredVersion clientTransport report+          case opened of+            Left failure -> pure (Fail (T.pack (show failure)))+            Right fresh -> do+              (valid, afterValid) <- continued fresh (Client.isValidPath fooPath)+              (referrers, afterReferrers) <- continued afterValid (Client.queryReferrers barPath)+              (version, _) <- continued afterReferrers Client.agreedVersion+              writeChan toDaemon Nothing+              end <- wait running+              pure $+                assertEqual "valid" (Right True) valid+                  `andThen` assertEqual "referrers" (Right (Set.singleton fooPath)) referrers+                  `andThen` assertEqual "version" (Right Client.offeredVersion) version+                  `andThen` assertEqual "end" Conn.ClientClosed end+    ]+  where+    latest = Client.offeredVersion+    isLeft = either (const True) (const False)++-- ---------------------------------------------------------------------------+-- The daemon's side, in memory+-- ---------------------------------------------------------------------------++-- | What the store in memory holds and was asked.+data Fake = Fake+  { fakeValid :: !(Map.Map StorePath Proto.UnkeyedValidPathInfo),+    fakeSettings :: !(Maybe Ops.ClientSettings),+    fakeTempRoots :: !(Set.Set StorePath),+    fakeIndirectRoots :: !(Set.Set BS.ByteString),+    fakeEnsured :: ![StorePath],+    fakeUploads :: ![BS.ByteString]+  }++-- | The store's starting state: @foo@ referring to @bar@, and a+-- derivation whose @out@ is @foo@.+startingFake :: Proto.NarHash -> Fake+startingFake narHash =+  Fake+    { fakeValid = Map.fromList [(fooPath, sampleInfo narHash (Set.singleton barPath)), (barPath, sampleInfo narHash Set.empty), (drvPath, sampleInfo narHash Set.empty)],+      fakeSettings = Nothing,+      fakeTempRoots = Set.empty,+      fakeIndirectRoots = Set.empty,+      fakeEnsured = [],+      fakeUploads = []+    }++-- | A session with the daemon, trusting the client or not and offering a+-- version, over the store in memory, and how the daemon's side ended.+session :: Proto.NarHash -> Proto.Trust -> Proto.Version -> Client.ClientT IO a -> IO (Either Client.ClientFailure a, Conn.ConnectionEnd)+session narHash trust version steps = (\(outcome, end, _) -> (outcome, end)) <$> sessionWith narHash trust version steps++-- | 'session', with the store's state after it.+sessionWith :: Proto.NarHash -> Proto.Trust -> Proto.Version -> Client.ClientT IO a -> IO (Either Client.ClientFailure a, Conn.ConnectionEnd, Fake)+sessionWith = sessionReporting (\_ -> pure ())++-- | 'sessionWith', the daemon's messages given to a report.+sessionReporting :: (Proto.StderrMessage -> IO ()) -> Proto.NarHash -> Proto.Trust -> Proto.Version -> Client.ClientT IO a -> IO (Either Client.ClientFailure a, Conn.ConnectionEnd, Fake)+sessionReporting report narHash trust version steps = do+  state <- newIORef (startingFake narHash)+  toDaemon <- newChan+  toClient <- newChan+  daemonTransport <- channelTransport toDaemon toClient+  clientTransport <- channelTransport toClient toDaemon+  let daemon = Conn.serveConnection (serverConfigAt version) trust (fakeStore narHash state) daemonTransport `finally` writeChan toClient Nothing+  withAsync daemon $ \running -> do+    outcome <- Client.runClient storeDir Client.offeredVersion clientTransport report steps `finally` writeChan toDaemon Nothing+    end <- wait running+    held <- readIORef state+    pure (outcome, end, held)++-- | What the daemon in memory tells every connection, offering a version.+serverConfigAt :: Proto.Version -> Conn.ServerConfig+serverConfigAt version =+  Conn.ServerConfig+    { Conn.scStoreDir = storeDir,+      Conn.scVersion = version,+      Conn.scNixVersion = nixVersion,+      Conn.scVerbosity = Proto.Verbosity 3,+      Conn.scConfig = defaultNixConfig+    }++-- | One side of a connection in memory: it reads what the other side+-- writes to the channel it reads, and writes to the other's.  A+-- 'Nothing' in its channel is the end of its input, and every read after+-- it is the end too.+channelTransport :: Chan (Maybe BS.ByteString) -> Chan (Maybe BS.ByteString) -> IO (Conn.Transport IO)+channelTransport incoming outgoing = do+  ended <- newIORef False+  let receive = do+        done <- readIORef ended+        if done+          then pure Nothing+          else+            readChan incoming >>= \case+              Nothing -> Nothing <$ writeIORef ended True+              Just bytes+                | BS.null bytes -> receive+                | otherwise -> pure (Just bytes)+      sendBytes builder = writeChan outgoing (Just (BL.toStrict (BB.toLazyByteString builder)))+  pure (Conn.Transport receive sendBytes)++-- | One side of a connection in memory that holds one write at a time: a+-- write waits until the other side has read the one before it, as a+-- socket's buffer fills, so a side that writes while the other does the+-- same stops until one of them reads.  A 'Nothing' is the end of the+-- input, and every read after it is the end too.+boundedTransport :: MVar (Maybe BS.ByteString) -> MVar (Maybe BS.ByteString) -> IO (Conn.Transport IO)+boundedTransport incoming outgoing = do+  ended <- newIORef False+  let receive = do+        done <- readIORef ended+        if done+          then pure Nothing+          else+            takeMVar incoming >>= \case+              Nothing -> Nothing <$ writeIORef ended True+              Just bytes+                | BS.null bytes -> receive+                | otherwise -> pure (Just bytes)+      sendBytes builder = putMVar outgoing (Just (BL.toStrict (BB.toLazyByteString builder)))+  pure (Conn.Transport receive sendBytes)++-- | How many chunks the upload of a connection that holds one write at a+-- time has: well past the writes the two directions hold between them.+uploadChunkCount :: Int+uploadChunkCount = 32++-- | How long that upload may take before it counts as stuck: well past+-- what it takes.+uploadDeadlockMicros :: Int+uploadDeadlockMicros = 30 * 1000 * 1000++-- | A dump the store takes that reports a line for each chunk it is sent,+-- and keeps the whole dump once it has it.+reportingEachChunk :: Ops.Work IO -> IORef Fake -> Proto.NarHash -> Ops.Intake IO Proto.ValidPathInfo+reportingEachChunk work state narHash = Ops.Taking (more BS.empty) (finish BS.empty) (pure ())+  where+    more held chunk = do+      Ops.workReport work (Ops.LogLine (Proto.Verbosity 0) "received a chunk")+      pure (Ops.Taking (more (held <> chunk)) (finish (held <> chunk)) (pure ()))+    finish dump = Right (Proto.ValidPathInfo dumpPath (sampleInfo narHash Set.empty)) <$ modifyIORef' state (\fake -> fake {fakeUploads = fakeUploads fake ++ [dump]})++-- | The store in memory, over its state.+fakeStore :: Proto.NarHash -> IORef Fake -> Ops.DaemonStore IO+fakeStore narHash state =+  Ops.DaemonStore+    { Ops.dsIsValidPath = \_ path -> Right . Map.member path <$> valid,+      Ops.dsQueryValidPaths = \_ _ paths -> Right . Set.intersection paths . Map.keysSet <$> valid,+      Ops.dsQuerySubstitutablePaths = \_ _ -> pure (Right Set.empty),+      Ops.dsQueryReferrers = \_ path ->+        if path == refusedPath+          then pure (Left (Ops.daemonError refusalMessage))+          else Right . Map.keysSet . Map.filter (Set.member path . Proto.upiReferences) <$> valid,+      Ops.dsQueryValidDerivers = \_ _ -> pure (Right Set.empty),+      Ops.dsQueryDerivationOutputMap = \_ _ -> pure (Right (Map.fromList [(Proto.OutputName "out", Just fooPath)])),+      Ops.dsQueryAllValidPaths = \work -> record work *> (Right . Map.keysSet <$> valid),+      Ops.dsQueryPathInfo = \_ path -> Right . Map.lookup path <$> valid,+      Ops.dsQueryMissing = \_ targets -> pure (Right (Proto.Missing Set.empty Set.empty (Set.fromList [path | Proto.DerivedOpaque path <- targets]) 0 0)),+      Ops.dsAddToStore = \_ _ -> pure (collecting (\dump -> Right (Proto.ValidPathInfo dumpPath (sampleInfo narHash Set.empty)) <$ upload dump)),+      Ops.dsAddToStoreNar = \_ (Proto.ValidPathInfo path info) _ _ ->+        pure (collecting (\nar -> Right () <$ (upload nar *> modifyIORef' state (\fake -> fake {fakeValid = Map.insert path info (fakeValid fake)})))),+      Ops.dsBuildPaths = \work _ _ -> Right () <$ mapM_ (Ops.workReport work) buildEvents,+      Ops.dsBuildPathsWithResults = \work targets _ -> Right [Proto.KeyedBuildResult target sampleBuildResult | target <- targets] <$ mapM_ (Ops.workReport work) buildEvents,+      Ops.dsEnsurePath = \work path -> Right () <$ (record work *> modifyIORef' state (\fake -> fake {fakeEnsured = fakeEnsured fake ++ [path]})),+      Ops.dsAddTempRoot = \work path -> Right () <$ (record work *> modifyIORef' state (\fake -> fake {fakeTempRoots = Set.insert path (fakeTempRoots fake)})),+      Ops.dsAddIndirectRoot = \_ link -> Right () <$ modifyIORef' state (\fake -> fake {fakeIndirectRoots = Set.insert link (fakeIndirectRoots fake)}),+      Ops.dsFindRoots = \_ _ -> pure (Right Map.empty),+      Ops.dsCollectGarbage = \_ _ -> pure (Left notHere),+      Ops.dsOptimiseStore = \_ -> pure (Left notHere),+      Ops.dsVerifyStore = \_ _ _ -> pure (Left notHere),+      Ops.dsAddSignatures = \_ _ _ -> pure (Left notHere),+      Ops.dsNarFromPath = \_ _ -> pure (Left notHere)+    }+  where+    valid = fakeValid <$> readIORef state+    notHere = Ops.daemonError "not in these tests"+    upload bytes = modifyIORef' state (\fake -> fake {fakeUploads = fakeUploads fake ++ [bytes]})+    -- The settings the client last sent, as an operation's work carries+    -- them.+    record work = modifyIORef' state (\fake -> fake {fakeSettings = Ops.connClient (Ops.workSettings work)})+    collecting finish = Ops.Taking (more BS.empty) (finish BS.empty) (pure ())+      where+        more held chunk = pure (Ops.Taking (more (held <> chunk)) (finish (held <> chunk)) (pure ()))++-- | What a build the store in memory runs reports, and what the client is+-- sent for it.+buildEvents :: [Ops.LogEvent]+buildEvents =+  [ Ops.LogLine (Proto.Verbosity 0) "a line",+    Ops.ActivityStarted buildActivity,+    Ops.ActivityResult (Proto.ActivityId 7) Proto.resBuildLogLine [Proto.FieldString "built a line"],+    Ops.ActivityStopped (Proto.ActivityId 7)+  ]++buildMessages :: [Proto.StderrMessage]+buildMessages =+  [ Proto.StderrNext "a line\n",+    Proto.StderrStartActivity buildActivity,+    Proto.StderrResult (Proto.ActivityId 7) Proto.resBuildLogLine [Proto.FieldString "built a line"],+    Proto.StderrStopActivity (Proto.ActivityId 7)+  ]++buildActivity :: Proto.Activity+buildActivity = Proto.Activity (Proto.ActivityId 7) (Proto.Verbosity 3) (Proto.ActivityType 105) "building 'foo'" [] (Proto.ActivityId 0)++-- | The result the store in memory gives each build.+sampleBuildResult :: Proto.BuildResult+sampleBuildResult = Proto.BuildResult (Proto.Succeeded (Proto.Success Proto.Built Map.empty)) 1 1700000000 1700000001 Nothing Nothing++-- | Settings a client sends.+sampleSettings :: Ops.ClientSettings+sampleSettings = Ops.ClientSettings False True False (Proto.Verbosity 4) 2 30 True 3 True (Map.fromList [("max-jobs", "2")])++-- | A path's info with the NAR hash and the references given.+sampleInfo :: Proto.NarHash -> Set.Set StorePath -> Proto.UnkeyedValidPathInfo+sampleInfo narHash references =+  Proto.UnkeyedValidPathInfo+    { Proto.upiDeriver = Nothing,+      Proto.upiNarHash = narHash,+      Proto.upiReferences = references,+      Proto.upiRegistrationTime = 1700000000,+      Proto.upiNarSize = 10,+      Proto.upiUltimate = False,+      Proto.upiSignatures = Set.empty,+      Proto.upiContentAddress = Nothing+    }++-- | A NAR hash: the SHA-256 of a NAR in these tests, which a SHA-256+-- digest always makes.+sampleNarHash :: Maybe Proto.NarHash+sampleNarHash = Proto.narHashFromDigest (sha256Digest "nar of new")++-- | Run tests given the NAR hash their infos carry, or fail them where+-- there is none.+withNarHash :: Text -> (Proto.NarHash -> IO [Bool]) -> IO [Bool]+withNarHash group tests = maybe (sequence [runTest (group <> ": a NAR hash from a SHA-256 digest") (Fail "a SHA-256 digest made no NAR hash")]) tests sampleNarHash++-- | The message the store in memory fails a query with.+refusalMessage :: Text+refusalMessage = "the store refuses this path"++-- | Paths the sessions name.+fooPath, barPath, drvPath, missingPath, newPath, refusedPath, dumpPath :: StorePath+fooPath = StorePath "00000000000000000000000000000001" "foo"+barPath = StorePath "00000000000000000000000000000002" "bar"+drvPath = StorePath "00000000000000000000000000000003" "foo.drv"+missingPath = StorePath "00000000000000000000000000000005" "missing"+newPath = StorePath "00000000000000000000000000000007" "new"+refusedPath = StorePath "00000000000000000000000000000008" "refused"+dumpPath = StorePath "00000000000000000000000000000009" "dump"++-- | The store directory paths cross the wire under.+storeDir :: StoreDir+storeDir = defaultStoreDir++-- | The Nix version the daemon in memory names itself by.+nixVersion :: BS.ByteString+nixVersion = "nova-nix (test)"++-- | An exception a test throws to a thread.+data Interrupted = Interrupted+  deriving (Eq, Show)++instance Exception Interrupted++-- | Where a thread stands once it can go no further.+data Standing+  = -- | Blocked on something another thread must do: an exception thrown+    -- to a thread that has not let it in, or a lock another holds.+    Waiting+  | -- | Run to its end, by returning or by an exception.+    Ended+  deriving (Eq, Show)++-- | Wait until a thread is blocked or has ended, and say which.+standing :: ThreadId -> IO Standing+standing thread =+  threadStatus thread >>= \case+    ThreadRunning -> yield *> standing thread+    ThreadBlocked _ -> pure Waiting+    ThreadFinished -> pure Ended+    ThreadDied -> pure Ended++-- | What a logger was given, as the calls the store makes.+data Logged+  = -- | A message, at a level.+    LoggedMessage !Level !Text+  | -- | A build line given to the logger itself, not to an activity.+    LoggedBuildLine !BS.ByteString+  | -- | An activity started.+    LoggedStart !ActivityStart+  | -- | A build line given to an activity's sink.+    LoggedActivityLine !ActivityStart !BS.ByteString+  | -- | An activity stopped.+    LoggedStop !ActivityStart+  deriving (Eq, Show)++-- | A logger that keeps each call it is given, and what has been given in+-- order.+eventLogger :: IO (Logger, IO [Logged])+eventLogger = do+  events <- newIORef []+  let record event = modifyIORef' events (event :)+      logger =+        Logger+          { logAt = \level message -> record (LoggedMessage level message),+            logBuildLine = record . LoggedBuildLine,+            logActivity = \start -> do+              record (LoggedStart start)+              pure (record . LoggedActivityLine start, record (LoggedStop start))+          }+  pure (logger, reverse <$> readIORef events)++-- | An absolute out-link as the client spells it, which a daemon records+-- unchanged: a Windows daemon takes only a drive-qualified or UNC link.+rootedLink :: BS.ByteString+rootedLink+  | SI.os == "mingw32" = "C:\\home\\u\\result"+  | otherwise = "/home/u/result"
+ test/Test/DaemonPipe.hs view
@@ -0,0 +1,713 @@+{-# LANGUAGE CPP #-}++-- | Tests of the daemon on Windows' named pipe ("Nix.Daemon.Pipe") with+-- nova-nix's own client ("Nix.Daemon.Client"): the client served a+-- handshake, a query and an add over the pipe; named by its account, and+-- admitted and trusted as @allowed-users@ and @trusted-users@ name its+-- SID, its name and its groups; a client refused for the build users'+-- group by its account whatever groups its token shows, and one the+-- daemon refuses closed without a byte read from it; a second daemon on+-- the pipe refused; who may open, write and add to the pipe, as a process+-- of the daemon's own account that is not elevated is held to it; the+-- client's check of who made the pipe, which accepts a daemon of its own+-- account and refuses a pipe another user owns or a process at Low+-- integrity made, with the owners Windows lets a token give a pipe; and a+-- quiet client's connection ended as the daemon stops.  Elsewhere the+-- groups are skipped: there the daemon listens on a Unix socket, which+-- "Test.Daemon" tests, and which accounts a client trusts to own a pipe+-- is tested there too, as it needs no pipe.+--+-- The daemon's pipe is also used by accounts other than the daemon's+-- ('daemonPipeAccounts'), which CI's Windows build runs as an+-- administrator, as it makes the local accounts those checks need.+module Test.DaemonPipe+  ( testDaemonPipe,+    testDaemonPipeIO,+    daemonPipeAccountsFlag,+    daemonPipeAccounts,+  )+where++#if defined(mingw32_HOST_OS)+import Control.Exception (bracket, finally)+import Control.Monad (void, when)+import Data.Bits ((.&.), (.|.))+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BS8+import Data.IORef (atomicModifyIORef', newIORef, readIORef, writeIORef)+import Data.Maybe (fromMaybe)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Word (Word32)+import DaemonLink (DaemonLink (..), connectDaemon, daemonAddress)+import DirDacl (entryOwner, processUserSid)+import Foreign.C.String (CString, CWString, peekCString, peekCWString, withCWString)+import Foreign.C.Types (CInt (..), CULong (..))+import Foreign.Marshal.Alloc (alloca)+import Foreign.Marshal.Utils (maybePeek)+import Foreign.Ptr (Ptr, nullPtr)+import Foreign.Storable (peek)+import Nix.Config (NixConfig (..))+import Nix.Daemon.Auth (AccountDatabase (..), AccountKind (..))+import qualified Nix.Daemon.Client as Client+import qualified Nix.Daemon.Listen as Listen+import Nix.Daemon.Ops (AddToStoreRequest (..), Repair (..))+import qualified Nix.Daemon.Pipe as Pipe+import qualified Nix.Daemon.Protocol as Proto+import Nix.Hash (makeTextPath, sha256Digest)+import Nix.Store.Access (sidFromText, sidText)+import Nix.Store.Path (defaultStoreDir)+import GHC.Clock (getMonotonicTime)+import System.Exit (ExitCode (..), exitWith)+import System.IO (BufferMode (..), hSetBuffering, stdout)+import qualified System.Process as Proc+import System.Timeout (timeout)+import Test.Daemon (fooPath, helloOver, socketTestMicros, withSocketDaemon)+import Test.Harness (TestResult (..), andThen, assertEqual, runTest, runTestM)+import Test.WindowsSandbox (SlotAccount (..), accountPrefix, makeAccount, removeAccount, withAccount, withBuildersGroup, withLogon)+#else+import System.Exit (die)+#endif++-- | The pipe's rules that need no pipe: which paths name one, and what+-- the pipe grants Users.+testDaemonPipe :: IO [Bool]++-- | The daemon on its pipe, with nova-nix's client.+testDaemonPipeIO :: IO [Bool]++-- | The flag CI's step runs the suite with, as an administrator, to run+-- 'daemonPipeAccounts'.+daemonPipeAccountsFlag :: String+daemonPipeAccountsFlag = "--daemon-pipe-accounts"++-- | Make two local accounts, one a member of the build users' group+-- @nixbld@ and one not, and check what each is to the daemon of the+-- administrator who runs this: the one outside the group is admitted+-- and not trusted, may not add an instance to the pipe or open it to+-- rewrite its DACL, and the one in the group is refused without a byte+-- read from it.  The accounts and the group are removed however the+-- checks end, and the exit status is 0 only when every check passed.+daemonPipeAccounts :: [String] -> IO ()++#if defined(mingw32_HOST_OS)++testDaemonPipe = do+  putStrLn "daemon/pipe"+  sequence+    [ runTest "a pipe's path is \\\\.\\pipe\\ and a name with no separator that is no step, 256 UTF-16 units at most" $+        let named = either (const Nothing) (Just . Pipe.pipePathText) . Pipe.pipePath+            longest = "\\\\.\\pipe\\" <> BS8.replicate (maxPipePathUnits - BS.length "\\\\.\\pipe\\") 'x'+         in assertEqual "plain" (Just "\\\\.\\pipe\\nova-nix-daemon") (named "\\\\.\\pipe\\nova-nix-daemon")+              `andThen` assertEqual "upper case" (Just "\\\\.\\PIPE\\x") (named "\\\\.\\PIPE\\x")+              `andThen` assertEqual "the longest" (Just (TE.decodeUtf8Lenient longest)) (named longest)+              `andThen` assertEqual "one too long" Nothing (named (longest <> "x"))+              `andThen` assertEqual "a socket's path" Nothing (named "/nix/var/nix/daemon-socket/socket")+              `andThen` assertEqual "no name" Nothing (named "\\\\.\\pipe\\")+              `andThen` assertEqual "a backslash in the name" Nothing (named "\\\\.\\pipe\\a\\b")+              `andThen` assertEqual "a slash in the name" Nothing (named "\\\\.\\pipe\\a/b")+              `andThen` assertEqual "a step up" Nothing (named "\\\\.\\pipe\\..")+              `andThen` assertEqual "another machine's" Nothing (named "\\\\host\\pipe\\x")+              `andThen` assertEqual "not UTF-8" Nothing (named "\\\\.\\pipe\\\xff"),+      runTest "Users may read the pipe and write its data, and may not create an instance of it" $+        assertEqual "read and write data" (fileReadData + fileWriteData) (Pipe.clientPipeAccess .&. (fileReadData + fileWriteData))+          `andThen` assertEqual "create an instance" 0 (Pipe.clientPipeAccess .&. fileCreatePipeInstance),+      runTest "the daemon's own account may create the pipe's next instance, and has not the rights to rewrite its DACL, take its owner or delete it" $+        assertEqual "create an instance" fileCreatePipeInstance (Pipe.daemonPipeAccess .&. fileCreatePipeInstance)+          `andThen` assertEqual "change the DACL, take the owner, delete" 0 (Pipe.daemonPipeAccess .&. (writeDac .|. writeOwner .|. delete)),+      runTest "the pipe's descriptor names its owner, and has an entry for the daemon's account only where the account owns the pipe and not Administrators" $+        case (sidFromText administratorsSid, sidFromText otherUser) of+          (Just administrators, Just account) ->+            assertEqual "an account owns the pipe it makes" (Pipe.OwnedByAccount account) (Pipe.pipeOwnerOf account)+              `andThen` assertEqual "Administrators owns what an elevated token makes" Pipe.OwnedByAdministrators (Pipe.pipeOwnerOf administrators)+              `andThen` assertEqual "Administrators" "O:S-1-5-32-544D:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x12008b;;;BU)" (Pipe.pipeSddl Pipe.OwnedByAdministrators)+              `andThen` assertEqual "an account" "O:S-1-5-21-1-2-3-1001D:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x12019f;;;S-1-5-21-1-2-3-1001)(A;;0x12008b;;;BU)" (Pipe.pipeSddl (Pipe.OwnedByAccount account))+          _ -> Fail "the tests' SIDs do not read as SIDs"+    ]+  where+    -- The most UTF-16 units Windows takes in a pipe's path.+    maxPipePathUnits = 256+    -- winnt.h's FILE_READ_DATA, FILE_WRITE_DATA and+    -- FILE_CREATE_PIPE_INSTANCE.+    fileReadData = 0x1+    fileWriteData = 0x2+    fileCreatePipeInstance = 0x4++daemonPipeAccounts _ = do+  hSetBuffering stdout LineBuffering+  tag <- T.pack . show <$> Proc.getCurrentPid+  let member = accountPrefix <> tag <> "m"+      outsider = accountPrefix <> tag <> "o"+  results <-+    withBuildersGroup $+      withAccount member $ \inGroup ->+        bracket (makeAccount outsider) (const (removeAccount outsider)) $ \notInGroup ->+          withLogon inGroup $ \(_, memberToken) ->+            withLogon notInGroup $ \(_, outsiderToken) ->+              sequence (accountChecks (saName notInGroup) memberToken outsiderToken)+  putStrLn (show (length (filter id results)) <> " of " <> show (length results) <> " checks passed")+  exitWith (if and results then ExitSuccess else ExitFailure 1)++-- | What the daemon makes of the account in the build users' group and of+-- the one outside it, given the name of the second and each one's token,+-- for a daemon run by the administrator that runs the checks, with+-- @trusted-users@ at its default.+accountChecks :: Text -> Handle -> Handle -> [IO Bool]+accountChecks outsiderName memberToken outsiderToken =+  [ runTestM "an account outside the build users' group is admitted and not trusted, and one inside it is refused without a byte read from it" $+      withSocketDaemon Listen.DefaultTrust (\config -> config {ncBuildUsersGroup = Just "nixbld", ncAllowedUsers = ["*"]}) $ \_ address logged -> do+        outsider <- connectedAndClosedAs outsiderToken address AllGroups+        member <- connectedAndClosedAs memberToken address EffectiveOnly+        messages <- logged+        let accepted message = "accepted connection from pid " `T.isPrefixOf` message && outsiderName `T.isInfixOf` message && not (" (trusted)" `T.isSuffixOf` message)+        pure $+          assertEqual "the account outside the group is held open" (Right False) outsider+            `andThen` assertEqual "the account in the group is closed" (Right True) member+            `andThen` assertEqual "logged" (1, 1) (length (filter accepted messages), length (filter refusalMessage messages)),+    runTestM "an account of another user may not add an instance to the daemon's pipe or open it to rewrite its DACL" $+      withSocketDaemon Listen.DefaultTrust id $ \_ address _ -> do+        added <- addInstanceAs outsiderToken address+        rewritten <- openAs outsiderToken address writeDac AllGroups+        either (const (pure ())) closeHandle added+        either (const (pure ())) closeHandle rewritten+        pure $+          assertEqual "adding an instance" (Left errorAccessDenied) (() <$ added)+            `andThen` assertEqual "opening to rewrite the DACL" (Left errorAccessDenied) (() <$ rewritten)+  ]++testDaemonPipeIO = do+  putStrLn "daemon/pipe-io"+  processUserSid >>= \process -> case process of+    Nothing -> (: []) <$> runTest "the process has a user SID" (Fail "it has none")+    Just user -> do+      named <- maybe (pure Nothing) (adAccountName Pipe.systemAccounts) (sidFromText user)+      pipeTests user (maybe user TE.decodeUtf8Lenient named)++-- | The tests, given the SID and the name of the account this process+-- runs as.+pipeTests :: Text -> Text -> IO [Bool]+pipeTests user name =+  sequence+    [ runTestM "nova-nix's client is served a handshake, a query and an add over the pipe, and the daemon names it by its account" $+        case makeTextPath "hello.txt" (sha256Digest helloText) [] of+          Left err -> pure (Fail (T.pack (show err)))+          Right expected ->+            withSocketDaemon Listen.DefaultTrust (\config -> config {ncTrustedUsers = [TE.encodeUtf8 user]}) $ \_ address logged -> do+              pid <- Proc.getCurrentPid+              source <- chunkSource [helloText]+              outcome <- withClient address $ do+                info <- Client.daemonInfo+                valid <- Client.isValidPath fooPath+                added <- Proto.vpiPath <$> Client.addToStore (AddToStoreRequest "hello.txt" "text:sha256" Set.empty NoRepair) source+                validAfter <- Client.isValidPath added+                pure (info >>= Proto.hiTrust, valid, added, validAfter)+              messages <- logged+              pure $+                assertEqual "outcome" (Right (Just Proto.Trusted, True, expected, True)) outcome+                  `andThen` assertEqual "logged" [accepted pid " (trusted)"] messages,+      runTestM "the client is admitted by its SID or its name, and refused where allowed-users names neither, as upstream's daemon refuses a client" $ do+        pid <- Proc.getCurrentPid+        bySid <- trustedAs [] [user] $ \outcome messages ->+          assertEqual "by SID" (Right (Just Proto.NotTrusted), [accepted pid ""]) (outcome, messages)+        byName <- trustedAs [] [name] $ \outcome messages ->+          assertEqual "by name" (Right (Just Proto.NotTrusted), [accepted pid ""]) (outcome, messages)+        neither <- trustedAs [] [otherUser] $ \outcome messages ->+          assertEqual+            "neither"+            (Left (Client.ConnectionLost Client.disconnectedMessage), ["error: while processing connection: user '" <> name <> "' is not allowed to connect to the Nix daemon"])+            (outcome, messages)+        pure (bySid `andThen` byName `andThen` neither),+      runTestM "trusted-users trusts the client by a group its token holds, named by SID or by name, and not by one it does not hold" $ do+        usersName <- maybe (pure Nothing) (adAccountName Pipe.systemAccounts) (sidFromText usersSid)+        bySid <- trustedAs ["@" <> authenticatedUsersSid] ["*"] $ \outcome _ ->+          assertEqual "by SID" (Right (Just Proto.Trusted)) outcome+        byName <- case usersName of+          Nothing -> pure (Fail "Users has no name")+          Just group -> trustedAs ["@" <> TE.decodeUtf8Lenient group] ["*"] $ \outcome _ ->+            assertEqual "by name" (Right (Just Proto.Trusted)) outcome+        notHeld <- trustedAs ["@" <> guestsSid] ["*"] $ \outcome _ ->+          assertEqual "not held" (Right (Just Proto.NotTrusted)) outcome+        pure (bySid `andThen` byName `andThen` notHeld),+      runTestM "a second daemon on the pipe is refused while the first listens" $+        withSocketDaemon Listen.DefaultTrust id $ \_ address _ ->+          Listen.openListener address >>= \opened -> case opened of+            Left refusal -> pure (assertEqual "refused" ("cannot listen on '" <> TE.decodeUtf8Lenient address <> "': a process already has the pipe open") refusal)+            Right second -> Fail "a second daemon listened on the pipe" <$ Listen.closeListener second,+      runTestM "a client of a pipe no daemon has is refused, in Windows' words" $+        daemonAddress "" >>= \unused -> case unused of+          Nothing -> pure (Fail "no pipe's path")+          Just address -> case Pipe.pipePath address of+            Left reason -> pure (Fail reason)+            Right path ->+              Pipe.connectPipe path >>= \connected -> case connected of+                Left reason -> pure (assertEqual "refused by CreateFileW" True ("CreateFileW: " `T.isPrefixOf` reason))+                Right conn -> Fail "a client connected to a pipe no daemon has" <$ Pipe.closeConnection conn,+      runTestM "a client trusts the pipe of a daemon run by its own account, which the daemon owns as Administrators where its token holds the group enabled and as its account otherwise" $ do+        held <- administratorsEnabled+        withSocketDaemon Listen.DefaultTrust (\config -> config {ncTrustedUsers = [TE.encodeUtf8 user]}) $ \_ address _ -> do+          owner <- entryOwner (BS8.unpack address)+          served <- withClient address Client.daemonInfo+          pure $+            assertEqual "the pipe's owner" (Just (if held then administratorsSid else user)) owner+              `andThen` assertEqual "the client connects and is served" True (either (const False) (const True) served),+      runTestM "a client refuses a pipe another user owns, naming the pipe, and uses it for nothing" $ do+        path <- freshPipe+        -- Another user's pipe is stood in for by one an account with the+        -- restore privilege makes, which can name any owner.+        made <- makePipeAs nullPtr WithRestore (Pipe.pipePathText path) (ownedBy otherUser)+        case made of+          Left code+            | code == errorNotAllAssigned -> Pass <$ putStrLn "  SKIP  the process lacks the restore privilege, which a pipe another user owns is made with"+            | otherwise -> pure (Fail ("making the pipe failed with Win32 error " <> T.pack (show code)))+          Right pipe ->+            ( Pipe.connectPipe path >>= \connected -> case connected of+                Left reason -> pure (assertEqual "refusal" (notTrusted path <> "it belongs to " <> otherUser <> ", not to you, SYSTEM, Administrators or the nova-nix service") reason)+                Right conn -> Fail "a client connected to a pipe another user owns" <$ Pipe.closeConnection conn+            )+              `finally` closeHandle pipe,+      runTestM "a token that holds Administrators for deny only owns a pipe as its own account, and Windows lets it give no pipe Administrators as its owner" $+        withFilteredToken $ \filtered -> do+          owner <- tokenPipeOwner filtered+          path <- freshPipe+          refused <- makePipeAs filtered Ordinary (Pipe.pipePathText path) (ownedBy administratorsSid)+          either (\code -> pure (assertEqual "owner of the pipe the daemon makes" user owner `andThen` assertEqual "making a pipe owned by Administrators" errorInvalidOwner code)) (\pipe -> Fail "a token that holds Administrators for deny only made a pipe owned by Administrators" <$ closeHandle pipe) refused,+      runTestM "a client refuses a pipe a process at Low integrity made, though its own account owns it" $ do+        path <- freshPipe+        withIntegrityToken nullPtr lowIntegrity $ \low -> do+          made <- makePipeAs low Ordinary (Pipe.pipePathText path) (ownedBy user)+          case made of+            Left code -> pure (Fail ("making the pipe failed with Win32 error " <> T.pack (show code)))+            Right pipe ->+              ( Pipe.connectPipe path >>= \connected -> case connected of+                  Left reason -> pure (assertEqual "refusal" (notTrusted path <> "it was made by a process below Medium integrity (level 0x1000)") reason)+                  Right conn -> Fail "a client connected to a pipe a process at Low integrity made" <$ Pipe.closeConnection conn+              )+                `finally` closeHandle pipe,+      runTestM "where the daemon owns its pipe as Administrators, a process of its account that is not elevated cannot add an instance to the pipe or open it to rewrite its DACL, and writes it as a client" $ do+        held <- administratorsEnabled+        if not held+          then Pass <$ putStrLn "  SKIP  the process is not elevated, so its daemon owns its pipe as its account"+          else withSocketDaemon Listen.DefaultTrust (\config -> config {ncTrustedUsers = [TE.encodeUtf8 user]}) $ \_ address _ ->+            withMediumToken $ \medium -> do+              added <- addInstanceAs medium address+              rewritten <- openAs medium address writeDac AllGroups+              connected <- openAs medium address Pipe.clientPipeAccess AllGroups+              either (const (pure ())) closeHandle added+              either (const (pure ())) closeHandle rewritten+              either (const (pure ())) closeHandle connected+              pure $+                assertEqual "adding an instance" (Left errorAccessDenied) (() <$ added)+                  `andThen` assertEqual "opening to rewrite the DACL" (Left errorAccessDenied) (() <$ rewritten)+                  `andThen` assertEqual "opening as a client" (Right ()) (() <$ connected),+      runTestM "where the daemon owns its pipe as its account, a process of the account adds the next instance, and cannot open the pipe to take its owner or delete it" $+        withFilteredToken $ \filtered -> do+          owner <- tokenPipeOwner filtered+          path <- freshPipe+          case sidFromText owner of+            Nothing -> pure (Fail "the token's pipe owner is not a SID")+            Just sid ->+              makePipeAs filtered Ordinary (Pipe.pipePathText path) (Pipe.pipeSddl (Pipe.pipeOwnerOf sid)) >>= \made -> case made of+                Left code -> pure (Fail ("making the pipe failed with Win32 error " <> T.pack (show code)))+                Right first -> do+                  added <- addInstanceAs filtered (TE.encodeUtf8 (Pipe.pipePathText path))+                  takenOver <- openAs filtered (TE.encodeUtf8 (Pipe.pipePathText path)) writeOwner AllGroups+                  deleted <- openAs filtered (TE.encodeUtf8 (Pipe.pipePathText path)) delete AllGroups+                  either (const (pure ())) closeHandle added+                  either (const (pure ())) closeHandle takenOver+                  either (const (pure ())) closeHandle deleted+                  closeHandle first+                  pure $+                    assertEqual "adding an instance" (Right ()) (() <$ added)+                      `andThen` assertEqual "opening to take the owner" (Left errorAccessDenied) (() <$ takenOver)+                      `andThen` assertEqual "opening to delete" (Left errorAccessDenied) (() <$ deleted),+      runTestM "a client the daemon refuses is closed without a byte read from it, again and again, so it holds neither an instance nor a thread" $+        withSocketDaemon Listen.DefaultTrust (\config -> config {ncTrustedUsers = [], ncAllowedUsers = []}) $ \_ address logged -> do+          outcomes <- mapM (const (connectedAndClosed address AllGroups)) [1 .. refusedClients]+          messages <- logged+          pure $+            assertEqual "each is closed" (replicate refusedClients (Right True)) outcomes+              `andThen` assertEqual "each is told why in the log" (replicate refusedClients True) (map refusalMessage messages),+      runTestM "a client is refused for the build users' group by its account, whatever groups its token shows, and is served where its account is not in the group" $+        withDeniedGroup usersSid $ \shaped -> do+          let building group = \config -> config {ncBuildUsersGroup = Just group, ncTrustedUsers = ["*"], ncAllowedUsers = ["*"]}+          refused <- withSocketDaemon Listen.DefaultTrust (building "BUILTIN\\Users") $ \_ address logged -> do+            outcome <- connectedAndClosedAs shaped address EffectiveOnly+            messages <- logged+            pure (assertEqual "closed" (Right True) outcome `andThen` assertEqual "logged" (map refusalMessage messages) [True])+          served <- withSocketDaemon Listen.DefaultTrust (building (TE.encodeUtf8 guestsSid)) $ \_ address logged -> do+            outcome <- connectedAndClosedAs shaped address EffectiveOnly+            messages <- logged+            pure (assertEqual "held open" (Right False) outcome `andThen` assertEqual "logged" True (any (T.isPrefixOf "accepted connection from pid ") messages))+          pure (refused `andThen` served),+      runTestM "a name is an account of this machine unless it names a domain, of the kind asked for, and an account's groups are those Windows holds for it" $ do+        let accounts = Pipe.systemAccounts+        own <- adAccountName accounts =<< maybe (ioError (userError "the process's SID")) pure (sidFromText user)+        ownUser <- maybe (pure (Right Nothing)) (adAccountSid accounts UserAccount) own+        ownAsGroup <- maybe (pure (Right Nothing)) (adAccountSid accounts GroupAccount) own+        builtin <- adAccountSid accounts GroupAccount "BUILTIN\\Administrators"+        builtinAsUser <- adAccountSid accounts UserAccount "BUILTIN\\Administrators"+        system <- adAccountSid accounts UserAccount "NT AUTHORITY\\SYSTEM"+        bareBuiltinGroup <- adAccountSid accounts GroupAccount "Administrators"+        bareSystem <- adAccountSid accounts UserAccount "SYSTEM"+        bareRoot <- adAccountSid accounts UserAccount "root"+        nobody <- adAccountSid accounts UserAccount "no-such-account-nova-nix"+        groups <- maybe (ioError (userError "the process's SID")) (adAccountGroups accounts) (sidFromText user)+        pure $+          assertEqual "the process's account, by its own name" (Right (sidFromText user)) ownUser+            `andThen` assertEqual "a user is no group" (Right Nothing) ownAsGroup+            `andThen` assertEqual "a group of another domain by name" (Right (sidFromText administratorsSid)) builtin+            `andThen` assertEqual "a group is no user" (Right Nothing) builtinAsUser+            `andThen` assertEqual "a well-known user by name" (Right (sidFromText "S-1-5-18")) system+            `andThen` assertEqual "a bare name is not a built-in group, which is BUILTIN\\NAME" (Right Nothing) bareBuiltinGroup+            `andThen` assertEqual "a bare name is not a well-known user, which is NT AUTHORITY\\NAME" (Right Nothing) bareSystem+            `andThen` assertEqual "root, which Windows has no account for" (Right Nothing) bareRoot+            `andThen` assertEqual "an account that does not exist" (Right Nothing) nobody+            `andThen` assertEqual "the groups hold Users and Everyone" (Right True) (fmap (\held -> all (`elem` map sidText held) [usersSid, everyoneSid]) groups),+      runTestM "a client of a pipe whose instances are all busy waits a bounded while, and is told the pipe is busy" $+        daemonAddress "" >>= \found -> case found of+          Nothing -> pure (Fail "no pipe's path")+          Just address -> case Pipe.pipePath address of+            Left reason -> pure (Fail reason)+            Right path ->+              Listen.openListener address >>= \opened -> case opened of+                Left refusal -> pure (Fail refusal)+                Right listener -> do+                  ( Pipe.connectPipe path >>= \first -> case first of+                      Left reason -> pure (Fail ("the first client was refused: " <> reason))+                      Right taken -> do+                        started <- getMonotonicTime+                        second <- timeout socketTestMicros (Pipe.connectPipe path)+                        waited <- subtract started <$> getMonotonicTime+                        Pipe.closeConnection taken+                        pure $ case second of+                          Nothing -> Fail "the second client waited without end"+                          Just (Right _) -> Fail "a second client connected to a busy pipe"+                          Just (Left reason) ->+                            assertEqual "the pipe is busy" True ("CreateFileW: " `T.isPrefixOf` reason)+                              `andThen` assertEqual "it waited the pipe's default wait" True (waited >= busyWaitSeconds)+                    )+                    `finally` Listen.closeListener listener,+      -- No daemon takes clients from the listener, so a check that+      -- connected to its one instance would leave none for the client+      -- after it, which would wait for one and give up.+      runTestM "a daemon's pipe is present while it listens, without the check taking its instance, and absent once it stops" $+        daemonAddress "" >>= \found -> case found of+          Nothing -> pure (Fail "no pipe's path")+          Just address -> case Pipe.pipePath address of+            Left reason -> pure (Fail reason)+            Right path -> do+              before <- Pipe.pipePresent path+              Listen.openListener address >>= \opened -> case opened of+                Left refusal -> pure (Fail refusal)+                Right listener -> do+                  (during, connects) <-+                    ( do+                        present <- Pipe.pipePresent path+                        taken <- Pipe.connectPipe path+                        either (const (pure ())) Pipe.closeConnection taken+                        pure (present, either (const False) (const True) taken)+                    )+                      `finally` Listen.closeListener listener+                  after <- Pipe.pipePresent path+                  pure $+                    assertEqual "before" False before+                      `andThen` assertEqual "while listening" True during+                      `andThen` assertEqual "a client connects after the check" True connects+                      `andThen` assertEqual "after" False after,+      -- The connection is left open when the daemon is stopped, which a+      -- daemon that cannot interrupt its read of a quiet client never+      -- finishes.+      runTestM "stopping the daemon ends the connection of a client that has gone quiet" $ do+        held <- newIORef Nothing+        served <- withSocketDaemon Listen.DefaultTrust (\config -> config {ncTrustedUsers = [TE.encodeUtf8 user]}) $ \_ address _ -> do+          link <- connectDaemon address+          writeIORef held (Just link)+          helloOver link Proto.Trusted+        readIORef held >>= \kept -> case kept of+          Nothing -> pure served+          Just link -> do+            after <- timeout socketTestMicros (linkReceive link 1) `finally` linkClose link+            pure (served `andThen` assertEqual "after the stop" (Just "") after)+    ]+  where+    accepted pid trusted = "accepted connection from pid " <> T.pack (show pid) <> ", user " <> name <> trusted+    -- A session that asks only how far the daemon trusts it, given what+    -- the daemon is told of trusted-users and allowed-users, judged with+    -- what the daemon logged.+    trustedAs trusted allowed judge =+      withSocketDaemon Listen.DefaultTrust (\config -> config {ncTrustedUsers = map TE.encodeUtf8 trusted, ncAllowedUsers = map TE.encodeUtf8 allowed}) $ \_ address logged -> do+        outcome <- withClient address ((>>= Proto.hiTrust) <$> Client.daemonInfo)+        judge outcome <$> logged++-- | A user's SID no account has, and the SIDs of the well-known groups+-- Authenticated Users, which every signed-in account's token holds,+-- Users, which holds them, and Guests, which the tests' account is not in.+otherUser, authenticatedUsersSid, usersSid, guestsSid :: Text+otherUser = "S-1-5-21-1-2-3-1001"+authenticatedUsersSid = "S-1-5-11"+usersSid = "S-1-5-32-545"+guestsSid = "S-1-5-32-546"++-- | The SID of Everyone, which every account is in.+everyoneSid :: Text+everyoneSid = "S-1-1-0"++-- | winnt.h's DELETE, WRITE_DAC and WRITE_OWNER, the rights to remove a+-- pipe, rewrite its DACL and take its owner.+delete, writeDac, writeOwner :: Word32+delete = 0x10000+writeDac = 0x40000+writeOwner = 0x80000++-- | The mandatory label RIDs of Low and Medium integrity (winnt.h's+-- @SECURITY_MANDATORY_LOW_RID@ and @SECURITY_MANDATORY_MEDIUM_RID@).+lowIntegrity, mediumIntegrity :: Word32+lowIntegrity = 0x1000+mediumIntegrity = 0x2000++-- | The least time, in seconds, a client of a pipe whose instances stay+-- busy waits: the pipe's default wait, which is five seconds, less what+-- the clock and the wait's start can differ by.+busyWaitSeconds :: Double+busyWaitSeconds = 4++-- | How many clients the daemon is to refuse one after the other.+refusedClients :: Int+refusedClients = 3++-- | How long, in milliseconds, a test waits for the daemon to end a+-- connection it has refused, well past what that takes, and how long it+-- watches one the daemon admits.+closeWaitMillis :: CULong+closeWaitMillis = 3000++-- | Whether a line the daemon logged says it refused a client.+refusalMessage :: Text -> Bool+refusalMessage message = "error: while processing connection: user '" `T.isPrefixOf` message && "' is not allowed to connect to the Nix daemon" `T.isSuffixOf` message++-- | What the daemon sees of the groups a client's token holds.+data Visibility+  = -- | Every group, those held for deny only too.+    AllGroups+  | -- | The groups enabled, as an impersonating server sees a client that+    -- asks for no more.+    EffectiveOnly++-- | What the client says of a pipe no trusted account made, up to the+-- reason.+notTrusted :: Pipe.PipePath -> Text+notTrusted path = "the pipe '" <> Pipe.pipePathText path <> "' is not served by a trusted account: "++-- | Administrators' SID, which the daemon owns its pipe as where its token+-- holds the group enabled.+administratorsSid :: Text+administratorsSid = "S-1-5-32-544"++-- | The SDDL of a security descriptor that gives the owner and lets every+-- account do anything, for the pipes the tests stand in a daemon's place+-- with.+ownedBy :: Text -> Text+ownedBy owner = "O:" <> owner <> "D:(A;;GA;;;WD)"++-- | Win32's @ERROR_INVALID_OWNER@, which a process that names an owner it+-- may not give gets, @ERROR_NOT_ALL_ASSIGNED@, which enabling a+-- privilege a token does not hold gets, and @ERROR_ACCESS_DENIED@, which a+-- pipe's DACL gives (winerror.h).+errorInvalidOwner, errorNotAllAssigned, errorAccessDenied :: CULong+errorInvalidOwner = 1307+errorNotAllAssigned = 1300+errorAccessDenied = 5++-- | A pipe's path no other test uses.+freshPipe :: IO Pipe.PipePath+freshPipe =+  daemonAddress "" >>= \address -> case address >>= either (const Nothing) Just . Pipe.pipePath of+    Just path -> pure path+    Nothing -> ioError (userError "no pipe's path")++-- | The text the add test adds.+helloText :: BS.ByteString+helloText = "hello\n"++-- | A chunk source over chunks, giving an empty chunk once they are+-- given.+chunkSource :: [BS.ByteString] -> IO (IO BS.ByteString)+chunkSource chunks = do+  pending <- newIORef chunks+  pure (atomicModifyIORef' pending (\left -> case left of [] -> ([], BS.empty); chunk : rest -> (rest, chunk)))++-- | Run a session of nova-nix's client with the daemon at the address,+-- its messages dropped, and close the connection after.+withClient :: BS.ByteString -> Client.ClientT IO a -> IO (Either Client.ClientFailure a)+withClient address steps = case Pipe.pipePath address of+  Left reason -> pure (Left (Client.ConnectionLost reason))+  Right path ->+    Pipe.connectPipe path >>= \connected -> case connected of+      Left reason -> pure (Left (Client.ConnectionLost reason))+      Right conn -> Client.runClient defaultStoreDir Client.offeredVersion (Pipe.connectionTransport conn) (\_ -> pure ()) steps `finally` Pipe.closeConnection conn++-- ---------------------------------------------------------------------------+-- Tokens and pipes+-- ---------------------------------------------------------------------------++-- | A Win32 handle.+type Handle = Ptr ()++-- | What a pipe made as a token is made with: the privileges it has, or+-- the restore privilege enabled as well, which lets it name any owner.+data Privilege = Ordinary | WithRestore++foreign import ccall unsafe "nn_test_administrators_enabled"+  c_nn_test_administrators_enabled :: Ptr CInt -> IO CULong++foreign import ccall unsafe "nn_test_filtered_token"+  c_nn_test_filtered_token :: Ptr Handle -> IO CULong++foreign import ccall unsafe "nn_test_integrity_token"+  c_nn_test_integrity_token :: Handle -> CULong -> Ptr Handle -> IO CULong++foreign import ccall unsafe "nn_test_deny_group_token"+  c_nn_test_deny_group_token :: CWString -> Ptr Handle -> IO CULong++foreign import ccall unsafe "nn_test_make_pipe"+  c_nn_test_make_pipe :: Handle -> CInt -> CWString -> CWString -> Ptr Handle -> IO CULong++foreign import ccall unsafe "nn_test_open_as"+  c_nn_test_open_as :: Handle -> CWString -> CULong -> CInt -> Ptr Handle -> IO CULong++-- Safe, as it waits for the daemon, which runs in this process.+foreign import ccall safe "nn_test_wait_closed"+  c_nn_test_wait_closed :: Handle -> CULong -> Ptr CInt -> IO CULong++foreign import ccall unsafe "nn_token_pipe_owner"+  c_nn_token_pipe_owner :: Handle -> Ptr CWString -> Ptr CString -> IO CULong++foreign import ccall unsafe "CloseHandle"+  c_CloseHandle :: Handle -> IO CInt++foreign import ccall unsafe "LocalFree"+  c_LocalFree :: Ptr a -> IO (Ptr a)++-- | Close a handle.+closeHandle :: Handle -> IO ()+closeHandle = void . c_CloseHandle++-- | Throw unless a call's Win32 error code is 0.+succeeded :: String -> CULong -> IO ()+succeeded call code = when (code /= 0) (ioError (userError (call <> " failed with Win32 error " <> show code)))++-- | Whether this process's token holds Administrators enabled, which a+-- filtered administrator's token does not.+administratorsEnabled :: IO Bool+administratorsEnabled =+  alloca $ \heldOut -> do+    succeeded "nn_test_administrators_enabled" =<< c_nn_test_administrators_enabled heldOut+    (/= 0) <$> peek heldOut++-- | Run an action with a copy of this process's token that holds+-- Administrators for deny only.+withFilteredToken :: (Handle -> IO a) -> IO a+withFilteredToken = bracket make closeHandle+  where+    make = alloca $ \tokenOut -> do+      succeeded "nn_test_filtered_token" =<< c_nn_test_filtered_token tokenOut+      peek tokenOut++-- | Run an action with a copy of a token, the process's where it is null,+-- at an integrity level.+withIntegrityToken :: Handle -> Word32 -> (Handle -> IO a) -> IO a+withIntegrityToken base level = bracket make closeHandle+  where+    make = alloca $ \tokenOut -> do+      succeeded "nn_test_integrity_token" =<< c_nn_test_integrity_token base (fromIntegral level) tokenOut+      peek tokenOut++-- | Run an action with a token as a process of the daemon's account that+-- is not elevated holds: Administrators for deny only, no privilege, and+-- Medium integrity.+withMediumToken :: (Handle -> IO a) -> IO a+withMediumToken action = withFilteredToken $ \filtered -> withIntegrityToken filtered mediumIntegrity action++-- | Run an action with a copy of this process's token that holds the group+-- the SID names for deny only.+withDeniedGroup :: Text -> (Handle -> IO a) -> IO a+withDeniedGroup group = bracket make closeHandle+  where+    make = withCWString (T.unpack group) $ \cGroup -> alloca $ \tokenOut -> do+      succeeded "nn_test_deny_group_token" =<< c_nn_test_deny_group_token cGroup tokenOut+      peek tokenOut++-- | The SID the daemon would make the owner of its pipe if it ran with the+-- token.+tokenPipeOwner :: Handle -> IO Text+tokenPipeOwner token =+  alloca $ \sidOut -> alloca $ \failedOut -> do+    code <- c_nn_token_pipe_owner token sidOut failedOut+    failed <- maybePeek peekCString =<< peek failedOut+    succeeded (fromMaybe "nn_token_pipe_owner" failed) code+    found <- peek sidOut+    (T.pack <$> peekCWString found) `finally` c_LocalFree found++-- | Make a pipe as a token, the process's own where it is null, or give+-- the Win32 error code that stopped it.  The pipe is for the caller to+-- close.+makePipeAs :: Handle -> Privilege -> Text -> Text -> IO (Either CULong Handle)+makePipeAs token privilege name sddl =+  withCWString (T.unpack name) $ \cName -> withCWString (T.unpack sddl) $ \cSddl -> alloca $ \pipeOut -> do+    code <- c_nn_test_make_pipe token restore cName cSddl pipeOut+    if code == 0 then Right <$> peek pipeOut else pure (Left code)+  where+    restore = case privilege of+      Ordinary -> 0+      WithRestore -> 1++-- | Add an instance to the pipe at the address as a token, or give the+-- Win32 error code that refused it.  The instance is for the caller to+-- close.+addInstanceAs :: Handle -> BS.ByteString -> IO (Either CULong Handle)+addInstanceAs token address =+  withCWString (T.unpack (TE.decodeUtf8Lenient address)) $ \cName -> alloca $ \pipeOut -> do+    code <- c_nn_test_make_pipe token 0 cName nullPtr pipeOut+    if code == 0 then Right <$> peek pipeOut else pure (Left code)++-- | Open the pipe at the address as a token, the process's where it is+-- null, as the library's client does, for the access, or give the Win32+-- error code that refused it.  The connection is for the caller to close.+openAs :: Handle -> BS.ByteString -> Word32 -> Visibility -> IO (Either CULong Handle)+openAs token address access visibility =+  withCWString (T.unpack (TE.decodeUtf8Lenient address)) $ \cName -> alloca $ \pipeOut -> do+    code <- c_nn_test_open_as token cName (fromIntegral access) effectiveOnly pipeOut+    if code == 0 then Right <$> peek pipeOut else pure (Left code)+  where+    effectiveOnly = case visibility of+      AllGroups -> 0+      EffectiveOnly -> 1++-- | Connect to the pipe at the address as a token, the process's where it+-- is null, and say whether the daemon ends the connection before the+-- client has sent a byte, or give the Win32 error code that stopped it.+connectedAndClosedAs :: Handle -> BS.ByteString -> Visibility -> IO (Either CULong Bool)+connectedAndClosedAs token address visibility =+  openAs token address Pipe.clientPipeAccess visibility >>= \opened -> case opened of+    Left code -> pure (Left code)+    Right pipe -> (waitClosed pipe `finally` closeHandle pipe)+  where+    waitClosed pipe = alloca $ \closedOut -> do+      code <- c_nn_test_wait_closed pipe closeWaitMillis closedOut+      if code == 0 then Right . (/= 0) <$> peek closedOut else pure (Left code)++-- | 'connectedAndClosedAs' as the process.+connectedAndClosed :: BS.ByteString -> Visibility -> IO (Either CULong Bool)+connectedAndClosed = connectedAndClosedAs nullPtr++#else++testDaemonPipe = [] <$ putStrLn "daemon/pipe\n  SKIP  Windows only"++testDaemonPipeIO = [] <$ putStrLn "daemon/pipe-io\n  SKIP  Windows only"++daemonPipeAccounts _ = die "the daemon's pipe is Windows only"++#endif
+ test/Test/DaemonStore.hs view
@@ -0,0 +1,1602 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TupleSections #-}++-- | Tests of a command's store through a daemon ("Nix.Daemon.ClientStore"):+-- the order derivations are added in, the spellings an add is sent in, the+-- settings a client sends and the words a failure is reported in; the+-- store's operations against a daemon in memory that records what it is+-- sent, and how its connection fails and is replaced; the connection a+-- socket makes, or on Windows a named pipe; and evaluation and adds+-- against a daemon serving a store of its own.+module Test.DaemonStore+  ( testDaemonStore,+    testDaemonStoreIO,+  )+where++import Control.Concurrent.Async (async, asyncThreadId, wait)+import Control.Concurrent.Chan (newChan, writeChan)+import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)+import Control.Exception (AsyncException (UserInterrupt), ErrorCall (..), IOException, bracket, displayException, finally, throwIO, try)+import Control.Monad (void, when)+import Control.Monad.Except (ExceptT (..), runExceptT)+import Control.Monad.IO.Class (liftIO)+import Data.Bifunctor (bimap, first)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Builder as BB+import qualified Data.ByteString.Char8 as BS8+import qualified Data.ByteString.Lazy as BL+import Data.Either (isRight)+import Data.Foldable (traverse_)+import Data.Functor (($>))+import Data.IORef (IORef, atomicModifyIORef', modifyIORef', newIORef, readIORef, writeIORef)+import Data.List (find, nub, sort)+import qualified Data.Map.Strict as Map+import Data.Maybe (mapMaybe)+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import HttpFixture (Reply (..), httpResponse, withHttpServer)+import Network.Socket (Family (AF_UNIX), SockAddr (SockAddrUnix), SocketType (Stream), accept, bind, close, defaultProtocol, listen, socket)+import Network.Socket.ByteString (recv, sendAll)+import Nix.Builder (BuildStop (..), defaultBuildConfig)+import Nix.Builder.BuildUser (ProcessPrivilege (..))+import Nix.Builder.Sandbox (SandboxMode (..))+import Nix.Builder.Settings (MachineDefaults (..))+import Nix.CacheDirectory (cacheInfoFileName, cacheInfoText, directoryUrl)+import Nix.Config (AssignedSettings (..), DefaultUse (..), HowAssigned (..), NixConfig (..), PathSetValue (..), defaultNixConfig)+import qualified Nix.Daemon.Client as Client+import Nix.Daemon.ClientStore+  ( Connector,+    DaemonAddress (..),+    DaemonOpFailure (..),+    DaemonStoreConfig (..),+    clientSettings,+    connectFailureText,+    daemonAddressPath,+    daemonOperation,+    daemonStoreName,+    derivationAddOrder,+    dialDaemon,+    evalWriteRequest,+    flatMethod,+    narMethod,+    opFailureText,+    openFailureText,+    previouslyFailedText,+    textMethod,+    withDaemonFixedOutputs,+    withDaemonPushSource,+    withDaemonSession,+    withDaemonStore,+  )+import qualified Nix.Daemon.Connection as Conn+import Nix.Daemon.Dial (closeDaemonConnection, connectDaemon, connectionTransport)+import qualified Nix.Daemon.Listen as Listen+import Nix.Daemon.LocalStore (newServedStore, serveLocal)+import qualified Nix.Daemon.Ops as Ops+import qualified Nix.Daemon.Protocol as Proto+import Nix.DependencyGraph (DepNode (..))+import Nix.Derivation (Derivation (..), DerivationOutput (..), Platform (..), currentPlatform, drvFile, drvFileATerm, drvFileDerivation, drvFilePath, inputAddressed, toATerm)+import Nix.Eval (NixValue (..), unrestrictedPolicy)+import Nix.Eval.IO (EvalState (..), SessionStore (..), newEvalStateWith, sourceCopies)+import Nix.Hash (FileIngestionMethod (..), bytesToHexText, makeFixedOutputPath, makeSourcePath, makeTextPath, sha256Digest)+import Nix.Logger (ActivityStart (..), Logger, plainLogger)+import Nix.Push (PushCompression (..), PushSummary (..))+import Nix.Push.Directory (DirectoryPush (..), ed25519SeedBytes, pushToDirectory)+import Nix.Push.Source (PushSource (..), PushedPath (..), localPushSource)+import Nix.Realise (ClosureOutcome (..))+import Nix.Store (GcRoot (..), Store (..), addToStore, closeStore, drvReferences, findRoots, isValid, openStore, queryReferences)+import Nix.Store.Ops (EvalObjects (..), EvalWrite (..), EvalWrites (..), MadeOps (..), StoreOps (..), StoreQueries (..), withLocalStore)+import Nix.Store.Path (StoreDir (..), StoreWriteMode (..), badStorePathText, defaultStoreDir, parseStorePath, storePathToFilePath, storePathToText)+import Nix.Store.Path.Internal (StorePath (..))+import Nix.Trust.Fetch (FixedOutputStore (..), fetchAndScan)+import Nix.Trust.Scan (scanFetched)+import qualified NovaCache.Hash as CHash+import qualified NovaCache.NAR as NAR+import qualified NovaCache.Signing as Signing+import qualified System.Directory as Dir+import System.FilePath (takeFileName, (</>))+import System.IO.Error (ioeGetErrorString, ioeSetErrorString, mkIOError, resourceVanishedErrorType)+import qualified System.Info as SI+import Test.Daemon (withSocketDaemon)+import Test.DaemonClient (Logged (..), Standing (..), barPath, channelTransport, eventLogger, fooPath, missingPath, sampleInfo, serverConfigAt, standing, withNarHash)+import Test.Harness (TestResult (..), andThen, assertEqual, evalNixIOIn, findTestShell, forceRemoveIfExists, mkTestBuildDrv, runTest, runTestM, symlinksAvailable, throwawayKey)+import Test.Push (cacheListing)+import qualified Test.QuickCheck as QC++-- ---------------------------------------------------------------------------+-- Without a connection+-- ---------------------------------------------------------------------------++-- | The order derivations are added in, the spellings an add is sent in,+-- and the words a failure is reported in.+testDaemonStore :: IO [Bool]+testDaemonStore = do+  putStrLn "daemon/client-store"+  sequence+    [ runTestM "derivations are added with everything each one refers to before it" $ do+        result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} (QC.forAll genDerivations inputsFirst)+        pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result))),+      runTest "an input derivation and a source come before what names them, whatever the order of their keys" $+        let early = StorePath (T.replicate 32 "0") "early.drv"+            late = StorePath (T.replicate 32 "z") "late.drv"+            earlyByName = StorePath (T.replicate 32 "1") "early-by-name.drv"+            lateByName = StorePath (T.replicate 32 "y") "late-by-name.drv"+            recipes =+              [ (early, recipe "early" [late] []),+                (late, recipe "late" [] []),+                (earlyByName, recipe "early-by-name" [] [lateByName]),+                (lateByName, recipe "late-by-name" [] [])+              ]+         in assertEqual "order" (Right [late, early, lateByName, earlyByName]) (map (\(path, _, _) -> path) <$> derivationAddOrder (recorded recipes)),+      runTest "a recorded derivation that names no path, or does not parse, is refused in words that name it" $+        let key = storePathToText defaultStoreDir (StorePath (T.replicate 32 "0") "garbled.drv")+            parseRefused = case derivationAddOrder (Map.singleton key "not a derivation") of+              Left message -> ("the recorded .drv for " <> key <> " does not parse: ") `T.isPrefixOf` message+              Right _ -> False+         in assertEqual "no path" (Left "no store path: not a path") (void <$> derivationAddOrder (Map.singleton "not a path" (toATerm (recipe "x" [] []))))+              `andThen` assertEqual "no parse" True parseRefused+              `andThen` assertEqual "nothing recorded" (Right []) (void <$> derivationAddOrder Map.empty),+      runTest "an evaluation's write is asked for in upstream's spellings, a text alone naming references" $+        assertEqual "text" (Ops.AddToStoreRequest "n" "text:sha256" (Set.singleton fooPath) Ops.NoRepair) (evalWriteRequest (TextWrite "n" (Set.singleton fooPath) "contents"))+          `andThen` assertEqual "recursive" (Ops.AddToStoreRequest "n" "fixed:r:sha256" Set.empty Ops.NoRepair) (evalWriteRequest (NarWrite "n" "contents"))+          `andThen` assertEqual "flat" (Ops.AddToStoreRequest "n" "fixed:sha256" Set.empty Ops.NoRepair) (evalWriteRequest (FlatWrite "n" "contents"))+          `andThen` assertEqual "spellings" ("text:sha256", "fixed:r:sha256", "fixed:sha256") (textMethod, narMethod, flatMethod),+      runTest "the settings a client sends come from its configuration, cores 0 where it sets none as upstream's client sends its own default, upstream's defaults for the rest, and as overrides the store settings a source set" $+        let configured = defaultNixConfig {ncKeepFailed = True, ncFallback = True, ncCores = Just 2}+            sent keepFailed tryFallback cores = Ops.ClientSettings keepFailed False tryFallback (Proto.Verbosity 3) 1 0 True cores True Map.empty+            overridden = configured {ncSandbox = Just SandboxDisabled, ncSubstituters = ["https://cache.example"], ncRestrictEval = True}+            assigned = replacedSettings ["sandbox", "substituters", "restrict-eval", "keep-failed", "cores"]+         in assertEqual "configured" (sent True True 2) (clientSettings noneAssigned configured)+              `andThen` assertEqual "defaults" (sent False False 0) (clientSettings noneAssigned defaultNixConfig)+              `andThen` assertEqual "zero set" (sent False False 0) (clientSettings noneAssigned defaultNixConfig {ncCores = Just 0})+              `andThen` assertEqual "overrides" ((sent True True 2) {Ops.csOverrides = Map.fromList [("sandbox", "false"), ("substituters", "https://cache.example")]}) (clientSettings assigned overridden)+              `andThen` assertEqual "unset cores" 0 Ops.unsetCores,+      runTest "a connection that cannot be made or opened, and a refusal, are worded as upstream words them" $+        let socketAddress = DefaultSocket "/s"+            named = NamedSocket "/run/s"+         in assertEqual "connect" ("cannot connect to " <> connectEndpoint <> " at \"/s\": Connection refused") (connectFailureText socketAddress "Connection refused")+              `andThen` assertEqual "previously failed" "opening a connection to remote store 'daemon' previously failed" (previouslyFailedText socketAddress)+              `andThen` assertEqual "previously failed, named" "opening a connection to remote store 'unix:///run/s' previously failed" (previouslyFailedText named)+              `andThen` assertEqual "open" "cannot open connection to remote store 'daemon': error: Nix daemon disconnected unexpectedly (maybe it crashed?)" (openFailureText socketAddress (Client.ConnectionLost Client.disconnectedMessage))+              `andThen` assertEqual "open, named" "cannot open connection to remote store 'unix:///run/s': error: no" (openFailureText named (Client.DaemonFailed (Ops.daemonError "no")))+              `andThen` assertEqual "refused" "the store refuses this" (opFailureText (DaemonRefused (Ops.daemonError "the store refuses this")))+              `andThen` assertEqual "link" "gone" (opFailureText (LinkFailed "gone"))+              `andThen` assertEqual "names" ("daemon", "unix:///run/s") (daemonStoreName socketAddress, daemonStoreName named)+              `andThen` assertEqual "encoded names" ("unix:///run/a%20b:c@d/100%25/~s_-.", "unix:///caf%C3%A9/s") (daemonStoreName (NamedSocket "/run/a b:c@d/100%/~s_-."), daemonStoreName (NamedSocket "/caf\xC3\xA9/s"))+              `andThen` assertEqual "path" "/run/s" (daemonAddressPath named)+    ]++-- | What a connection to the daemon is to on this platform, in the+-- words of a failure to make one.+connectEndpoint :: Text+connectEndpoint = if onWindows then "named pipe" else "socket"++-- | Whether this is Windows, where the daemon listens on a named pipe and+-- not a Unix socket.+onWindows :: Bool+onWindows = SI.os == "mingw32"++-- | A derivation as evaluation records it, in the order to add it: its+-- path, the derivation, and its ATerm.+type Recorded = (StorePath, Derivation, BS.ByteString)++-- | Derivations as evaluation records them: each ATerm by the text of its+-- path.+recorded :: [(StorePath, Derivation)] -> Map.Map Text BS.ByteString+recorded recipes = Map.fromList [(storePathToText defaultStoreDir path, toATerm drv) | (path, drv) <- recipes]++-- | A derivation that names input derivations and sources, whose name+-- makes it differ from another.+recipe :: Text -> [StorePath] -> [StorePath] -> Derivation+recipe name inputs sources =+  Derivation+    { drvOutputs = [DerivationOutput "out" (StorePath (T.replicate 32 "c") (name <> "-out")) "" ""],+      drvInputDrvs = Map.fromList [(input, ["out"]) | input <- inputs],+      drvInputSrcs = sort sources,+      drvPlatform = X86_64_Linux,+      drvBuilder = "/bin/sh",+      drvArgs = [],+      drvEnv = Map.singleton "name" (TE.encodeUtf8 name)+    }++-- | Derivations, each naming some of those generated before it as inputs+-- and some as sources, and an input that is not among them.  The paths'+-- hashes are random, so the order of their keys is unrelated to which+-- names which.+genDerivations :: QC.Gen [(StorePath, Derivation)]+genDerivations = do+  count <- QC.choose (0, 8)+  hashes <- QC.vectorOf count (T.pack <$> QC.vectorOf 32 (QC.elements nix32Alphabet))+  let paths = [StorePath hash ("d" <> T.pack (show index) <> ".drv") | (index, hash) <- zip [0 :: Int ..] (nub hashes)]+      outside = StorePath (T.replicate 32 "a") "outside.drv"+  mapM+    ( \(position, path) -> do+        inputs <- QC.sublistOf (take position paths)+        sources <- QC.sublistOf (take position paths)+        pure (path, recipe (spName path) (outside : inputs) sources)+    )+    (zip [0 ..] paths)+  where+    nix32Alphabet = "0123456789abcdfghijklmnpqrsvwxyz"++-- | Whether the order derivations are added in places each once, each+-- after every derivation of the map that it names, and keeps what was+-- recorded.+inputsFirst :: [(StorePath, Derivation)] -> QC.Property+inputsFirst recipes = case derivationAddOrder (recorded recipes) of+  Left refusal -> QC.counterexample (T.unpack refusal) False+  Right order ->+    let paths = [path | (path, _, _) <- order]+        position = Map.fromList (zip paths [0 :: Int ..])+        before dependency dependent = case (Map.lookup dependency position, Map.lookup dependent position) of+          (Just earlier, Just later) -> earlier < later+          _ -> True+     in QC.conjoin+          [ QC.counterexample "each derivation once" (sort paths QC.=== sort (map fst recipes)),+            QC.counterexample "references first" (and [before reference path | (path, drv, _) <- order, reference <- drvReferences drv]),+            QC.counterexample "what was recorded" (Map.fromList [(path, (drv, aterm)) | (path, drv, aterm) <- order] QC.=== Map.fromList [(path, (drv, toATerm drv)) | (path, drv) <- recipes])+          ]++-- ---------------------------------------------------------------------------+-- A daemon in memory+-- ---------------------------------------------------------------------------++-- | What the daemon in memory holds, and every upload it was sent.+data Held = Held+  { heldValid :: !(Map.Map StorePath Proto.UnkeyedValidPathInfo),+    heldUploads :: ![Upload],+    -- | The temporary roots and the validity queries the daemon was asked,+    -- in order.+    heldCalls :: ![Called],+    -- | The settings the client had sent when each validity query came, in+    -- order: none before it has sent any.+    heldSettings :: ![Maybe Ops.ClientSettings],+    -- | The builds the daemon was asked for, in order: what to build and+    -- in which mode.+    heldBuilds :: ![([Proto.DerivedPath], Proto.BuildMode)],+    -- | The bytes of each link the daemon was asked to root, in order.+    heldIndirectRoots :: ![BS.ByteString],+    -- | What the daemon reports while it builds, and the error it ends a+    -- build with, if it fails the build.+    heldBuildReport :: ![Ops.LogEvent],+    heldBuildFailure :: !(Maybe Proto.DaemonError),+    -- | The result the daemon gives for each opaque path it is asked to+    -- realise, none for a path not here.+    heldResults :: !(Map.Map StorePath Proto.BuildResult)+  }++-- | What the daemon in memory was asked: to root a path, which paths it+-- holds, a path's record, and which paths a substituter offers.+data Called+  = TempRooted !StorePath+  | Queried !(Set StorePath)+  | InfoQueried !StorePath+  | OfferQueried !(Set StorePath)+  deriving (Eq, Show)++-- | An upload as the daemon in memory was sent it.+data Upload = Upload+  { upName :: !BS.ByteString,+    upMethod :: !Proto.ContentAddressMethod,+    upAlgo :: !Text,+    upReferences :: !(Set StorePath),+    upBytes :: !BS.ByteString+  }+  deriving (Eq, Show)++-- | The path the daemon in memory makes of an upload, or why it refuses.+type PathFor = Ops.DumpUpload -> BS.ByteString -> Either Proto.DaemonError StorePath++-- | The path an upload's content makes, as the daemon makes it.+contentPath :: PathFor+contentPath upload bytes = first (Ops.daemonError . badStorePathText) $ case Ops.duMethod upload of+  Proto.TextMethod -> makeTextPath name digest (Set.toList (Ops.duReferences upload))+  Proto.FixedMethod NarIngestion -> makeSourcePath name digest (Ops.duReferences upload)+  Proto.FixedMethod FlatIngestion -> makeFixedOutputPath name "sha256" FlatIngestion digest+  where+    name = TE.decodeUtf8Lenient (Ops.duName upload)+    digest = sha256Digest bytes++-- | A store that refuses what a test does not ask of it.+unavailableStore :: Ops.DaemonStore IO+unavailableStore =+  Ops.DaemonStore+    { Ops.dsIsValidPath = \_ _ -> pure (Left notHere),+      Ops.dsQueryValidPaths = \_ _ _ -> pure (Left notHere),+      Ops.dsQuerySubstitutablePaths = \_ _ -> pure (Left notHere),+      Ops.dsQueryReferrers = \_ _ -> pure (Left notHere),+      Ops.dsQueryValidDerivers = \_ _ -> pure (Left notHere),+      Ops.dsQueryDerivationOutputMap = \_ _ -> pure (Left notHere),+      Ops.dsQueryAllValidPaths = \_ -> pure (Left notHere),+      Ops.dsQueryPathInfo = \_ _ -> pure (Left notHere),+      Ops.dsQueryMissing = \_ _ -> pure (Left notHere),+      Ops.dsAddToStore = \_ _ -> pure (Ops.Taken (Left notHere)),+      Ops.dsAddToStoreNar = \_ _ _ _ -> pure (Ops.Taken (Left notHere)),+      Ops.dsBuildPaths = \_ _ _ -> pure (Left notHere),+      Ops.dsBuildPathsWithResults = \_ _ _ -> pure (Left notHere),+      Ops.dsEnsurePath = \_ _ -> pure (Left notHere),+      Ops.dsAddTempRoot = \_ _ -> pure (Left notHere),+      Ops.dsAddIndirectRoot = \_ _ -> pure (Left notHere),+      Ops.dsFindRoots = \_ _ -> pure (Left notHere),+      Ops.dsCollectGarbage = \_ _ -> pure (Left notHere),+      Ops.dsOptimiseStore = \_ -> pure (Left notHere),+      Ops.dsVerifyStore = \_ _ _ -> pure (Left notHere),+      Ops.dsAddSignatures = \_ _ _ -> pure (Left notHere),+      Ops.dsNarFromPath = \_ _ -> pure (Left notHere)+    }+  where+    notHere = Ops.daemonError "not in these tests"++-- | The daemon in memory: it answers which paths are valid and a path's+-- info, takes temporary roots and indirect roots, records every dump it is+-- sent and every build it is asked for, and makes the path 'PathFor' says.+fakeDaemonStore :: Proto.NarHash -> PathFor -> IORef Held -> Ops.DaemonStore IO+fakeDaemonStore narHash pathFor state =+  unavailableStore+    { Ops.dsQueryValidPaths = \work _ paths -> do+        modifyIORef' state (\held -> held {heldCalls = heldCalls held ++ [Queried paths], heldSettings = heldSettings held ++ [Ops.connClient (Ops.workSettings work)]})+        Right . Set.intersection paths . Map.keysSet . heldValid <$> readIORef state,+      Ops.dsAddTempRoot = \_ path -> Right () <$ modifyIORef' state (\held -> held {heldCalls = heldCalls held ++ [TempRooted path]}),+      Ops.dsAddIndirectRoot = \_ bytes -> Right () <$ modifyIORef' state (\held -> held {heldIndirectRoots = heldIndirectRoots held ++ [bytes]}),+      Ops.dsBuildPaths = \work targets mode -> do+        modifyIORef' state (\held -> held {heldBuilds = heldBuilds held ++ [(targets, mode)]})+        held <- readIORef state+        traverse_ (Ops.workReport work) (heldBuildReport held)+        pure (maybe (Right ()) Left (heldBuildFailure held)),+      Ops.dsQueryPathInfo = \_ path -> do+        modifyIORef' state (\held -> held {heldCalls = heldCalls held ++ [InfoQueried path]})+        Right . Map.lookup path . heldValid <$> readIORef state,+      Ops.dsQueryAllValidPaths = \_ -> Right . Map.keysSet . heldValid <$> readIORef state,+      Ops.dsQuerySubstitutablePaths = \_ paths -> do+        modifyIORef' state (\held -> held {heldCalls = heldCalls held ++ [OfferQueried paths]})+        pure (Right Set.empty),+      Ops.dsBuildPathsWithResults = \_ targets mode -> do+        modifyIORef' state (\held -> held {heldBuilds = heldBuilds held ++ [(targets, mode)]})+        held <- readIORef state+        pure (Right [Proto.KeyedBuildResult target result | target@(Proto.DerivedOpaque path) <- targets, Just result <- [Map.lookup path (heldResults held)]]),+      Ops.dsAddToStore = \_ upload -> pure (collecting (finish upload))+    }+  where+    finish upload bytes = do+      let received = Upload (Ops.duName upload) (Ops.duMethod upload) (Ops.duAlgo upload) (Ops.duReferences upload) bytes+      modifyIORef' state (\held -> held {heldUploads = heldUploads held ++ [received]})+      case pathFor upload bytes of+        Left refusal -> pure (Left refusal)+        Right path -> do+          let info = sampleInfo narHash (Ops.duReferences upload)+          Right (Proto.ValidPathInfo path info) <$ modifyIORef' state (\held -> held {heldValid = Map.insert path info (heldValid held)})+    collecting finishWith = Ops.Taking (more BS.empty) (finishWith BS.empty) (pure ())+      where+        more held chunk = pure (Ops.Taking (more (held <> chunk)) (finishWith (held <> chunk)) (pure ()))++-- | How many connections a connector made, and how many it closed.+data Dials = Dials+  { dialsMade :: !(IORef Int),+    dialsClosed :: !(IORef Int)+  }++newDials :: IO Dials+newDials = Dials <$> newIORef 0 <*> newIORef 0++-- | How many connections a daemon in memory was given, and how many were+-- closed.+dialCounts :: Dials -> IO (Int, Int)+dialCounts dials = (,) <$> readIORef (dialsMade dials) <*> readIORef (dialsClosed dials)++-- | A connector to a daemon in memory: each connection is served, as the+-- function given serves it, on a thread of its own, and closing it ends+-- the daemon's input and waits for the thread.+memoryConnector :: Dials -> (Conn.Transport IO -> IO Conn.ConnectionEnd) -> Connector+memoryConnector dials serve = do+  modifyIORef' (dialsMade dials) (+ 1)+  toDaemon <- newChan+  toClient <- newChan+  daemonTransport <- channelTransport toDaemon toClient+  clientTransport <- channelTransport toClient toDaemon+  running <- async (serve daemonTransport `finally` writeChan toClient Nothing)+  pure (Right (clientTransport, modifyIORef' (dialsClosed dials) (+ 1) *> writeChan toDaemon Nothing *> void (wait running)))++-- | The daemon in memory, and a connector to it.+data FakeDaemon = FakeDaemon+  { fakeHeld :: !(IORef Held),+    fakeDials :: !Dials,+    fakeConnector :: !Connector+  }++-- | The version the daemon command serves: the newest, with the one+-- feature its codec carries and not the one that stops a client sending+-- settings.+daemonVersion :: Proto.Version+daemonVersion = Proto.Version Proto.latestVersionNumber (Set.singleton Proto.featureRealisationWithPath)++-- | A daemon in memory that holds the paths given, with their references,+-- and makes the paths 'PathFor' says.+newFakeDaemon :: Proto.NarHash -> PathFor -> [(StorePath, Set StorePath)] -> IO FakeDaemon+newFakeDaemon narHash = newFakeDaemonServing narHash daemonVersion++-- | 'newFakeDaemon' offering a version.+newFakeDaemonServing :: Proto.NarHash -> Proto.Version -> PathFor -> [(StorePath, Set StorePath)] -> IO FakeDaemon+newFakeDaemonServing narHash version pathFor valid = do+  state <- newIORef (Held (Map.fromList [(path, sampleInfo narHash references) | (path, references) <- valid]) [] [] [] [] [] [] Nothing Map.empty)+  dials <- newDials+  let serve = Conn.serveConnection (serverConfigAt version) Proto.Trusted (fakeDaemonStore narHash pathFor state)+  pure (FakeDaemon state dials (memoryConnector dials serve))++-- | The store a command is given over a daemon, reading its files from a+-- directory.+storeConfig :: StoreDir -> DaemonStoreConfig+storeConfig dir =+  DaemonStoreConfig+    { dscAddress = DefaultSocket "/run/nix/daemon-socket/socket",+      dscFileDir = dir,+      dscSettings = clientSettings noneAssigned defaultNixConfig,+      dscLogger = quietLogger+    }++-- | No setting a source set.+noneAssigned :: AssignedSettings+noneAssigned = AssignedSettings Map.empty++-- | Settings each of which a plain assignment set.+replacedSettings :: [ByteString] -> AssignedSettings+replacedSettings names = AssignedSettings (Map.fromList [(name, Replaced) | name <- names])++-- | The directory a test gives a store whose files it never reads.+unusedDir :: StoreDir+unusedDir = StoreDir "/nonexistent/nn-daemon-store"++-- | A logger that says nothing.+quietLogger :: Logger+quietLogger = plainLogger (\_ _ -> pure ()) (const (pure ()))++-- | Run an action with an empty scratch directory under the temporary+-- directory, removed after.+withScratch :: FilePath -> (FilePath -> IO a) -> IO a+withScratch name action = do+  tmp <- Dir.getTemporaryDirectory+  let dir = tmp </> name+  forceRemoveIfExists dir+  Dir.createDirectoryIfMissing True dir+  action dir `finally` forceRemoveIfExists dir++-- | A derivation as evaluation makes it, named and recorded with the path+-- its ATerm and references make.+recordedDerivation :: Text -> [StorePath] -> [StorePath] -> Either Text Recorded+recordedDerivation name inputs sources = do+  file <- first badStorePathText (drvFile name (recipe name inputs sources))+  pure (drvFilePath file, drvFileDerivation file, drvFileATerm file)++-- | An input derivation, and a derivation naming it whose path sorts+-- before the input's, so that adding in the order of the keys would add+-- the dependent first.+dependentSortingFirst :: Either Text (Recorded, Recorded)+dependentSortingFirst = do+  input@(inputPath, _, _) <- recordedDerivation "input" [] []+  candidates <- traverse (\index -> recordedDerivation ("dependent" <> T.pack (show index)) [inputPath] []) [1 .. dependentCount]+  dependent <- maybe (Left "no dependent derivation sorts before its input") Right (find (\(path, _, _) -> path < inputPath) candidates)+  pure (input, dependent)++-- | How many derivations name an input at once: each sorts before it with+-- probability one half, so that none does is vanishingly unlikely.+dependentCount :: Int+dependentCount = 64++-- | The derivations as the map evaluation records them is keyed.+derivationMap :: [Recorded] -> Map.Map Text BS.ByteString+derivationMap derivations = Map.fromList [(storePathToText defaultStoreDir path, aterm) | (path, _, aterm) <- derivations]++-- | The upload that adds a derivation: its name, as a text that refers to+-- what it refers to.+derivationUpload :: Recorded -> Upload+derivationUpload (path, drv, aterm) = Upload (TE.encodeUtf8 (spName path)) Proto.TextMethod "sha256" (Set.fromList (drvReferences drv)) aterm++-- | What an evaluation made, as a command adds it.+noObjects :: EvalObjects+noObjects = EvalObjects Map.empty Map.empty Map.empty++-- ---------------------------------------------------------------------------+-- With a connection+-- ---------------------------------------------------------------------------++-- | The store's operations against a daemon in memory, the connection a+-- socket makes, and evaluation and adds against a daemon serving a store+-- of its own.+testDaemonStoreIO :: IO [Bool]+testDaemonStoreIO = do+  putStrLn "daemon/client-store-sessions"+  sockets <- socketTests+  memory <- withNarHash "daemon/client-store-sessions" (\narHash -> concat <$> sequence [memoryTests narHash, unreadableTests narHash, pushTrustTests narHash])+  served <- servedTests+  pure (sockets <> memory <> served)++-- | A connection to the daemon at an address, made and closed.+socketTests :: IO [Bool]+socketTests = do+  raw <- rawSocketTests+  rest <-+    sequence+      [ runTestM "an address nobody listens at and one that cannot name a daemon fail to connect, in the platform's words" $+          if onWindows+            then do+              absent <- reached (connectDaemon "\\\\.\\pipe\\nn-dial-absent")+              long <- reached (connectDaemon (BS.replicate 300 97))+              pure $+                assertEqual "absent" True (either ("CreateFileW: " `T.isPrefixOf`) (const False) absent)+                  `andThen` assertEqual "not a pipe" (Left "not a named pipe's path, which is \\\\.\\pipe\\ and a name") long+            else withScratch "nn-dial" $ \dir -> do+              let stale = dir </> "stale"+              bound <- socket AF_UNIX Stream defaultProtocol+              bind bound (SockAddrUnix stale)+              close bound+              absent <- reached (connectDaemon (BS8.pack (dir </> "absent")))+              refused <- reached (connectDaemon (BS8.pack stale))+              long <- reached (connectDaemon (BS.replicate 300 97))+              pure $+                assertEqual "absent" (Left "No such file or directory") absent+                  `andThen` assertEqual "refused" (Left "Connection refused") refused+                  `andThen` assertEqual "too long" (Left "path is too long") long,+        runTestM "a store over a daemon listening on a socket, or on Windows a named pipe, reads what the daemon's store holds and adds to it" $+          withSocketDaemon Listen.ForceTrusted id $ \_ address _ -> do+            let daemonAt = NamedSocket address+                config = (storeConfig unusedDir) {dscAddress = daemonAt}+                entry = NAR.NarRegular False "added through the daemon"+            withDaemonStore config (dialDaemon daemonAt) $ \ops -> do+              valid <- sqValidPaths (soQueries ops) (Set.fromList [fooPath, missingPath])+              added <- soAddSourceTree ops "tree" Set.empty entry+              validAfter <- traverse (sqValidPaths (soQueries ops) . Set.singleton) (either (const []) pure added)+              pure $+                assertEqual "valid" (Set.singleton fooPath) valid+                  `andThen` assertEqual "added" (first badStorePathText (makeSourcePath "tree" (sha256Digest (NAR.serialise entry)) Set.empty)) added+                  `andThen` assertEqual "valid after" (either (const []) (pure . Set.singleton) added) validAfter+      ]+  pure (raw <> rest)+  where+    reached connect = connect >>= either (pure . Left) (\connection -> Right () <$ closeDaemonConnection connection)++-- | A Unix socket's connection, which a test binds and listens on itself.+rawSocketTests :: IO [Bool]+rawSocketTests+  | onWindows = [] <$ putStrLn "  SKIP  Windows connects to the daemon's named pipe, not a Unix socket a test binds"+  | otherwise =+      sequence+        [ runTestM "a daemon's socket connects, its transport carries bytes both ways, and a read after the daemon closes is the end" $+            withScratch "nn-dial" $ \dir -> do+              let path = dir </> "socket"+              listener <- socket AF_UNIX Stream defaultProtocol+              ( do+                  bind listener (SockAddrUnix path)+                  listen listener 1+                  connected <- connectDaemon (BS8.pack path)+                  case connected of+                    Left reason -> pure (Fail reason)+                    Right connection -> do+                      (peer, _) <- accept listener+                      let transport = connectionTransport connection+                      sendAll peer "from the daemon"+                      heard <- Conn.transportReceive transport+                      Conn.transportSend transport (BB.byteString "from the client")+                      received <- recv peer 64+                      close peer+                      ended <- Conn.transportReceive transport+                      endedAgain <- Conn.transportReceive transport+                      closeDaemonConnection connection+                      pure $+                        assertEqual "heard" (Just "from the daemon") heard+                          `andThen` assertEqual "received" "from the client" received+                          `andThen` assertEqual "ended" (Nothing, Nothing) (ended, endedAgain)+                )+                `finally` close listener+        ]++-- | The store's operations over a daemon in memory.+memoryTests :: Proto.NarHash -> IO [Bool]+memoryTests narHash =+  sequence+    [ runTestM "a store asked nothing, or asked only what the daemon took as it was made, never connects" $ do+        daemon <- newFakeDaemon narHash contentPath []+        let writesOnly = noObjects {eoStoreWrites = Map.singleton (storePathToText defaultStoreDir fooPath) ([], WriteText)}+        answers <-+          withDaemonStore (storeConfig unusedDir) (fakeConnector daemon) $ \ops ->+            (,,) <$> soAddEvalObjects ops noObjects <*> soAddEvalObjects ops writesOnly <*> sqValidPaths (soQueries ops) Set.empty+        dials <- dialCounts (fakeDials daemon)+        pure (assertEqual "answers" (Right (), Right (), Set.empty) answers `andThen` assertEqual "connections made and closed" (0, 0) dials),+      runTestM "the queries ask the daemon: the valid paths among those given, and a path's references, none for one it does not hold" $ do+        daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.singleton barPath), (barPath, Set.empty)]+        answers <-+          withDaemonStore (storeConfig unusedDir) (fakeConnector daemon) $ \ops ->+            let queries = soQueries ops+             in (,,,) <$> sqValidPaths queries (Set.fromList [fooPath, barPath, missingPath]) <*> sqReferences queries fooPath <*> sqReferences queries barPath <*> sqReferences queries missingPath+        dials <- dialCounts (fakeDials daemon)+        pure $+          assertEqual "answers" (Set.fromList [fooPath, barPath], Right (Set.singleton barPath), Right Set.empty, Right Set.empty) answers+            `andThen` assertEqual "one connection, made and closed" (1, 1) dials,+      runTestM "a daemon that cannot be reached fails the operation that tried in upstream's words and every one after in its words for a failed connection, and is not tried again" $ do+        calls <- newIORef (0 :: Int)+        let config = storeConfig unusedDir+            unreachable = modifyIORef' calls (+ 1) $> Left "Connection refused"+            expected = connectFailureText (dscAddress config) "Connection refused"+            entry = NAR.NarRegular False "x"+        (queried, added, addedAgain) <-+          withDaemonStore config unreachable $ \ops ->+            (,,) <$> try (sqValidPaths (soQueries ops) (Set.singleton fooPath)) <*> soAddSourceTree ops "tree" Set.empty entry <*> soAddSourceTree ops "tree" Set.empty entry+        tried <- readIORef calls+        pure $ case queried of+          Left (err :: IOException) ->+            assertEqual "query" expected (T.pack (ioeGetErrorString err))+              `andThen` assertEqual "add" (Left (previouslyFailedText (dscAddress config))) added+              `andThen` assertEqual "add again" (Left (previouslyFailedText (dscAddress config))) addedAgain+              `andThen` assertEqual "connections tried" 1 tried+          Right found -> Fail ("expected the query to fail, got: " <> T.pack (show found)),+      runTestM "a daemon that fails the handshake fails the operation that tried in upstream's words and every one after in its words for a failed connection, is closed at once, and is not tried again" $ do+        made <- newIORef (0 :: Int)+        closed <- newIORef (0 :: Int)+        let config = storeConfig unusedDir+            gone = Conn.Transport (pure Nothing) (\_ -> pure ())+            connector = modifyIORef' made (+ 1) $> Right (gone, modifyIORef' closed (+ 1))+            expected = openFailureText (dscAddress config) (Client.ConnectionLost Client.disconnectedMessage)+        (queried, added) <-+          withDaemonStore config connector $ \ops ->+            (,) <$> try (sqValidPaths (soQueries ops) (Set.singleton fooPath)) <*> soAddSourceTree ops "tree" Set.empty (NAR.NarRegular False "x")+        counts <- (,) <$> readIORef made <*> readIORef closed+        pure $ case queried of+          Left (err :: IOException) ->+            assertEqual "query" expected (T.pack (ioeGetErrorString err))+              `andThen` assertEqual "add" (Left (previouslyFailedText (dscAddress config))) added+              `andThen` assertEqual "connections made and closed" (1, 1) counts+          Right found -> Fail ("expected the query to fail, got: " <> T.pack (show found)),+      runTestM "a connection that is lost while the settings are sent fails the operation that opened it with the reason, closes it, and fails every one after as a failed connection" $ do+        daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]+        let config = storeConfig unusedDir+            connector = fakeConnector daemon >>= traverse (\(transport, closing) -> (,closing) <$> losingOnSetOptions transport)+        (queried, added) <-+          withDaemonStore config connector $ \ops ->+            (,) <$> try (sqValidPaths (soQueries ops) (Set.singleton fooPath)) <*> soAddSourceTree ops "tree" Set.empty (NAR.NarRegular False "x")+        dials <- dialCounts (fakeDials daemon)+        pure $ case queried of+          Left (err :: IOException) ->+            assertEqual "query" Client.disconnectedMessage (T.pack (ioeGetErrorString err))+              `andThen` assertEqual "add" (Left (previouslyFailedText (dscAddress config))) added+              `andThen` assertEqual "connections made and closed" (1, 1) dials+          Right found -> Fail ("expected the query to fail, got: " <> T.pack (show found)),+      runTestM "an exception thrown while the settings are sent is reported as it is, not as a failed handshake, and closes the connection and fails every operation after as a failed connection" $ do+        daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]+        let config = storeConfig unusedDir+            connector = fakeConnector daemon >>= traverse (\(transport, closing) -> pure (throwingOnSetOptions transport, closing))+            reason = either (\(err :: IOException) -> T.pack (ioeGetErrorString err)) (const "no failure")+        (queried, added) <-+          withDaemonStore config connector $ \ops ->+            (,) <$> try (sqValidPaths (soQueries ops) (Set.singleton fooPath)) <*> soAddSourceTree ops "tree" Set.empty (NAR.NarRegular False "x")+        dials <- dialCounts (fakeDials daemon)+        pure $+          assertEqual "query" "the settings failed" (reason queried)+            `andThen` assertEqual "add" (Left (previouslyFailedText (dscAddress config))) added+            `andThen` assertEqual "connections made and closed" (1, 1) dials,+      runTestM "an exception thrown while the handshake is made is worded as a failed handshake, closes the connection, and fails every operation after as a failed connection" $ do+        made <- newIORef (0 :: Int)+        closed <- newIORef (0 :: Int)+        let config = storeConfig unusedDir+            broken = Conn.Transport (throwIO (ErrorCall "the transport failed")) (\_ -> pure ())+            connector = modifyIORef' made (+ 1) $> Right (broken, modifyIORef' closed (+ 1))+            reason = either (\(err :: IOException) -> T.pack (ioeGetErrorString err)) (const "no failure")+        (queried, added) <-+          withDaemonStore config connector $ \ops ->+            (,) <$> try (sqValidPaths (soQueries ops) (Set.singleton fooPath)) <*> soAddSourceTree ops "tree" Set.empty (NAR.NarRegular False "x")+        counts <- (,) <$> readIORef made <*> readIORef closed+        pure $+          assertEqual "query" (openFailureText (dscAddress config) (Client.ConnectionLost "the transport failed")) (reason queried)+            `andThen` assertEqual "add" (Left (previouslyFailedText (dscAddress config))) added+            `andThen` assertEqual "connections made and closed" (1, 1) counts,+      runTestM "a connector that throws is a failed connection, reported as the exception reads and not as a failed handshake, while an interrupt goes up and leaves the next operation to connect" $ do+        daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]+        thrown <- newIORef (0 :: Int)+        let config = storeConfig unusedDir+            failing = modifyIORef' thrown (+ 1) *> throwIO (ErrorCall "the connector failed")+            interrupted = throwIO UserInterrupt+            reason = either (\(err :: IOException) -> T.pack (ioeGetErrorString err)) (const "no failure")+        (ordinary, afterOrdinary) <- withDaemonStore config failing $ \ops ->+          (,) <$> try (sqValidPaths (soQueries ops) (Set.singleton fooPath)) <*> try (sqValidPaths (soQueries ops) (Set.singleton fooPath))+        attempts <- newIORef (0 :: Int)+        let interruptedOnce = do+              attempt <- atomicModifyIORef' attempts (\n -> (n + 1, n))+              if attempt == 0 then interrupted else fakeConnector daemon+        (interrupt, afterInterrupt) <- withDaemonStore config interruptedOnce $ \ops ->+          (,) <$> try (sqValidPaths (soQueries ops) (Set.singleton fooPath)) <*> sqValidPaths (soQueries ops) (Set.singleton fooPath)+        failures <- readIORef thrown+        pure $+          assertEqual "ordinary" "the connector failed" (reason ordinary)+            `andThen` assertEqual "after" (previouslyFailedText (dscAddress config)) (reason afterOrdinary)+            `andThen` assertEqual "tried" 1 failures+            `andThen` assertEqual "interrupt" (Left UserInterrupt) interrupt+            `andThen` assertEqual "after the interrupt" (Set.singleton fooPath) afterInterrupt,+      runTestM "a connection that breaks fails the operation that finds it with the reason and is closed, and the next operation connects again" $ do+        daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]+        broken <- newIORef False+        let lossy transport = transport {Conn.transportReceive = readIORef broken >>= \gone -> if gone then pure Nothing else Conn.transportReceive transport}+            connector = fmap (fmap (first lossy)) (fakeConnector daemon)+            reason = either (\(err :: IOException) -> T.pack (ioeGetErrorString err)) (const "no failure")+        (before, second, third) <-+          withDaemonStore (storeConfig unusedDir) connector $ \ops -> do+            before <- sqValidPaths (soQueries ops) (Set.singleton fooPath)+            writeIORef broken True+            second <- try (sqValidPaths (soQueries ops) (Set.singleton fooPath))+            writeIORef broken False+            third <- sqValidPaths (soQueries ops) (Set.singleton fooPath)+            pure (before, second, third)+        dials <- dialCounts (fakeDials daemon)+        pure $+          assertEqual "before" (Set.singleton fooPath) before+            `andThen` assertEqual "second" Client.disconnectedMessage (reason second)+            `andThen` assertEqual "third" (Set.singleton fooPath) third+            `andThen` assertEqual "connections made and closed" (2, 2) dials,+      runTestM "a transport that throws an IOException as an operation is sent fails the operation with its words and is closed, and the next operation connects again" $ do+        daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]+        broken <- newIORef False+        let reset = ioeSetErrorString (mkIOError resourceVanishedErrorType "send" Nothing Nothing) "Broken pipe"+            resetting transport = transport {Conn.transportSend = \builder -> readIORef broken >>= \gone -> if gone then ioError reset else Conn.transportSend transport builder}+            connector = fmap (fmap (first resetting)) (fakeConnector daemon)+            reason = either (\(err :: IOException) -> T.pack (ioeGetErrorString err)) (const "no failure")+        (second, third) <-+          withDaemonStore (storeConfig unusedDir) connector $ \ops -> do+            void (sqValidPaths (soQueries ops) (Set.singleton fooPath))+            writeIORef broken True+            second <- try (sqValidPaths (soQueries ops) (Set.singleton fooPath))+            writeIORef broken False+            third <- sqValidPaths (soQueries ops) (Set.singleton fooPath)+            pure (second, third)+        dials <- dialCounts (fakeDials daemon)+        pure $+          assertEqual "second" (T.pack (displayException reset)) (reason second)+            `andThen` assertEqual "third" (Set.singleton fooPath) third+            `andThen` assertEqual "connections made and closed" (2, 2) dials,+      runTestM "an exception that is not a failure to read from the connection or a file, thrown while a file is read for an upload, goes up and closes the connection, and the next operation connects again" $ do+        daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]+        let request = Ops.AddToStoreRequest "tree" narMethod Set.empty Ops.NoRepair+            valid = Client.queryValidPaths (Set.singleton fooPath) Ops.NoSubstitute+        (upload, afterUpload) <-+          withDaemonSession (fakeConnector daemon) (dscAddress (storeConfig unusedDir)) (dscSettings (storeConfig unusedDir)) (\_ -> pure ()) $ \session ->+            (,) <$> try (daemonOperation session (pure ()) (Client.addToStore request (throwIO (ErrorCall "the source failed")))) <*> daemonOperation session (pure ()) valid+        dials <- dialCounts (fakeDials daemon)+        pure $+          assertEqual "upload" (Left (ErrorCall "the source failed")) (void <$> upload)+            `andThen` assertEqual "next" (Right (Set.singleton fooPath)) afterUpload+            `andThen` assertEqual "connections made and closed" (2, 2) dials,+      runTestM "an operation settles while it holds the session, so the next operation starts after it and stops none of its activities" $ do+        daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]+        settling <- newEmptyMVar+        settled <- newEmptyMVar+        let valid = Client.queryValidPaths (Set.singleton fooPath) Ops.NoSubstitute+        (waiting, answers) <-+          withDaemonSession (fakeConnector daemon) (dscAddress (storeConfig unusedDir)) (dscSettings (storeConfig unusedDir)) (\_ -> pure ()) $ \session -> do+            earlier <- async (daemonOperation session (putMVar settling () *> takeMVar settled) valid)+            takeMVar settling+            -- Steps that ask the daemon nothing, so the one thing this+            -- operation can wait on is the session.+            later <- async (daemonOperation session (pure ()) (pure ()))+            waiting <- standing (asyncThreadId later)+            putMVar settled ()+            answers <- (,) <$> wait earlier <*> wait later+            pure (waiting, answers)+        pure $+          assertEqual "the next operation waits while the earlier settles" Waiting waiting+            `andThen` assertEqual "both answered" (Right (Set.singleton fooPath), Right ()) answers,+      runTestM "the settings go to the daemon once the handshake is made, from the command's configuration, and are not sent where the daemon grants the feature that stops them" $ do+        let configured = defaultNixConfig {ncKeepFailed = True, ncFallback = True, ncCores = Just 2}+            config = (storeConfig unusedDir) {dscSettings = clientSettings noneAssigned configured}+            queryOnce daemon = withDaemonStore config (fakeConnector daemon) (\ops -> sqValidPaths (soQueries ops) (Set.singleton fooPath))+            stoppable = Proto.Version Proto.latestVersionNumber (Set.fromList [Proto.featureRealisationWithPath, Proto.featureDisableSetOptions])+        sending <- newFakeDaemon narHash contentPath []+        granting <- newFakeDaemonServing narHash stoppable contentPath []+        unsetting <- newFakeDaemon narHash contentPath []+        void (queryOnce sending)+        void (queryOnce granting)+        void (withDaemonStore (storeConfig unusedDir) (fakeConnector unsetting) (\ops -> sqValidPaths (soQueries ops) (Set.singleton fooPath)))+        sentTo <- heldSettings <$> readIORef (fakeHeld sending)+        grantedTo <- heldSettings <$> readIORef (fakeHeld granting)+        unsetTo <- heldSettings <$> readIORef (fakeHeld unsetting)+        pure $+          assertEqual "sent" [Just (clientSettings noneAssigned configured)] sentTo+            `andThen` assertEqual "sent keep-failed, fallback and cores" [Just (Ops.ClientSettings True False True (Proto.Verbosity 3) 1 0 True 2 True Map.empty)] sentTo+            `andThen` assertEqual "cores where the configuration sets none" [Just (Ops.ClientSettings False False False (Proto.Verbosity 3) 1 0 True 0 True Map.empty)] unsetTo+            `andThen` assertEqual "granted" [Nothing] grantedTo,+      runTestM "a source tree is added as a NAR under its name and references, as the path its content makes" $ do+        daemon <- newFakeDaemon narHash contentPath []+        let entry = NAR.NarDirectory [("a", NAR.NarRegular False "x")]+            nar = NAR.serialise entry+            refs = Set.singleton fooPath+        added <- withDaemonStore (storeConfig unusedDir) (fakeConnector daemon) (\ops -> soAddSourceTree ops "tree" refs entry)+        held <- readIORef (fakeHeld daemon)+        pure $+          assertEqual "path" (first badStorePathText (makeSourcePath "tree" (sha256Digest nar) refs)) added+            `andThen` assertEqual "uploads" [Upload "tree" (Proto.FixedMethod NarIngestion) "sha256" refs nar] (heldUploads held),+      runTestM "a daemon that makes another path than the one computed is refused, for a tree and for a derivation" $ do+        daemon <- newFakeDaemon narHash (\_ _ -> Right barPath) []+        let entry = NAR.NarRegular False "x"+            wrong = StorePath (T.replicate 32 "d") "wrong.drv"+            spelled = storePathToText defaultStoreDir+            refusal computed = Left ("the store added '" <> spelled barPath <> "' where '" <> spelled computed <> "' was computed")+        (tree, derivation) <-+          withDaemonStore (storeConfig unusedDir) (fakeConnector daemon) $ \ops ->+            (,) <$> soAddSourceTree ops "tree" Set.empty entry <*> soAddEvalObjects ops noObjects {eoDerivations = recorded [(wrong, recipe "wrong" [] [])]}+        pure $ case makeSourcePath "tree" (sha256Digest (NAR.serialise entry)) Set.empty of+          Right computed -> assertEqual "tree" (refusal computed) tree `andThen` assertEqual "derivation" (refusal wrong) derivation+          Left bad -> Fail (badStorePathText bad),+      runTestM "an evaluation's copies, then its derivations inputs first, are added, a copy or derivation the daemon holds passed over and its writes not sent" $+        withScratch "nn-store-objects" $ \root -> do+          let sourceDir = root </> "src"+              keptDir = root </> "kept"+              nar = NAR.serialise (NAR.NarDirectory [("f", NAR.NarRegular False "contents")])+              keptNar = NAR.serialise (NAR.NarDirectory [("g", NAR.NarRegular False "kept")])+          Dir.createDirectoryIfMissing True sourceDir+          Dir.createDirectoryIfMissing True keptDir+          BS.writeFile (sourceDir </> "f") "contents"+          BS.writeFile (keptDir </> "g") "kept"+          case (makeSourcePath "src" (sha256Digest nar) Set.empty, makeSourcePath "kept" (sha256Digest keptNar) Set.empty, recordedDerivation "held" [] [], dependentSortingFirst) of+            (Right copyPath, Right keptPath, Right held@(heldPath, _, _), Right (input, dependent)) -> do+              daemon <- newFakeDaemon narHash contentPath [(heldPath, Set.empty), (keptPath, Set.empty)]+              let objects =+                    EvalObjects+                      { eoSources = Map.fromList [(copyPath, T.pack sourceDir), (keptPath, T.pack keptDir)],+                        eoStoreWrites = Map.singleton (storePathToText defaultStoreDir fooPath) ([], WriteText),+                        eoDerivations = derivationMap [held, input, dependent]+                      }+              added <- withDaemonStore (storeConfig (StoreDir root)) (fakeConnector daemon) (`soAddEvalObjects` objects)+              state <- readIORef (fakeHeld daemon)+              let candidates = Set.fromList [copyPath, keptPath, heldPath, derivationPath input, derivationPath dependent]+              pure $+                assertEqual "added" (Right ()) added+                  `andThen` assertEqual "uploads" [Upload "src" (Proto.FixedMethod NarIngestion) "sha256" Set.empty nar, derivationUpload input, derivationUpload dependent] (heldUploads state)+                  `andThen` assertEqual "every copy and derivation rooted before the daemon was asked which it holds" (Just (candidates, candidates)) (rootedBeforeAsked (heldCalls state))+            (copy, kept, heldDrv, pair) -> pure (Fail ("expected two copy paths and three derivations, got: " <> T.pack (show (copy, kept, fmap fst3 heldDrv, fmap (bimap fst3 fst3) pair)))),+      runTestM "the store roots the path moHold is given on the daemon, and answers a validity query put after it with the daemon's answer" $ do+        daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]+        held <- withDaemonStore (storeConfig unusedDir) (fakeConnector daemon) $ \ops -> case soEvalWrites ops of+          AddedAsMade made -> do+            rooted <- moHold made fooPath+            (,) rooted <$> sqValidPaths (soQueries ops) (Set.singleton fooPath)+          WrittenInDirectory -> pure (Left "the store did not take writes as they are made", Set.empty)+        state <- readIORef (fakeHeld daemon)+        pure $+          assertEqual "held" (Right (), Set.singleton fooPath) held+            `andThen` assertEqual "calls" [TempRooted fooPath, Queried (Set.singleton fooPath)] (heldCalls state),+      runTestM "a copy that changed after evaluation hashed it is refused in the local words, and no derivation is sent after it" $+        withScratch "nn-store-changed" $ \root -> do+          let sourceDir = root </> "src"+              hashed = NAR.serialise (NAR.NarDirectory [("f", NAR.NarRegular False "contents")])+          Dir.createDirectoryIfMissing True sourceDir+          BS.writeFile (sourceDir </> "f") "changed"+          case (makeSourcePath "src" (sha256Digest hashed) Set.empty, recordedDerivation "later" [] []) of+            (Right copyPath, Right later) -> do+              daemon <- newFakeDaemon narHash contentPath []+              let objects = noObjects {eoSources = Map.singleton copyPath (T.pack sourceDir), eoDerivations = derivationMap [later]}+              added <- withDaemonStore (storeConfig (StoreDir root)) (fakeConnector daemon) (`soAddEvalObjects` objects)+              state <- readIORef (fakeHeld daemon)+              pure $+                assertEqual "refused" (Left ("refusing to register " <> storePathToText defaultStoreDir copyPath <> ": " <> T.pack sourceDir <> " changed after evaluation hashed it, so it no longer reproduces its store path; re-evaluate")) added+                  `andThen` assertEqual "sent" 1 (length (heldUploads state))+            (copy, derivation) -> pure (Fail ("expected a copy path and a derivation, got: " <> T.pack (show (copy, fst3 <$> derivation)))),+      runTestM "an add the daemon refuses fails with the daemon's message, and the connection goes on" $ do+        daemon <- newFakeDaemon narHash (\_ _ -> Left (Ops.daemonError "the daemon refuses this")) [(fooPath, Set.empty)]+        (tree, written, valid) <-+          withDaemonStore (storeConfig unusedDir) (fakeConnector daemon) $ \ops -> do+            tree <- soAddSourceTree ops "tree" Set.empty (NAR.NarRegular False "x")+            written <- case soEvalWrites ops of+              AddedAsMade made -> moAdd made (TextWrite "note" Set.empty "text")+              WrittenInDirectory -> pure (Left "the store did not take writes as they are made")+            valid <- sqValidPaths (soQueries ops) (Set.singleton fooPath)+            pure (tree, written, valid)+        dials <- dialCounts (fakeDials daemon)+        pure $+          assertEqual "tree" (Left "the daemon refuses this") tree+            `andThen` assertEqual "write" (Left "the daemon refuses this") written+            `andThen` assertEqual "query" (Set.singleton fooPath) valid+            `andThen` assertEqual "connections made and closed" (1, 1) dials,+      runTestM "a tree evaluation makes is sent in its kind's spelling, and the path the daemon makes is the answer" $ do+        daemon <- newFakeDaemon narHash contentPath []+        let nar = NAR.serialise (NAR.NarRegular False "x")+            writes =+              [ TextWrite "note" (Set.singleton fooPath) "text",+                NarWrite "tree" nar,+                FlatWrite "file" "bytes"+              ]+        answered <-+          withDaemonStore (storeConfig unusedDir) (fakeConnector daemon) $ \ops -> case soEvalWrites ops of+            AddedAsMade made -> traverse (moAdd made) writes+            WrittenInDirectory -> pure [Left "the store did not take writes as they are made"]+        state <- readIORef (fakeHeld daemon)+        pure $+          assertEqual+            "paths"+            [ first badStorePathText (makeTextPath "note" (sha256Digest "text") [fooPath]),+              first badStorePathText (makeSourcePath "tree" (sha256Digest nar) Set.empty),+              first badStorePathText (makeFixedOutputPath "file" "sha256" FlatIngestion (sha256Digest "bytes"))+            ]+            answered+            `andThen` assertEqual+              "uploads"+              [ Upload "note" Proto.TextMethod "sha256" (Set.singleton fooPath) "text",+                Upload "tree" (Proto.FixedMethod NarIngestion) "sha256" Set.empty nar,+                Upload "file" (Proto.FixedMethod FlatIngestion) "sha256" Set.empty "bytes"+              ]+              (heldUploads state),+      runTestM "a build asks the daemon to build each derivation's named outputs, and one naming no output is not asked" $ do+        daemon <- newFakeDaemon narHash contentPath []+        idle <- newFakeDaemon narHash contentPath []+        built <-+          withDaemonStore (storeConfig unusedDir) (fakeConnector daemon) $ \ops ->+            soBuild ops [(fooPath, Set.singleton "out"), (barPath, Set.fromList ["out", "dev"]), (missingPath, Set.empty)]+        nothingAsked <-+          withDaemonStore (storeConfig unusedDir) (fakeConnector idle) $ \ops ->+            (,) <$> soBuild ops [] <*> soBuild ops [(fooPath, Set.empty)]+        state <- readIORef (fakeHeld daemon)+        dials <- dialCounts (fakeDials idle)+        pure $+          assertEqual "built" (Right ()) built+            `andThen` assertEqual+              "asked"+              [ ( [(fooPath, Just (Set.singleton (Proto.OutputName "out"))), (barPath, Just (Set.fromList [Proto.OutputName "dev", Proto.OutputName "out"]))],+                  Proto.BuildNormal+                )+              ]+              [([(path, Proto.outputsSpecNames spec) | Proto.DerivedBuilt path spec <- targets], mode) | (targets, mode) <- heldBuilds state]+            `andThen` assertEqual "nothing to build" (Right (), Right ()) nothingAsked+            `andThen` assertEqual "connections made" (0, 0) dials,+      runTestM "a check asks the daemon for every output of the derivation under the check mode" $ do+        daemon <- newFakeDaemon narHash contentPath []+        checked <- withDaemonStore (storeConfig unusedDir) (fakeConnector daemon) (`soCheck` fooPath)+        state <- readIORef (fakeHeld daemon)+        pure $+          assertEqual "checked" (Right ()) checked+            `andThen` assertEqual "asked" [([Proto.DerivedBuilt fooPath Proto.AllOutputs], Proto.BuildCheck)] (heldBuilds state),+      runTestM "a build the daemon fails stops with its message, and with status 1 from protocol 1.26 on, the activities it left open stopped, and one that cannot ask the daemon stops with the reason" $ do+        let building = Building fooPath+            report =+              [ Ops.ActivityStarted (Ops.storeActivity defaultStoreDir (Proto.ActivityId 1) building),+                Ops.ActivityResult (Proto.ActivityId 1) Proto.resBuildLogLine [Proto.FieldString "the builder says"]+              ]+            failure = (Ops.daemonError "builder for the derivation failed") {Proto.errExitStatus = 104}+            failing version = do+              daemon <- newFakeDaemonServing narHash version contentPath []+              modifyIORef' (fakeHeld daemon) (\held -> held {heldBuildReport = report, heldBuildFailure = Just failure})+              (logger, events) <- eventLogger+              built <- withDaemonStore (storeConfig unusedDir) {dscLogger = logger} (fakeConnector daemon) $ \ops -> (,) <$> soBuild ops [(fooPath, Set.singleton "out")] <*> soCheck ops fooPath+              logged <- events+              pure (built, logged)+            unreachable = pure (Left "Connection refused")+        (current, currentLogged) <- failing daemonVersion+        (older, _) <- failing (Proto.Version (Proto.VersionNumber 1 25) Set.empty)+        cannot <- withDaemonStore (storeConfig unusedDir) unreachable $ \ops -> soBuild ops [(fooPath, Set.singleton "out")]+        let stopped = [LoggedStart building, LoggedActivityLine building "the builder says", LoggedStop building]+        pure $+          assertEqual "current" (Left (BuildStop "builder for the derivation failed" 1), Left (BuildStop "builder for the derivation failed" 1)) current+            `andThen` assertEqual "older" (Left (BuildStop "builder for the derivation failed" 104), Left (BuildStop "builder for the derivation failed" 104)) older+            `andThen` assertEqual "each operation's activity started, given its line and stopped" (stopped <> stopped) currentLogged+            `andThen` assertEqual "cannot ask" (Left (BuildStop (connectFailureText (dscAddress (storeConfig unusedDir)) "Connection refused") 1)) cannot,+      runTestM "a session's settings carry the overrides a source set, and no override a source did not set" $ do+        let configured = defaultNixConfig {ncSandbox = Just SandboxRelaxed, ncSubstituters = ["https://cache.example"], ncRestrictEval = True, ncKeepFailed = True, ncSandboxPaths = PathSetValue KeepsDefault (Set.singleton "/bin/sh"), ncRequireSigs = False}+            assigned = replacedSettings ["sandbox", "substituters", "restrict-eval", "keep-failed", "sandbox-paths"]+            config = (storeConfig unusedDir) {dscSettings = clientSettings assigned configured}+        daemon <- newFakeDaemon narHash contentPath []+        void (withDaemonStore config (fakeConnector daemon) (\ops -> sqValidPaths (soQueries ops) (Set.singleton fooPath)))+        sentTo <- heldSettings <$> readIORef (fakeHeld daemon)+        pure (assertEqual "sent" [Just (Ops.ClientSettings True False False (Proto.Verbosity 3) 1 0 True 0 True (Map.fromList [("extra-sandbox-paths", "/bin/sh"), ("sandbox", "relaxed"), ("substituters", "https://cache.example")]))] sentTo),+      runTestM "an out-link is made by the client and rooted by the daemon, and a link inside the store, or a file in its place, is refused as the local store refuses it" $ do+        linked <- symlinksAvailable+        if not linked+          then Pass <$ putStrLn "  SKIP  out-link roots need symlink privilege"+          else withScratch "nn-store-outlink" $ \root -> do+            let fileDir = StoreDir (root </> "store")+                linkPath = root </> "links" </> "result"+                insidePath = root </> "store" </> "result"+                plainFile = root </> "plain"+                config = storeConfig fileDir+            daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]+            BS.writeFile plainFile "not a link"+            (made, inside, clobbered) <-+              withDaemonStore config (fakeConnector daemon) $ \ops ->+                (,,) <$> soAddOutLinkRoot ops linkPath fooPath <*> soAddOutLinkRoot ops insidePath fooPath <*> soAddOutLinkRoot ops plainFile fooPath+            target <- Dir.getSymbolicLinkTarget linkPath+            state <- readIORef (fakeHeld daemon)+            let quoted path = "\"" <> T.pack path <> "\""+            pure $+              assertEqual "made" (Right linkPath) made+                `andThen` assertEqual "points at the path in the directory the files are read from" (storePathToFilePath fileDir fooPath) target+                `andThen` assertEqual "inside the store" (Left ("creating a garbage collector root (" <> quoted insidePath <> ") in the Nix store is forbidden (are you running nova-nix build inside the store?)")) inside+                `andThen` assertEqual "a file in the way" (Left ("cannot create symlink " <> quoted plainFile <> "; already exists")) clobbered+                `andThen` assertEqual "rooted for the connection before the link was looked at, the link made and the one refused" [TempRooted fooPath, TempRooted fooPath] (heldCalls state)+                `andThen` assertEqual "the link's bytes recorded as an indirect root, for the link made alone" [BS8.pack linkPath] (heldIndirectRoots state)+    ]+  where+    fst3 (path, _, _) = path+    derivationPath (path, _, _) = path++-- ---------------------------------------------------------------------------+-- Push and trust+-- ---------------------------------------------------------------------------++-- | A build result that succeeded, as the daemon in memory is told to give+-- it for a path.+succeededResult :: Proto.BuildResult+succeededResult = builtResult (Proto.Succeeded (Proto.Success Proto.Substituted Map.empty))++-- | A build result that failed with a status.+failedResult :: Proto.FailureStatus -> Proto.BuildResult+failedResult status = builtResult (Proto.Failed (Proto.Failure status "failed" False))++-- | A build result of an outcome, with no time taken.+builtResult :: Proto.BuildOutcome -> Proto.BuildResult+builtResult outcome = Proto.BuildResult outcome 0 0 0 Nothing Nothing++-- | What a push reads of a path the daemon in memory holds with the NAR+-- hash given, as a store's database spells the hash.+pushedWith :: Proto.NarHash -> [StorePath] -> PushedPath+pushedWith narHash references = PushedPath (CHash.formatNixHash (CHash.NixHash (Proto.narHashDigest narHash))) references Nothing++-- | A store path, by the letter its hash repeats and its name.+lettered :: Char -> Text -> StorePath+lettered letter = StorePath (T.replicate 32 (T.singleton letter))++-- | What a push reads and trust asks of a store through a daemon in+-- memory that records what it is asked.+pushTrustTests :: Proto.NarHash -> IO [Bool]+pushTrustTests narHash =+  sequence+    [ runTestM "a push through the daemon roots each path before it asks its info, and reads the references, NAR hash and deriver the daemon gives" $ do+        daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.singleton barPath), (barPath, Set.empty)]+        (found, absent, listed, referenced, unreferenced) <-+          withDaemonPushSource (storeConfig unusedDir) (fakeConnector daemon) $ \source ->+            (,,,,) <$> psPathInfo source fooPath <*> psPathInfo source missingPath <*> psAllValid source <*> psReferences source fooPath <*> psReferences source missingPath+        state <- readIORef (fakeHeld daemon)+        dials <- dialCounts (fakeDials daemon)+        let rootedThenAsked path = [TempRooted path, InfoQueried path]+        pure $+          assertEqual "the record" (Right (Just (pushedWith narHash [barPath]))) found+            `andThen` assertEqual "a path the daemon does not hold" (Right Nothing) absent+            `andThen` assertEqual "every valid path" (Right (sort [fooPath, barPath])) listed+            `andThen` assertEqual "the references of a held path" (Right [barPath]) referenced+            `andThen` assertEqual "the references of a path the daemon does not hold" (Right []) unreferenced+            `andThen` assertEqual "each path rooted, then asked, for its record and for its references" (concatMap rootedThenAsked [fooPath, missingPath, fooPath, missingPath]) (heldCalls state)+            `andThen` assertEqual "connections made and closed" (1, 1) dials,+      runTestM "a push through a daemon that cannot be reached fails each read with the reason, and is not tried again, and one that asks nothing never connects" $ do+        let config = storeConfig unusedDir+            unreachable = pure (Left "Connection refused")+        (info, listed) <- withDaemonPushSource config unreachable $ \source -> (,) <$> psPathInfo source fooPath <*> psAllValid source+        idle <- newFakeDaemon narHash contentPath []+        withDaemonPushSource config (fakeConnector idle) (\_ -> pure ())+        dials <- dialCounts (fakeDials idle)+        pure $+          assertEqual "info" (Left (connectFailureText (dscAddress config) "Connection refused")) info+            `andThen` assertEqual "listing" (Left (previouslyFailedText (dscAddress config))) listed+            `andThen` assertEqual "no connection for a source asked nothing" (0, 0) dials,+      runTestM "a fetch through the daemon adds the fetch's derivation as a text with no references, unless the daemon holds it, and builds all its outputs" $+        case recordedDerivation "fetched" [] [] of+          Left bad -> pure (Fail bad)+          Right (drvPath, drv, aterm) -> do+            let node = DepNode drvPath drv Map.empty+                recordedAterm path = if path == drvPath then Right aterm else Left "no .drv was recorded"+                fetchWith daemon recorder = withDaemonFixedOutputs (storeConfig unusedDir) (fakeConnector daemon) recorder (`fosFetch` node)+                buildsAll = [([Proto.DerivedBuilt drvPath Proto.AllOutputs], Proto.BuildNormal)]+                upload = Upload (TE.encodeUtf8 (spName drvPath)) Proto.TextMethod "sha256" Set.empty aterm+            empty <- newFakeDaemon narHash contentPath []+            holding <- newFakeDaemon narHash contentPath [(drvPath, Set.empty)]+            failing <- newFakeDaemon narHash contentPath []+            modifyIORef' (fakeHeld failing) (\held -> held {heldBuildFailure = Just (Ops.daemonError "the builder failed")})+            unrecorded <- newFakeDaemon narHash contentPath []+            added <- fetchWith empty recordedAterm+            skipped <- fetchWith holding recordedAterm+            refused <- fetchWith failing recordedAterm+            unknown <- fetchWith unrecorded (const (Left "no .drv was recorded"))+            [addedState, skippedState, unrecordedState] <- traverse (readIORef . fakeHeld) [empty, holding, unrecorded]+            unrecordedDials <- dialCounts (fakeDials unrecorded)+            pure $+              assertEqual "added" (Right ()) added+                `andThen` assertEqual "uploaded" [upload] (heldUploads addedState)+                `andThen` assertEqual "rooted before the daemon was asked which it holds" (Just (Set.singleton drvPath, Set.singleton drvPath)) (rootedBeforeAsked (heldCalls addedState))+                `andThen` assertEqual "built" buildsAll (heldBuilds addedState)+                `andThen` assertEqual "held" (Right ()) skipped+                `andThen` assertEqual "not uploaded again" [] (heldUploads skippedState)+                `andThen` assertEqual "built when held" buildsAll (heldBuilds skippedState)+                `andThen` assertEqual "a build the daemon fails" (Left "the builder failed") refused+                `andThen` assertEqual "no recorded derivation" (Left "no .drv was recorded") unknown+                `andThen` assertEqual "nothing asked of the daemon" ([], [], (0, 0)) (heldCalls unrecordedState, heldBuilds unrecordedState, unrecordedDials),+      runTestM "a substitution through the daemon roots the path first, asks nothing more for one the daemon holds, and ends as the daemon's result for any other says, never asking which substituters offer a path" $ do+        let succeeded = lettered '3' "succeeded"+            unoffered = lettered '4' "unoffered"+            incomplete = lettered '5' "incomplete"+            failed = lettered '6' "failed"+            silent = lettered '7' "silent"+            others = [succeeded, unoffered, incomplete, failed, silent]+            results =+              Map.fromList+                [ (succeeded, succeededResult),+                  (unoffered, failedResult Proto.NoSubstituters),+                  (incomplete, failedResult Proto.DependencyFailed),+                  (failed, failedResult Proto.MiscFailure)+                ]+        daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]+        modifyIORef' (fakeHeld daemon) (\held -> held {heldResults = results})+        outcomes <- withDaemonFixedOutputs (storeConfig unusedDir) (fakeConnector daemon) (const (Left "unused")) (\fixed -> traverse (fosSubstitute fixed) (fooPath : others))+        state <- readIORef (fakeHeld daemon)+        let rootedThenAsked path = [TempRooted path, Queried (Set.singleton path)]+        pure $+          assertEqual "outcomes, a result of no status being a failure" (map Right [ClosureComplete, ClosureComplete, ClosureUnavailable, ClosureIncomplete, ClosureFailed, ClosureFailed]) outcomes+            `andThen` assertEqual "each path rooted, then asked whether the daemon holds it, and nothing else" (concatMap rootedThenAsked (fooPath : others)) (heldCalls state)+            `andThen` assertEqual "only a path the daemon does not hold is realised, as an opaque path" [([Proto.DerivedOpaque path], Proto.BuildNormal) | path <- others] (heldBuilds state)+            `andThen` assertEqual "no substituter was asked which paths it offers" [] [paths | OfferQueried paths <- heldCalls state],+      runTestM "a substitution through a daemon older than protocol 1.34 fails with the client's reason for a path the daemon does not hold, and a path it holds needs no such answer" $ do+        daemon <- newFakeDaemonServing narHash (Proto.Version (Proto.VersionNumber 1 33) Set.empty) contentPath [(fooPath, Set.empty)]+        outcomes <- withDaemonFixedOutputs (storeConfig unusedDir) (fakeConnector daemon) (const (Left "unused")) (\fixed -> traverse (fosSubstitute fixed) [fooPath, barPath])+        state <- readIORef (fakeHeld daemon)+        pure $+          assertEqual "outcomes" [Right ClosureComplete, Left "BuildPathsWithResults needs protocol 1.34, which the daemon does not speak"] outcomes+            `andThen` assertEqual "nothing built" [] (heldBuilds state),+      runTestM "a path held is asked of the daemon after it is rooted, and a daemon that cannot be reached is the reason" $ do+        daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]+        held <- withDaemonFixedOutputs (storeConfig unusedDir) (fakeConnector daemon) (const (Left "unused")) (\fixed -> traverse (fosHeld fixed) [fooPath, barPath])+        state <- readIORef (fakeHeld daemon)+        unreachable <- withDaemonFixedOutputs (storeConfig unusedDir) (pure (Left "Connection refused")) (const (Left "unused")) (\fixed -> (,) <$> fosHeld fixed fooPath <*> fosSubstitute fixed fooPath)+        pure $+          assertEqual "held" [Right True, Right False] held+            `andThen` assertEqual "each path rooted, then asked" [TempRooted fooPath, Queried (Set.singleton fooPath), TempRooted barPath, Queried (Set.singleton barPath)] (heldCalls state)+            `andThen` assertEqual "unreachable" (Left (connectFailureText (dscAddress (storeConfig unusedDir)) "Connection refused"), Left (previouslyFailedText (dscAddress (storeConfig unusedDir)))) unreachable+    ]++-- ---------------------------------------------------------------------------+-- A source the process cannot read+-- ---------------------------------------------------------------------------++-- | Adds of a source the process cannot read, through the archive walk+-- itself ('NAR.withNarSource'), to a store reached through a daemon and to+-- the local store.  A file, or a directory, with every permission removed+-- is the unreadable source.  Windows has no mode that stops a file's owner+-- reading it, and a process with the superuser's privileges reads a file+-- whatever its mode, so these are skipped there, each with its reason.+unreadableTests :: Proto.NarHash -> IO [Bool]+unreadableTests narHash+  | onWindows = [] <$ putStrLn "  SKIP  Windows has no file mode that stops a file's owner reading it"+  | otherwise = withScratch "nn-store-unreadable" $ \root -> do+      Dir.createDirectoryIfMissing True (root </> "store")+      filed <- unreadableSource root "filed"+      directoried <- unreadableSource root "directoried"+      case (filed, directoried) of+        (Right (filePath, fileDir), Right (dirPath, dirDir)) -> do+          let file = fileDir </> unreadableName+              storeRoot = StoreDir (root </> "store")+              sourcesOf path dir = noObjects {eoSources = Map.singleton path (T.pack dir)}+              walkWords path access = Left (T.pack path <> ": " <> access <> ": permission denied (Permission denied)")+          readable <- denied file (isRight <$> (try (BS.readFile file) :: IO (Either IOException BS.ByteString)))+          if readable+            then [] <$ putStrLn "  SKIP  this process reads a file whose permissions are all removed, as the superuser does"+            else+              sequence+                [ runTestM "an unreadable file in a source fails the add with the walk's words, closes the connection the upload was sent on, and leaves the next operation to connect again" $ do+                    daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]+                    (added, valid) <-+                      denied file $+                        withDaemonStore (storeConfig (StoreDir root)) (fakeConnector daemon) $ \ops ->+                          (,) <$> soAddEvalObjects ops (sourcesOf filePath fileDir) <*> sqValidPaths (soQueries ops) (Set.singleton fooPath)+                    state <- readIORef (fakeHeld daemon)+                    dials <- dialCounts (fakeDials daemon)+                    pure $+                      assertEqual "added" (walkWords file "reading file") added+                        `andThen` assertEqual "valid" (Set.singleton fooPath) valid+                        `andThen` assertEqual "uploads" [] (heldUploads state)+                        `andThen` assertEqual "connections made and closed" (2, 2) dials,+                  runTestM "an unreadable directory in a source fails the add with the walk's words before anything is sent, and the connection goes on" $ do+                    daemon <- newFakeDaemon narHash contentPath [(fooPath, Set.empty)]+                    (added, valid) <-+                      denied dirDir $+                        withDaemonStore (storeConfig (StoreDir root)) (fakeConnector daemon) $ \ops ->+                          (,) <$> soAddEvalObjects ops (sourcesOf dirPath dirDir) <*> sqValidPaths (soQueries ops) (Set.singleton fooPath)+                    state <- readIORef (fakeHeld daemon)+                    dials <- dialCounts (fakeDials daemon)+                    pure $+                      assertEqual "added" (walkWords dirDir "listing directory") added+                        `andThen` assertEqual "valid" (Set.singleton fooPath) valid+                        `andThen` assertEqual "uploads" [] (heldUploads state)+                        `andThen` assertEqual "connections made and closed" (1, 1) dials,+                  runTestM "the local store answers an unreadable file in a source with the walk's words, and holds nothing of it" $ do+                    (added, valid) <-+                      denied file $+                        withLocalStore quietLogger (defaultBuildConfig storeRoot) $ \ops ->+                          (,) <$> soAddEvalObjects ops (sourcesOf filePath fileDir) <*> sqValidPaths (soQueries ops) (Set.singleton filePath)+                    left <- Dir.doesPathExist (storePathToFilePath storeRoot filePath)+                    pure $+                      assertEqual "added" (walkWords file "reading file") added+                        `andThen` assertEqual "valid" Set.empty valid+                        `andThen` assertEqual "left behind" False left+                ]+        (copy, other) -> sequence [runTest "an unreadable source can be set up" (Fail ("expected two source trees, got: " <> T.pack (show (copy, other))))]++-- | The name of the file in each source 'unreadableSource' makes.+unreadableName :: FilePath+unreadableName = "unreadable.txt"++-- | A directory holding one file, and the path evaluation computes for it+-- while it is readable.+unreadableSource :: FilePath -> FilePath -> IO (Either Text (StorePath, FilePath))+unreadableSource root name = do+  let dir = root </> name+      contents = "contents"+      entry = NAR.NarDirectory [(BS8.pack unreadableName, NAR.NarRegular False contents)]+  Dir.createDirectoryIfMissing True dir+  BS.writeFile (dir </> unreadableName) contents+  pure (bimap badStorePathText (,dir) (makeSourcePath (T.pack name) (sha256Digest (NAR.serialise entry)) Set.empty))++-- | Run an action with every permission removed from a path, restored+-- after so that the scratch directory can be removed.+denied :: FilePath -> IO a -> IO a+denied path = bracket (Dir.getPermissions path <* Dir.setPermissions path Dir.emptyPermissions) (Dir.setPermissions path) . const++-- | The paths rooted before the first validity query, and the paths that+-- query asked about, where the daemon was asked nothing else first and+-- rooted something.+rootedBeforeAsked :: [Called] -> Maybe (Set StorePath, Set StorePath)+rootedBeforeAsked calls = case span isRooted calls of+  (roots@(_ : _), Queried asked : _) -> Just (Set.fromList [path | TempRooted path <- roots], asked)+  _ -> Nothing+  where+    isRooted = \case+      TempRooted _ -> True+      _ -> False++-- | A transport whose reads end once the client has sent the operation+-- that sets its options, as a daemon that goes away while it reads them+-- looks to the client.+losingOnSetOptions :: Conn.Transport IO -> IO (Conn.Transport IO)+losingOnSetOptions transport = do+  lost <- newIORef False+  let send builder = do+        when (BS.take (BS.length setOptionsCode) (BL.toStrict (BB.toLazyByteString builder)) == setOptionsCode) (writeIORef lost True)+        Conn.transportSend transport builder+      receive = readIORef lost >>= \gone -> if gone then pure Nothing else Conn.transportReceive transport+  pure transport {Conn.transportReceive = receive, Conn.transportSend = send}++-- | A transport that throws once the client sends the operation that sets+-- its options.+throwingOnSetOptions :: Conn.Transport IO -> Conn.Transport IO+throwingOnSetOptions transport = transport {Conn.transportSend = send}+  where+    send builder+      | BS.take (BS.length setOptionsCode) (BL.toStrict (BB.toLazyByteString builder)) == setOptionsCode = throwIO (ErrorCall "the settings failed")+      | otherwise = Conn.transportSend transport builder++-- | What a request that sets the client's options begins with: its+-- operation code, 19 on the wire, as a 64-bit number.+setOptionsCode :: BS.ByteString+setOptionsCode = BL.toStrict (BB.toLazyByteString (BB.word64LE 19))++-- ---------------------------------------------------------------------------+-- A daemon serving a store of its own+-- ---------------------------------------------------------------------------++-- | Evaluation and adds against a daemon serving a store of its own, over+-- memory.+servedTests :: IO [Bool]+servedTests =+  sequence+    [ runTestM "an evaluation hands the daemon builtins.toFile's text as it makes it, after the copy it names, and the daemon then takes the derivation" $+        withServedDaemon $ \served -> do+          Dir.createDirectoryIfMissing True (servedRoot served </> "src")+          BS.writeFile (servedRoot served </> "src" </> "hello.txt") "hello"+          withDaemonStore (servedConfig served) (servedConnector served) $ \ops -> do+            evaluated <- evaluateRecording served ops "(let src = ./src; note = builtins.toFile \"note\" \"see ${src}\"; in derivation { name = \"served\"; system = \"x86_64-linux\"; builder = \"/bin/sh\"; inherit src note; }).drvPath"+            case evaluated of+              Left failure -> pure (Fail failure)+              Right (_, objects) -> case (Map.keys (eoSources objects), mapMaybe (parseStorePath defaultStoreDir) (Map.keys (eoStoreWrites objects)), mapMaybe (parseStorePath defaultStoreDir) (Map.keys (eoDerivations objects))) of+                ([src], [note], [drv]) -> do+                  let store = servedStore served+                  during <- traverse (isValid store) [src, note, drv]+                  added <- soAddEvalObjects ops objects+                  after <- traverse (isValid store) [src, note, drv]+                  references <- traverse (referencesIn store) [src, note, drv]+                  pure $+                    assertEqual "valid as evaluation made them" [True, True, False] during+                      `andThen` assertEqual "added" (Right ()) added+                      `andThen` assertEqual "valid after" [True, True, True] after+                      `andThen` assertEqual "references" [Set.empty, Set.singleton src, Set.fromList [src, note]] references+                (sources, writes, derivations) -> pure (Fail ("expected one copy, one write and one derivation, got: " <> T.pack (show (sources, writes, derivations)))),+      runTestM "a tree added through the daemon is valid in its store with the references it was added with" $+        withServedDaemon $ \served ->+          withDaemonStore (servedConfig served) (servedConnector served) $ \ops -> do+            let entry = NAR.NarDirectory [("link", NAR.NarSymlink "somewhere"), ("data", NAR.NarRegular False "data")]+                store = servedStore served+            dependency <- soAddSourceTree ops "dependency" Set.empty (NAR.NarRegular False "dependency")+            case dependency of+              Left refusal -> pure (Fail refusal)+              Right dependencyPath -> do+                tree <- soAddSourceTree ops "tree" (Set.singleton dependencyPath) entry+                held <- traverse (isValid store) (either (const []) (\path -> [dependencyPath, path]) tree)+                references <- either (const (pure Set.empty)) (referencesIn store) tree+                pure $+                  assertEqual "path" (first badStorePathText (makeSourcePath "tree" (sha256Digest (NAR.serialise entry)) (Set.singleton dependencyPath))) tree+                    `andThen` assertEqual "valid" [True, True] held+                    `andThen` assertEqual "references" (Set.singleton dependencyPath) references,+      runTestM "derivations the daemon only takes with their inputs valid are all added, whichever order their keys give" $+        withServedDaemon $ \served ->+          withDaemonStore (servedConfig served) (servedConnector served) $ \ops -> do+            evaluated <- evaluateRecording served ops manyDependents+            case evaluated of+              Left failure -> pure (Fail failure)+              Right (_, objects) -> do+                added <- soAddEvalObjects ops objects+                held <- traverse (isValid (servedStore served)) (mapMaybe (parseStorePath defaultStoreDir) (Map.keys (eoDerivations objects)))+                pure $+                  assertEqual "derivations" (dependentCount + 1) (Map.size (eoDerivations objects))+                    `andThen` assertEqual "added" (Right ()) added+                    `andThen` assertEqual "all valid" True (and held && not (null held)),+      runTestM "a derivation whose input the daemon does not hold is refused in the daemon's words, and is not added" $+        withServedDaemon $ \served ->+          withDaemonStore (servedConfig served) (servedConnector served) $ \ops -> do+            evaluated <- evaluateRecording served ops "(let input = derivation { name = \"input\"; system = \"x86_64-linux\"; builder = \"/bin/sh\"; }; in derivation { name = \"dependent\"; system = \"x86_64-linux\"; builder = \"/bin/sh\"; args = [ \"${input}\" ]; }).drvPath"+            case evaluated of+              Left failure -> pure (Fail failure)+              Right (named, objects) -> case (parseStorePath defaultStoreDir named, Map.keys (Map.delete named (eoDerivations objects))) of+                (Just dependentPath, [inputKey]) -> do+                  added <- soAddEvalObjects ops objects {eoDerivations = Map.filterWithKey (\key _ -> key == named) (eoDerivations objects)}+                  held <- isValid (servedStore served) dependentPath+                  pure $ case added of+                    Left message -> assertEqual "the daemon's words" True (("cannot read derivation '" <> inputKey <> "': ") `T.isPrefixOf` message) `andThen` assertEqual "valid" False held+                    Right () -> Fail "expected the add to be refused"+                other -> pure (Fail ("expected the named derivation and its input, got: " <> T.pack (show other))),+      runTestM "a build through the daemon realises the output, gives its builder's lines to the logger and roots ./result" $ do+        shell <- findTestShell+        linked <- symlinksAvailable+        withServedDaemonConfigured unsandboxed $ \served -> case builtRecipe shell of+          Left failure -> pure (Fail failure)+          Right (built@(drvPath, _, _), builtOutput) -> do+            (logger, events) <- eventLogger+            let store = servedStore served+                config = (servedConfig served) {dscLogger = logger}+            withDaemonStore config (servedConnector served) $ \ops -> do+              added <- soAddEvalObjects ops noObjects {eoDerivations = derivationMap [built]}+              realised <- soBuild ops [(drvPath, Set.singleton "out")]+              valid <- isValid store builtOutput+              contents <- try (BS.readFile (storePathToFilePath (stDir store) builtOutput))+              logged <- events+              rooted <-+                if linked+                  then outLinkRooted served ops builtOutput+                  else Pass <$ putStrLn "  SKIP  out-link roots need symlink privilege"+              let building = Building drvPath+                  activity = [event | event <- logged, not (isMessage event)]+                  isMessage = \case LoggedMessage _ _ -> True; _ -> False+              pure $+                assertEqual "added" (Right ()) added+                  `andThen` assertEqual "built" (Right ()) realised+                  `andThen` assertEqual "valid" True valid+                  `andThen` assertEqual "contents" (Right "built\n") (first (\(err :: IOException) -> displayException err) contents)+                  `andThen` assertEqual "the build an activity of the logger, its builder's line the activity's" [LoggedStart building, LoggedActivityLine building "hi", LoggedStop building] activity+                  `andThen` rooted,+      runTestM "a push through the daemon writes to a cache byte for byte what a push of the store opened directly writes" $+        withServedDaemon $ \served -> case throwawayKey (BS.replicate ed25519SeedBytes 5) >>= Signing.parseSecretKey . fst of+          Left failure -> pure (Fail (T.pack failure))+          Right secretKey -> pushedBothWays served secretKey,+      runTestM "a fetch through the daemon makes a builtin fetch's output valid in the daemon's store, and the scan reads it, while an input no substituter offers is left unread" $+        let contents = "fetched through the daemon\n"+         in withHttpServer (\_ _ -> Send (httpResponse "200 OK" contents)) $ \url _ _ -> withServedDaemonConfigured unsandboxed $ \served ->+              case (fetchRecipe "fetched" (OtherPlatform "builtin") "builtin:fetchurl" url contents, fetchRecipe "offered-nowhere" currentPlatform "/bin/sh" "http://127.0.0.1:9/never" contents) of+                (Right ((fetchedPath, fetchedDrv, fetchedAterm), fetchedOutput), Right ((otherPath, otherDrv, otherAterm), otherOutput)) -> do+                  let store = servedStore served+                      inputs = [(DepNode fetchedPath fetchedDrv Map.empty, fetchedOutput), (DepNode otherPath otherDrv Map.empty, otherOutput)]+                      recordedAterm path = maybe (Left "no .drv was recorded") Right (lookup path [(fetchedPath, fetchedAterm), (otherPath, otherAterm)])+                  scanned <- withDaemonFixedOutputs (servedConfig served) (servedConnector served) recordedAterm (`fetchAndScan` inputs)+                  held <- traverse (isValid store) [fetchedOutput, otherOutput]+                  fetched <- try (BS.readFile (storePathToFilePath (stDir store) fetchedOutput))+                  expected <- scanFetched (storePathToFilePath (stDir store) fetchedOutput)+                  pure $+                    assertEqual "scanned" (Right (Map.singleton fetchedOutput expected)) scanned+                      `andThen` assertEqual "held in the daemon's store" [True, False] held+                      `andThen` assertEqual "contents" (Right contents) (first (\(err :: IOException) -> displayException err) fetched)+                (fetch, other) -> pure (Fail ("expected two fixed-output recipes, got: " <> T.pack (show (snd <$> fetch, snd <$> other)))),+      runTestM "a substitution through the daemon takes a path from a file:// cache that does not declare mass queries, and a path the cache lacks is unavailable" $+        withScratch "nn-daemon-store-cache" $ \cacheRoot -> case signingKeys (BS.replicate ed25519SeedBytes 6) of+          Left failure -> pure (Fail (T.pack failure))+          Right (secretKey, publicKey) -> do+            let cache = cacheRoot </> "cache"+                cached = lettered 'p' "cached"+                lacking = lettered 'q' "lacking"+                daemonConfig = unsandboxed {ncSubstituters = [directoryUrl cache], ncTrustedPublicKeys = [Signing.renderPublicKey publicKey]}+            pushed <- pushedToCache (cacheRoot </> "source") cache secretKey cached+            cacheInfo <- BS.readFile (cache </> cacheInfoFileName)+            withServedDaemonConfigured daemonConfig $ \served -> do+              outcomes <- withDaemonFixedOutputs (servedConfig served) (servedConnector served) (const (Left "unused")) (\fixed -> traverse (fosSubstitute fixed) [cached, lacking])+              held <- traverse (isValid (servedStore served)) [cached, lacking]+              contents <- try (BS.readFile (storePathToFilePath (stDir (servedStore served)) cached </> "data"))+              pure $+                assertEqual "pushed to the cache" (Right (PushSummary 1 0)) pushed+                  `andThen` assertEqual "the cache names its store directory and no mass query" cacheInfoText cacheInfo+                  `andThen` assertEqual "outcomes" (map Right [ClosureComplete, ClosureUnavailable]) outcomes+                  `andThen` assertEqual "held in the daemon's store" [True, False] held+                  `andThen` assertEqual "contents" (Right (treeContents cached)) (first (\(err :: IOException) -> displayException err) contents)+    ]++-- | A fixed-output derivation named @name@ that fetches a URL with a+-- builder and for a platform, as evaluation records it, and the path of its+-- output, which the contents it is fixed to make.+fetchRecipe :: Text -> Platform -> BS.ByteString -> Text -> BS.ByteString -> Either Text (Recorded, StorePath)+fetchRecipe name platform builder url contents = do+  output <- first badStorePathText (makeFixedOutputPath name "sha256" FlatIngestion (sha256Digest contents))+  let drv =+        Derivation+          { drvOutputs = [DerivationOutput "out" output "sha256" (bytesToHexText (sha256Digest contents))],+            drvInputDrvs = Map.empty,+            drvInputSrcs = [],+            drvPlatform = platform,+            drvBuilder = builder,+            drvArgs = [],+            drvEnv = Map.fromList [("url", TE.encodeUtf8 url), ("out", TE.encodeUtf8 (storePathToText defaultStoreDir output))]+          }+  file <- first badStorePathText (drvFile name drv)+  pure ((drvFilePath file, drvFileDerivation file, drvFileATerm file), output)++-- | Paths added through the daemon, and one the store's own writer+-- registers with a deriver, pushed to a cache directory through the daemon+-- and, signed by the same key, from the store opened directly: the two+-- caches hold the same files.+pushedBothWays :: Served -> Signing.SecretKey -> IO TestResult+pushedBothWays served secretKey = fmap (either Fail id) . runExceptT $ do+  let store = servedStore served+      derived = lettered 'd' "derived.drv"+      derivedOutput = lettered 'f' "derived"+      derivedSource = servedRoot served </> "derived-source"+      daemonCache = servedRoot served </> "cache-daemon"+      directCache = servedRoot served </> "cache-direct"+      pushTo cache = pushToDirectory (DirectoryPush cache secretKey PushNone)+      entry = NAR.NarDirectory [("link", NAR.NarSymlink "somewhere"), ("data", NAR.NarRegular False "data")]+  tree <- ExceptT . withDaemonStore (servedConfig served) (servedConnector served) $ \ops -> runExceptT $ do+    dependency <- ExceptT (soAddSourceTree ops "dependency" Set.empty (NAR.NarRegular False "dependency"))+    ExceptT (soAddSourceTree ops "tree" (Set.singleton dependency) entry)+  -- The writer records a deriver, which a tree added through the daemon+  -- has none of, so the narinfos carry that line too.+  liftIO $ do+    Dir.createDirectoryIfMissing True derivedSource+    BS.writeFile (derivedSource </> "data") "built from a derivation"+    addToStore store derivedSource derivedOutput (Just (T.pack (storePathToFilePath (stDir store) derived))) [tree]+  let roots = [derivedOutput, tree]+  (throughDaemon, direct, daemonFiles, directFiles) <- liftIO $ do+    throughDaemon <- withDaemonPushSource (servedConfig served) (servedConnector served) (\source -> pushTo daemonCache source roots)+    direct <- pushTo directCache (localPushSource store) roots+    (,,,) throughDaemon direct <$> cacheListing daemonCache <*> cacheListing directCache+  pure $+    assertEqual "pushed through the daemon" (Right (PushSummary 3 0)) throughDaemon+      `andThen` assertEqual "pushed directly" (Right (PushSummary 3 0)) direct+      `andThen` assertEqual "the files of the two caches" directFiles daemonFiles+      `andThen` assertEqual "a narinfo and a NAR for each path, and the cache's own file" True (length daemonFiles > 6)++-- | A secret key from a seed, with the public key that verifies what it+-- signs.+signingKeys :: BS.ByteString -> Either String (Signing.SecretKey, Signing.PublicKey)+signingKeys seed = do+  (keyText, publicKey) <- throwawayKey seed+  secretKey <- Signing.parseSecretKey keyText+  pure (secretKey, publicKey)++-- | What the tree of a path holds in its file @data@.+treeContents :: StorePath -> BS.ByteString+treeContents path = TE.encodeUtf8 (spName path) <> "\n"++-- | A store of its own under a directory, holding a path with a tree, which+-- is pushed to a @file://@ cache directory as 'pushToDirectory' writes one.+pushedToCache :: FilePath -> FilePath -> Signing.SecretKey -> StorePath -> IO (Either Text PushSummary)+pushedToCache sourceDir cache secretKey path = do+  let tree = sourceDir </> "tree"+      storeDir = sourceDir </> "store"+  traverse_ (Dir.createDirectoryIfMissing True) [tree, storeDir]+  BS.writeFile (tree </> "data") (treeContents path)+  bracket (openStore quietLogger (StoreDir storeDir)) closeStore $ \store -> do+    addToStore store tree path Nothing []+    pushToDirectory (DirectoryPush cache secretKey PushNone) (localPushSource store) [path]++-- | The daemon's own settings for a build: unsandboxed, with no cache to+-- ask.+unsandboxed :: NixConfig+unsandboxed = defaultNixConfig {ncSandbox = Just SandboxDisabled, ncSubstituters = []}++-- | A derivation named @built@ whose builder, run by the shell given,+-- writes a line and its output, as evaluation records it, and the output's+-- path: input-addressed, as a daemon checks it is before it builds.+builtRecipe :: Text -> Either Text (Recorded, StorePath)+builtRecipe shell = do+  file <- first badStorePathText (inputAddressed "built" [] (mkTestBuildDrv shell (StorePath (T.replicate 32 "0") "built") "echo hi; echo built > $out"))+  case drvOutputs (drvFileDerivation file) of+    [output] -> Right ((drvFilePath file, drvFileDerivation file, drvFileATerm file), doPath output)+    other -> Left ("expected the one output, got " <> T.pack (show (length other)))++-- | The link a build's output is given in the working directory, a+-- directory of its own, by name alone: made, pointing at the output, and+-- the output the daemon's store roots through it.+outLinkRooted :: Served -> StoreOps IO -> StorePath -> IO TestResult+outLinkRooted served ops builtOutput = do+  let store = servedStore served+  rooted <- Dir.withCurrentDirectory (servedRoot served) (soAddOutLinkRoot ops "result" builtOutput)+  case rooted of+    Left failure -> pure (Fail failure)+    Right link -> do+      target <- Dir.getSymbolicLinkTarget link+      roots <- findRoots store+      pure $+        assertEqual "named in the working directory" "result" (takeFileName link)+          `andThen` assertEqual "points at the output" (storePathToFilePath (stDir store) builtOutput) target+          `andThen` assertEqual "rooted by the daemon's store" [GcRoot link (T.pack (storePathToFilePath (stDir store) builtOutput))] roots++-- | An expression of one input derivation and the many that name it as an+-- input, so that some sort before it.+manyDependents :: Text+manyDependents =+  T.unlines+    [ "let",+      "  input = derivation { name = \"input\"; system = \"x86_64-linux\"; builder = \"/bin/sh\"; };",+      "  dependent = n: derivation { name = \"dependent-${toString n}\"; system = \"x86_64-linux\"; builder = \"/bin/sh\"; args = [ \"${input}\" ]; };",+      "in builtins.concatStringsSep \"\\n\" (map (n: (dependent n).drvPath) (builtins.genList (n: n) " <> T.pack (show dependentCount) <> "))"+    ]++-- | Evaluate an expression that is a string in a read-write session over+-- the daemon's store, and answer the string and what the session recorded+-- for the store to add, as a command reads it from the session.+evaluateRecording :: Served -> StoreOps IO -> Text -> IO (Either Text (Text, EvalObjects))+evaluateRecording served ops source = do+  st <- newEvalStateWith quietLogger unrestrictedPolicy [] (ReadWriteSession ops) (servedFileDir served) (servedRoot served)+  evaluated <- evalNixIOIn st (servedRoot served) source+  made <- EvalObjects . sourceCopies <$> readIORef (esSourcePathCache st) <*> readIORef (esStoreWriteCache st) <*> readIORef (esDrvClosure st)+  pure $ case evaluated of+    Right (VStr bytes _) -> either (\err -> Left ("the string is not UTF-8: " <> T.pack (show err))) (\text -> Right (text, made)) (TE.decodeUtf8' bytes)+    Right other -> Left ("expected a string, got: " <> T.pack (show other))+    Left failure -> Left failure++-- | The references a store records for a path.+referencesIn :: Store -> StorePath -> IO (Set StorePath)+referencesIn store path = Set.fromList . mapMaybe (parseStorePath (stDir store)) <$> queryReferences (stDB store) path++-- | A daemon serving a store of its own in a scratch directory, over+-- memory.+data Served = Served+  { servedRoot :: !FilePath,+    servedStore :: !Store,+    servedConnector :: !Connector+  }++-- | The directory the served store's files are in, which a command's+-- store configuration reads them from and an evaluation over it gives its+-- session as its store directory.  Paths cross the wire under the+-- canonical store directory whatever it is.+servedFileDir :: Served -> StoreDir+servedFileDir = stDir . servedStore++-- | The configuration of a command's store over the served daemon.+servedConfig :: Served -> DaemonStoreConfig+servedConfig = storeConfig . servedFileDir++-- | Run a test against a daemon serving a store of its own in a scratch+-- directory, over memory, which serves the version the daemon command+-- serves and names paths under the canonical store directory.+withServedDaemon :: (Served -> IO TestResult) -> IO TestResult+withServedDaemon = withServedDaemonConfigured defaultNixConfig++-- | 'withServedDaemon', the daemon's own settings given.+withServedDaemonConfigured :: NixConfig -> (Served -> IO TestResult) -> IO TestResult+withServedDaemonConfigured daemonConfig body = withScratch "nn-daemon-store" $ \root -> do+  Dir.createDirectoryIfMissing True (root </> "store")+  bracket (openStore quietLogger (StoreDir (root </> "store"))) closeStore $ \store -> do+    served <- newServedStore servedDefaults store+    dials <- newDials+    body (Served root store (memoryConnector dials (serveLocal served (serverConfigAt daemonVersion) {Conn.scConfig = daemonConfig} Proto.Trusted)))++-- | Machine defaults a served store's builds fall back on, the same on+-- every machine: one core, no sandbox helper or bundled shell, not root,+-- so no build users, and no certificate bundle.+servedDefaults :: MachineDefaults+servedDefaults =+  MachineDefaults+    { mdCores = 1,+      mdSandboxHelper = Nothing,+      mdSandboxShell = Set.empty,+      mdPrivilege = RunsUnprivileged,+      mdUserPool = "/nix/var/nix/userpool",+      mdCaFile = Nothing+    }
+ test/Test/Derivation.hs view
@@ -0,0 +1,1386 @@+{-# LANGUAGE LambdaCase #-}++-- | Tests of derivations, their ATerm and structured attributes, and the+-- build environments develop captures from them.+module Test.Derivation+  ( testDerivation,+    testBatchG,+    testDerivationWrapper,+    testStructuredAttrs,+    testFromATerm,+    testInputAddressed,+    testDevelopCapture,+    testDevelopEnvironment,+    testDevelopShell,+  )+where++import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BS8+import Data.Either (isLeft, isRight)+import Data.List (find, sort)+import Data.List.NonEmpty (NonEmpty (..))+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import qualified Nix.Cli.Args as Cli+import Nix.Derivation (Derivation (..), DerivationOutput (..), DrvFile, Platform (..), currentPlatform, drvFileATerm, drvFileDerivation, drvFilePath, extraPlatforms, fromATerm, inputAddressed, platformToText, textToPlatform, toATerm, toATermForHash)+import Nix.Derivation.StructuredAttrs (StructuredAttrs (..), decodeStructuredAttrs, encodeStructuredAttrs, renderAttrsShell, stringsAttr, withOutputPlaceholders)+import Nix.Develop.Capture (CaptureFailure (..), OutputObject (..), captureDerivation, captureFailureMessage, environmentOutput, getEnvScriptPath, noEnvironmentMessage)+import Nix.Develop.Environment (AttrsFiles (..), BuildEnvironment (..), EnvironmentScript (..), Prompt (..), ScriptDirectories (..), ScriptFile (..), Shell (..), ShellMode (..), Variable (..), buildEnvironmentJson, environmentScript, escapeShellArgAlways, ignoreVars, parseBuildEnvironment, renderRcfile)+import Nix.Develop.Shell (EnvironmentBase (..), EnvironmentChanges (..), bashProgram, shellArguments, shellEnvironment, shellModeFor)+import Nix.Eval (MonadEval (..), NixValue (..), evalParsed, mkStr, typeName)+import Nix.Eval.CanonPath (canonPathValue)+import Nix.Eval.IO (evalBaseEnv, runEvalIO)+import Nix.Hash (hashPlaceholder, sha256Digest)+import qualified Nix.Hash as Hash+import Nix.Json (IntegerRange (..), Json (..), JsonBuilder (..), parseJson, parseJsonInto, renderJson)+import Nix.Parser (parseNix)+import Nix.Store (Store (..), closeStore, isValid, openStore, writeDrv, writeDrvClosure)+import Nix.Store.DB (PathRegistration (..), RegistrationTime (..), Ultimate (..), queryReferences, registerPath)+import Nix.Store.Path (StoreDir (..), StorePath, defaultStoreDir, storePathToFilePath, storePathToText)+import Nix.Store.Path.Internal (StorePath (..))+import System.Directory (createDirectoryIfMissing, getTemporaryDirectory, removeDirectoryRecursive)+import System.Exit (ExitCode (..))+import System.FilePath ((</>))+import qualified System.Info as SI+import qualified System.Process as Proc+import Test.Harness (TestResult (..), andThen, assertEqual, assertEval, assertEvalError, assertEvalFail, assertLeft, assertRight, bytesText, evalDerivationIO, evalNixIO, evalNixIOStoreDir, forceRemoveIfExists, genDrvName, genFixturePath, genJson, genTextOf, runTest, runTestIO, runTestM, simpleTestDrv, testBaseDir, testEvalState, testLogger, testOrigin)+import qualified Test.QuickCheck as QC++-- ---------------------------------------------------------------------------+-- Test harness+-- ---------------------------------------------------------------------------++-- | The bytes of a string value, and nothing for any other value.+stringBytes :: NixValue -> BS.ByteString+stringBytes (VStr bytes _) = bytes+stringBytes _ = BS.empty++-- ---------------------------------------------------------------------------+-- Tests: Derivation (existing)+-- ---------------------------------------------------------------------------++testDerivation :: IO [Bool]+testDerivation = do+  putStrLn "derivation"+  sequence+    [ runTest "current platform is known" $+        case currentPlatform of+          OtherPlatform _ -> Fail "currentPlatform returned OtherPlatform"+          _ -> Pass+    ]++-- ---------------------------------------------------------------------------+-- Tests: Batch G - ATerm serialization+-- ---------------------------------------------------------------------------++testBatchG :: IO [Bool]+testBatchG = do+  putStrLn "derivation/aterm"+  let minimalDrv =+        Derivation+          { drvOutputs = [],+            drvInputDrvs = Map.empty,+            drvInputSrcs = [],+            drvPlatform = X86_64_Linux,+            drvBuilder = "/bin/sh",+            drvArgs = [],+            drvEnv = Map.empty+          }+  let drvWithOutput =+        minimalDrv+          { drvOutputs =+              [ DerivationOutput+                  { doName = "out",+                    doPath = StorePath "abc" "hello",+                    doHashAlgo = "",+                    doHash = ""+                  }+              ]+          }+  let drvWithEnv =+        minimalDrv+          { drvEnv = Map.fromList [("name", "hello"), ("system", "x86_64-linux")]+          }+  sequence+    [ runTest "ATerm minimal" $+        let aterm = toATerm minimalDrv+         in if BS.isPrefixOf "Derive(" aterm && BS.isSuffixOf ")" aterm+              then Pass+              else Fail ("bad ATerm: " <> bytesText aterm),+      runTest "ATerm has output" $+        let aterm = toATerm drvWithOutput+         in if "\"out\"" `BS.isInfixOf` aterm+              then Pass+              else Fail ("missing output in ATerm: " <> bytesText aterm),+      runTest "ATerm env sorted" $+        let aterm = toATerm drvWithEnv+         in -- "name" should come before "system" in sorted order+            case (BS.breakSubstring "\"name\"" aterm, BS.breakSubstring "\"system\"" aterm) of+              ((before1, _), (before2, _)) ->+                if BS.length before1 < BS.length before2+                  then Pass+                  else Fail ("env not sorted in ATerm: " <> bytesText aterm),+      runTest "ATerm string escaping" $+        let drv = minimalDrv {drvEnv = Map.fromList [("msg", "hello\nworld")]}+            aterm = toATerm drv+         in if "\\n" `BS.isInfixOf` aterm+              then Pass+              else Fail ("missing escaped newline: " <> bytesText aterm),+      runTest "ATerm deterministic" $+        assertEqual "deterministic" (toATerm minimalDrv) (toATerm minimalDrv),+      -- platformToText+      runTest "platformToText linux" $+        assertEqual "linux" "x86_64-linux" (platformToText X86_64_Linux),+      runTest "platformToText darwin" $+        assertEqual "darwin" "x86_64-darwin" (platformToText X86_64_Darwin),+      runTest "platformToText aarch64-darwin" $+        assertEqual "aarch64" "aarch64-darwin" (platformToText Aarch64_Darwin),+      runTest "platformToText windows" $+        assertEqual "windows" "x86_64-windows" (platformToText X86_64_Windows),+      runTest "platformToText aarch64-linux" $+        assertEqual "aarch64-linux" "aarch64-linux" (platformToText Aarch64_Linux),+      runTest "platformToText i686" $+        assertEqual "i686" ["i686-linux", "i686-windows"] (map platformToText [I686_Linux, I686_Windows]),+      runTest "platformToText other" $+        assertEqual "other" "riscv64-freebsd" (platformToText (OtherPlatform "riscv64-freebsd")),+      -- The i686 spellings parse to their own constructors, not to+      -- OtherPlatform, or extraPlatforms could never name them.+      runTest "textToPlatform round-trips every named platform" $+        assertEqual+          "round-trip"+          namedPlatforms+          (map (textToPlatform . platformToText) namedPlatforms),+      -- Upstream's default extra-platforms, and nothing more: the x86_64+      -- hosts run their i686 counterpart, every other host runs only itself.+      runTest "extraPlatforms is the i686 counterpart on x86_64 hosts only" $+        assertEqual+          "extra"+          [[I686_Linux], [I686_Windows], [], [], [], [], []]+          (map extraPlatforms [X86_64_Linux, X86_64_Windows, X86_64_Darwin, Aarch64_Darwin, Aarch64_Linux, I686_Linux, I686_Windows])+    ]+  where+    namedPlatforms = [X86_64_Linux, X86_64_Darwin, Aarch64_Darwin, X86_64_Windows, Aarch64_Linux, I686_Linux, I686_Windows]++-- ---------------------------------------------------------------------------+-- Tests: what a program can observe of the derivation wrapper+-- ---------------------------------------------------------------------------++-- | What a program can observe of @derivation@ beyond the attributes+-- 'testBatchH' reads, each expected value written out: the name the+-- pattern binds, which builtin forces @outputs@ and in what order, how the+-- layers of the result replace each other, and the arguments' own values+-- in the result.  The parity job probes the same things against upstream's+-- nix-instantiate (test/data/derivation-probes.txt).+testDerivationWrapper :: IO [Bool]+testDerivationWrapper = do+  putStrLn "derivation/wrapper"+  tmpBase <- getTemporaryDirectory+  let required = "name = \"w\"; system = \"x86_64-linux\"; builder = \"/bin/sh\"; "+      drv fields = "derivation { " <> required <> fields <> " }"+      atWhnf fields = "builtins.seq (" <> drv fields <> ") null"+      throwing = drv "outputs = [ \"out\" \"dev\" ]; x = throw \"forced\";"+  sequence+    [ runTest "toXML shows the name the pattern binds" $+        assertEval+          "xml"+          "builtins.toXML derivation"+          (mkStr "<?xml version='1.0' encoding='utf-8'?>\n<expr>\n  <function>\n    <attrspat ellipsis=\"1\" name=\"drvAttrs\">\n      <attr name=\"outputs\" />\n    </attrspat>\n  </function>\n</expr>\n"),+      -- map's error rather than head's: map forces outputs first.+      runTest "map forces outputs before head does" $+        assertEvalError "map" (atWhnf "outputs = \"out\";") "builtins.map: expected a list, got a string",+      runTest "listToAttrs forces the output names first to last" $+        assertEvalError "first" (atWhnf "outputs = [ (throw \"the first\") \"out\" (throw \"the last\") ];") "the first",+      runTest "every output name is forced with the derivation" $+        assertEvalError "last" (atWhnf "outputs = [ \"out\" (throw \"the last\") ];") "the last",+      runTest "an argument that throws stays unforced through the result's attributes" $+        assertEval+          "spine"+          ("let d = " <> throwing <> "; in builtins.toJSON [ (builtins.attrNames d) (map (o: o.outputName) d.all) d.dev.type (builtins.attrNames d.drvAttrs) ]")+          (mkStr "[[\"all\",\"builder\",\"dev\",\"drvAttrs\",\"drvPath\",\"name\",\"out\",\"outPath\",\"outputName\",\"outputs\",\"system\",\"type\",\"x\"],[\"out\",\"dev\"],\"derivation\",[\"builder\",\"name\",\"outputs\",\"system\",\"x\"]]"),+      -- == forces both sides, then takes one value as equal to itself, so a+      -- function is equal only to itself.  Under the IO evaluator, which+      -- keeps a forced binding's value as upstream's does, where the pure+      -- one evaluates args again at each use.+      runTestIO+        "the arguments' values reach the result unchanged"+        tmpBase+        ("let args = { " <> required <> "f = y: y; }; d = derivation args; in builtins.intersectAttrs { f = null; } d == builtins.intersectAttrs { f = null; } args")+        (VBool True),+      runTest "the result's own attributes replace the outputs' and the arguments'" $+        assertEval+          "layers"+          ("let d = " <> drv "outputs = [ \"out\" \"all\" ]; type = \"t\"; all = 1; out = 6;" <> "; in builtins.toJSON [ d.type (builtins.isList d.all) d.out.outputName d.drvAttrs.type d.drvAttrs.all ]")+          (mkStr "[\"derivation\",true,\"out\",\"t\",1]")+    ]++-- ---------------------------------------------------------------------------+-- Tests: structured attributes and the JSON they travel as+-- ---------------------------------------------------------------------------++-- | @__structuredAttrs@ end to end on the evaluation side, and the JSON+-- rules the evaluator and builder share.  Every drvPath, rendering and+-- @.attrs.sh@ expected here was read off Nix 2.33.2 (nix-instantiate and+-- a build on aarch64-darwin), whose code for each is 2.24.9's.+testStructuredAttrs :: IO [Bool]+testStructuredAttrs = do+  putStrLn "derivation/structured-attrs"+  tmpBase <- getTemporaryDirectory+  let base = "name = \"sa\"; system = \"x86_64-linux\"; builder = \"/bin/sh\"; __structuredAttrs = true; "+      structured attrs = "(derivation { " <> base <> attrs <> " })"+      withoutContext expr = "builtins.unsafeDiscardStringContext " <> expr+      drvPathIs label attrs expected =+        runTest label (assertEval label (withoutContext (structured attrs <> ".drvPath")) (mkStr expected))+      dependency = "let d = derivation { name = \"d\"; system = \"x\"; builder = \"b\"; }; in "+  envResult <- evalDerivationIO tmpBase (structured "outputs = [ \"out\" \"dev\" \"lib\" ];")+  -- A file for the outPath that is a path, copied to the store as upstream+  -- copies it: "hello\n" named x is m5zd3qj7...-x there.+  let jsonDir = tmpBase </> "nova-nix-test-json-outpath"+  createDirectoryIfMissing True jsonDir+  BS.writeFile (jsonDir </> "x") "hello\n"+  copiedOutPath <- evalNixIO jsonDir "builtins.unsafeDiscardStringContext (builtins.toJSON { outPath = ./x; })"+  lengthOfPath <- evalNixIO jsonDir "builtins.stringLength ./x"+  substringOfPath <- evalNixIO jsonDir "builtins.substring 11 32 ./x"+  substringContext <- evalNixIO jsonDir "builtins.hasContext (builtins.substring 11 32 ./x)"+  discardedPath <- evalNixIO jsonDir "builtins.unsafeDiscardStringContext ./x"+  discardedContext <- evalNixIO jsonDir "builtins.hasContext (builtins.unsafeDiscardStringContext ./x)"+  copiedContext <- evalNixIO jsonDir "builtins.attrNames (builtins.getContext (builtins.toJSON { outPath = ./x; })) == [ \"/nix/store/m5zd3qj7c4bs4g5d8hqvs5pc5xicclfg-x\" ]"+  -- The IO evaluator, because it is the one with a store to copy into.+  uncopiedPath <- evalNixIO jsonDir "builtins.toJSON { __toString = s: ./x; }"+  uncopiedNested <- evalNixIO jsonDir "builtins.toJSON { __toString = s: { outPath = ./x; }; }"+  removeDirectoryRecursive jsonDir+  let jsonDirPath = mkStr ("\"" <> canonPathValue (T.pack (jsonDir </> "x")) <> "\"")+  sequence+    [ drvPathIs+        "a nested set and a mixed list are one JSON object"+        "nested = { a = 1; b = { c = [ \"x\" \"y\" ]; }; \"with space\" = true; }; list = [ \"a\" \"b c\" 1 2.5 null true false ];"+        "/nix/store/rkxyljjwm2miccr3ffbkvgm7fzmjqddg-sa.drv",+      drvPathIs+        "scalars render as nlohmann renders them"+        "i = 42; neg = -7; f = 1.0; f2 = 0.1; big = 1.0e20; small = 1.0e-7; b = true; n = null; s = \"str\\n\\t\\\"q\\\"\\\\\";"+        "/nix/store/hgzhpjmp6cpjj0r768xp982an303rh2q-sa.drv",+      drvPathIs+        "member names order by their bytes"+        "\"\233\" = 1; \"Z\" = 2; \"a\" = 3; \"_\" = 4; \"1x\" = 5;"+        "/nix/store/s2aaxxxqvmdh95wqq3sa75fqal0nv2vf-sa.drv",+      drvPathIs "a kept null is a JSON null" "n = null;" "/nix/store/r3880xygjwsqk8a4xiq8zrbhpanlf9a3-sa.drv",+      drvPathIs+        "__ignoreNulls leaves a null out of the object"+        "n = null; __ignoreNulls = true;"+        "/nix/store/cms7b67rf9bn7b376f64i05v1cw2chrh-sa.drv",+      drvPathIs+        "a placeholder stays a placeholder in the object"+        "here = builtins.placeholder \"out\";"+        "/nix/store/2iqn1i3rl4x9ll8a6j46k1rkk9c3fkd5-sa.drv",+      drvPathIs+        "a fixed-output derivation keeps its hash fields in the object"+        "outputHash = \"sha256-47DEQpj8HBSKTXA6xJbgU1CNMmz7W08F06XOTYP1hmM=\"; outputHashMode = \"flat\"; outputHashAlgo = \"sha256\";"+        "/nix/store/dp6sib5psffrm1krca5l9wn9nshspn7f-sa.drv",+      drvPathIs+        "a set under outputChecks is passed as it is"+        "outputChecks.out = { allowedReferences = [ ]; maxSize = 100; };"+        "/nix/store/xzkk2dxqm69akjjshlvk45s8yd6y1dbn-sa.drv",+      runTest "__structuredAttrs = false keeps one variable per attribute" $+        assertEval+          "sa-false"+          (withoutContext "(derivation { name = \"sa\"; system = \"x86_64-linux\"; builder = \"/bin/sh\"; __structuredAttrs = false; x = [ \"a\" \"b\" ]; }).drvPath")+          (mkStr "/nix/store/i9rm0fa7pbzrbrsaakninfa4232wmj7c-sa.drv"),+      runTest "every output of a structured derivation gets upstream's path" $+        assertEval+          "sa-outputs"+          (withoutContext (structured "outputs = [ \"out\" \"dev\" \"lib\" ];" <> ".dev.outPath"))+          (mkStr "/nix/store/jfnikb9k7953srg5mlp3mccmqaijvxyy-sa-dev"),+      runTest "the environment holds __json and the outputs, nothing else" $+        assertRight "sa-env" envResult $ \drv ->+          assertEqual+            "sa-env"+            [ ("__json", "{\"builder\":\"/bin/sh\",\"name\":\"sa\",\"outputs\":[\"out\",\"dev\",\"lib\"],\"system\":\"x86_64-linux\"}"),+              ("dev", "/nix/store/jfnikb9k7953srg5mlp3mccmqaijvxyy-sa-dev"),+              ("lib", "/nix/store/zpjd7d2l5jqzynv3377a36nk6rzb5il4-sa-lib"),+              ("out", "/nix/store/bs6ppbphi38qlbjfz67pfk86sx7l4vks-sa")+            ]+            (Map.toList (drvEnv drv)),+      -- toJSON's rules for a set, which the object above shares.+      runTest "toJSON of a set with outPath converts the outPath value, not its string" $+        assertEval "json-outpath-int" "builtins.toJSON { outPath = 1; }" (mkStr "1")+          `andThen` assertEval "json-outpath-set" "builtins.toJSON { outPath = { a = 1; }; }" (mkStr "{\"a\":1}")+          `andThen` assertEval "json-outpath-list" "builtins.toJSON { outPath = [ 1 { outPath = 2; } ]; }" (mkStr "[1,2]")+          `andThen` assertEval "json-outpath-null" "builtins.toJSON { outPath = null; }" (mkStr "null"),+      runTest "toJSON of a set whose outPath is a path copies it to the store, with context" $+        assertRight "json-outpath-path" copiedOutPath (assertEqual "json-outpath-path" (mkStr "\"/nix/store/m5zd3qj7c4bs4g5d8hqvs5pc5xicclfg-x\""))+          `andThen` assertRight "json-outpath-path-context" copiedContext (assertEqual "json-outpath-path-context" (VBool True)),+      runTest "a builtin taking a string copies a path to the store first" $+        assertRight "strlen-path" lengthOfPath (assertEqual "strlen-path" (VInt 45))+          `andThen` assertRight "substring-path" substringOfPath (assertEqual "substring-path-text" "m5zd3qj7c4bs4g5d8hqvs5pc5xicclfg" . stringBytes)+          `andThen` assertRight "substring-path-context" substringContext (assertEqual "substring-path-context" (VBool True))+          `andThen` assertRight "discard-path" discardedPath (assertEqual "discard-path" (mkStr "/nix/store/m5zd3qj7c4bs4g5d8hqvs5pc5xicclfg-x"))+          `andThen` assertRight "discard-path-context" discardedContext (assertEqual "discard-path-context" (VBool False)),+      runTest "toJSON of a __toString set returning a path keeps the path's own text, uncopied" $+        assertRight "json-tostring-path" uncopiedPath (assertEqual "json-tostring-path" jsonDirPath)+          `andThen` assertRight "json-tostring-nested" uncopiedNested (assertEqual "json-tostring-nested" jsonDirPath),+      runTest "toJSON of a __toString set returning a string keeps its context" $+        let json = "(builtins.toJSON { __toString = s: \"${d}\"; })"+         in assertEval "json-tostring-string" (dependency <> withoutContext json) (mkStr "\"/nix/store/74ii7m3ms7x609g9mcy8j52jfvpdizcp-d\"")+              `andThen` assertEval+                "json-tostring-context"+                (dependency <> "builtins.getContext " <> json <> " == { \"/nix/store/nzvhjdd45mdh8mkqm4vz4hdqsjrvkm8j-d.drv\" = { outputs = [ \"out\" ]; }; }")+                (VBool True),+      runTest "toJSON of a __toString set returning an integer is an error, not a coercion" $+        assertEvalFail "json-tostring-int" "builtins.toJSON { __toString = s: 1; }",+      drvPathIs+        "a structured attribute's outPath and __toString follow toJSON's rules"+        "o = { outPath = { inner = 1; }; }; i = { outPath = 1; }; t = { __toString = s: \"str\"; };"+        "/nix/store/rz7pfawzsr1a5ig11s1xssbsc2mxys9b-sa.drv",+      runTest "toJSON escapes backspace and form feed by name" $+        assertEval+          "json-bf"+          "builtins.toJSON (builtins.fromJSON \"\\\"\\\\u0008\\\\u000c\\\\u0001\\\"\")"+          (mkStr "\"\\b\\f\\u0001\""),+      runTest "__structuredAttrs must be a boolean" $+        assertEvalFail "sa-flag" "(derivation { name = \"sa\"; system = \"x\"; builder = \"b\"; __structuredAttrs = \"yes\"; }).drvPath",+      runTest "a structured system may not refer to a store path" $+        assertEvalError+          "sa-system-ctx"+          (dependency <> "(derivation { name = \"sa\"; builder = \"/bin/sh\"; __structuredAttrs = true; system = \"${d}\"; }).drvPath")+          "the string '/nix/store/74ii7m3ms7x609g9mcy8j52jfvpdizcp-d' is not allowed to refer to a store path (such as '/nix/store/nzvhjdd45mdh8mkqm4vz4hdqsjrvkm8j-d.drv^out')",+      runTest "a structured output name may not refer to a store path" $+        assertEvalError+          "sa-output-ctx"+          (dependency <> structured "outputs = [ \"out\" \"${d}\" ];" <> ".drvPath")+          "the string '/nix/store/74ii7m3ms7x609g9mcy8j52jfvpdizcp-d' is not allowed to refer to a store path (such as '/nix/store/nzvhjdd45mdh8mkqm4vz4hdqsjrvkm8j-d.drv^out')",+      runTest "a structured builder must be a string, not a value coerced to one" $+        assertEvalError+          "sa-builder"+          "(derivation { name = \"sa\"; system = \"x\"; __structuredAttrs = true; builder = 1; }).drvPath"+          "expected a string but found an integer: 1",+      runTest "a structured outputHash must be a string" $+        assertEvalError "sa-outputhash" (structured "outputHash = 1;" <> ".drvPath") "expected a string but found an integer: 1",+      runTest "a function cannot become JSON" $+        assertEvalFail "sa-function" (structured "f = x: x;" <> ".drvPath"),+      -- The JSON both halves share.+      runTest "JSON escapes control characters as nlohmann does" $+        assertEqual+          "json-escape"+          (TE.encodeUtf8 "\"a\\b\\f\\n\\r\\t\\u0001\\u001f\127/\\\"\\\\\233\"")+          (renderJson (JsonString "a\b\f\n\r\t\1\31\127/\"\\\233")),+      runTest "JSON numbers render as nlohmann renders them" $+        assertEqual+          "json-numbers"+          "[1.0,1e+20,1e-07,0.1,null,null,-7,18446744073709551615]"+          (renderJson (JsonArray [JsonFloat 1, JsonFloat 1e20, JsonFloat 1e-7, JsonFloat 0.1, JsonFloat (1 / 0), JsonFloat (0 / 0), JsonInt (-7), JsonInt 18446744073709551615])),+      runTest "upstream's .attrs.json reads back and renders to the same bytes" $+        assertRight "json-upstream" (decodeStructuredAttrs upstreamAttrsJson) $ \attrs ->+          assertEqual "json-upstream" (TE.encodeUtf8 upstreamAttrsJson) (encodeStructuredAttrs attrs),+      runTest "the .attrs.sh renderer writes what upstream writes" $+        assertRight "attrs-sh" (decodeStructuredAttrs upstreamAttrsJson) $ \attrs ->+          assertEqual "attrs-sh" upstreamAttrsShell (renderAttrsShell attrs),+      runTest "outputs become an object of placeholders" $+        assertEqual+          "outputs-object"+          (StructuredAttrs (Map.fromList [("outputs", JsonObject (Map.fromList [("dev", JsonString (hashPlaceholder "dev")), ("out", JsonString (hashPlaceholder "out"))]))]))+          (withOutputPlaceholders ["out", "dev"] (StructuredAttrs (Map.fromList [("outputs", JsonArray [JsonString "out", JsonString "dev"])]))),+      runTest "a null __json is an empty object, another non-object an error" $+        assertEqual "decode-shape" (Right (StructuredAttrs Map.empty)) (decodeStructuredAttrs "null")+          `andThen` assertLeft "decode-array" (decodeStructuredAttrs "[1]"),+      runTest "a list-of-strings attribute is read strictly" $+        let attrs = StructuredAttrs (Map.fromList [("good", JsonArray [JsonString "a", JsonString "b"]), ("mixed", JsonArray [JsonString "a", JsonInt 1]), ("scalar", JsonString "a b")])+         in assertEqual "strings-good" (Right (Just ["a", "b"])) (stringsAttr "good" attrs)+              `andThen` assertEqual "strings-absent" (Right Nothing) (stringsAttr "absent" attrs)+              `andThen` assertLeft "strings-mixed" (stringsAttr "mixed" attrs)+              `andThen` assertLeft "strings-scalar" (stringsAttr "scalar" attrs),+      runTest "JSON parsing decodes every escape, surrogate pairs included" $+        assertEqual+          "parse-escapes"+          (Right (JsonString "\"\\/\b\f\n\r\t\233\128512"))+          (parseJson "\"\\\"\\\\\\/\\b\\f\\n\\r\\t\\u00E9\\ud83d\\ude00\""),+      runTest "JSON parsing keeps integers apart from floats, as nlohmann's lexer does" $+        assertEqual+          "parse-numbers"+          (Right (JsonArray [JsonInt 18446744073709551615, JsonFloat 18446744073709551616, JsonInt (-9223372036854775808), JsonFloat (-9223372036854775809), JsonInt 0, JsonFloat 1, JsonFloat 100]))+          (parseJson "[18446744073709551615,18446744073709551616,-9223372036854775808,-9223372036854775809,-0,1.0,1E2]"),+      runTest "JSON parsing takes the last of a repeated name, whitespace and a byte order mark around" $+        assertEqual+          "parse-object"+          (Right (JsonObject (Map.fromList [("a", JsonArray [JsonInt 2, JsonNull])])))+          (parseJson "\65279 \n{ \"a\" : 1 , \"a\":[ 2 ,null ] }\r\n"),+      runTest "JSON parsing hands a builder each object's members in document order, a repeated name each time" $+        let memberNames =+              JsonBuilder+                { buildNull = [],+                  buildBool = const [],+                  buildInt = const [],+                  buildFloat = const [],+                  buildString = const [],+                  buildArray = concat,+                  buildObject = concatMap (uncurry (:))+                }+         in assertEqual+              "parse-member-order"+              (Right ["zb", "zc", "za", "zd", "zb"])+              (parseJsonInto NixRange memberNames "{\"zb\":{\"zc\":1},\"za\":[{\"zd\":null}],\"zb\":2}"),+      runTest "JSON parsing refuses what nlohmann refuses" $+        foldr+          (\bad acc -> assertLeft ("parse-refuses " <> bad) (parseJson bad) `andThen` acc)+          Pass+          ["\"a\tb\"", "01", "[1,]", "1e400", "{\"a\" 1}", "tru", "1 2", "\"\\ud800\"", "\"\\udc00\"", "\"\\x\"", "1.", "-", "\"unterminated", ""],+      runTestM "rendered JSON parses back to the value it came from" $ do+        result <-+          QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} $+            QC.forAll (genJson 3) $ \json ->+              (parseJson =<< either (Left . T.pack . show) Right (TE.decodeUtf8' (renderJson json))) QC.=== Right json+        pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))+    ]++-- | A subset of the @.attrs.json@ a Nix 2.33.2 build handed its builder+-- (the members holding no store path), byte for byte.+upstreamAttrsJson :: Text+upstreamAttrsJson =+  "{\"1x\":\"skipped\",\"badList\":[\"a\",[\"nested\"]],\"badObj\":{\"k\":{\"nested\":1}},\"big\":1099511627776,\"ctl\":\"a\\b\\f\\u0001\\u001f\127/\\\"\\\\z\",\"emptyList\":[],\"emptyObj\":{},\"f\":1.5,\"fbig\":1e+20,\"fi\":3.0,\"fl\":false,\"fltList\":[1.5],\"fltObj\":{\"a\":1,\"b\":2.5},\"fneg\":-1e+20,\"fneg2\":-2.5,\"fsmall\":0.1,\"ftrunc\":16777217.5,\"huge\":9223372036854775807,\"int\":42,\"list\":[\"a\",\"b c\",1,2.0,true,false,null],\"n\":null,\"neg\":-7,\"obj\":{\"b\":false,\"k\":\"v\",\"key with space\":1,\"q\":\"'\"},\"str\":\"it's a \\\"test\\\"\\n\",\"t\":true,\"uni\":\"\233\8364\128512\",\"with space\":\"skipped\"}"++-- | The lines of that build's @.attrs.sh@ for the members of+-- 'upstreamAttrsJson'.  Missing ones (a non-integral number, a nested+-- array or object, a name bash cannot hold) are upstream's omissions;+-- @fbig@ and @fneg@ are aarch64's saturating float conversion.+upstreamAttrsShell :: Text+upstreamAttrsShell =+  "declare big=0\ndeclare ctl='a\8\12\1\31\127/\"\\z'\ndeclare -a emptyList=()\ndeclare -A emptyObj=()\ndeclare fbig=2147483647\ndeclare fi=3\ndeclare fl=\ndeclare fneg=-2147483648\ndeclare ftrunc=16777217\ndeclare huge=-1\ndeclare int=42\ndeclare -a list=('a' 'b c' 1 2 1  '' )\ndeclare n=''\ndeclare neg=-7\ndeclare -A obj=(['b']= ['k']='v' ['key with space']=1 ['q']=''\\''' )\ndeclare str='it'\\''s a \"test\"\n'\ndeclare t=1\ndeclare uni='\233\8364\128512'\n"++-- ---------------------------------------------------------------------------+-- Tests: fromATerm + Derivation Output Population (Phase 2, Batch 3)+-- ---------------------------------------------------------------------------++-- | A complex test derivation with multiple outputs, input drvs, and input srcs.+complexTestDrv :: Derivation+complexTestDrv =+  Derivation+    { drvOutputs =+        [ DerivationOutput "dev" (StorePath "dddddddddddddddddddddddddddddddd" "pkg-2.0-dev") "" "",+          DerivationOutput "out" (StorePath "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "pkg-2.0") "" ""+        ],+      drvInputDrvs =+        Map.fromList+          -- Hash fixtures stay inside the nix-base32 alphabet (no e o u t):+          -- fromATerm parses these through parseStorePath, which+          -- charset-checks the hash component.+          [ (StorePath "cccccccccccccccccccccccccccccccc" "dep1.drv", ["out"]),+            (StorePath "ffffffffffffffffffffffffffffffff" "dep2.drv", ["lib", "out"])+          ],+      drvInputSrcs = [StorePath "gggggggggggggggggggggggggggggggg" "source.tar.gz"],+      drvPlatform = Aarch64_Darwin,+      drvBuilder = "/nix/store/hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh-bash/bin/bash",+      drvArgs = ["-e", "build.sh"],+      drvEnv =+        Map.fromList+          [ ("buildInputs", "/nix/store/cccccccccccccccccccccccccccccccc-dep1"),+            ("name", "pkg-2.0"),+            ("out", "/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-pkg-2.0"),+            ("system", "aarch64-darwin")+          ]+    }++testFromATerm :: IO [Bool]+testFromATerm = do+  putStrLn "derivation/fromATerm"+  sequence+    [ -- Round-trip: simple derivation+      runTest "fromATerm round-trip simple" $+        assertEqual "simple round-trip" (Right simpleTestDrv) (fromATerm (toATerm simpleTestDrv)),+      -- Round-trip: complex derivation+      runTest "fromATerm round-trip complex" $+        assertEqual "complex round-trip" (Right complexTestDrv) (fromATerm (toATerm complexTestDrv)),+      -- A .drv read from disk is input: an output name that violates the+      -- store-name rules (here a traversal shape that would later join+      -- the build dir) must refuse at parse.+      runTest "fromATerm rejects a traversal-shaped output name" $+        let evil =+              simpleTestDrv+                { drvOutputs =+                    [DerivationOutput "../evil" (StorePath (T.replicate 32 "a") "pkg") "" ""]+                }+         in case fromATerm (toATerm evil) of+              Left _ -> Pass+              Right _ -> Fail "parsed a drv with a traversal output name",+      -- drv4: the modulo-substitution section merges input-drv entries that+      -- share a modulo-hash key, unioning their output-name sets, so it is+      -- byte-identical to the already-merged form.  (Just subs replaces the+      -- whole input-drv section, so simpleTestDrv's own inputs are irrelevant.)+      runTest "inputDrvsSubst merges equal modulo keys" $+        assertEqual+          "subst-merge"+          (toATermForHash False (Just [("00000000", ["dev", "out"])]) simpleTestDrv)+          (toATermForHash False (Just [("00000000", ["out"]), ("00000000", ["dev"])]) simpleTestDrv),+      runTest "inputDrvsSubst unions and dedups merged out-names" $+        assertEqual+          "subst-union"+          (toATermForHash False (Just [("aabbccdd", ["dev", "out"])]) simpleTestDrv)+          (toATermForHash False (Just [("aabbccdd", ["out"]), ("aabbccdd", ["out", "dev"])]) simpleTestDrv),+      -- Distinct keys are untouched: still one entry each, ascending by key.+      runTest "inputDrvsSubst preserves distinct keys in order" $+        assertEqual+          "subst-distinct"+          (toATermForHash False (Just [("00000000", ["out"]), ("11111111", ["out"])]) simpleTestDrv)+          (toATermForHash False (Just [("11111111", ["out"]), ("00000000", ["out"])]) simpleTestDrv),+      -- Round-trip: empty derivation (no outputs, no inputs, no args, no env)+      runTest "fromATerm round-trip empty" $+        let emptyDrv =+              Derivation+                { drvOutputs = [],+                  drvInputDrvs = Map.empty,+                  drvInputSrcs = [],+                  drvPlatform = X86_64_Linux,+                  drvBuilder = "/bin/true",+                  drvArgs = [],+                  drvEnv = Map.empty+                }+         in assertEqual "empty round-trip" (Right emptyDrv) (fromATerm (toATerm emptyDrv)),+      -- Reject empty string+      runTest "fromATerm rejects empty" $+        assertLeft "empty" (fromATerm ""),+      -- Reject malformed+      runTest "fromATerm rejects malformed" $+        assertLeft "malformed" (fromATerm "NotADerivation"),+      -- Reject truncated+      runTest "fromATerm rejects truncated" $+        assertLeft "truncated" (fromATerm "Derive(["),+      -- Escaping round-trip: strings with special chars+      runTest "fromATerm escaping round-trip" $+        let escapeDrv =+              Derivation+                { drvOutputs =+                    [ DerivationOutput+                        { doName = "out",+                          doPath = StorePath "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "esc-test",+                          doHashAlgo = "",+                          doHash = ""+                        }+                    ],+                  drvInputDrvs = Map.empty,+                  drvInputSrcs = [],+                  drvPlatform = X86_64_Linux,+                  drvBuilder = "/bin/bash",+                  drvArgs = ["-c", "echo \"hello\nworld\""],+                  drvEnv = Map.fromList [("msg", "line1\nline2\ttab\\slash")]+                }+         in assertEqual "escape round-trip" (Right escapeDrv) (fromATerm (toATerm escapeDrv)),+      -- A non-standard escape keeps the byte and drops the backslash,+      -- matching upstream's .drv string parser.+      runTest "fromATerm drops the backslash on a non-standard escape" $+        let aterm = "Derive([(\"out\",\"/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-x\",\"\",\"\")],[],[],\"x86_64-linux\",\"/bin/sh\",[],[(\"k\",\"a\\xb\")])"+         in assertRight "nonstandard escape" (fromATerm aterm) $ \drv ->+              assertEqual "escape dropped" (Just "axb") (Map.lookup "k" (drvEnv drv)),+      -- writeDrv writes correct ATerm+      runTestM "writeDrv writes correct ATerm" $ do+        tmpBase <- getTemporaryDirectory+        let tmpStore = tmpBase </> "nova-nix-test-writeDrv"+        forceRemoveIfExists tmpStore+        store <- openStore testLogger (StoreDir tmpStore)+        let sp = StorePath "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "test.drv"+            destFile = storePathToFilePath (stDir store) sp+        writeDrv store simpleTestDrv sp+        contents <- BS.readFile destFile+        closeStore store+        forceRemoveIfExists tmpStore+        pure (assertEqual "writeDrv content" (toATerm simpleTestDrv) contents),+      -- The .drv closure registers as store objects: a row for every+      -- recipe plus edges to its input sources and input .drvs, so an+      -- output reference scan that names an input .drv resolves instead+      -- of failing the registration batch.+      runTestM "writeDrvClosure registers recipes with their references" $ do+        tmpBase <- getTemporaryDirectory+        let tmpStore = tmpBase </> "nova-nix-test-drv-closure"+            sd = StoreDir tmpStore+        forceRemoveIfExists tmpStore+        store <- openStore testLogger sd+        let srcSp = StorePath "gggggggggggggggggggggggggggggggg" "source.tar.gz"+            drvASp = StorePath "cccccccccccccccccccccccccccccccc" "dep1.drv"+            drvBSp = StorePath "dddddddddddddddddddddddddddddddd" "top.drv"+            drvB =+              simpleTestDrv+                { drvInputDrvs = Map.fromList [(drvASp, ["out"])],+                  drvInputSrcs = [srcSp]+                }+        -- The source row registers first, as in the build driver, where+        -- materializeEvalSources precedes the closure write.+        registerPath (stDB store) (PathRegistration srcSp "sha256:0" 0 Nothing [] NotUltimate Set.empty Nothing RegisteredNow)+        writeDrvClosure+          store+          ( Map.fromList+              [ (storePathToText defaultStoreDir drvASp, toATerm simpleTestDrv),+                (storePathToText defaultStoreDir drvBSp, toATerm drvB)+              ]+          )+        validA <- isValid store drvASp+        validB <- isValid store drvBSp+        refsB <- queryReferences (stDB store) drvBSp+        closeStore store+        forceRemoveIfExists tmpStore+        let expectedRefs =+              sort+                [ T.pack (storePathToFilePath sd drvASp),+                  T.pack (storePathToFilePath sd srcSp)+                ]+        pure $+          if not validA+            then Fail "input .drv not registered"+            else+              if not validB+                then Fail "root .drv not registered"+                else assertEqual "drv references" expectedRefs (sort refsB),+      -- The recorded derivation populates drvOutputs.  These three read the+      -- Derivation the session records, which only the IO evaluator keeps.+      runTestM "derivationStrict populates drvOutputs" $ do+        tmpBase <- getTemporaryDirectory+        result <- evalDerivationIO tmpBase "derivation { name = \"test\"; system = \"x86_64-linux\"; builder = \"/bin/sh\"; }"+        pure $ assertRight "drvOutputs" result $ \drv ->+          case drvOutputs drv of+            [] -> Fail "drvOutputs is empty"+            (firstOut : _) ->+              if doName firstOut == "out"+                then Pass+                else Fail ("first output name: " <> doName firstOut),+      -- The .drv lists outputs sorted by name, as upstream writes them; the+      -- declared order lives in the value's outputs and all.+      runTestM "derivationStrict multi-output" $ do+        tmpBase <- getTemporaryDirectory+        result <- evalDerivationIO tmpBase "derivation { name = \"multi\"; system = \"x86_64-linux\"; builder = \"/bin/sh\"; outputs = [\"out\" \"dev\"]; }"+        pure $ assertRight "multi-output" result $ \drv ->+          let names = map doName (drvOutputs drv)+           in if names == ["dev", "out"]+                then Pass+                else Fail ("output names: " <> T.pack (show names)),+      -- The .drv env carries the output paths ($out, ...) and the build+      -- attributes, and no "drvPath" key - matching C++ Nix, which never+      -- writes one.+      runTestM "derivationStrict populates drvEnv" $ do+        tmpBase <- getTemporaryDirectory+        result <- evalDerivationIO tmpBase "derivation { name = \"test\"; system = \"x86_64-linux\"; builder = \"/bin/sh\"; }"+        pure $ assertRight "drvEnv" result $ \drv ->+          case (Map.lookup "out" (drvEnv drv), Map.lookup "name" (drvEnv drv)) of+            (Just op, Just "test")+              | "/nix/store/" `BS.isPrefixOf` op -> Pass+            _ -> Fail ("drvEnv keys: " <> T.pack (show (Map.toList (drvEnv drv))))+    ]++-- ---------------------------------------------------------------------------+-- Tests: input-addressed derivations+-- ---------------------------------------------------------------------------++-- | 'inputAddressed' over derivations whose paths upstream computed, as the+-- evaluator tests pin them: @a@ and the @b@ chains are nix-instantiate+-- 2.24.9's ('selfHoldingPrintedStrict', 'testDeepContextClosureIO'), @sa@+-- is 2.33.2's ('testStructuredAttrs').  Then its laws over generated+-- derivations, and what derivationStrict records held to them.+testInputAddressed :: IO [Bool]+testInputAddressed = do+  putStrLn "derivation/input-addressed"+  storeDir <- evalNixIOStoreDir+  sequence+    [ runTest "a derivation gets upstream's drvPath and output path"+        $ assertRight "a" aFile+        $ assertEqual "a" ("/nix/store/l9ldjc53ry43x24hvq73jx7dx0489mhj-a.drv", [("out", "/nix/store/0pd4llb3k36fnppfxwp6nlwsxwlv0y2c-a")]) . drvFilePathTexts,+      runTest "every output gets upstream's path, and the variable of its name holds it" $+        assertRight "sa" (inputAddressed "sa" [] structured) $ \file ->+          assertEqual "sa-outputs" saOutputs (snd (drvFilePathTexts file))+            `andThen` assertEqual "sa-env" (Map.fromList (("__json", saJson) : [(output, TE.encodeUtf8 path) | (output, path) <- saOutputs])) (drvEnv (drvFileDerivation file)),+      runTest "an input derivation's modulo hash stands in for its path" $+        assertRight "a" aFile $ \a ->+          assertRight "b" (inputAddressed "b" [(moduloHex [] a, ["out"])] (overDrvPath "b" a [a])) $+            assertEqual "b" "/nix/store/r3pz4ykyxg5s9f08fafcksw6bxfds40r-b.drv" . fst . drvFilePathTexts,+      runTest "each input of a chain stands in by its own modulo hash" $+        assertRight "a" aFile $ \a ->+          let aHash = (moduloHex [] a, ["out"])+              m = (plainDerivation "m" [("dep", outPathBytes a)]) {drvInputDrvs = Map.singleton (drvFilePath a) ["out"]}+           in assertRight "m" (inputAddressed "m" [aHash] m) $ \mFile ->+                assertRight "b" (inputAddressed "b" [aHash, (moduloHex [aHash] mFile, ["out"])] (overDrvPath "b" mFile [a, mFile])) $+                  assertEqual "b" "/nix/store/00pfjcd57v5dd5j4w4zmsp3s8lcpv6wg-b.drv" . fst . drvFilePathTexts,+      runTestM "only the outputs and their variables change, each variable holding its output's path" $+        quickCheckPasses $+          QC.forAll genFillCase $ \(FillCase name inputHashes drv) ->+            case inputAddressed name inputHashes drv of+              Left err -> QC.counterexample (show err) False+              Right file ->+                let filled = drvFileDerivation file+                    withoutOutputs d = d {drvOutputs = [], drvEnv = foldr (Map.delete . doName) (drvEnv d) (drvOutputs drv)}+                 in ( withoutOutputs filled,+                      map doName (drvOutputs filled),+                      [(Map.lookup (doName output) (drvEnv filled), doHashAlgo output, doHash output) | output <- drvOutputs filled],+                      drvFileATerm file,+                      spName (drvFilePath file)+                    )+                      QC.=== ( withoutOutputs drv,+                               sort (map doName (drvOutputs drv)),+                               [(Just (TE.encodeUtf8 (storePathToText defaultStoreDir (doPath output))), "", "") | output <- drvOutputs filled],+                               toATerm filled,+                               name <> ".drv"+                             ),+      runTestM "the file does not depend on what the outputs and their variables held" $+        quickCheckPasses $+          QC.forAll genFillCase $ \(FillCase name inputHashes drv) ->+            QC.forAll (genHolding drv) $ \holding ->+              let file = inputAddressed name inputHashes drv+               in (inputAddressed name inputHashes holding, inputAddressed name inputHashes . drvFileDerivation =<< file) QC.=== (file, file),+      runTestM "what derivationStrict records is filled in already, at the paths it returns" $+        quickCheckPasses (QC.forAll genStrictCase (QC.ioProperty . strictCaseAgrees storeDir))+    ]+  where+    quickCheckPasses property = do+      result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} property+      pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))+    aFile = inputAddressed "a" [] (plainDerivation "a" [])+    -- The modulo hash a dependent substitutes for a filled-in derivation:+    -- upstream's hashDerivationModulo, unmasked, over its own inputs' hashes.+    moduloHex inputHashes file = Hash.bytesToHexText (sha256Digest (toATermForHash False (Just inputHashes) (drvFileDerivation file)))+    -- @x = "${dep.drvPath}";@: the .drv closure in inputSrcs, and each .drv+    -- in it among the inputs with every output, here @out@ alone.+    overDrvPath name dep closure =+      (plainDerivation name [("x", TE.encodeUtf8 (fst (drvFilePathTexts dep)))])+        { drvInputDrvs = Map.fromList [(drvFilePath file, ["out"]) | file <- closure],+          drvInputSrcs = map drvFilePath closure+        }+    structured =+      Derivation+        { drvOutputs = map pendingOutput ["out", "dev", "lib"],+          drvInputDrvs = Map.empty,+          drvInputSrcs = [],+          drvPlatform = X86_64_Linux,+          drvBuilder = "/bin/sh",+          drvArgs = [],+          drvEnv = Map.singleton "__json" saJson+        }+    saJson = "{\"builder\":\"/bin/sh\",\"name\":\"sa\",\"outputs\":[\"out\",\"dev\",\"lib\"],\"system\":\"x86_64-linux\"}"+    saOutputs =+      [ ("dev", "/nix/store/jfnikb9k7953srg5mlp3mccmqaijvxyy-sa-dev"),+        ("lib", "/nix/store/zpjd7d2l5jqzynv3377a36nk6rzb5il4-sa-lib"),+        ("out", "/nix/store/bs6ppbphi38qlbjfz67pfk86sx7l4vks-sa")+      ]++-- | A file's drvPath, and each output's name and path, as text.+drvFilePathTexts :: DrvFile -> (Text, [(Text, Text)])+drvFilePathTexts file =+  ( storePathToText defaultStoreDir (drvFilePath file),+    [(doName output, storePathToText defaultStoreDir (doPath output)) | output <- drvOutputs (drvFileDerivation file)]+  )++-- | The path of a file's @out@, as an environment value holds it.+outPathBytes :: DrvFile -> BS.ByteString+outPathBytes file = TE.encodeUtf8 (fromMaybe "" (lookup "out" (snd (drvFilePathTexts file))))++-- | An output carrying only its name, as derivationStrict hands one to+-- 'inputAddressed'.+pendingOutput :: Text -> DerivationOutput+pendingOutput name = DerivationOutput name (StorePath "" "") "" ""++-- | @derivation { name = <name>; system = "x"; builder = "/bin/sh"; }@+-- with more variables, as derivationStrict hands it to 'inputAddressed':+-- no inputs, and its @out@ pending.+plainDerivation :: Text -> [(Text, BS.ByteString)] -> Derivation+plainDerivation name variables =+  Derivation+    { drvOutputs = [pendingOutput "out"],+      drvInputDrvs = Map.empty,+      drvInputSrcs = [],+      drvPlatform = OtherPlatform "x",+      drvBuilder = "/bin/sh",+      drvArgs = [],+      drvEnv = Map.fromList ([("builder", "/bin/sh"), ("name", TE.encodeUtf8 name), ("system", "x")] <> variables)+    }++-- | A derivation for 'inputAddressed''s laws with the name and input hashes+-- it is filled in with: outputs and their variables holding anything,+-- inputs the hashes need not match, and any bytes in its fields.+data FillCase = FillCase !Text ![(Text, [Text])] !Derivation+  deriving (Show)++genFillCase :: QC.Gen FillCase+genFillCase = do+  name <- genDrvName+  outputs <- genOutputNames >>= traverse genHeldOutput+  inputDrvs <- Map.fromList <$> QC.resize 3 (QC.listOf ((,) <$> genFixturePath ".drv" <*> genOutputNames))+  inputSrcs <- QC.resize 3 (QC.listOf (genFixturePath ""))+  platform <- QC.elements [X86_64_Linux, Aarch64_Darwin, OtherPlatform "x"]+  builder <- genFieldBytes+  args <- QC.resize 3 (QC.listOf genFieldBytes)+  env <- Map.fromList <$> QC.resize 6 (QC.listOf ((,) <$> QC.elements (["name", "system", "builder", "src", "__json"] <> outputPool) <*> genFieldBytes))+  inputHashes <- QC.resize 3 (QC.listOf ((,) <$> genTextOf 64 "0123456789abcdef" <*> genOutputNames))+  pure+    ( FillCase+        name+        inputHashes+        Derivation+          { drvOutputs = outputs,+            drvInputDrvs = inputDrvs,+            drvInputSrcs = inputSrcs,+            drvPlatform = platform,+            drvBuilder = builder,+            drvArgs = args,+            drvEnv = env+          }+    )++-- | A derivation with each output, and the variable of its name, holding+-- something else.+genHolding :: Derivation -> QC.Gen Derivation+genHolding drv = do+  outputs <- traverse (genHeldOutput . doName) (drvOutputs drv)+  held <- traverse (const genFieldBytes) outputs+  pure drv {drvOutputs = outputs, drvEnv = foldr (uncurry Map.insert) (drvEnv drv) (zip (map doName outputs) held)}++-- | An output holding a path and hash fields of any kind.+genHeldOutput :: Text -> QC.Gen DerivationOutput+genHeldOutput name =+  DerivationOutput name+    <$> genFixturePath ""+    <*> QC.elements ["", "sha256", "r:sha256"]+    <*> QC.elements ["", "0123456789abcdef", "impure"]++-- | Output names, at least one and none twice, in any order.+genOutputNames :: QC.Gen [Text]+genOutputNames = QC.sublistOf outputPool `QC.suchThat` (not . null) >>= QC.shuffle++-- | The output names the generators draw on.+outputPool :: [Text]+outputPool = ["out", "dev", "lib", "bin", "doc", "man"]++-- | Bytes for a builder, an argument or a variable: any bytes, the ATerm+-- specials among them.+genFieldBytes :: QC.Gen BS.ByteString+genFieldBytes = BS.pack <$> QC.resize 12 (QC.listOf QC.arbitrary)++-- | A derivationStrict call as Nix source, with the name it gives: its+-- outputs in any order, structured or not, some attributes, and perhaps+-- one that depends on another derivation, through an output, through its+-- drvPath, or through a fixed output.+data StrictCase = StrictCase !Text !Text+  deriving (Show)++genStrictCase :: QC.Gen StrictCase+genStrictCase = do+  name <- genDrvName+  system <- QC.elements ["x", "x86_64-linux"]+  builder <- QC.elements ["/bin/sh", "b"]+  outputs <- genOutputNames+  structured <- QC.elements ["true", "false"]+  attributes <- QC.sublistOf ["s = \"line\\n\\\"quoted\\\" \\\\ \\${x}\";", "i = 42;", "l = [ \"a\" \"b c\" ];", "n = null;", "t = true;"]+  dependency <- QC.elements ["", "dep = d;", "dep = d.dev;", "dep = \"${d.drvPath}\";", "dep = f;"]+  pure . StrictCase name . T.unwords $+    [ "let d = derivation { name = \"d\"; system = \"x\"; builder = \"b\"; outputs = [ \"out\" \"dev\" ]; };",+      "f = derivation { name = \"f\"; system = \"x\"; builder = \"b\"; outputHash = \"sha256-47DEQpj8HBSKTXA6xJbgU1CNMmz7W08F06XOTYP1hmM=\"; };",+      "r = derivationStrict { name = \"" <> name <> "\"; system = \"" <> system <> "\"; builder = \"" <> builder <> "\";",+      "outputs = [ " <> T.unwords ["\"" <> output <> "\"" | output <- outputs] <> " ]; __structuredAttrs = " <> structured <> ";"+    ]+      <> attributes+      <> [ dependency,+           "}; in builtins.concatStringsSep \"\\n\" (map (n: n + \"=\" + builtins.unsafeDiscardStringContext r.${n}) (builtins.attrNames r))"+         ]++-- | Whether what derivationStrict records for a case is filled in already:+-- 'inputAddressed', given the case's name and the modulo hashes the session+-- cached for the recorded inputs, gives back the recorded derivation, at+-- the drvPath and output paths derivationStrict returned.+strictCaseAgrees :: StoreDir -> StrictCase -> IO QC.Property+strictCaseAgrees storeDir (StrictCase name source) = case parseNix testBaseDir testOrigin (TE.encodeUtf8 source) of+  Left err -> pure (QC.counterexample (show err) False)+  Right parsed -> do+    st <- testEvalState storeDir testBaseDir+    outcome <- runEvalIO st $ do+      returned <-+        evalParsed (pure (evalBaseEnv st)) parsed >>= \case+          VStr bytes _ -> pure [T.drop 1 <$> T.breakOn "=" line | line <- T.lines (bytesText bytes)]+          other -> throwEvalError ("expected a string, got " <> typeName other)+      recorded <- maybe (pure Nothing) lookupSessionDrv (lookup "drvPath" returned)+      drv <- maybe (throwEvalError "no .drv was recorded") pure recorded+      inputHashes <- traverse cachedHash (Map.toList (drvInputDrvs drv))+      pure (returned, drv, inputHashes)+    pure $ case outcome of+      Left err -> QC.counterexample (T.unpack err) False+      Right (returned, drv, inputHashes) -> case inputAddressed name inputHashes drv of+        Left err -> QC.counterexample (show err) False+        Right file ->+          let (drvPath, outputs) = drvFilePathTexts file+           in (drvFileDerivation file, sort returned) QC.=== (drv, sort (("drvPath", drvPath) : outputs))+  where+    cachedHash (input, outputs) = do+      let inputText = storePathToText defaultStoreDir input+      lookupDrvHash inputText >>= maybe (throwEvalError ("no modulo hash was cached for " <> inputText)) (\hash -> pure (hash, outputs))++-- ---------------------------------------------------------------------------+-- Tests: develop's capture+-- ---------------------------------------------------------------------------++-- | The derivation develop builds to capture a target's environment+-- ("Nix.Develop.Capture"), over fixtures and over generated derivations.+-- The script is data/develop/get-env.sh, and its store path is the one+-- upstream 2.34.9 and 2.35.4 add the same bytes at.+testDevelopCapture :: IO [Bool]+testDevelopCapture = do+  putStrLn "develop/capture"+  scriptPath <- getEnvScriptPath <$> BS.readFile ("data" </> "develop" </> "get-env.sh")+  let capture name target check = assertRight "script" scriptPath $ \script -> assertRight "capture" (captureDerivation script name [] target) (check script)+      taken target = capture "hello" target (\_ _ -> Pass)+      refused target failure = assertRight "script" scriptPath $ \script -> assertEqual "refusal" (Left failure) (drvFilePath <$> captureDerivation script "hello" [] target)+  sequence+    [ runTest "get-env.sh is at the store path upstream adds it at"+        $ assertRight "script" scriptPath+        $ assertEqual "path" "/nix/store/hyhh9rhzxhzmfspllmpf75xzkzns109r-get-env.sh" . storePathToText defaultStoreDir,+      runTest "the script is the builder's one argument and an input source, and the capture is named NAME-env" $+        capture "hello" plain $ \script file ->+          let result = drvFileDerivation file+           in assertEqual "args" [pathBytes script] (drvArgs result)+                `andThen` assertEqual "inputSrcs" [source, script] (drvInputSrcs result)+                `andThen` assertEqual "name" (Just "hello-env") (Map.lookup "name" (drvEnv result))+                `andThen` assertEqual "file" "hello-env.drv" (spName (drvFilePath file)),+      runTest "a script already among the input sources is there once" $+        assertRight "script" scriptPath $ \script ->+          let target = plain {drvInputSrcs = [script, source]}+           in assertRight "capture" (captureDerivation script "hello" [] target) $+                assertEqual "inputSrcs" [script, source] . drvInputSrcs . drvFileDerivation,+      runTest "the four checks on references are removed and every other variable kept" $+        capture "hello" plain $ \_ file ->+          let result = drvFileDerivation file+           in assertEqual "env" (Map.fromList [("builder", "/bin/sh"), ("kept", "k"), ("name", "hello-env"), ("out", outputBytes result "out"), ("system", "x")]) (drvEnv result),+      runTest "under structured attributes outputChecks is removed, __json written as nlohmann's dump() writes it, and name is a variable" $+        capture "s" structured $ \_ file ->+          let result = drvFileDerivation file+           in assertEqual+                "env"+                (Map.fromList [("__json", "{\"a\":[1,2.5,\"x\"],\"name\":\"s\",\"z\":1}"), ("allowedReferences", "kept"), ("name", "s-env"), ("out", outputBytes result "out")])+                (drvEnv result),+      runTest "a fixed-output target's capture is input-addressed, its hash variables kept" $+        capture "f" fixed $ \_ file ->+          let result = drvFileDerivation file+           in assertEqual "outputs" [("out", "", "")] [(doName output, doHashAlgo output, doHash output) | output <- drvOutputs result]+                `andThen` assertEqual "outputHash" (Just (TE.encodeUtf8 fixedHash)) (Map.lookup "outputHash" (drvEnv result))+                `andThen` assertEqual "out" (outputBytes result "out") (fromMaybe "" (Map.lookup "out" (drvEnv result))),+      runTest "a builder whose base name is bash is taken, trailing slashes dropped" $+        foldr (andThen . (\builder -> taken plain {drvBuilder = builder})) Pass ["bash", "/bin/bash", "/nix/store/x-bash/bin/bash/", "/bin/bash//"],+      runTest "a builder of another base name is refused in upstream's words" $+        foldr (andThen . (\builder -> refused plain {drvBuilder = builder} NotBashBuilder)) Pass ["/bin/sh", "/bin/bash5", "", "/", "///", "bash.exe", "/bin/bash/x"]+          `andThen` assertEqual "message" "'nix develop' only works on derivations that use 'bash' as their builder" (captureFailureMessage NotBashBuilder),+      runTest "a floating content-addressed or impure output is refused" $+        refused plain {drvOutputs = [DerivationOutput "out" (StorePath "" "") "r:sha256" ""]} UncapturableOutputs+          `andThen` refused plain {drvOutputs = [DerivationOutput "out" (StorePath "" "") "r:sha256" "impure"]} UncapturableOutputs,+      -- Upstream defers every input-addressed and fixed output before+      -- anything reads the outputs together, so a fixed output beside+      -- others, or under another name than out, is captured.+      runTest "a fixed output beside another, or named other than out, is captured input-addressed" $+        let fixedOut = drvOutputs fixed+            renamed = [output {doName = "bin"} | output <- fixedOut]+            addressing file = [(doName output, doHashAlgo output, doHash output) | output <- drvOutputs (drvFileDerivation file)]+         in capture "f" fixed {drvOutputs = fixedOut <> [pendingOutput "dev"]} (\_ file -> assertEqual "beside" [("dev", "", ""), ("out", "", "")] (addressing file))+              `andThen` capture "f" fixed {drvOutputs = renamed} (\_ file -> assertEqual "renamed" [("bin", "", "")] (addressing file)),+      runTest "structured attributes that are not an object are refused" $+        foldr+          (andThen . (\json -> assertRight "script" scriptPath $ \script -> assertLeft json (drvFilePath <$> captureDerivation script "s" [] structured {drvEnv = Map.insert "__json" (TE.encodeUtf8 json) (drvEnv structured)})))+          Pass+          ["null", "[1]", "{", "\"x\""],+      runTestM "the capture keeps the builder, input derivations, platform and every variable but the checks, name and the outputs" $+        either (pure . Fail . T.pack . show) (quickCheckPasses . QC.forAll genCaptureCase . capturedKeeps) scriptPath,+      runTest "the environment is read from the first output in name order that is a regular file of at least one byte" $+        assertEqual "out" (Just "out") (environmentOutput (Map.fromList [("dev", RegularFile 0), ("lib", NotRegularFile), ("out", RegularFile 10)]))+          `andThen` assertEqual "a" (Just "a") (environmentOutput (Map.fromList [("a", RegularFile 5), ("b", RegularFile 9)])),+      runTest "no output holding such a file is upstream's missing environment" $+        assertEqual "none" Nothing (environmentOutput (Map.fromList [("dev", RegularFile 0), ("out", NotRegularFile)]))+          `andThen` assertEqual "message" "get-env.sh failed to produce an environment" noEnvironmentMessage+    ]+  where+    quickCheckPasses property = do+      result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} property+      pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))+    bash = "/nix/store/00000000000000000000000000000000-bash/bin/bash"+    source = StorePath "11111111111111111111111111111111" "builder.sh"+    pathBytes = TE.encodeUtf8 . storePathToText defaultStoreDir+    outputBytes drv name = maybe "" (pathBytes . doPath) (find ((== name) . doName) (drvOutputs drv))+    plain =+      (plainDerivation "hello" [("allowedReferences", "a"), ("allowedRequisites", "b"), ("disallowedReferences", "c"), ("disallowedRequisites", "d"), ("kept", "k")])+        { drvBuilder = bash,+          drvInputSrcs = [source]+        }+    -- Upstream reads a structured derivation's name from __json; the+    -- variable it adds is the capture's alone.+    structured =+      (plainDerivation "s" [])+        { drvBuilder = bash,+          drvEnv =+            Map.fromList+              [ ("__json", "{ \"z\": 1, \"outputChecks\": { \"out\": { \"allowedReferences\": [] } }, \"a\": [1, 2.5, \"x\"], \"name\": \"s\" }"),+                ("allowedReferences", "kept"),+                ("out", "")+              ]+        }+    fixedHash = "0000000000000000000000000000000000000000000000000000000000000000" :: Text+    fixed =+      (plainDerivation "f" [("outputHash", TE.encodeUtf8 fixedHash), ("outputHashAlgo", "sha256"), ("outputHashMode", "recursive")])+        { drvBuilder = bash,+          drvOutputs = [DerivationOutput "out" (StorePath "22222222222222222222222222222222" "f") "r:sha256" fixedHash]+        }++-- | A derivation the capture takes, from 'genFillCase''s: a builder that+-- is bash, its outputs input-addressed, no structured attributes, and+-- some of the checks on references set.+genCaptureCase :: QC.Gen FillCase+genCaptureCase = do+  FillCase name inputHashes drv <- genFillCase+  directory <- genFieldBytes+  checks <- QC.sublistOf ["allowedReferences", "allowedRequisites", "disallowedReferences", "disallowedRequisites"]+  values <- traverse (const genFieldBytes) checks+  pure+    ( FillCase+        name+        inputHashes+        drv+          { drvBuilder = BS8.filter (/= '/') directory <> "/bash",+            drvOutputs = [output {doHashAlgo = "", doHash = ""} | output <- drvOutputs drv],+            drvEnv = Map.union (Map.fromList (zip checks values)) (Map.delete "__json" (drvEnv drv))+          }+    )++-- | What a capture of a generated derivation keeps: everything but the+-- checks on references, @name@ and the outputs and their variables, with+-- the script its one argument and among its input sources once.+capturedKeeps :: StorePath -> FillCase -> QC.Property+capturedKeeps script (FillCase name inputHashes drv) =+  case captureDerivation script name inputHashes drv of+    Left failure -> QC.counterexample (show failure) False+    Right file ->+      let result = drvFileDerivation file+          outputNames = map doName (drvOutputs drv)+          rest d = foldr Map.delete (drvEnv d) ("name" : outputNames <> ["allowedReferences", "allowedRequisites", "disallowedReferences", "disallowedRequisites"])+       in ( drvBuilder result,+            drvInputDrvs result,+            drvPlatform result,+            sort (map doName (drvOutputs result)),+            rest result,+            drvArgs result,+            Set.fromList (drvInputSrcs result),+            length (filter (== script) (drvInputSrcs result)),+            Map.lookup "name" (drvEnv result)+          )+            QC.=== ( drvBuilder drv,+                     drvInputDrvs drv,+                     drvPlatform drv,+                     sort outputNames,+                     rest drv,+                     [TE.encodeUtf8 (storePathToText defaultStoreDir script)],+                     Set.insert script (Set.fromList (drvInputSrcs drv)),+                     1,+                     Just (TE.encodeUtf8 (name <> "-env"))+                   )++-- ---------------------------------------------------------------------------+-- Tests: develop's captured environment and rcfile+-- ---------------------------------------------------------------------------++-- | The captured environment and the scripts made from it.  Three of the+-- fixtures in test/data/develop are what upstream's get-env.sh (2.35.4)+-- writes when bash 5.3 runs it over a stand-in stdenv setup: one output,+-- three, and structured attributes with two.  Two more are small+-- documents for the rewriting rules.  Each golden is what upstream's own+-- code makes of a fixture: develop.cc's BuildEnvironment, makeRcScript and+-- the rcfile lines of CmdDevelop::run, with util.cc's escapeShellArgAlways+-- and rewriteStrings, built against nlohmann_json 3.11.3 with the store+-- taken out.+testDevelopEnvironment :: IO [Bool]+testDevelopEnvironment = do+  putStrLn "develop/environment"+  tmpBase <- getTemporaryDirectory+  sequence $+    map dumpGolden developFixtures+      <> [rcfileGolden fixture mode | fixture <- developFixtures, mode <- developModes]+      <> map (rcfileGolden "one-output") promptModes+      <> [ scriptGolden "rewrites" (ScriptDirectories "/w" "/t") [],+           scriptGolden "paths" (ScriptDirectories "/" "/t/") [ScriptFile "/t/.attrs.sh" "declare x=1", ScriptFile "/t/.attrs.json" "{\"x\":1}"],+           runTestM "the structured attributes' files are written to the temporary directory" $+             withDevelopFixture "structured" $ \env ->+               pure . assertRight "script" (environmentScript goldenDirectories env) $ \script ->+                 assertEqual+                   "files"+                   [ScriptFile (goldenTemporary <> "/.attrs.sh") (attrsFileBytes attrsSh env), ScriptFile (goldenTemporary <> "/.attrs.json") (attrsFileBytes attrsJson env)]+                   (scriptFiles script),+           runTestM "a script without structured attributes names no files" $+             withDevelopFixture "several-outputs" $ \env ->+               pure (assertRight "script" (environmentScript goldenDirectories env) (assertEqual "files" [] . scriptFiles)),+           runTestM "a variable of a kind get-env.sh writes as unknown is dropped" $+             withDevelopFixture "one-output" $ \env ->+               pure (assertEqual "dropped" [Nothing, Nothing, Just "impure"] [kept <$> Map.lookup name (beVariables env) | name <- ["BASHOPTS", "NIX_FIXTURE_COUNT", "IN_NIX_SHELL"]]),+           runTest "a variable of any kind but the four is dropped" $+             assertEqual+               "dropped"+               (Right (BuildEnvironment Map.empty Map.empty Nothing))+               (parseBuildEnvironment "{\"bashFunctions\":{},\"variables\":{\"i\":{\"type\":\"integer\",\"value\":3},\"r\":{\"type\":\"unknown\"}}}"),+           runTest "a document of another shape is refused" $+             assertEqual "accepted" [] [document | document <- malformedEnvironments, isRight (parseBuildEnvironment document)],+           runTest "ignoreVars is upstream's" $+             assertEqual "ignoreVars" (Set.fromList upstreamIgnoreVars) ignoreVars,+           runTest "a variable in ignoreVars is left as the shell has it"+             $ assertRight "script" (developScript (("KEPT", ExportedString "k") : ("outputs", ShellString "") : [(name, ExportedString "x") | name <- upstreamIgnoreVars]))+             $ assertEqual "assigned" ["KEPT", "outputs"] . assignedNames,+           runTest "an outputs string splits on carriage returns too"+             $ assertRight "script" (developScript [("a", ShellString "/s/a"), ("b", ShellString "/s/b"), ("outputs", ShellString "a\rb"), ("v", ShellString "/s/a /s/b")])+             $ assertEqual "v" True . BS.isInfixOf "\nv='/w/outputs/a /w/outputs/b'\n" . scriptText,+           runTest "an outputs array names the outputs, the first of two with one path taking it"+             $ assertRight "script" (developScript [("a", ShellString "/s/same"), ("b", ShellString "/s/same"), ("outputs", IndexedArray ["b", "a"]), ("v", ShellString "/s/same")])+             $ assertEqual "v" True . BS.isInfixOf "\nv='/w/outputs/b'\n" . scriptText,+           runTest "an outputs associative array names the outputs by its keys"+             $ assertRight "script" (developScript [("a", ShellString "/s/a"), ("b", ShellString "/s/b"), ("outputs", AssociativeArray (Map.fromList [("a", "/s/x"), ("b", "/s/y")])), ("v", ShellString "/s/a /s/b /s/x")])+             $ assertEqual "v" True . BS.isInfixOf "\nv='/w/outputs/a /w/outputs/b /s/x'\n" . scriptText,+           runTest "an environment with no outputs is refused in upstream's words" $+             assertEqual "refused" (Left "derivation does not have an 'outputs' attribute") (scriptText <$> developScript [("out", ShellString "/s/o")]),+           runTest "an output's variable that is not a string is refused in upstream's words" $+             assertEqual "refused" (Left "bash variable is not a string") (scriptText <$> developScript [("outputs", ShellString "out"), ("out", IndexedArray ["/s/o"])]),+           runTest "structured attributes' outputs that are not an associative array are refused in upstream's words" $+             assertEqual "refused" (Left "bash variable is not an associative array") (scriptText <$> structuredScript [("outputs", ShellString "out"), ("out", ShellString "/s/o")]),+           runTest "an output with no variable is refused" $+             assertEqual "refused" (Left "the build environment has no variable 'out'") (scriptText <$> developScript [("outputs", ShellString "out")]),+           runTest "structured attributes with no file variable are refused" $+             assertEqual "refused" (Left "the build environment has no variable 'NIX_ATTRS_SH_FILE'") (scriptText <$> structuredScript [("outputs", AssociativeArray (Map.singleton "out" "/s/o"))]),+           runTest "a file variable that is not a string is refused in upstream's words" $+             assertEqual "refused" (Left "bash variable is not a string") (scriptText <$> structuredScript [("NIX_ATTRS_SH_FILE", IndexedArray []), ("outputs", AssociativeArray (Map.singleton "out" "/s/o"))]),+           runTest "a replacement holding what it replaces is refused where upstream's replacing never ends" $+             assertEqual "accepted" [] [path | path <- ["/w", "", "/w/outputs"], isRight (developScript [("outputs", ShellString "out"), ("out", ShellString path)])],+           runTest "a replacement holding what it replaces is harmless where the script does not hold it" $+             assertEqual "refused" [] [path | path <- ["/w", "/w/", "/w/outputs"], isLeft (developScript [("outputs", ShellString "HOME"), ("HOME", ShellString path)])],+           runTest "a path that is its own replacement is left as it is"+             $ assertRight "script" (developScript [("outputs", ShellString "out"), ("out", ShellString "/w/outputs/out")])+             $ assertEqual "out" True . BS.isInfixOf "\nout='/w/outputs/out'\n" . scriptText,+           runTestM "reading what is written gives the environment back" $+             quickCheckPasses (QC.forAll genBuildEnvironment (\env -> parseBuildEnvironment (renderJson (buildEnvironmentJson env)) QC.=== Right env)),+           shellWordLaw (tmpBase </> "nova-nix-test-shell-word")+         ]+  where+    dumpGolden fixture =+      runTestM (fixture <> ": written back as upstream's toJSON writes it") $+        withDevelopFixture fixture $ \env -> do+          expected <- BS.readFile (developData (fixture <> ".dump.json"))+          pure (assertEqual "dump" expected (renderJson (buildEnvironmentJson env)))+    rcfileGolden fixture (modeName, mode) =+      runTestM (fixture <> ": the " <> modeName <> " rcfile is upstream's") $+        withDevelopFixture fixture $ \env -> do+          expected <- BS.readFile (developData (fixture <> "." <> modeName <> ".rcfile"))+          pure . assertRight "script" (environmentScript goldenDirectories env) $+            assertEqual "rcfile" expected . renderRcfile (Shell "/tmp/nix-shell.Xc9Tq2" mode "bash")+    scriptGolden fixture directories files =+      runTestM (fixture <> ": the script is upstream's") $+        withDevelopFixture fixture $ \env -> do+          expected <- BS.readFile (developData (fixture <> ".script"))+          pure . assertRight "script" (environmentScript directories env) $ \script ->+            assertEqual "script" expected (scriptText script) `andThen` assertEqual "files" files (scriptFiles script)+    goldenDirectories = ScriptDirectories "/home/user/project" goldenTemporary+    goldenTemporary = "/tmp/nix-develop-4242-0"+    developModes =+      [ ("interactive", Interactive (Prompt "" "" "")),+        ("prompts", Interactive goldenPrompt),+        ("command", RunCommand ("make" :| ["CFLAGS=-O2 -g", "it's"])),+        ("phase", RunPhase "build")+      ]+    promptModes =+      [ ("prompt", Interactive (Prompt (bashPrompt goldenPrompt) "" "")),+        ("prompt-prefix", Interactive (Prompt "" (bashPromptPrefix goldenPrompt) "")),+        ("prompt-suffix", Interactive (Prompt "" "" (bashPromptSuffix goldenPrompt)))+      ]+    goldenPrompt = Prompt "\\[\\e[1;32m\\]dev\\$ " "(nix) " " it's"+    attrsFileBytes field env = maybe "" (TE.encodeUtf8 . field) (beAttrsFiles env)+    kept variable = case variable of+      ExportedString s -> s+      ShellString s -> s+      _ -> ""+    developScript variables = environmentScript (ScriptDirectories "/w" "/t") (BuildEnvironment (Map.fromList variables) Map.empty Nothing)+    structuredScript variables = environmentScript (ScriptDirectories "/w" "/t") (BuildEnvironment (Map.fromList variables) Map.empty (Just (AttrsFiles "" "")))+    -- The names a script assigns a quoted string to.+    assignedNames script = [name | line <- BS8.lines (scriptText script), (name, rest) <- [BS8.break (== '=') line], "='" `BS.isPrefixOf` rest]+    quickCheckPasses property = do+      result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} property+      pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))++-- | The fixtures get-env.sh wrote, each with goldens in every mode.+developFixtures :: [Text]+developFixtures = ["one-output", "several-outputs", "structured"]++-- | A file of test/data/develop.+developData :: Text -> FilePath+developData name = "test" </> "data" </> "develop" </> T.unpack name++-- | Run a check over a fixture's environment as 'parseBuildEnvironment'+-- reads it.+withDevelopFixture :: Text -> (BuildEnvironment -> IO TestResult) -> IO TestResult+withDevelopFixture fixture check = do+  document <- BS.readFile (developData (fixture <> ".json"))+  either (pure . Fail . ("fixture: " <>)) check (parseBuildEnvironment document)++-- | Upstream's @ignoreVars@ (develop.cc).+upstreamIgnoreVars :: [Text]+upstreamIgnoreVars = ["BASHOPTS", "HOME", "NIX_BUILD_TOP", "NIX_ENFORCE_PURITY", "NIX_LOG_FD", "NIX_REMOTE", "PPID", "SHELLOPTS", "SSL_CERT_FILE", "TEMP", "TEMPDIR", "TERM", "TMP", "TMPDIR", "TZ", "UID"]++-- | Documents upstream's reader has no defined answer for, each refused.+malformedEnvironments :: [BS.ByteString]+malformedEnvironments =+  [ "{\"bashFunctions\":{},\"variables\":{\"v\":{\"type\":\"var\",\"value\":\"\xff\"}}}",+    "[]",+    "{\"bashFunctions\":{}}",+    "{\"variables\":{}}",+    "{\"bashFunctions\":[],\"variables\":{}}",+    "{\"bashFunctions\":{\"f\":1},\"variables\":{}}",+    "{\"bashFunctions\":{},\"variables\":{\"v\":\"x\"}}",+    "{\"bashFunctions\":{},\"variables\":{\"v\":{\"value\":\"x\"}}}",+    "{\"bashFunctions\":{},\"variables\":{\"v\":{\"type\":1,\"value\":\"x\"}}}",+    "{\"bashFunctions\":{},\"variables\":{\"v\":{\"type\":\"exported\"}}}",+    "{\"bashFunctions\":{},\"variables\":{\"v\":{\"type\":\"var\",\"value\":1}}}",+    "{\"bashFunctions\":{},\"variables\":{\"v\":{\"type\":\"array\",\"value\":[\"a\",1]}}}",+    "{\"bashFunctions\":{},\"variables\":{\"v\":{\"type\":\"array\",\"value\":{}}}}",+    "{\"bashFunctions\":{},\"variables\":{\"v\":{\"type\":\"associative\",\"value\":[]}}}",+    "{\"bashFunctions\":{},\"variables\":{\"v\":{\"type\":\"associative\",\"value\":{\"k\":null}}}}",+    "{\"bashFunctions\":{},\"variables\":{},\"structuredAttrs\":null}",+    "{\"bashFunctions\":{},\"variables\":{},\"structuredAttrs\":{\".attrs.sh\":\"\"}}",+    "{\"bashFunctions\":{},\"variables\":{},\"structuredAttrs\":{\".attrs.sh\":\"\",\".attrs.json\":{}}}"+  ]++-- | Environments of every shape: any text, control characters and quotes+-- among it, in names, values, function bodies and the files.+genBuildEnvironment :: QC.Gen BuildEnvironment+genBuildEnvironment =+  BuildEnvironment+    <$> genEntries genVariable+    <*> genEntries genAnyText+    <*> QC.oneof [pure Nothing, Just <$> (AttrsFiles <$> genAnyText <*> genAnyText)]+  where+    genEntries genValue = Map.fromList <$> QC.resize 6 (QC.listOf ((,) <$> genAnyText <*> genValue))+    genVariable =+      QC.oneof+        [ ShellString <$> genAnyText,+          ExportedString <$> genAnyText,+          IndexedArray <$> QC.resize 4 (QC.listOf genAnyText),+          AssociativeArray <$> genEntries genAnyText+        ]+    genAnyText = T.pack <$> QC.resize 12 (QC.listOf (QC.frequency [(4, QC.arbitrary), (1, QC.elements "'\"\\\n\t\0{}[]")]))++-- | A POSIX sh reads a word 'escapeShellArgAlways' quotes back as the same+-- bytes, whatever they are but NUL, which no shell word holds.+shellWordLaw :: FilePath -> IO Bool+shellWordLaw scriptPath+  | SI.os == "mingw32" = True <$ putStrLn "  SKIP  a POSIX sh reads an escapeShellArgAlways word back: POSIX only"+  | otherwise =+      runTestM "a POSIX sh reads an escapeShellArgAlways word back as the same bytes" $ do+        result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} (QC.forAll genWord (QC.ioProperty . readBack))+        pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))+  where+    genWord = BS.pack <$> QC.resize 16 (QC.listOf (QC.frequency [(1, pure 0x27), (1, QC.elements [0x5c, 0x22, 0x24, 0x60, 0x0a]), (4, QC.choose (1, 255))]))+    readBack word = do+      BS.writeFile scriptPath ("printf '%s' " <> escapeShellArgAlways word)+      printed <-+        Proc.withCreateProcess (Proc.proc "/bin/sh" [scriptPath]) {Proc.std_out = Proc.CreatePipe, Proc.env = Just [("LC_ALL", "C")]} $ \_ out _ process -> do+          bytes <- maybe (pure BS.empty) BS.hGetContents out+          code <- Proc.waitForProcess process+          pure (code, bytes)+      pure (printed QC.=== (ExitSuccess, word))++-- ---------------------------------------------------------------------------+-- Tests: develop's shell and its command line+-- ---------------------------------------------------------------------------++-- | What @develop@'s shell runs and the environment it starts with, and+-- how the command line gives them, each refusal in upstream's words.+testDevelopShell :: IO [Bool]+testDevelopShell = do+  putStrLn "develop/shell"+  sequence+    [ runTest "a phase, a command, or else an interactive shell with the prompt" $+        assertEqual "phase" (Right (RunPhase "build")) (shellModeFor Nothing (Just "build") prompt)+          `andThen` assertEqual "command" (Right (RunCommand ("sh" :| ["-c", "true"]))) (shellModeFor (Just ("sh" :| ["-c", "true"])) Nothing prompt)+          `andThen` assertEqual "interactive" (Right (Interactive prompt)) (shellModeFor Nothing Nothing prompt),+      runTest "a command beside a phase is refused in upstream's words" $+        assertEqual "both" (Left "you cannot use both '--command' and '--phase'") (shellModeFor (Just ("true" :| [])) (Just "build") prompt),+      runTest "an interactive shell reads the rcfile through --rcfile, a command or a phase runs it as a script" $+        assertEqual "interactive" ["--rcfile", "/t/rc"] (shellArguments (Interactive prompt) "/t/rc")+          `andThen` assertEqual "command" ["/t/rc"] (shellArguments (RunCommand ("true" :| [])) "/t/rc")+          `andThen` assertEqual "phase" ["/t/rc"] (shellArguments (RunPhase "build") "/t/rc")+          `andThen` assertEqual "program" "bash" bashProgram,+      runTest "the caller's environment, set variables replacing its own and unset ones removed, then NIX_GCROOT and SHELL" $+        assertEqual+          "environment"+          (Right (Map.fromList [("A", "set"), ("C", "c"), ("NIX_GCROOT", gcroot), ("SHELL", "bash")]))+          (shellEnvironment (changes CallerEnvironment [] ["B", "NIX_GCROOT"] [("A", "set"), ("SHELL", "zsh")]) gcroot caller),+      runTest "--ignore-env keeps only the variables --keep-env-var names, with those --set-env-var sets" $+        assertEqual+          "environment"+          (Right (Map.fromList [("B", "b"), ("D", "d"), ("NIX_GCROOT", gcroot), ("SHELL", "bash")]))+          (shellEnvironment (changes EmptyEnvironment ["B", "missing"] [] [("D", "d")]) gcroot caller),+      runTest "--unset-env-var under --ignore-env, and --keep-env-var without it, are refused in upstream's words" $+        assertEqual "unset" (Left "--unset-env-var does not make sense with --ignore-env") (shellEnvironment (changes EmptyEnvironment [] ["A"] []) gcroot caller)+          `andThen` assertEqual "keep" (Left "--keep-env-var does not make sense without --ignore-env") (shellEnvironment (changes CallerEnvironment ["A"] [] []) gcroot caller),+      runTest "a name setenv refuses is left out, as upstream's replaceEnv goes on without it" $+        assertEqual+          "names"+          (Right ["A", "B", "C", "NIX_GCROOT", "SHELL", "x"])+          (Map.keys <$> shellEnvironment (changes CallerEnvironment [] [] [("", "empty"), ("A=B", "eq"), ("x", "y")]) gcroot caller),+      runTestM "under --ignore-env the environment depends on the caller's only through the variables kept" $+        quickCheckPasses . QC.forAll ((,,) <$> genChanges <*> genCaller <*> genCaller) $ \(given, first, second) ->+          let kept = ecKeep given+              agreeing = Map.union (Map.restrictKeys first kept) (Map.withoutKeys second kept)+           in shellEnvironment given gcroot first QC.=== shellEnvironment given gcroot agreeing,+      runTest "develop takes a target and build's target and store flags" $+        assertEqual+          "parsed"+          (Right (Cli.CmdDevelop (Cli.TargetExpr "1") (Just "a.b") developDefaults))+          (Cli.optCommand <$> Cli.parseArgs ["develop", "--expr", "1", "-A", "a.b", "--store", "/s", "--no-sandbox", "--substituter", "u", "--arg", "x", "1"])+          `andThen` assertEqual "requires a target" (Left "develop requires a PATH, <NAME> or --expr EXPR") (Cli.optCommand <$> Cli.parseArgs ["develop"])+          `andThen` assertEqual "exec-wrapper" (Left "unknown develop flag: --exec-wrapper") (Cli.optCommand <$> Cli.parseArgs ["develop", "--exec-wrapper", "s=p", "--expr", "1"])+          `andThen` assertEqual "out-link" (Left "unknown develop flag: --no-out-link") (Cli.optCommand <$> Cli.parseArgs ["develop", "--no-out-link", "--expr", "1"]),+      runTest "--command takes every argument after it, flags and --help included, and needs one" $+        assertEqual+          "command"+          (Right (Just ("sh" :| ["-c", "exit 7", "--phase", "x", "--help"])))+          (developed ["develop", "--expr", "1", "-c", "sh", "-c", "exit 7", "--phase", "x", "--help"] Cli.daCommand)+          `andThen` assertEqual "long" (Right (Just ("true" :| []))) (developed ["develop", "--expr", "1", "--command", "true"] Cli.daCommand)+          `andThen` assertEqual "none" (Left "error: --command requires at least one argument") (Cli.optCommand <$> Cli.parseArgs ["develop", "--expr", "1", "-c"])+          `andThen` assertEqual "none, short" (Left "error: --command requires at least one argument") (Cli.optCommand <$> Cli.parseArgs ["develop", "--expr", "1", "--command"]),+      runTest "the last phase flag wins, installcheck naming installCheck, and --check is develop's phase there" $+        assertEqual "last" (Right (Just "install")) (developed ["develop", "--phase", "build", "--install", "--expr", "1"] Cli.daPhase)+          `andThen` assertEqual "installcheck" (Right (Just "installCheck")) (developed ["develop", "--unpack", "--installcheck", "--expr", "1"] Cli.daPhase)+          `andThen` assertEqual "check" (Right (Just "check")) (developed ["develop", "--check", "--expr", "1"] Cli.daPhase)+          `andThen` assertEqual "phase" (Right (Just "fixup")) (developed ["develop", "--configure", "--phase", "fixup", "--expr", "1"] Cli.daPhase)+          `andThen` assertEqual "build's check" (Right True) (Cli.optCheck <$> Cli.parseArgs ["build", "--check", "--expr", "1"])+          `andThen` assertEqual "a command beside a phase parses" (Right (Just ("true" :| []), Just "build")) (developed ["develop", "--build", "--expr", "1", "-c", "true"] (\args -> (Cli.daCommand args, Cli.daPhase args))),+      runTest "the environment flags, under each spelling, gather what they name" $+        assertEqual+          "gathered"+          (Right (EmptyEnvironment, Set.fromList ["K", "L"], Set.fromList ["U", "V"], Map.fromList [("S", "s"), ("T", "t")]))+          ( developed+              ["develop", "-i", "-k", "K", "--keep-env-var", "L", "-u", "U", "--unset", "V", "-s", "S", "s", "--set-env-var", "T", "t", "--expr", "1"]+              (\args -> (Cli.daEnvironmentBase args, Cli.daKeep args, Cli.daUnset args, Cli.daSet args))+          )+          `andThen` assertEqual "ignore-environment" (Right EmptyEnvironment) (developed ["develop", "--ignore-environment", "--expr", "1"] Cli.daEnvironmentBase)+          `andThen` assertEqual "keep" (Right (Set.singleton "K")) (developed ["develop", "--keep", "K", "--expr", "1"] Cli.daKeep),+      runTest "a variable both set and unset, or set twice, is refused as it is read, in upstream's words" $+        assertEqual "unset after set" (Left "error: Cannot unset environment variable 'X' that is set with '--set-env-var'") (Cli.optCommand <$> Cli.parseArgs ["develop", "-s", "X", "1", "-u", "X", "--expr", "1"])+          `andThen` assertEqual "set after unset" (Left "error: Cannot set environment variable 'X' that is unset with '--unset-env-var'") (Cli.optCommand <$> Cli.parseArgs ["develop", "--unset", "X", "--set-env-var", "X", "1", "--expr", "1"])+          `andThen` assertEqual "set twice" (Left "error: Duplicate definition of environment variable 'X' with '--set-env-var' is ambiguous") (Cli.optCommand <$> Cli.parseArgs ["develop", "-s", "X", "1", "-s", "X", "2", "--expr", "1"])+          `andThen` assertEqual "one value" (Left "-s requires a name and a value") (Cli.optCommand <$> Cli.parseArgs ["develop", "--expr", "1", "-s", "X"]),+      runTest "print-dev-env prints the script, or with --json the environment, and takes no develop flag" $+        assertEqual "script" (Right (Cli.CmdPrintDevEnv (Cli.TargetFile "f.nix") Nothing Cli.DevEnvScript Cli.IndentedOnTerminal)) (Cli.optCommand <$> Cli.parseArgs ["print-dev-env", "f.nix"])+          `andThen` assertEqual "json" (Right (Cli.CmdPrintDevEnv (Cli.TargetExpr "1") (Just "a") Cli.DevEnvJson Cli.IndentedOnTerminal)) (Cli.optCommand <$> Cli.parseArgs ["print-dev-env", "--json", "--expr", "1", "-A", "a"])+          `andThen` assertEqual "pretty" (Right (Cli.CmdPrintDevEnv (Cli.TargetExpr "1") Nothing Cli.DevEnvJson Cli.Indented)) (Cli.optCommand <$> Cli.parseArgs ["print-dev-env", "--no-pretty", "--json", "--pretty", "--expr", "1"])+          `andThen` assertEqual "no-pretty" (Right (Cli.CmdPrintDevEnv (Cli.TargetExpr "1") Nothing Cli.DevEnvScript Cli.Compact)) (Cli.optCommand <$> Cli.parseArgs ["print-dev-env", "--expr", "1", "--pretty", "--no-pretty"])+          `andThen` assertEqual "develop's pretty" (Left "unknown develop flag: --pretty") (Cli.optCommand <$> Cli.parseArgs ["develop", "--pretty", "--expr", "1"])+          `andThen` assertEqual "command" (Left "unknown print-dev-env flag: --command") (Cli.optCommand <$> Cli.parseArgs ["print-dev-env", "--command", "true", "--expr", "1"])+          `andThen` assertEqual "develop's json" (Left "unknown develop flag: --json") (Cli.optCommand <$> Cli.parseArgs ["develop", "--json", "--expr", "1"])+    ]+  where+    prompt = Prompt "p" "" ""+    gcroot = "/s/hash-x-env"+    caller = Map.fromList [("A", "a"), ("B", "b"), ("C", "c")]+    changes base keep unset set = EnvironmentChanges base (Set.fromList keep) (Set.fromList unset) (Map.fromList set)+    developDefaults = Cli.DevelopArgs Nothing Nothing CallerEnvironment Set.empty Set.empty Map.empty+    developed args field = case Cli.optCommand <$> Cli.parseArgs args of+      Right (Cli.CmdDevelop _ _ given) -> Right (field given)+      Right other -> Left (T.pack (show other))+      Left err -> Left (T.pack err)+    genName = QC.elements ["A", "B", "C", "D", "NIX_GCROOT", "SHELL", "", "E=F"]+    genNames = Set.fromList <$> QC.listOf genName+    genCaller = Map.fromList <$> QC.listOf ((,) <$> genName <*> QC.elements ["1", "2", ""])+    genChanges = EnvironmentChanges EmptyEnvironment <$> genNames <*> pure Set.empty <*> (Map.fromList <$> QC.listOf ((,) <$> genName <*> QC.elements ["s", ""]))+    quickCheckPasses property = do+      result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} property+      pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))
+ test/Test/Eval.hs view

11461 lines of diff, too many to show among the others: show this file

+ test/Test/Exceptions.hs view
@@ -0,0 +1,190 @@+-- | Tests that an interrupt stops an operation rather than becoming its+-- fallback value.+module Test.Exceptions+  ( testInterruptsPropagate,+  )+where++import Control.Concurrent (threadDelay)+import Control.Concurrent.Async (asyncThreadId, waitCatch, withAsync)+import Control.Exception (AsyncException (..), SomeException, bracket, bracket_, fromException, throw, throwIO, throwTo, try)+import qualified Data.ByteString as BS+import qualified Data.Map.Strict as Map+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import HttpFixture (Reply (..), withHttpServer)+import Nix.Builder (buildWithDeps, defaultBuildConfig)+import Nix.Builder.Unpack (builtinUnpackBuilder, defaultUnpackLimits, envSrcs, runBuiltinUnpack)+import Nix.Derivation (Derivation (..), currentPlatform)+import Nix.Eval (MonadEval (..))+import Nix.Eval.IO (runEvalIO)+import Nix.Hash (sha256Digest)+import qualified Nix.Hash as Hash+import Nix.Http (defaultFetchRetryPolicy)+import Nix.Push (PushCompression (..), PushConfig (..), defaultPartSize, loadKeyFile, pushPaths)+import Nix.Push.Source (localPushSource)+import Nix.Store (closeStore, openStore)+import Nix.Store.Path (StoreDir (..), defaultStoreDir, storePathToFilePath, storePathToText)+import Nix.Store.Path.Internal (StorePath (..))+import System.Directory (createDirectoryIfMissing, getTemporaryDirectory)+import qualified System.Directory as Dir+import System.Environment (lookupEnv, setEnv, unsetEnv)+import System.FilePath (takeDirectory, (</>))+import System.IO (IOMode (..), withBinaryFile)+import qualified System.Info as SI+import qualified System.Process as Proc+import Test.Harness (TestResult (..), forceRemoveIfExists, runTestM, testEvalState, testLogger)++-- ---------------------------------------------------------------------------+-- Tests: an interrupt stops the operation it reaches+-- ---------------------------------------------------------------------------++-- | How long 'interruptedAfterStall' lets an action run before+-- interrupting it: far longer than any of these actions takes to reach+-- the read it stalls in.+stallMicros :: Int+stallMicros = 200000++-- | Run an action in a thread of its own, deliver a user interrupt to it+-- once it has had time to stall, and report how it ended: @Left@ the+-- exception that stopped it, or @Right@ the value it returned instead.+interruptedAfterStall :: IO a -> IO (Either SomeException a)+interruptedAfterStall action =+  withAsync action $ \running -> do+    threadDelay stallMicros+    throwTo (asyncThreadId running) UserInterrupt+    waitCatch running++-- | Pass when the interrupt is what stopped the action.+interruptPropagated :: (Show a) => Either SomeException a -> TestResult+interruptPropagated outcome = case outcome of+  Left err+    | fromException err == Just UserInterrupt -> Pass+    | otherwise -> Fail ("stopped by another exception: " <> T.pack (show err))+  Right value -> Fail ("the interrupt became a value: " <> T.pack (show value))++-- | Run an action while a FIFO sits at the path with a writer that never+-- writes, so a read of the path blocks until something interrupts the+-- reader.  A FIFO with no writer at all reads as empty at once, because+-- GHC opens a file non-blocking.+withStalledFifo :: FilePath -> IO a -> IO a+withStalledFifo path action =+  bracket_ (Proc.callProcess "mkfifo" [path]) (Dir.removePathForcibly path) $+    withBinaryFile path ReadWriteMode (const action)++-- | Each of these operations has a fallback value for a failure (an+-- unreadable file, a cache miss, a failed push), and an interrupt stops+-- it rather than becoming that value.  A file read is made to stall+-- on a FIFO ('withStalledFifo') and interrupted there from another+-- thread, so those cases need POSIX; the request a push makes stalls on+-- the loopback fixture on every platform.  A walk of a tree on disk+-- refuses a FIFO before it reads one and has no other read that blocks,+-- so no case interrupts a walk: 'ExecBit.serialiseIfReadable' and the+-- push's 'catchSync' catch only synchronous exceptions.  A fetch cache write never+-- blocks, so its interrupt is raised from inside the write.  The removal+-- behind a build's cleanup neither blocks nor forces anything the caller+-- supplies, so no case reaches it.+testInterruptsPropagate :: IO [Bool]+testInterruptsPropagate = do+  putStrLn "exceptions/interrupts-propagate"+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-interrupts"+      storeDir = StoreDir (root </> "store")+      cacheHome = root </> "cache"+      inStore = storePathToFilePath storeDir+      pushTo base =+        PushConfig+          { pcCacheUrl = base,+            pcApiKey = Nothing,+            pcCompression = PushNone,+            pcPartSize = defaultPartSize,+            pcRetry = defaultFetchRetryPolicy+          }+      plainDrv =+        Derivation+          { drvOutputs = [],+            drvInputDrvs = Map.empty,+            drvInputSrcs = [],+            drvPlatform = currentPlatform,+            drvBuilder = builtinUnpackBuilder,+            drvArgs = [],+            drvEnv = Map.empty+          }+      unpacking archive = plainDrv {drvEnv = Map.singleton envSrcs (TE.encodeUtf8 (storePathToText defaultStoreDir archive))}+      withCacheHome =+        bracket+          (lookupEnv "XDG_CACHE_HOME" <* setEnv "XDG_CACHE_HOME" cacheHome)+          (maybe (unsetEnv "XDG_CACHE_HOME") (setEnv "XDG_CACHE_HOME"))+          . const+      fifoCase name test+        | SI.os == "mingw32" = True <$ putStrLn ("  SKIP  " ++ T.unpack name ++ ": needs a FIFO")+        | otherwise = runTestM name test+  forceRemoveIfExists root+  createDirectoryIfMissing True (unStoreDir storeDir)+  results <- bracket (openStore testLogger storeDir) closeStore $ \store ->+    sequence+      [ runTestM "an interrupt during a push request stops the push" $+          withHttpServer (\_ _ -> Trickle) $ \base _ requested -> do+            outcome <- withAsync (pushPaths (pushTo base) (localPushSource store) [StorePath (T.replicate 32 "a") "pushed"]) $ \pushing -> do+              requested+              throwTo (asyncThreadId pushing) UserInterrupt+              waitCatch pushing+            pure (interruptPropagated outcome),+        fifoCase "an interrupt reading the API key file is not an unreadable key" $ do+          let keyFile = root </> "stalled-key"+          outcome <- withStalledFifo keyFile (interruptedAfterStall (loadKeyFile keyFile))+          pure (interruptPropagated outcome),+        fifoCase "an interrupt reading a store derivation is not a missing one" $ do+          st <- testEvalState storeDir root+          let sp = StorePath (T.replicate 32 "d") "stalled.drv"+          outcome <- withStalledFifo (inStore sp) (interruptedAfterStall (runEvalIO st (readStoreDerivation sp)))+          pure (interruptPropagated outcome),+        -- The entry's path is the cache's layout: one file per key, named+        -- by the key's SHA-256 (fetchCacheFile).+        fifoCase "an interrupt reading the fetch cache is not a cache miss" $+          withCacheHome $ do+            st <- testEvalState storeDir root+            let key = "stalled-entry"+                entry = cacheHome </> "nova-nix" </> "fetch" </> T.unpack (Hash.bytesToHexText (sha256Digest (TE.encodeUtf8 key)))+            createDirectoryIfMissing True (takeDirectory entry)+            outcome <- withStalledFifo entry (interruptedAfterStall (runEvalIO st (lookupFetchCache key)))+            pure (interruptPropagated outcome),+        -- The entry's text is the interrupt, raised when the write forces it.+        runTestM "an interrupt writing the fetch cache is not an unwritable cache" $+          withCacheHome $ do+            st <- testEvalState storeDir root+            outcome <- try (runEvalIO st (writeFetchCache "interrupted-entry" (throw UserInterrupt)))+            pure (interruptPropagated outcome),+        -- The suite's own harness has a fallback too: a test's FAIL line.+        runTestM "an interrupt in a test stops the suite, not just that test" $ do+          outcome <- try (runTestM "interrupted" (throwIO UserInterrupt))+          pure (interruptPropagated outcome),+        fifoCase "an interrupt unpacking an archive is not a failed unpack" $ do+          let archive = StorePath (T.replicate 32 "f") "stalled.tar"+          outcome <- withStalledFifo (inStore archive) (interruptedAfterStall (runBuiltinUnpack storeDir defaultUnpackLimits (unpacking archive) [("out", root </> "stalled-out")]))+          pure (interruptPropagated outcome),+        fifoCase "an interrupt reading an input derivation is not an unreadable one" $ do+          let input = StorePath (T.replicate 32 "g") "stalled-input.drv"+              rootDrv = plainDrv {drvInputDrvs = Map.singleton input ["out"]}+              config = defaultBuildConfig storeDir+          outcome <- withStalledFifo (inStore input) (interruptedAfterStall (buildWithDeps config store rootDrv (StorePath (T.replicate 32 "h") "root.drv")))+          pure (interruptPropagated outcome),+        -- The failures the unpacker does catch: the gzip decoder throws a+        -- DecompressError, and a missing archive is an IOException.  Each+        -- is the archive's failure, not an escape.+        runTestM "a corrupt gzip archive and a missing one fail the unpack" $ do+          let corruptGzip = StorePath (T.replicate 32 "k") "corrupt.tar.gz"+              missing = StorePath (T.replicate 32 "j") "missing.tar"+          BS.writeFile (inStore corruptGzip) "not a gzip stream"+          corruptGzipOutcome <- runBuiltinUnpack storeDir defaultUnpackLimits (unpacking corruptGzip) [("out", root </> "corrupt-gzip-out")]+          missingOutcome <- runBuiltinUnpack storeDir defaultUnpackLimits (unpacking missing) [("out", root </> "missing-out")]+          pure $ case (corruptGzipOutcome, missingOutcome) of+            (Left (1, corruptGzipMsg), Left (1, missingMsg))+              | "corrupt.tar.gz" `T.isInfixOf` corruptGzipMsg+                  && not ("unsupported archive format" `T.isInfixOf` corruptGzipMsg)+                  && "missing.tar" `T.isInfixOf` missingMsg ->+                  Pass+            other -> Fail ("expected both unpacks to fail: " <> T.pack (show other))+      ]+  forceRemoveIfExists root+  pure results
+ test/Test/Fetch.hs view
@@ -0,0 +1,347 @@+-- | Tests of fetcher inputs, their URLs and flake references, read and+-- written as upstream 2.36.0 reads and writes them, and of the+-- experimental features they need.+module Test.Fetch+  ( testFetchUrls,+    testFlakeRefs,+    testExperimentalFeatures,+    testFlakeRefBuiltins,+  )+where++import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BC+import qualified Data.Map.Strict as Map+import Data.Text (Text)+import qualified Data.Text as T+import Data.Word (Word8)+import Nix.Config (ConfigAssignment (..), NixConfig (..), resolveConfig)+import Nix.Eval.IO (newEvalStateWith)+import Nix.Eval.Policy (EvalPolicy (..), PathRules (..), unrestrictedPolicy)+import Nix.Eval.Types (NixValue (..), mkStr)+import Nix.ExperimentalFeature (addFeatures, featureEnabled, featureSetWarnings, flakesFeature, noFeatures, parseFeatures, replaceFeatures)+import Nix.Fetch.Attrs (AttrValue (..), Attrs)+import Nix.Fetch.Input (InputContext (..), isLegalRefName)+import Nix.Fetch.Url (Authority (..), HostType (..), Leniency (..), ParsedUrl (..), fixGitUrl, parseUrl, pathToUrlPath, percentEncode, renderUrl, runChecked, urlPathToPath)+import Nix.Flake.Ref (FlakeRef, flakeRefAttrs, flakeRefFromAttrs, flakeRefToString, parseFlakeRef, parseFlakeRefWithFragment)+import Test.Harness (TestResult (..), andThen, assertEqual, assertEval, assertEvalError, evalNixIOIn, evalNixIOStoreDir, runTest, runTestM, testBaseDir, testLogger, testSessionStore)+import qualified Test.QuickCheck as QC++-- | A QuickCheck property as a test result.+property :: (QC.Testable prop) => prop -> IO TestResult+property prop = do+  result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} prop+  pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))++-- | A context with flakes on, under POSIX paths.+flakesOn :: InputContext+flakesOn = InputContext (parseFeatures "flakes") PosixPaths++-- | A context with no feature on.+featuresOff :: InputContext+featuresOff = InputContext noFeatures PosixPaths++-- ---------------------------------------------------------------------------+-- URLs+-- ---------------------------------------------------------------------------++-- | Upstream's URL grammar, encodings, Git URLs and paths.+testFetchUrls :: IO [Bool]+testFetchUrls = do+  putStrLn "fetch/urls"+  roundTrip <- property (QC.forAll genUrl (\url -> fst (runChecked (parseUrl Strict (renderUrl url))) == Right url))+  sequence+    [ runTest "a rendered URL parses back to itself" roundTrip,+      runTest "a URL's parts decode" $+        assertEqual+          "parsed"+          (Right (ParsedUrl "https" (Just (Authority HostName "example.org" (Just "me") Nothing (Just 8080))) ["", "a b", "c"] (Map.fromList [("k", "v w")]) "f g"))+          (fst (runChecked (parseUrl Strict "https://me@example.org:8080/a%20b/c?k=v%20w#f%20g"))),+      runTest "a lenient parse encodes a query's spaces and quotes and a fragment's carets" $+        assertEqual+          "rendered"+          (Right "github:a/b?ref=x%20y#%22n%5E%22")+          (renderUrl <$> fst (runChecked (parseUrl Lenient "github:a/b?ref=x y#\"n^\""))),+      runTest "a strict parse refuses a space" $+        assertEqual "refused" (Left "'github:a/b?ref=x y' is not a valid URL: leftover") (fst (runChecked (parseUrl Strict "github:a/b?ref=x y"))),+      runTest "a URL needs a scheme" $+        assertEqual "refused" (Left "'/tmp/x' doesn't have a scheme") (fst (runChecked (parseUrl Lenient "/tmp/x"))),+      runTest "a file URL names no host" $+        assertEqual "refused" (Left "file:// URL 'file://host/x' has unexpected authority 'host'") (fst (runChecked (parseUrl Strict "file://host/x"))),+      runTest "a file URL with no path has the root" $+        assertEqual "path" (Right ["", ""]) (urlPath <$> fst (runChecked (parseUrl Strict "file://"))),+      runTest "a port must be from 1 to 65535" $+        assertEqual "refused" (Left "port '0' is invalid") (fst (runChecked (parseUrl Strict "http://h:0/"))),+      runTest "a parameter with no value is dropped with a warning" $+        assertEqual+          "parsed"+          (Right (Map.fromList [("b", "1")]), ["dubious URI query 'a' is missing equal sign '=', ignoring"])+          (let (result, warnings) = runChecked (parseUrl Strict "x:y?a&b=1&b=2") in (urlQuery <$> result, warnings)),+      runTest "encoding keeps the unreserved characters and those asked" $+        assertEqual "encoded" "a-._~%2B%2F:@%25" (percentEncode ":@" "a-._~+/:@%"),+      runTest "an SCP-style Git URL becomes an SSH URL with an absolute path, and warns" $+        let (result, warnings) = runChecked (fixGitUrl PosixPaths "git@github.com:NixOS/nix")+         in assertEqual "url" (Right "ssh://git@github.com/NixOS/nix") (renderUrl <$> result)+              `andThen` assertEqual "warned" 1 (length warnings),+      runTest "an SCP-style URL's bracketed IPv6 host is written canonically" $+        assertEqual "url" (Right "ssh://u@[::1]/~/r") (renderUrl <$> fst (runChecked (fixGitUrl PosixPaths "u@[0:0::1]:~/r"))),+      runTest "an absolute path is a file URL, and a git+ scheme loses its git" $+        assertEqual+          "urls"+          [Right "file:///tmp/repo", Right "https://example.org/r"]+          (map (fmap renderUrl . fst . runChecked . fixGitUrl PosixPaths) ["/tmp/repo", "git+https://example.org/r"]),+      runTest "a path's URL segments are std::filesystem's elements" $+        assertEqual+          "segments"+          [["", "a", "b"], ["", ""], ["", "a", "", ""], [".", "x"], ["", "C:", "x"]]+          (map (uncurry pathToUrlPath) [(PosixPaths, "/a//b"), (PosixPaths, "/"), (PosixPaths, "/a/"), (PosixPaths, "./x"), (WindowsPaths, "C:/x")]),+      runTest "a path from URL segments appends as std::filesystem's /= does" $+        assertEqual+          "paths"+          [Right "/a/b", Right "/a/", Right "C:/x", Left "URL path component 'a/b' contains '/', which is not allowed in file names"]+          (map (fst . runChecked . uncurry urlPathToPath) [(PosixPaths, ["", "a", "b"]), (PosixPaths, ["", "a", "", ""]), (WindowsPaths, ["", "C:", "x"]), (PosixPaths, ["", "a/b"])])+    ]++-- | A URL the grammar admits, its parts as a parse of its rendering+-- gives them back: a scheme that is not a file URL's, a path that starts+-- with an empty segment under an authority and never with two without+-- one, and any bytes in the segments, the query and the fragment.+genUrl :: QC.Gen ParsedUrl+genUrl = do+  scheme <- QC.elements ["https", "git+ssh", "github", "x-y.z"]+  authority <- QC.oneof [pure Nothing, Just <$> genAuthority]+  segments <- QC.listOf genBytes+  firstSegment <- genNonEmptyBytes+  path <- case authority of+    Just _ -> QC.elements [[""], "" : segments]+    Nothing -> QC.elements [[""], "" : firstSegment : segments, firstSegment : segments]+  query <- Map.fromList <$> QC.listOf ((,) <$> genBytes <*> genBytes)+  ParsedUrl scheme authority path query <$> genBytes+  where+    genAuthority = do+      host <- QC.elements ["example.org", "", "h"]+      user <- QC.oneof [pure Nothing, Just <$> genBytes]+      password <- maybe (pure Nothing) (const (QC.oneof [pure Nothing, Just <$> genBytes])) user+      port <- QC.oneof [pure Nothing, Just <$> QC.choose (1, maxBound)]+      pure (Authority HostName host user password port)+    genBytes = BS.pack <$> QC.listOf genByte+    genNonEmptyBytes = BS.pack <$> QC.listOf1 genByte+    genByte = QC.frequency [(3, QC.elements (BS.unpack "abc/?#%:@ +=&")), (1, QC.arbitrary :: QC.Gen Word8)]++-- ---------------------------------------------------------------------------+-- Flake references+-- ---------------------------------------------------------------------------++-- | A reference read with flakes on: its attributes and its string.+readRef :: ByteString -> Either Text (Attrs, ByteString)+readRef ref = fst (runChecked (parseFlakeRef flakesOn ref >>= \flakeRef -> (,) (flakeRefAttrs flakeRef) <$> flakeRefToString flakesOn flakeRef))++-- | Attributes from strings.+strings :: [(Text, ByteString)] -> Attrs+strings = Map.fromList . map (fmap AttrString)++-- | Flake references in each of upstream's forms, and what they read as.+testFlakeRefs :: IO [Bool]+testFlakeRefs = do+  putStrLn "fetch/flake-refs"+  githubRoundTrip <- property (QC.forAll genForgeAttrs (\attrs -> fmap fst (readRef . snd =<< rendered attrs) == Right attrs))+  sequence+    [ runTest "a forge reference that renders reads back to its attributes" githubRoundTrip,+      runTest "a flake ID with a ref and a revision, its empty segments skipped" $+        assertEqual+          "read"+          (Right (strings [("type", "indirect"), ("id", "nixpkgs"), ("ref", "branch"), ("rev", rev)], "flake:nixpkgs/branch/" <> rev))+          (readRef ("nixpkgs/branch///" <> rev <> "///")),+      runTest "an indirect URL's empty segments are skipped" $+        assertEqual "read" (Right (strings [("type", "indirect"), ("id", "nixpkgs"), ("ref", "branch")], "flake:nixpkgs/branch")) (readRef "flake:/nixpkgs///branch////"),+      runTest "a GitHub URL's path is decoded and its authority ignored" $+        assertEqual+          "read"+          (Right (strings [("type", "github"), ("owner", "ownerB"), ("repo", "repoA"), ("ref", "branchC")], "github:ownerB/repoA/branchC"))+          (readRef "github://////owner%42/////repo%41///branch%43////"),+      runTest "a GitLab owner keeps a percent it decodes to, encoded again" $+        assertEqual+          "read"+          (Right (strings [("type", "gitlab"), ("owner", "owner%2Fsubgroup"), ("repo", "repoA"), ("ref", "branchC")], "gitlab:owner%252Fsubgroup/repoA/branchC"))+          (readRef "gitlab:/owner%252Fsubgroup/////repo%41///branch%43////"),+      runTest "a GitHub ref of several segments is one segment, encoded" $+        assertEqual "string" (Right "github:nixos/nix/master%2Fsomething") (snd <$> readRef "github:nixos/nix//master///something/"),+      runTest "a ref with a hash sign" $+        assertEqual "strings" [Right "github:foo/bar/branch%23", Right "github:foo/bar/branch%23"] (map (fmap snd . readRef) ["github:foo/bar/branch%23", "github:foo/bar?ref=branch%23"]),+      runTest "a fragment with quotes is read leniently" $+        assertEqual+          "fragment"+          (Right "\"name.with.dot\"")+          (snd <$> fst (runChecked (parseFlakeRefWithFragment flakesOn "github:foo/bar?ref=branch#\"name.with.dot\""))),+      runTest "a Git URL loses its git+ and keeps its ref" $+        assertEqual+          "read"+          (Right (strings [("type", "git"), ("ref", "branch"), ("url", "https://somewhere.example/repo")], "git+https://somewhere.example/repo?ref=branch"))+          (readRef "git+https://somewhere.example/repo?ref=branch"),+      runTest "a path's query becomes attributes, its counts numbers" $+        assertEqual+          "read"+          (Right (Map.fromList [("type", AttrString "path"), ("path", AttrString "/foo/bar"), ("rev", AttrString aRev), ("revCount", AttrInt 123)], "path:/foo/bar?rev=" <> aRev <> "&revCount=123"))+          (readRef ("/foo/bar?revCount=123&rev=" <> aRev)),+      runTest "a path's subdirectory is its dir parameter" $+        assertEqual+          "read"+          (Right (strings [("type", "path"), ("path", "/foo bar/baz"), ("dir", "bla space")], "path:/foo%20bar/baz?dir=bla%20space"))+          (readRef "/foo bar/baz?dir=bla space"),+      runTest "a tarball's plus sign is encoded" $+        assertEqual "string" (Right "http://localhost:8181/test/%2B3d.tar.gz") (snd <$> readRef "http://localhost:8181/test/+3d.tar.gz"),+      runTest "the refusals are upstream's" $+        assertEqual+          "refusals"+          [ Left "URL 'github:NixOS' is invalid",+            Left "URL 'github:a/b?xyzzy=1' contains unknown parameter 'xyzzy'",+            Left "flake reference './relative' is not an absolute path",+            Left "unexpected fragment 'hello' in flake reference 'nixpkgs#hello'",+            Left "input 'foo:bar' is unsupported",+            Left "input 'file+git:///x' is unsupported; did you mean 'git+file' instead of 'file+git'?",+            Left "'1abc' is not a valid flake ID",+            Left "GitHub URL 'flake:nixpkgs/a/b/c' is invalid"+          ]+          (map (fmap snd . readRef) ["github:NixOS", "github:a/b?xyzzy=1", "./relative", "nixpkgs#hello", "foo:bar", "file+git:///x", "flake:1abc", "flake:nixpkgs/a/b/c"]),+      runTest "attributes become a reference" $+        assertEqual+          "strings"+          [Right "github:NixOS/nixpkgs/23.05?dir=lib", Right "git+file:///tmp/repo", Right ("tarball+https://x/y?narHash=sha256-" <> zeroSri), Right "path:/a?narHash=&revCount=3"]+          ( map+              fromAttrs+              [ strings [("type", "github"), ("owner", "NixOS"), ("repo", "nixpkgs"), ("ref", "23.05"), ("dir", "lib")],+                strings [("type", "git"), ("url", "/tmp/repo")],+                strings [("type", "tarball"), ("url", "tarball+https://x/y"), ("narHash", "")],+                Map.fromList [("type", AttrString "path"), ("path", AttrString "/a"), ("narHash", AttrString ""), ("revCount", AttrInt 3)]+              ]+          ),+      runTest "the attribute refusals are upstream's" $+        assertEqual+          "refusals"+          [ Left "input attribute 'foo' not supported by scheme 'github'",+            Left "'type' attribute to specify input scheme is required but not provided",+            Left "cannot show unsupported input '{\"type\":\"unknown\",\"x\":1}'",+            Left ("input {\"owner\":\"a\",\"ref\":\"x\",\"repo\":\"b\",\"rev\":\"" <> T.pack (BC.unpack aRev) <> "\",\"type\":\"github\"} contains both a commit hash ('" <> T.pack (BC.unpack aRev) <> "') and a branch/tag name ('x')")+          ]+          ( map+              fromAttrs+              [ strings [("type", "github"), ("owner", "a"), ("repo", "b"), ("foo", "c")],+                strings [("owner", "a")],+                Map.fromList [("type", AttrString "unknown"), ("x", AttrInt 1)],+                strings [("type", "github"), ("owner", "a"), ("repo", "b"), ("ref", "x"), ("rev", aRev)]+              ]+          ),+      runTest "a scheme flakes own needs the feature, and Git's needs none" $+        assertEqual+          "read"+          [Left missingFlakes, Left missingFlakes, Left missingFlakes, Right "git+https://example.org/r?ref=main"]+          (map (\ref -> fst (runChecked (parseFlakeRef featuresOff ref >>= flakeRefToString featuresOff))) ["github:NixOS/nixpkgs", "nixpkgs", "/tmp/x", "git+https://example.org/r?ref=main"]),+      runTest "Git accepts the ref names libgit2 does" $+        assertEqual+          "legal"+          [True, True, True, True, False, False, False, False, False, False, False, False]+          (map isLegalRefName ["main", "refs/heads/x", "HEAD", "v1.0", "@", "a..b", "a.lock", ".a", "a/", "a b", "a@{1}", "a."])+    ]+  where+    rev = "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed"+    aRev = BC.replicate 40 'a'+    zeroSri = BC.replicate 43 'A' <> "%3D"+    missingFlakes = "experimental Nix feature 'flakes' is disabled; add '--extra-experimental-features flakes' to enable it"+    fromAttrs attrs = fst (runChecked (flakeRefFromAttrs flakesOn attrs >>= flakeRefToString flakesOn))+    rendered :: Attrs -> Either Text (FlakeRef, ByteString)+    rendered attrs = fst (runChecked (flakeRefFromAttrs flakesOn attrs >>= \flakeRef -> (,) flakeRef <$> flakeRefToString flakesOn flakeRef))++-- | Forge and flake ID attributes upstream writes back as they read:+-- names of letters and digits, a legal ref or a lower-case revision.+genForgeAttrs :: QC.Gen Attrs+genForgeAttrs = do+  scheme <- QC.elements ["github", "gitlab", "sourcehut", "indirect"]+  name <- genName+  repo <- genName+  pin <- QC.oneof [pure [], (\r -> [("ref", r)]) <$> genRef, (\r -> [("rev", r)]) <$> genRev]+  subdir <- QC.oneof [pure [], (\d -> [("dir", d)]) <$> genName]+  let base+        | scheme == "indirect" = [("type", scheme), ("id", name)]+        | otherwise = [("type", scheme), ("owner", name), ("repo", repo)]+  pure (strings (base ++ pin ++ subdir))+  where+    genName = BC.pack <$> ((:) <$> QC.elements ['a' .. 'z'] <*> QC.listOf (QC.elements (['a' .. 'z'] ++ ['0' .. '9'])))+    genRef = BC.intercalate "/" <$> QC.listOf1 genName+    genRev = BC.pack <$> QC.vectorOf 40 (QC.elements "0123456789abcdef")++-- ---------------------------------------------------------------------------+-- Experimental features+-- ---------------------------------------------------------------------------++-- | The setting's values, its warnings, and its place in nix.conf.+testExperimentalFeatures :: IO [Bool]+testExperimentalFeatures = do+  putStrLn "fetch/experimental-features"+  sequence+    [ runTest "a value's names are read in byte order, an unknown one dropped with a warning" $+        assertEqual+          "warnings"+          ["unknown experimental feature 'aaa'", "experimental feature 'no-url-literals' has been stabilized and renamed; use 'lint-url-literals = fatal' setting instead", "unknown experimental feature 'zzz'"]+          (featureSetWarnings (parseFeatures "zzz flakes no-url-literals aaa flakes")),+      runTest "a value turns on the features it names" $+        assertEqual "flakes" (True, False) (featureEnabled flakesFeature (parseFeatures " nix-command\tflakes "), featureEnabled flakesFeature (parseFeatures "nix-command")),+      runTest "an assignment replaces the features and an extra one adds to them, the warnings of both kept" $+        let replaced = replaceFeatures (parseFeatures "flakes bogus") (parseFeatures "nix-command")+            added = addFeatures (parseFeatures "nix-command") (parseFeatures "flakes")+         in assertEqual "replaced" (False, ["unknown experimental feature 'bogus'"]) (featureEnabled flakesFeature replaced, featureSetWarnings replaced)+              `andThen` assertEqual "added" True (featureEnabled flakesFeature added),+      runTest "nix.conf sets the features, extra- adds to them" $+        assertEqual+          "flakes"+          [Right True, Right False, Right True]+          ( map+              (fmap (featureEnabled flakesFeature . ncExperimentalFeatures) . resolveConfig . map (uncurry ConfigAssignment))+              [ [("experimental-features", "nix-command flakes")],+                [("experimental-features", "flakes"), ("experimental-features", "nix-command")],+                [("experimental-features", "nix-command"), ("extra-experimental-features", "flakes")]+              ]+          )+    ]++-- ---------------------------------------------------------------------------+-- The builtins+-- ---------------------------------------------------------------------------++-- | The policy with flakes on.+flakesPolicy :: EvalPolicy+flakesPolicy = unrestrictedPolicy {epExperimentalFeatures = parseFeatures "flakes"}++-- | Evaluate under the IO evaluator with flakes on, as the pure one+-- evaluates under the default policy whatever its builtins were made+-- under.+evalWithFlakes :: Text -> IO (Either Text NixValue)+evalWithFlakes source = do+  storeDir <- evalNixIOStoreDir+  st <- newEvalStateWith testLogger flakesPolicy [] (testSessionStore storeDir) storeDir testBaseDir+  evalNixIOIn st testBaseDir source++-- | @builtins.parseFlakeRef@ and @builtins.flakeRefToString@.+testFlakeRefBuiltins :: IO [Bool]+testFlakeRefBuiltins = do+  putStrLn "fetch/flake-ref-builtins"+  sequence+    [ runTestM "parseFlakeRef gives a reference's attributes" $+        assertEqual "attrs" (Right (mkStr "{\"dir\":\"lib\",\"owner\":\"NixOS\",\"ref\":\"23.05\",\"repo\":\"nixpkgs\",\"type\":\"github\"}"))+          <$> evalWithFlakes "builtins.toJSON (builtins.parseFlakeRef \"github:NixOS/nixpkgs/23.05?dir=lib\")",+      runTestM "parseFlakeRef gives a count as an integer" $+        assertEqual "count" (Right (VInt 123)) <$> evalWithFlakes "(builtins.parseFlakeRef \"path:/foo?revCount=123\").revCount",+      runTestM "flakeRefToString writes a reference back" $+        assertEqual "string" (Right (mkStr "github:NixOS/nixpkgs/23.05?dir=lib"))+          <$> evalWithFlakes "builtins.flakeRefToString { dir = \"lib\"; owner = \"NixOS\"; ref = \"23.05\"; repo = \"nixpkgs\"; type = \"github\"; }",+      runTestM "flakeRefToString checks the set's attributes in its order" $+        assertEqual "refusal" (Left "flake reference attribute sets may only contain integers, Booleans, and strings, but attribute 'type' is a list")+          <$> evalWithFlakes "builtins.flakeRefToString { type = [ ]; zz = throw \"later\"; }",+      runTestM "flakeRefToString refuses a negative integer" $+        assertEqual "refusal" (Left "negative value given for flake ref attr revCount: -1")+          <$> evalWithFlakes "builtins.flakeRefToString { type = \"path\"; path = \"/a\"; revCount = -1; }",+      runTest "with no feature on, a GitHub reference is refused" $+        assertEvalError "parseFlakeRef" "builtins.parseFlakeRef \"github:NixOS/nixpkgs\"" "experimental Nix feature 'flakes' is disabled; add '--extra-experimental-features flakes' to enable it",+      runTest "both are builtins whatever the features, getFlake is not listed, and fetchTree is not there" $+        assertEval "listed" "builtins.toJSON [ (builtins ? parseFlakeRef) (builtins ? flakeRefToString) (builtins ? getFlake) (builtins ? fetchTree) ]" (mkStr "[true,true,false,false]")+    ]
+ test/Test/Harness.hs view
@@ -0,0 +1,1498 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | What the test modules share: the result type, its runners and+-- assertions, evaluation under the pure and the IO evaluator, and the+-- fixtures the tests of more than one module use.+module Test.Harness+  ( TestResult (..),+    runTest,+    runTestM,+    assertEqual,+    andThen,+    allFailures,+    bytesText,+    storePathStringValue,+    fetchedStorePath,+    assertRight,+    assertLeft,+    testBaseDir,+    testOrigin,+    testPos,+    assertParse,+    assertParseIn,+    withGlobals,+    evalNix,+    evalNixBytes,+    parseErrorTag,+    assertEval,+    assertEvalFail,+    assertEvalError,+    assertEvalErrorIO,+    assertParseFail,+    findTestShell,+    repeatedMarker,+    selfHoldingDerivation,+    selfHoldingPrinted,+    selfHoldingPrintedStrict,+    censusStoreHash,+    setLayerRhsMax,+    setMaxLayers,+    sitesAdded,+    evalNixIOStoreDir,+    evalNixIO,+    testEvalState,+    testSessionStore,+    evalDerivationIO,+    evalDerivationIOStore,+    runTestIO,+    nixQuotedPath,+    symlinksAvailable,+    walkWatchdogMicros,+    positionsFile,+    evalNixInFile,+    jsonInFile,+    positionJson,+    envSpelling,+    genJson,+    pureDepGraph,+    chunkReader,+    removeIfExists,+    quotedAsCxx,+    throwawayKey,+    withTempStore,+    deleteNamed,+    forceRemoveIfExists,+    tarPathOrDie,+    tarDir,+    tarFile,+    profileFixture,+    narSpecStr,+    narSpecVector,+    narSpecFileVector,+    offeredThenFetched,+    offeredSubstitute,+    servedPaths,+    servedNar,+    narInfoRequest,+    narRequest,+    sessionClosure,+    fixtureGit,+    makeGitFixture,+    evalNixIOStore,+    evalNixIOIn,+    canonicalAs,+    simpleTestDrv,+    genDrvName,+    genFixturePath,+    genTextOf,+    testDrvPath,+    mkTestBuildDrv,+    hostToolsEnv,+    withHostTools,+    hostToolsAttrs,+    evalAndBuild,+    unexpectedOps,+    trustPe,+    evalChildFlag,+    evalChild,+    emits,+    inTestSession,+    posixOnlyEntries,+    decodeFormals,+    compiledBindings,+    sigTestKeyText,+    sigTestWrongKeyText,+    sigTestSecretKeyFile,+    signedTestNarInfo,+    asciiOsPath,+    upstreamBaseEnvNames,+    purePolicy,+    restrictedPolicy,+    evalNixWith,+    withEnvVar,+    testLogger,+    genSignatures,+    genContentAddress,+  )+where++import qualified Codec.Archive.Tar.Entry as TarEntry+import Control.Exception (SomeAsyncException (..), SomeException, bracket, fromException, throwIO, try)+import Control.Monad (filterM, unless, when)+import Control.Monad.State.Strict (evalStateT)+import Data.Bits (shiftR, (.&.))+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BS8+import qualified Data.ByteString.Lazy as BL+import Data.Functor.Identity (Identity (..))+import Data.IORef (atomicModifyIORef', newIORef, readIORef)+import Data.Int (Int64)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Text.Encoding.Error (lenientDecode)+import Data.Time.Clock.POSIX (posixSecondsToUTCTime)+import Data.Word (Word32, Word64, Word8)+import qualified GHC.Foreign as GHCForeign+import GHC.IO.Encoding (getFileSystemEncoding)+import HttpFixture (Reply (..), httpResponse)+import Nix.Builder (BuildConfig (..), BuildResult (..), BuildStop (..), buildDerivation, defaultBuildConfig)+import Nix.Builtins (builtinEnv, rootScopeNames)+import qualified Nix.Daemon.Protocol as Proto+import qualified Nix.DependencyGraph as DepGraph+import Nix.Derivation (Derivation (..), DerivationOutput (..), Platform (..), currentPlatform, platformToText)+import Nix.Eval (EvalPolicy (..), MonadEval (..), NixValue (..), StringContext (..), StringContextElement (..), attrSetLookup, evalParsed, force, mkStr, runPureEval, typeName, unrestrictedPolicy)+import Nix.Eval.CBytecode (cbcArg1, cbcCountedPayload)+import Nix.Eval.CRegion (Regions (..))+import Nix.Eval.CStats (EnvSiteFigures (..), SetSiteFigures (..), SiteCounts (..), siteCounts)+import Nix.Eval.Compile (BcBindings (..), decodeBcBindings, decodeBcFormals)+import Nix.Eval.EvalFormals (EvalFormals (..))+import Nix.Eval.IO (EvalState (..), SessionSettings (..), SessionStore (..), evalBaseEnv, newEvalStateWith, runEvalIO, sourceCopies, withEvalSession)+import Nix.Expr.Resolve (staticGlobalNames, undefinedVariableMessage)+import Nix.Expr.Types+import Nix.Hash (FileIngestionMethod (..), hashAlgoBytes)+import Nix.Http (FetchRetryPolicy (..), RetryEffects (..))+import Nix.Json (Json (..))+import Nix.Logger (EscapeFilter (..), Logger, handleLogger)+import Nix.Parser (SourceError (..), parseNix, parseNixWithScope, parsedExpr)+import Nix.Push (storePathBasename)+import Nix.Push.Directory (ed25519SeedBytes)+import qualified Nix.Realise as Realise+import Nix.Store (DeleteOutcome (..), Store (..), closeStore, deleteStorePathRaw, materializeEvalSources, materializeEvalStoreWrites, openStore, storeEntryName)+import Nix.Store.Metadata (storeModificationTime)+import Nix.Store.Ops (EvalWrites (..), StoreOps (..), StoreQueries (..), localQueries, withLocalStore)+import Nix.Store.Path (StoreDir (..), StorePath, defaultStoreDir, parseStorePath, storePathToText)+import Nix.Store.Path.Internal (StorePath (..))+import qualified Nix.Substituter as Subst+import NodeStatus (NodeStatus (..), nodeStatus)+import qualified NovaCache.Base64 as B64+import qualified NovaCache.Hash as CHash+import qualified NovaCache.NAR as NAR+import qualified NovaCache.NarInfo as NarInfo+import qualified NovaCache.Signing as Signing+import System.Directory (createDirectoryIfMissing, doesDirectoryExist, getPermissions, getTemporaryDirectory, removeDirectoryRecursive, writable)+import qualified System.Directory as Dir+import System.Environment (getExecutablePath, lookupEnv, unsetEnv)+import qualified System.Environment.Blank as Blank+import System.Exit (ExitCode (..))+import System.FilePath ((</>))+import System.IO (hPutStrLn, stderr)+import qualified System.Info as SI+import System.OsPath (OsPath)+import qualified System.OsPath as OP+import qualified System.Process as Proc+import qualified Test.QuickCheck as QC++-- ---------------------------------------------------------------------------+-- Test harness+-- ---------------------------------------------------------------------------++data TestResult = Pass | Fail !Text++runTest :: Text -> TestResult -> IO Bool+runTest name result = case result of+  Pass -> do+    putStrLn $ "  PASS  " ++ T.unpack name+    pure True+  Fail msg -> do+    putStrLn $ "  FAIL  " ++ T.unpack name ++ ": " ++ T.unpack msg+    pure False++-- | Like 'runTest' but for tests that need IO to produce their result.+-- A synchronous exception escaping the action becomes one FAIL line+-- instead of aborting the whole suite (which would skip every later group+-- and its cleanup).  An asynchronous one, an interrupt or a killed+-- thread, stops the suite, as it stops any program.+runTestM :: Text -> IO TestResult -> IO Bool+runTestM name action = do+  outcome <- try action+  case outcome of+    Left (e :: SomeException)+      | Just (_ :: SomeAsyncException) <- fromException e -> throwIO e+      | otherwise -> runTest name (Fail ("uncaught exception: " <> T.pack (show e)))+    Right result -> runTest name result++assertEqual :: (Eq a, Show a) => Text -> a -> a -> TestResult+assertEqual label expected actual+  | expected == actual = Pass+  | otherwise =+      Fail $+        label+          <> ": expected "+          <> T.pack (show expected)+          <> " but got "+          <> T.pack (show actual)++-- | The first failure of two results, or 'Pass' when both pass.+andThen :: TestResult -> TestResult -> TestResult+andThen first second = case first of+  Pass -> second+  failed -> failed++-- | Every failure among the results, in order, as one failure, or 'Pass'+-- when all pass: for checks that do not depend on one another, so that a+-- run that breaks several reports all of them.+allFailures :: [TestResult] -> TestResult+allFailures results = case [message | Fail message <- results] of+  [] -> Pass+  messages -> Fail (T.intercalate "; " messages)++-- | Render string-value bytes in a failure message (display-only decode).+bytesText :: BS.ByteString -> Text+bytesText = TE.decodeUtf8With lenientDecode++-- | A store path as a fetcher or a source importer returns it: its text,+-- carrying itself as context.+storePathStringValue :: StorePath -> NixValue+storePathStringValue sp = VStr (TE.encodeUtf8 (storePathToText defaultStoreDir sp)) (StringContext (Set.singleton (SCPlain sp)))++-- | The store path a fetcher's result names, when it is the string with+-- itself as context that upstream's fetchers return.+fetchedStorePath :: NixValue -> Maybe StorePath+fetchedStorePath val = case val of+  VStr bytes _ -> do+    sp <- parseStorePath defaultStoreDir (bytesText bytes)+    if val == storePathStringValue sp then Just sp else Nothing+  _ -> Nothing++assertRight :: (Show e) => Text -> Either e a -> (a -> TestResult) -> TestResult+assertRight label result check = case result of+  Left err -> Fail (label <> ": got error: " <> T.pack (show err))+  Right val -> check val++assertLeft :: (Show a) => Text -> Either e a -> TestResult+assertLeft _ (Left _) = Pass+assertLeft label (Right val) = Fail (label <> ": expected error but got: " <> T.pack (show val))++-- | What a test expression's relative path literals resolve against.+-- Absolute, because that is the invariant the parser establishes: no+-- relative path literal survives parsing, so nothing downstream has to know+-- what one would have meant.+testBaseDir :: FilePath+testBaseDir = "/nova-nix-test"++-- | Where a test expression's source comes from: text with no file, as an+-- @--expr@ argument is.+testOrigin :: SourceOrigin+testOrigin = SourceText "<test>"++-- | A position in a test expression's source.+testPos :: Int -> Int -> SrcPos+testPos = SrcPos testOrigin++-- | Helper: parse and check result.+assertParse :: Text -> Text -> Expr -> TestResult+assertParse = assertParseIn []++-- | 'assertParse' for source whose free variables are bound around it, the+-- way @scopedImport@ binds its scope: each stays a name-based 'EVar'.+assertParseIn :: [Text] -> Text -> Text -> Expr -> TestResult+assertParseIn names label source expected =+  assertRight label (parsedExpr <$> parseNixWithScope (withGlobals names) testBaseDir testOrigin (TE.encodeUtf8 source)) $ \actual ->+    assertEqual label expected actual++-- | The root environment's names with more bound around them.+withGlobals :: [Text] -> Set.Set Text+withGlobals names = Set.union (Set.fromList names) staticGlobalNames++-- | Helper: parse Nix source and evaluate with builtinEnv.  Parse errors+-- are tagged so failure assertions can tell them apart from eval errors.+evalNix :: Text -> Either Text NixValue+evalNix = evalNixBytes . TE.encodeUtf8++-- | 'evalNix' over source bytes, which need not be UTF-8.+evalNixBytes :: BS.ByteString -> Either Text NixValue+evalNixBytes source = case parseNix testBaseDir testOrigin source of+  Left err -> Left (sourceFailure err)+  Right parsed -> runPureEval (evalParsed (builtinEnv unrestrictedPolicy 0 []) parsed)++-- | Prefix marking a parse (not eval) failure in 'evalNix' results.+parseErrorTag :: Text+parseErrorTag = "parse error: "++-- | A source failure as an 'evalNix' result: a syntax error carries+-- 'parseErrorTag'; an unbound variable reads as the evaluation error+-- upstream raises for it, before evaluating anything.+sourceFailure :: SourceError -> Text+sourceFailure (SyntaxError err) = parseErrorTag <> T.pack (show err)+sourceFailure (UndefinedVariable name) = undefinedVariableMessage name++-- | Assert that a Nix expression evaluates to the expected value.+assertEval :: Text -> Text -> NixValue -> TestResult+assertEval label source expected =+  assertRight label (evalNix source) $ \actual ->+    assertEqual label expected actual++-- | Assert that a Nix expression parses but fails to EVALUATE.  A parse+-- failure fails the assertion: a test documenting a runtime error must+-- not keep passing after a regression stops the construct from parsing.+assertEvalFail :: Text -> Text -> TestResult+assertEvalFail label source = case evalNix source of+  Left err+    | parseErrorTag `T.isPrefixOf` err ->+        Fail (label <> ": expected an eval error but the source did not parse: " <> err)+    | otherwise -> Pass+  Right val -> Fail (label <> ": expected eval failure but got: " <> T.pack (show val))++-- | Assert that a Nix expression parses and fails to evaluate with exactly+-- the given message, for errors whose wording is upstream's.+assertEvalError :: Text -> Text -> Text -> TestResult+assertEvalError label source expected = case evalNix source of+  Left err+    | parseErrorTag `T.isPrefixOf` err ->+        Fail (label <> ": expected an eval error but the source did not parse: " <> err)+    | otherwise -> assertEqual label expected err+  Right val -> Fail (label <> ": expected eval failure but got: " <> T.pack (show val))++-- | 'assertEvalError' under the IO evaluator, which keeps a forced+-- thunk's value and marks one while it is being forced, as upstream's+-- evaluator does; the pure one does neither.+assertEvalErrorIO :: FilePath -> Text -> Text -> Text -> IO TestResult+assertEvalErrorIO baseDir label source expected = do+  result <- evalNixIO baseDir source+  pure $ case result of+    Left err -> assertEqual label expected err+    Right val -> Fail (label <> ": expected eval failure but got: " <> T.pack (show val))++-- | Assert that a Nix expression fails at PARSE time.+assertParseFail :: Text -> Text -> TestResult+assertParseFail label source = case evalNix source of+  Left err+    | parseErrorTag `T.isPrefixOf` err -> Pass+    | otherwise ->+        Fail (label <> ": expected a parse error but evaluation failed instead: " <> err)+  Right val -> Fail (label <> ": expected parse failure but got: " <> T.pack (show val))++-- ---------------------------------------------------------------------------+-- Shell discovery for builder tests+-- ---------------------------------------------------------------------------++-- | Find a POSIX-compatible shell for builder tests.+-- On Unix, always @\/bin\/sh@.  On Windows, searches for @bash.exe@+-- at known Git for Windows locations first, then PATH.  Checks known+-- paths first to avoid picking up the WSL launcher at+-- @C:\\Windows\\System32\\bash.exe@ which exits 1 when WSL is not+-- configured.  Real Nix builders always use bash from the store -+-- this bridges the gap until nova-nix bootstraps its own bash+-- derivation.+findTestShell :: IO Text+findTestShell = case SI.os of+  "mingw32" -> do+    let known =+          [ "C:\\Program Files\\Git\\bin\\bash.exe",+            "C:\\Program Files (x86)\\Git\\bin\\bash.exe"+          ]+    found <- filterM Dir.doesFileExist known+    case found of+      (p : _) -> pure (T.pack p)+      [] -> do+        inPath <- Dir.findExecutable "bash"+        case inPath of+          Just p -> pure (T.pack p)+          Nothing ->+            error+              "bash not found: install Git for Windows or add bash to PATH"+  _ -> pure "/bin/sh"++-- ---------------------------------------------------------------------------+-- Tests: Eval - Values reached twice+-- ---------------------------------------------------------------------------++-- | Upstream's repeated marker, @printRepeated@ (print.cc at 2.24.9).+repeatedMarker :: Text+repeatedMarker = "\x00ABrepeated\x00BB"++-- | A derivation with one output, which its @all@ and @out@ attributes+-- hold, so the derivation holds itself.+selfHoldingDerivation :: Text+selfHoldingDerivation = "derivation { name = \"a\"; system = \"x\"; builder = \"/bin/sh\"; }"++-- | What @nix-instantiate --eval@ 2.24.9 prints for+-- 'selfHoldingDerivation', as its wrapper (primops/derivation.nix) and+-- @printAmbiguous@ make it: forcing the result forces the arguments and+-- the output's set and neither @all@ nor the paths, and the output+-- attribute is the result's own set, printed first, so it prints as+-- repeated.+selfHoldingPrinted :: Text+selfHoldingPrinted =+  "{ all = <CODE>; builder = \"/bin/sh\"; drvAttrs = { builder = \"/bin/sh\"; name = \"a\"; system = \"x\"; }; drvPath = <CODE>; name = \"a\"; out = "+    <> repeatedMarker+    <> "; outPath = <CODE>; outputName = \"out\"; system = \"x\"; type = \"derivation\"; }"++-- | What @nix-instantiate --eval --strict@ 2.24.9 prints for+-- 'selfHoldingDerivation'.  The drvPath is 2.24.9's, and the outPath is+-- the one that .drv names: the drvPath hashes the .drv's text, which+-- holds it.+selfHoldingPrintedStrict :: Text+selfHoldingPrintedStrict =+  "{ all = [ "+    <> repeatedMarker+    <> " ]; builder = \"/bin/sh\"; drvAttrs = { builder = \"/bin/sh\"; name = \"a\"; system = \"x\"; }; drvPath = \"/nix/store/l9ldjc53ry43x24hvq73jx7dx0489mhj-a.drv\"; name = \"a\"; out = "+    <> repeatedMarker+    <> "; outPath = \"/nix/store/0pd4llb3k36fnppfxwp6nlwsxwlv0y2c-a\"; outputName = \"out\"; system = \"x\"; type = \"derivation\"; }"++-- ---------------------------------------------------------------------------+-- Tests: Eval - frames tied in C+-- ---------------------------------------------------------------------------++-- | A store path hash: 32 characters of the base-32 alphabet.+censusStoreHash :: Text+censusStoreHash = "0123456789abcdfghijklmnpqrsvwxyz"++-- | The most entries a right operand of @//@ has for the result to be a+-- layer, and the most sets a chain of layers holds:+-- @NN_ATTRSET_LAYER_RHS_MAX@ on a 64-bit target and+-- @NN_ATTRSET_MAX_LAYERS@ (cbits/nn_attrset.h).+setLayerRhsMax, setMaxLayers :: Int+setLayerRhsMax = 16+setMaxLayers = 8++-- | The figures of each site and size that counting by site adds while+-- an action runs; a site or size that gains nothing is left out.+sitesAdded :: IO () -> IO (Either Text SiteCounts)+sitesAdded action = do+  before <- siteCounts+  action+  after <- siteCounts+  pure $ case (before, after) of+    (Just earlier, Just later) ->+      Right+        SiteCounts+          { sitesEnvs = gained envMinus (EnvSiteFigures 0 0 0) (sitesEnvs later) (sitesEnvs earlier),+            sitesEnvSizes = gained (-) 0 (sitesEnvSizes later) (sitesEnvSizes earlier),+            sitesSets = gained setMinus (SetSiteFigures 0 0 0) (sitesSets later) (sitesSets earlier),+            sitesUpdateCopied = sitesUpdateCopied later - sitesUpdateCopied earlier+          }+    _ -> Left "counting by site is off"+  where+    gained minus none later earlier =+      Map.filter (/= none) (Map.mapWithKey (\k figures -> maybe figures (minus figures) (Map.lookup k earlier)) later)+    envMinus (EnvSiteFigures a b c) (EnvSiteFigures x y z) = EnvSiteFigures (a - x) (b - y) (c - z)+    setMinus (SetSiteFigures a b c) (SetSiteFigures x y z) = SetSiteFigures (a - x) (b - y) (c - z)++-- ---------------------------------------------------------------------------+-- Tests: import and IO builtins (IO)+-- ---------------------------------------------------------------------------++-- | The per-suite temp store 'evalNixIO' evaluates against, exposed so+-- a test inspecting materialized trees resolves the same directory.+evalNixIOStoreDir :: IO StoreDir+evalNixIOStoreDir = do+  tmpBase <- getTemporaryDirectory+  pure (StoreDir (tmpBase </> "nova-nix-test-eval-store"))++-- | IO eval against a per-suite temp store, so no test needs a real,+-- writable platform store root: eval-time store writes land under the+-- temp directory, and the suite runs everywhere without provisioning.+evalNixIO :: FilePath -> Text -> IO (Either Text NixValue)+evalNixIO baseDir source = do+  storeDir <- evalNixIOStoreDir+  evalNixIOStore storeDir baseDir source++-- | An evaluation state with no search path, whatever @NIX_PATH@ the suite+-- runs under.  'nixPathSearchPath' makes @NIX_PATH@'s entries, interning+-- their strings, so a test whose result depends on the order names were+-- interned in would otherwise depend on the machine; a test of+-- @NIX_PATH@ itself uses 'evalNixIOWithNixPath'.+testEvalState :: StoreDir -> FilePath -> IO EvalState+testEvalState storeDir = newEvalStateWith testLogger unrestrictedPolicy [] (testSessionStore storeDir) storeDir++-- | The store a test's evaluation realises contexts against: the local+-- store in the directory, read-write as a build's session is, so what+-- evaluation writes reads back.  Each operation opens the store for+-- itself and closes it ('eachOpening'), since a test's state is made+-- outside any bracket.+testSessionStore :: StoreDir -> SessionStore+testSessionStore storeDir = ReadWriteSession (eachOpening (defaultBuildConfig storeDir))++-- | The local store's operations, each opening the store for itself and+-- closing it once it is done.+eachOpening :: BuildConfig -> StoreOps IO+eachOpening config =+  StoreOps+    { soQueries =+        StoreQueries+          { sqValidPaths = \paths -> withLocalStore testLogger config (\ops -> sqValidPaths (soQueries ops) paths),+            sqReferences = \path -> withLocalStore testLogger config (\ops -> sqReferences (soQueries ops) path)+          },+      soAddEvalObjects = \objects -> withLocalStore testLogger config (`soAddEvalObjects` objects),+      soAddSourceTree = \name refs entry -> withLocalStore testLogger config (\ops -> soAddSourceTree ops name refs entry),+      soBuild = \requests -> withLocalStore testLogger config (`soBuild` requests),+      soCheck = \drvPath -> withLocalStore testLogger config (`soCheck` drvPath),+      soAddOutLinkRoot = \link path -> withLocalStore testLogger config (\ops -> soAddOutLinkRoot ops link path),+      soEvalWrites = WrittenInDirectory+    }++-- | IO eval of a derivation expression to the 'Derivation' the session+-- recorded for it: forcing the expression's @drvPath@ runs derivationStrict,+-- which records the @.drv@ under that path, and the recipe is read back the+-- way the build driver reads it.  Only the IO evaluator keeps the record.+evalDerivationIO :: FilePath -> Text -> IO (Either Text Derivation)+evalDerivationIO baseDir source = do+  storeDir <- evalNixIOStoreDir+  evalDerivationIOStore storeDir baseDir source++-- | 'evalDerivationIO' against an explicit store directory.+evalDerivationIOStore :: StoreDir -> FilePath -> Text -> IO (Either Text Derivation)+evalDerivationIOStore storeDir baseDir source = case parseNix baseDir testOrigin (TE.encodeUtf8 ("(" <> source <> ").drvPath")) of+  Left err -> pure (Left (T.pack (show err)))+  Right parsed -> do+    st <- testEvalState storeDir baseDir+    runEvalIO st $ do+      pathVal <- evalParsed (pure (evalBaseEnv st)) parsed+      case pathVal of+        VStr pathBytes _ -> do+          recorded <- lookupSessionDrv (bytesText pathBytes)+          maybe (throwEvalError ("no .drv was recorded for " <> bytesText pathBytes)) pure recorded+        other -> throwEvalError ("expected a drvPath string, got " <> typeName other)++-- | Run a named IO eval test - single label, no double-wrapping.+runTestIO :: Text -> FilePath -> Text -> NixValue -> IO Bool+runTestIO label baseDir source expected = do+  result <- evalNixIO baseDir source+  runTest label $ assertRight label result $ \actual ->+    assertEqual label expected actual++-- | Quoted path literal for embedding absolute paths in Nix source.+nixQuotedPath :: FilePath -> Text+nixQuotedPath p = T.pack (show p)++-- | Whether this host can create symlinks (Windows needs Developer Mode+-- or elevation).  The symlink-walk fixtures cannot be built without it,+-- so their groups skip loudly rather than fail.+symlinksAvailable :: IO Bool+symlinksAvailable = do+  tmpBase <- getTemporaryDirectory+  let probeDir = tmpBase </> "nova-nix-test-link-probe"+  Dir.removePathForcibly probeDir+  createDirectoryIfMissing True probeDir+  BS.writeFile (probeDir </> "target.txt") "t"+  outcome <- try (Dir.createFileLink "target.txt" (probeDir </> "link"))+  Dir.removePathForcibly probeDir+  pure $ case (outcome :: Either SomeException ()) of+    Left _ -> False+    Right () -> True++-- | Watchdog for cycle-termination tests: with symlinks as leaves every+-- walk returns promptly, while a regression to link-following recurses+-- forever - and a hung suite is worse than a failed one.+walkWatchdogMicros :: Int+walkWatchdogMicros = 30 * 1000 * 1000++-- ---------------------------------------------------------------------------+-- Tests: builtins.unsafeGetAttrPos+-- ---------------------------------------------------------------------------++-- | The file 'evalNixInFile' parses its source as.+positionsFile :: Text+positionsFile = "/nova-nix-test/positions.nix"++-- | 'evalNix' for source parsed as the file 'positionsFile', so the+-- positions recorded in it name that file, as upstream's do for a file.+evalNixInFile :: Text -> Either Text NixValue+evalNixInFile source = case parseNix testBaseDir (SourceFile positionsFile) (TE.encodeUtf8 source) of+  Left err -> Left (sourceFailure err)+  Right parsed -> runPureEval (evalParsed (builtinEnv unrestrictedPolicy 0 []) parsed)++-- | Assert that @builtins.toJSON@ of source parsed as 'positionsFile' is+-- the expected JSON.  toJSON pins the set @EvalState::mkPos@ builds: its+-- three attributes only, the file a string and the line and column+-- integers.+jsonInFile :: Text -> Text -> Text -> IO Bool+jsonInFile label source expected =+  runTest label $+    assertRight label (evalNixInFile ("builtins.toJSON (" <> source <> ")")) $ \actual ->+      assertEqual label (mkStr expected) actual++-- | The JSON of the position set for a line and column in a file.+positionJson :: Text -> Int -> Int -> Text+positionJson file line column =+  "{\"column\":" <> T.pack (show column) <> ",\"file\":\"" <> file <> "\",\"line\":" <> T.pack (show line) <> "}"++-- ---------------------------------------------------------------------------+-- Tests: environment values as bytes+-- ---------------------------------------------------------------------------++-- | The 'String' that base's environment setters and file functions, and+-- a spawned process's environment, write as the given bytes: on POSIX+-- they encode with the file-system encoding, whose round-trip escape+-- restores every byte its decoding escaped, and on Windows they write+-- UTF-16.+envSpelling :: BS.ByteString -> IO (Maybe String)+envSpelling bytes+  | SI.os == "mingw32" = pure (either (const Nothing) (Just . T.unpack) (TE.decodeUtf8' bytes))+  | otherwise = do+      encoding <- getFileSystemEncoding+      Just <$> BS.useAsCStringLen bytes (GHCForeign.peekCStringLen encoding)++-- ---------------------------------------------------------------------------+-- Tests: structured attributes and the JSON they travel as+-- ---------------------------------------------------------------------------++-- | JSON values up to a nesting depth, strings drawn from what the+-- renderer escapes and what it passes through as UTF-8, numbers across+-- both integer types and finite floats.+genJson :: Int -> QC.Gen Json+genJson depth = QC.oneof (scalars <> [nested | depth > 0])+  where+    scalars =+      [ pure JsonNull,+        JsonBool <$> QC.arbitrary,+        JsonInt . toInteger <$> (QC.arbitrary :: QC.Gen Int64),+        JsonInt . toInteger <$> (QC.arbitrary :: QC.Gen Word64),+        JsonFloat <$> (QC.arbitrary `QC.suchThat` (\d -> not (isNaN d || isInfinite d))),+        JsonString <$> genJsonText+      ]+    nested =+      QC.oneof+        [ JsonArray <$> QC.resize 4 (QC.listOf (genJson (depth - 1))),+          JsonObject . Map.fromList <$> QC.resize 4 (QC.listOf ((,) <$> genJsonText <*> genJson (depth - 1)))+        ]++-- | Text mixing the characters JSON escapes with plain and multi-byte ones.+genJsonText :: QC.Gen Text+genJsonText =+  T.pack <$> QC.listOf (QC.elements ['"', '\\', '/', '\b', '\f', '\n', '\r', '\t', '\0', '\31', '\127', 'a', ' ', '\233', '\8364', '\128512'])++-- ---------------------------------------------------------------------------+-- Tests: DependencyGraph (Phase 3, Batch 5)+-- ---------------------------------------------------------------------------++-- | 'DepGraph.buildDepGraph' over a pure .drv lookup.+pureDepGraph :: (StorePath -> Either Text Derivation) -> Derivation -> StorePath -> Either Text DepGraph.DepGraph+pureDepGraph readDrv rootDrv rootPath = runIdentity (DepGraph.buildDepGraph (Identity . readDrv) rootDrv rootPath)++-- ---------------------------------------------------------------------------+-- Tests: Substituter (Phase 3, Batch 6)+-- ---------------------------------------------------------------------------++-- | A fake HTTP body reader: yields the given chunks, then empty+-- forever (an HTTP BodyReader is just an IO ByteString).+chunkReader :: [BS.ByteString] -> IO (IO BS.ByteString)+chunkReader chunks = do+  ref <- newIORef chunks+  pure $+    atomicModifyIORef' ref $ \case+      [] -> ([], BS.empty)+      (c : cs) -> (cs, c)++-- ---------------------------------------------------------------------------+-- Tests: Store.DB (Phase 2, Batch 1)+-- ---------------------------------------------------------------------------++removeIfExists :: FilePath -> IO ()+removeIfExists path = do+  exists <- doesDirectoryExist path+  when exists (removeDirectoryRecursive path)++-- | A path as upstream's formatter streams a @std::filesystem::path@:+-- through @std::quoted@, in double quotes with a double quote or a+-- backslash inside escaped by a backslash.+quotedAsCxx :: FilePath -> Text+quotedAsCxx path = "\"" <> T.replace "\"" "\\\"" (T.replace "\\" "\\\\" (T.pack path)) <> "\""++-- ---------------------------------------------------------------------------+-- Tests: Push (pure narinfo construction + closure computation)+-- ---------------------------------------------------------------------------++-- | A secret key from the seed, as the text @nix-store+-- --generate-binary-cache-key@ writes (@name:@ and the base64 of the seed+-- and its public half), with the public key.+throwawayKey :: BS.ByteString -> Either String (Text, Signing.PublicKey)+throwawayKey seed = do+  publicKey <- Signing.parseSecretKey (keyText (seed <> BS.replicate ed25519SeedBytes 0)) >>= Signing.toPublicKey+  pure (keyText (seed <> Signing.pkBytes publicKey), publicKey)+  where+    keyText bytes = "test-cache-1:" <> B64.encode bytes++-- | Helper: create a fresh temp store for IO tests.+withTempStore :: (Store -> IO [Bool]) -> IO [Bool]+withTempStore action = do+  tmpBase <- getTemporaryDirectory+  let tmpStore = tmpBase </> "nova-nix-test-store-ops"+  forceRemoveIfExists tmpStore+  createDirectoryIfMissing True tmpStore+  store <- openStore testLogger (StoreDir tmpStore)+  results <- action store+  closeStore store+  forceRemoveIfExists tmpStore+  pure results++-- | 'deleteStorePathRaw' of a name spelled as text, refused as+-- 'storeEntryName' refuses it.+deleteNamed :: Store -> Text -> IO (Either Text DeleteOutcome)+deleteNamed store = either (pure . Left) (deleteStorePathRaw store) . storeEntryName++-- | Recursively restore writable permissions then remove.+-- Needed because addToStore/canonicalizeMetadata makes paths read-only.+forceRemoveIfExists :: FilePath -> IO ()+forceRemoveIfExists path = do+  exists <- doesDirectoryExist path+  when exists $ do+    restoreWritable path+    removeDirectoryRecursive path++-- | Give a tree's owner write permission on everything in it, so it can be+-- removed.  A symlink is passed over, never followed: it has no mode of+-- its own, and what it names, such as a chroot's /dev/fd naming+-- /proc/self/fd, is not the tree's to change.+restoreWritable :: FilePath -> IO ()+restoreWritable path = do+  isLink <- Dir.pathIsSymbolicLink path+  unless isLink $ do+    isDir <- doesDirectoryExist path+    when isDir $ do+      perms <- getPermissions path+      -- Read and search too, for a directory a test left closed.+      Dir.setPermissions path (Dir.setOwnerWritable True (Dir.setOwnerReadable True (Dir.setOwnerSearchable True perms)))+      entries <- Dir.listDirectory path+      mapM_ (restoreWritable . (path </>)) entries+    isFile <- Dir.doesFileExist path+    when isFile $ do+      perms <- getPermissions path+      Dir.setPermissions path (Dir.setOwnerWritable True perms)++-- | A test archive's entry path.  The paths the tests pass are short+-- literals, so encoding one cannot fail; 'error' marks a setup bug, not a+-- test failure.+tarPathOrDie :: Bool -> FilePath -> TarEntry.TarPath+tarPathOrDie isDir p =+  either (error . ("test tar path: " ++)) id (TarEntry.toTarPath isDir p)++tarDir :: FilePath -> TarEntry.Entry+tarDir p = TarEntry.directoryEntry (tarPathOrDie True p)++tarFile :: FilePath -> BL.ByteString -> TarEntry.Entry+tarFile p = TarEntry.fileEntry (tarPathOrDie False p)++-- ---------------------------------------------------------------------------+-- Tests: profiles+-- ---------------------------------------------------------------------------++-- | A store path of a test's own, by the letter its hash ends in and its+-- name.+profileFixture :: Char -> Text -> StorePath+profileFixture letter = StorePath (T.replicate 31 "0" <> T.singleton letter)++-- ---------------------------------------------------------------------------+-- Tests: NAR and hash known-answer vectors+-- ---------------------------------------------------------------------------++-- | Encode one NAR string per the spec: little-endian u64 length, the+-- bytes, zero-padding to the next 8-byte boundary.  Written here from the+-- format definition, deliberately independent of nova-cache's encoder, so+-- these vectors pin the wire layout rather than the library against+-- itself.+narSpecStr :: BS.ByteString -> BS.ByteString+narSpecStr s = lenLE <> s <> padding+  where+    n = BS.length s+    lenLE = BS.pack [fromIntegral ((n `shiftR` (8 * i)) .&. 0xff) | i <- [0 .. 7]]+    padding = BS.replicate ((8 - n `mod` 8) `mod` 8) 0++-- | Hand-encoded NAR of a directory holding an executable, a plain file,+-- and a symlink - covering entry ordering, the executable marker, content+-- padding, and all node kinds.+narSpecVector :: BS.ByteString+narSpecVector =+  BS.concat $+    map+      narSpecStr+      [ "nix-archive-1",+        "(",+        "type",+        "directory",+        "entry",+        "(",+        "name",+        "bin",+        "node",+        "(",+        "type",+        "directory",+        "entry",+        "(",+        "name",+        "tool",+        "node",+        "(",+        "type",+        "regular",+        "executable",+        "",+        "contents",+        "#!x",+        ")",+        ")",+        ")",+        ")",+        "entry",+        "(",+        "name",+        "data.txt",+        "node",+        "(",+        "type",+        "regular",+        "contents",+        "hello\n",+        ")",+        ")",+        "entry",+        "(",+        "name",+        "link",+        "node",+        "(",+        "type",+        "symlink",+        "target",+        "data.txt",+        ")",+        ")",+        ")"+      ]++-- | Hand-encoded NAR of just @data.txt@, for the on-disk addToStore vector.+-- No executable entry, so the vector stays a fixture for addToStore rather+-- than for the exec bit; 'testExecBit' covers that on both platforms.+narSpecFileVector :: BS.ByteString+narSpecFileVector =+  BS.concat $+    map+      narSpecStr+      [ "nix-archive-1",+        "(",+        "type",+        "directory",+        "entry",+        "(",+        "name",+        "data.txt",+        "node",+        "(",+        "type",+        "regular",+        "contents",+        "hello\n",+        ")",+        ")",+        ")"+      ]++-- | Fetch a path as a build does, from the first cache that offers it: the+-- reference query, then the fetch from its substitute.  A path no cache+-- offers is 'Subst.SubstNotFound', and a query that fails is+-- 'Subst.SubstError' with its message.+offeredThenFetched :: FetchRetryPolicy -> RetryEffects IO -> Store -> [Subst.CacheConfig] -> StorePath -> IO Subst.SubstResult+offeredThenFetched policy effects store caches sp = do+  offer <- evalStateT (Subst.queryReferencesWith testLogger policy effects Realise.NoFallback caches sp) Subst.emptyCacheMemo+  case offer of+    Realise.Offered substitute _ -> Subst.fetchSubstituteWith policy effects store substitute+    Realise.NotOffered -> pure Subst.SubstNotFound+    Realise.QueryFailed failure -> pure (Subst.SubstError failure)++-- | The substitute a cache offered, if one did.+offeredSubstitute :: Realise.Offer s -> Maybe s+offeredSubstitute (Realise.Offered substitute _) = Just substitute+offeredSubstitute Realise.NotOffered = Nothing+offeredSubstitute (Realise.QueryFailed _) = Nothing++-- | What a loopback cache answers for paths with their references: each+-- one's narinfo, signed by 'sigTestKeyText' and naming them, at+-- 'narInfoRequest', and its NAR ('servedNar'), uncompressed at+-- 'narRequest'.  Any other request is a 404.  With the public key that+-- verifies the narinfos.+servedPaths :: [(StorePath, [StorePath])] -> Either String (Text, BS.ByteString -> Reply)+servedPaths entries = do+  publicKey <- Signing.renderPublicKey <$> (Signing.parseSecretKey sigTestKeyText >>= Signing.toPublicKey)+  answers <- Map.fromList . concat <$> traverse served entries+  pure (publicKey, \target -> Send (maybe (httpResponse "404 Not Found" "") (httpResponse "200 OK") (Map.lookup target answers)))+  where+    served (path, references) = do+      (_, narInfo) <- signedTestNarInfo path references (narUrl path) (servedNar path)+      pure [(narInfoRequest path, TE.encodeUtf8 narInfo), (narRequest path, servedNar path)]+    narUrl path = "nar/" <> spName path <> ".nar"++-- | The request target of a path's narinfo.+narInfoRequest :: StorePath -> BS.ByteString+narInfoRequest path = "/" <> TE.encodeUtf8 (spHash path) <> ".narinfo"++-- | The request target of a path's NAR in 'servedPaths'.+narRequest :: StorePath -> BS.ByteString+narRequest path = "/nar/" <> TE.encodeUtf8 (spName path) <> ".nar"++-- | The NAR 'servedPaths' serves for a path: one file holding its name.+servedNar :: StorePath -> BS.ByteString+servedNar path = NAR.serialise (NAR.NarRegular False (TE.encodeUtf8 (spName path) <> "\n"))++-- | Every derivation reachable from @roots@ through input derivations, keyed+-- by @.drv@ path, as the evaluation session recorded them.+sessionClosure :: (MonadEval m) => [Text] -> m (Map.Map Text Derivation)+sessionClosure = go Map.empty+  where+    go seen [] = pure seen+    go seen (path : rest)+      | Map.member path seen = go seen rest+      | otherwise = do+          recorded <- lookupSessionDrv path+          case recorded of+            Nothing -> throwEvalError ("no .drv was recorded for " <> path)+            Just drv ->+              go (Map.insert path drv seen) (map (storePathToText defaultStoreDir) (Map.keys (drvInputDrvs drv)) ++ rest)++-- ---------------------------------------------------------------------------+-- builtins.fetchGit against a real repository+-- ---------------------------------------------------------------------------++-- | One git command against a fixture repository, identity and signing+-- pinned so no host configuration participates.  Nonzero exit throws+-- with git's stderr, failing the calling test loudly.+fixtureGit :: FilePath -> [String] -> IO Text+fixtureGit dir args = do+  (code, out, errOut) <-+    Proc.readCreateProcessWithExitCode+      (Proc.proc "git" (["-C", dir, "-c", "user.name=nova-nix-test", "-c", "user.email=test@nova-nix.invalid", "-c", "commit.gpgsign=false", "-c", "core.autocrlf=false"] ++ args))+      ""+  case code of+    ExitSuccess -> pure (T.strip (T.pack out))+    ExitFailure n -> fail ("fixture git " ++ unwords args ++ " exited " ++ show n ++ ": " ++ errOut)++-- | A repository whose history is one commit per given file, oldest+-- first; returns the commit SHAs in that order.  SHA wants are enabled+-- up front: a pinned rev that is no branch tip is only fetchable when+-- the serving side allows it, the same opt-in real servers use.+makeGitFixture :: FilePath -> [(FilePath, Text)] -> IO [Text]+makeGitFixture dir files = do+  Dir.createDirectoryIfMissing True dir+  _ <- fixtureGit dir ["init", "--quiet"]+  _ <- fixtureGit dir ["config", "uploadpack.allowAnySHA1InWant", "true"]+  mapM commitOne files+  where+    commitOne (name, contents) = do+      BS.writeFile (dir </> name) (TE.encodeUtf8 contents)+      _ <- fixtureGit dir ["add", "-A"]+      _ <- fixtureGit dir ["commit", "--quiet", "-m", name]+      fixtureGit dir ["rev-parse", "HEAD"]++-- | 'evalNixIO' against an explicit store directory, for expressions+-- whose evaluation writes store objects.+evalNixIOStore :: StoreDir -> FilePath -> Text -> IO (Either Text NixValue)+evalNixIOStore storeDir baseDir source = do+  st <- testEvalState storeDir baseDir+  evalNixIOIn st baseDir source++-- | Evaluate the source under the IO evaluator in the given state.+evalNixIOIn :: EvalState -> FilePath -> Text -> IO (Either Text NixValue)+evalNixIOIn st baseDir source = case parseNix baseDir testOrigin (TE.encodeUtf8 source) of+  Left err -> pure (Left (T.pack (show err)))+  Right parsed -> runEvalIO st (evalParsed (pure (evalBaseEnv st)) parsed)++-- | Whether a node has the form 'canonicalizeMetadata' gives it.  On+-- POSIX that is the given mode and the store's time, as @lstat@ reads+-- them.  Windows has no mode, so there it is a file or directory that is+-- read-only and has the store's time.+canonicalAs :: Word32 -> FilePath -> IO TestResult+canonicalAs expected path = do+  status <- nodeStatus path+  case status of+    Just found -> pure (assertEqual (T.pack path) (NodeStatus expected storeModificationTime) found)+    Nothing -> do+      perms <- getPermissions path+      time <- Dir.getModificationTime path+      pure (assertEqual (T.pack path) (False, storeTime) (writable perms, time))+  where+    storeTime = posixSecondsToUTCTime (fromIntegral storeModificationTime)++-- ---------------------------------------------------------------------------+-- Tests: fromATerm + Derivation Output Population (Phase 2, Batch 3)+-- ---------------------------------------------------------------------------++-- | A simple test derivation for round-trip testing.+simpleTestDrv :: Derivation+simpleTestDrv =+  Derivation+    { drvOutputs =+        [ DerivationOutput+            { doName = "out",+              doPath = StorePath "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "hello-1.0",+              doHashAlgo = "",+              doHash = ""+            }+        ],+      drvInputDrvs = Map.empty,+      drvInputSrcs = [],+      drvPlatform = X86_64_Linux,+      drvBuilder = "/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-bash-5.2/bin/bash",+      drvArgs = ["-e", "/nix/store/cccccccccccccccccccccccccccccccc-stdenv/setup"],+      drvEnv = Map.fromList [("name", "hello-1.0"), ("system", "x86_64-linux")]+    }++-- ---------------------------------------------------------------------------+-- Tests: input-addressed derivations+-- ---------------------------------------------------------------------------++-- | A derivation name the store accepts, short enough that every output's+-- composed name is accepted too.+genDrvName :: QC.Gen Text+genDrvName = T.pack <$> ((:) <$> QC.elements nameStart <*> QC.resize 15 (QC.listOf (QC.elements (nameStart <> "+-._?="))))+  where+    nameStart = ['a' .. 'z'] <> ['A' .. 'Z'] <> ['0' .. '9']++-- | A store path of a generated name, its hash in the nix-base32 alphabet.+genFixturePath :: Text -> QC.Gen StorePath+genFixturePath suffix = StorePath <$> genTextOf 32 "0123456789abcdfghijklmnpqrsvwxyz" <*> ((<> suffix) <$> genDrvName)++-- | Text of a given length drawn from an alphabet.+genTextOf :: Int -> String -> QC.Gen Text+genTextOf len alphabet = T.pack <$> QC.vectorOf len (QC.elements alphabet)++-- ---------------------------------------------------------------------------+-- Tests: Builder (Phase 2, Batch 4)+-- ---------------------------------------------------------------------------++-- | The @.drv@ path a builder test hands 'buildDerivation'.  Only a failure+-- message that names the derivation reads it.+testDrvPath :: StorePath+testDrvPath = StorePath (T.replicate 32 "d") "test-build.drv"++-- | Create a minimal Derivation for builder tests.+-- The shell path is discovered once via 'findTestShell' and threaded through.+-- All scripts are POSIX shell - bash is used on every platform - and may+-- run the host's own tools ('withHostTools').+mkTestBuildDrv :: Text -> StorePath -> Text -> Derivation+mkTestBuildDrv shell outSP script =+  withHostTools+    Derivation+      { drvOutputs =+          [ DerivationOutput+              { doName = "out",+                doPath = outSP,+                doHashAlgo = "",+                doHash = ""+              }+          ],+        drvInputDrvs = Map.empty,+        drvInputSrcs = [],+        drvPlatform = currentPlatform,+        drvBuilder = TE.encodeUtf8 shell,+        drvArgs = ["-c", TE.encodeUtf8 script],+        drvEnv = Map.fromList [("name", "test-build"), ("system", TE.encodeUtf8 (platformToText currentPlatform))]+      }++-- | What a test derivation that runs the host's own tools sets so that it+-- finds them, as any derivation must name the programs it runs: on Unix+-- a @PATH@ of the directories they are in, since a build's own names none;+-- on Windows nothing, since a build's @PATH@ there holds the test shell's+-- own tools.+hostToolsEnv :: Map.Map Text BS.ByteString+hostToolsEnv+  | SI.os == "mingw32" = Map.empty+  | otherwise = Map.singleton "PATH" "/usr/bin:/bin"++-- | A test derivation with 'hostToolsEnv' among its variables, its own+-- winning.+withHostTools :: Derivation -> Derivation+withHostTools drv = drv {drvEnv = Map.union (drvEnv drv) hostToolsEnv}++-- | 'hostToolsEnv' as attributes of a derivation written in source.+hostToolsAttrs :: Text+hostToolsAttrs = Map.foldrWithKey (\name value rest -> name <> " = \"" <> TE.decodeUtf8 value <> "\"; " <> rest) "" hostToolsEnv++-- ---------------------------------------------------------------------------+-- Tests: CLI Integration (Phase 2, Batch 5)+-- ---------------------------------------------------------------------------++-- | End-to-end: eval .nix source, extract derivation, build, verify output.+evalAndBuild :: StoreDir -> Text -> IO (Either Text (BuildResult, Store))+evalAndBuild storeDir source = do+  case parseNix testBaseDir testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left ("parse error: " <> T.pack (show err)))+    Right parsed -> do+      -- The SAME store the build below is given.  Evaluating against the+      -- platform default while building elsewhere is what let a store dir+      -- honored on writes but not on reads pass the whole suite.+      st <- testEvalState storeDir "."+      evalResult <- runEvalIO st $ do+        val <- evalParsed (pure (evalBaseEnv st)) parsed+        -- What the CLI driver does: force drvPath, which runs+        -- derivationStrict (so a missing required attr surfaces as an eval+        -- error) and records the .drv the build reads back by that path.+        drvPathThunk <- case val of+          VAttrs attrs -> attrSetLookup "drvPath" attrs+          _ -> pure Nothing+        case drvPathThunk of+          Just thunk -> do+            pathVal <- force thunk+            case pathVal of+              VStr pathBytes _ -> lookupSessionDrv (bytesText pathBytes)+              _ -> pure Nothing+          Nothing -> pure Nothing+      case evalResult of+        Left err -> pure (Left ("eval error: " <> err))+        Right Nothing -> pure (Left "result is not a derivation")+        Right (Just drv) -> do+          store <- openStore testLogger storeDir+          let config = defaultBuildConfig storeDir+          -- What the CLI driver does before building, in the same+          -- order: eval has no store DB handle, so anything it wrote+          -- is registered here or not at all.  Skipping it made this+          -- harness unable to see a whole class of driver bug.+          sourceCache <- readIORef (esSourcePathCache st)+          storeWrites <- readIORef (esStoreWriteCache st)+          materializeEvalSources store (sourceCopies sourceCache)+          materializeEvalStoreWrites store storeWrites+          result <- buildDerivation config store drv testDrvPath+          pure (Right (result, store))++-- ---------------------------------------------------------------------------+-- Tests: realising a string's context+-- ---------------------------------------------------------------------------++-- | The operations of a read-only session that should add and realise+-- nothing: each is a failure the test sees.+unexpectedOps :: StoreOps IO+unexpectedOps =+  StoreOps+    { soQueries = StoreQueries {sqValidPaths = \_ -> pure Set.empty, sqReferences = \_ -> pure (Right Set.empty)},+      soAddEvalObjects = \_ -> pure (Left "an add no test asked for"),+      soAddSourceTree = \_ _ _ -> pure (Left "a tree no test asked for"),+      soBuild = \requests -> pure (Left (BuildStop ("a build no test asked for: " <> T.pack (show requests)) 1)),+      soCheck = \_ -> pure (Left (BuildStop "a check no test asked for" 1)),+      soAddOutLinkRoot = \_ _ -> pure (Left "a root no test asked for"),+      soEvalWrites = WrittenInDirectory+    }++-- ---------------------------------------------------------------------------+-- Tests: trust+-- ---------------------------------------------------------------------------++-- | The smallest Portable Executable the scanner recognises: an @MZ@+-- header whose @e_lfanew@, at 0x3C, points at a @PE\\0\\0@ signature at+-- 0x40.+trustPe :: BS.ByteString+trustPe = "MZ" <> BS.replicate 0x3A 0 <> BS.pack [0x40, 0, 0, 0] <> "PE\0\0"++-- ---------------------------------------------------------------------------+-- Arena lifecycle guard (C FFI)+-- ---------------------------------------------------------------------------++-- | Run as a child, evaluate one expression under the IO evaluator, which+-- writes traces and warnings to stderr as it goes, then write its failure+-- to the same stream, so the parent reads them in the order they came.+evalChildFlag :: String+evalChildFlag = "--eval-child"++evalChild :: String -> IO ()+evalChild source = do+  result <- evalNixIO "." (T.pack source)+  either (\err -> hPutStrLn stderr ("error: " <> T.unpack err)) (const (pure ())) result++-- | Evaluate the source in a child process running 'evalChild' and+-- compare the lines it wrote to stderr with the expected ones.+emits :: Text -> Text -> [Text] -> IO Bool+emits label source expected = runTestM label $ do+  self <- getExecutablePath+  (_, _, err) <- Proc.readCreateProcessWithExitCode (Proc.proc self [evalChildFlag, T.unpack source]) ""+  pure (assertEqual label expected (T.lines (T.pack err)))++-- | Run an action in an evaluation session with no search path, as the+-- suite and its children run theirs; a state made inside it is its own.+inTestSession :: IO a -> IO a+inTestSession action = do+  storeDir <- evalNixIOStoreDir+  withEvalSession (SessionSettings unrestrictedPolicy (pure []) storeDir testBaseDir RegionsCollect (ReadOnlySession (localQueries storeDir) unexpectedOps) testLogger) (const action)++-- ---------------------------------------------------------------------------+-- Tests: store-path name validation at write sinks+-- ---------------------------------------------------------------------------++-- | Entry names upstream's restore writes on POSIX as it finds them and+-- Windows cannot hold, each as compared against @nix-store --restore@+-- 2.33.2: device stems (one with a superscript digit), trailing dots and+-- spaces, colons (perl's man pages carry them), a backslash, the+-- punctuation Win32 reserves, a control character, and links pointing+-- at such names.+posixOnlyEntries :: [(BS.ByteString, NAR.NarEntry)]+posixOnlyEntries =+  [ ("COM1", NAR.NarRegular False "com1"),+    ("ExtUtils::MakeMaker.3", NAR.NarRegular False "man"),+    ("LPT\xC2\xB9.txt", NAR.NarRegular False "lpt"),+    ("NUL", NAR.NarRegular False "nul"),+    ("a:b", NAR.NarRegular False "colon"),+    ("a\\b", NAR.NarRegular False "backslash"),+    ("aux.c", NAR.NarRegular False "aux"),+    ("con.h", NAR.NarRegular False "con"),+    ("ctl\x01", NAR.NarRegular False "control"),+    ("dir.", NAR.NarDirectory [("prn", NAR.NarRegular True "prn")]),+    ("link-aux", NAR.NarSymlink "aux.c"),+    ("link-colon", NAR.NarSymlink "a:b"),+    ("link-dot", NAR.NarSymlink "x."),+    ("q\"*?<>|", NAR.NarRegular False "reserved"),+    ("x.", NAR.NarRegular False "dot"),+    ("y ", NAR.NarRegular False "space")+  ]++-- ---------------------------------------------------------------------------+-- Bytecode tags: what the compiler writes decodes back, and nothing else does+-- ---------------------------------------------------------------------------++-- | A lambda's formals decoded from the bytecode ('decodeBcFormals'),+-- failing on a default kind the compiler never writes.+decodeFormals :: Word8 -> Word32 -> IO (Maybe EvalFormals)+decodeFormals = decodeBcFormals (\kind -> ioError (userError ("a formal's default has kind " <> show kind)))++-- | The bindings of a compiled set or let, their names counted.+compiledBindings :: Word32 -> IO BcBindings+compiledBindings idx = do+  (count, dataOff) <- cbcCountedPayload idx =<< cbcArg1 idx+  decodeBcBindings count dataOff++-- ---------------------------------------------------------------------------+-- Tests: substituter signature verification (the --trusted-key trust gate)+-- ---------------------------------------------------------------------------++-- | Deterministic Ed25519 test keys: a nix secret key file is+-- seed(32) + public(32), and both signing and public-key derivation use+-- only the seed, so the public half can be zeros here.  Both keys carry+-- the SAME name so the wrong-key test exercises the cryptographic+-- verification, not just the name comparison.+sigTestKeyText, sigTestWrongKeyText :: Text+sigTestKeyText = "test-key-1:" <> B64.encode (BS.pack ([1 .. 32] ++ replicate 32 0))+sigTestWrongKeyText = "test-key-1:" <> B64.encode (BS.pack ([101 .. 132] ++ replicate 32 0))++-- | The key 'sigTestKeyText' signs with as a key file holds it, and as+-- upstream reads one: its seed, then the public key of that seed, which+-- upstream reads off as the key's public key, where 'sigTestKeyText'+-- has zeros.+sigTestSecretKeyFile :: Either String BS.ByteString+sigTestSecretKeyFile = do+  secretKey <- Signing.parseSecretKey sigTestKeyText+  publicKey <- Signing.toPublicKey secretKey+  pure (TE.encodeUtf8 (Signing.skName secretKey <> ":" <> B64.encode (BS.take ed25519SeedBytes (Signing.skBytes secretKey) <> Signing.pkBytes publicKey)) <> "\n")++-- | The narinfo of a path whose NAR is these bytes, served uncompressed+-- at this URL and naming these references, signed by 'sigTestKeyText',+-- with the public key that verifies it.  Left on any setup failure.+signedTestNarInfo :: StorePath -> [StorePath] -> Text -> BS.ByteString -> Either String (Text, Text)+signedTestNarInfo path references url nar = do+  secretKey <- Signing.parseSecretKey sigTestKeyText+  publicKey <- Signing.toPublicKey secretKey+  sig <- Signing.sign secretKey unsigned+  pure (Signing.renderPublicKey publicKey, NarInfo.renderNarInfo unsigned {NarInfo.niSigs = [sig]})+  where+    unsigned =+      NarInfo.NarInfo+        { NarInfo.niStorePath = storePathToText defaultStoreDir path,+          NarInfo.niUrl = url,+          NarInfo.niCompression = "none",+          NarInfo.niFileHash = Nothing,+          NarInfo.niFileSize = Nothing,+          NarInfo.niNarHash = CHash.formatNixHash (CHash.hashBytes nar),+          NarInfo.niNarSize = fromIntegral (BS.length nar),+          NarInfo.niReferences = map storePathBasename references,+          NarInfo.niDeriver = Nothing,+          NarInfo.niSigs = [],+          NarInfo.niCA = Nothing+        }++-- | A test path as the config expander names it.  Test paths spelled+-- this way are ASCII, which 'OP.unsafeFromChar' narrows to one path unit+-- exactly on every platform.+asciiOsPath :: FilePath -> OsPath+asciiOsPath = OP.pack . map OP.unsafeFromChar++-- ---------------------------------------------------------------------------+-- Tests: resolver static globals stay in sync with the root env+-- ---------------------------------------------------------------------------++-- | The names upstream 2.24.9's base environment binds with default+-- settings, recorded from its source: every @addConstant@ and @addPrimOp@+-- in @createBaseEnv@ (src/libexpr/primops.cc) and every @RegisterPrimOp@+-- in libexpr and libflake not gated on an experimental feature, under the+-- name it registers, and the three flake builtins @__getFlake@,+-- @__parseFlakeRef@ and @__flakeRefToString@, which 2.36.0's @nix@ adds to+-- every evaluator whatever the features (src/libflake/settings.cc).+-- @__importNative@ and @__exec@ need+-- @allow-unsafe-native-code-during-evaluation@ and are not here.+upstreamBaseEnvNames :: Set.Set Text+upstreamBaseEnvNames =+  Set.fromList+    [ "__add",+      "__addDrvOutputDependencies",+      "__addErrorContext",+      "__all",+      "__any",+      "__appendContext",+      "__attrNames",+      "__attrValues",+      "__bitAnd",+      "__bitOr",+      "__bitXor",+      "__catAttrs",+      "__ceil",+      "__compareVersions",+      "__concatLists",+      "__concatMap",+      "__concatStringsSep",+      "__convertHash",+      "__currentSystem",+      "__currentTime",+      "__deepSeq",+      "__div",+      "__elem",+      "__elemAt",+      "__fetchurl",+      "__filter",+      "__filterSource",+      "__findFile",+      "__flakeRefToString",+      "__floor",+      "__foldl'",+      "__fromJSON",+      "__functionArgs",+      "__genList",+      "__genericClosure",+      "__getAttr",+      "__getContext",+      "__getEnv",+      "__getFlake",+      "__groupBy",+      "__hasAttr",+      "__hasContext",+      "__hashFile",+      "__hashString",+      "__head",+      "__intersectAttrs",+      "__isAttrs",+      "__isBool",+      "__isFloat",+      "__isFunction",+      "__isInt",+      "__isList",+      "__isPath",+      "__isString",+      "__langVersion",+      "__length",+      "__lessThan",+      "__listToAttrs",+      "__mapAttrs",+      "__match",+      "__mul",+      "__nixPath",+      "__nixVersion",+      "__parseDrvName",+      "__parseFlakeRef",+      "__partition",+      "__path",+      "__pathExists",+      "__readDir",+      "__readFile",+      "__readFileType",+      "__replaceStrings",+      "__seq",+      "__sort",+      "__split",+      "__splitVersion",+      "__storeDir",+      "__storePath",+      "__stringLength",+      "__sub",+      "__substring",+      "__tail",+      "__toFile",+      "__toJSON",+      "__toPath",+      "__toXML",+      "__trace",+      "__traceVerbose",+      "__tryEval",+      "__typeOf",+      "__unsafeDiscardOutputDependency",+      "__unsafeDiscardStringContext",+      "__unsafeGetAttrPos",+      "__warn",+      "__zipAttrsWith",+      "abort",+      "baseNameOf",+      "break",+      "builtins",+      "derivation",+      "derivationStrict",+      "dirOf",+      "false",+      "fetchGit",+      "fetchMercurial",+      "fetchTarball",+      "fromTOML",+      "import",+      "isNull",+      "map",+      "null",+      "placeholder",+      "removeAttrs",+      "scopedImport",+      "throw",+      "toString",+      "true"+    ]++-- ---------------------------------------------------------------------------+-- Tests: evaluation policy - restricted and pure modes+-- ---------------------------------------------------------------------------++-- | The policies under test.+restrictedPolicy, purePolicy :: EvalPolicy+restrictedPolicy = unrestrictedPolicy {epRestrictEval = True}+purePolicy = unrestrictedPolicy {epPureEval = True}++-- | Parse and evaluate in 'PureEval' with the given policy's builtins+-- table, for the constants the table itself decides.+evalNixWith :: EvalPolicy -> Text -> Either Text NixValue+evalNixWith policy source = case parseNixWithScope (rootScopeNames policy) testBaseDir testOrigin (TE.encodeUtf8 source) of+  Left err -> Left (sourceFailure err)+  Right parsed -> runPureEval (evalParsed (builtinEnv policy 0 []) parsed)++-- | Run an action with a variable set (to an empty value too, which+-- 'setEnv' would unset), restoring what the variable held afterwards.+withEnvVar :: String -> String -> IO a -> IO a+withEnvVar name value action =+  bracket (lookupEnv name) restore (const (Blank.setEnv name value True >> action))+  where+    restore = maybe (unsetEnv name) (\saved -> Blank.setEnv name saved True)++-- ---------------------------------------------------------------------------+-- Logging+-- ---------------------------------------------------------------------------++-- | The logger the suite's stores, builds and evaluations report to:+-- each message and each build line on stderr, as the command line+-- writes them, with every escape sequence dropped from a build line.+testLogger :: Logger+testLogger = handleLogger DropEscapes stderr++-- ---------------------------------------------------------------------------+-- Generators shared by the daemon and store tests+-- ---------------------------------------------------------------------------++-- | A signature: a key name of letters, dashes, dots and digits, and+-- bytes that are not empty.+genSignature :: QC.Gen Proto.Signature+genSignature = QC.suchThatMap ((,) <$> keyName <*> (BS.pack <$> QC.resize 70 (QC.listOf1 QC.arbitrary))) (uncurry Proto.signatureFromParts)+  where+    keyName = BS8.pack <$> QC.listOf1 (QC.elements (['a' .. 'z'] ++ "-.0"))++-- | A few signatures, possibly none.+genSignatures :: QC.Gen (Set.Set Proto.Signature)+genSignatures = Set.fromList <$> QC.resize 3 (QC.listOf genSignature)++-- | A content address under each method and algorithm upstream's has.+genContentAddress :: QC.Gen Proto.ContentAddress+genContentAddress = do+  method <- QC.elements [Proto.TextMethod, Proto.FixedMethod FlatIngestion, Proto.FixedMethod NarIngestion]+  algo <- QC.elements ["md5", "sha1", "sha256", "sha512"]+  QC.suchThatMap (BS.pack <$> QC.vectorOf (fromMaybe 0 (hashAlgoBytes algo)) QC.arbitrary) (Proto.contentAddressFromParts method algo)
+ test/Test/Key.hs view
@@ -0,0 +1,131 @@+-- | Tests of signing keys as @key generate-secret@ and+-- @key convert-secret-to-public@ make and read them ("Nix.Key").+module Test.Key+  ( testKeys,+  )+where++import Control.Exception (bracket_)+import Control.Monad (void)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BS8+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Nix.Key (ColonBase64Refusal (..), KeyRefusal (..), generateSecretKey, keyRefusalMessage, parseColonBase64, parseSecretKey, renderColonBase64, renderPublicKey, renderSecretKey)+import Nix.Push.Directory (loadSecretKeyFile, signNarInfo)+import qualified NovaCache.NarInfo as NarInfo+import qualified NovaCache.Signing as Signing+import System.Directory (createDirectoryIfMissing, getTemporaryDirectory)+import System.FilePath ((</>))+import Test.Harness (TestResult (..), andThen, assertEqual, assertRight, forceRemoveIfExists, runTest, runTestM)+import qualified Test.QuickCheck as QC++-- | Keys: upstream's own example of a secret key and the public key its+-- documentation prints for it, the keys a generation makes, which push+-- signs with and a substituter verifies under the converted key, the+-- spelling read back, and each refusal in upstream's words.+testKeys :: IO [Bool]+testKeys = do+  putStrLn "key"+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-key"+  bracket_ (forceRemoveIfExists root >> createDirectoryIfMissing True root) (forceRemoveIfExists root) $+    sequence+      [ -- The pair in upstream's documentation of nix key+        -- convert-secret-to-public, read as its example reads it, from+        -- echo, with the line feed echo adds.+        runTest "upstream's example secret key gives the public key upstream's documentation prints for it, a line feed after it read" $+          assertRight "read" (parseSecretKey (upstreamSecret <> "\n")) $ \secretKey ->+            assertEqual "public key" "cache.example.org-0:tVeHVMaFaKi8lieGBErmScEOuxlSJLA7eO6IPrT1VGc=" (renderPublicKey secretKey)+              `andThen` assertEqual "secret key" upstreamSecret (renderSecretKey secretKey),+        runTestM "a generated key is its name, a colon and 88 characters of base64, and two are not the same" $ do+          first <- renderSecretKey <$> generateSecretKey "cache.example.org-1"+          second <- renderSecretKey <$> generateSecretKey "cache.example.org-1"+          pure $+            assertEqual "shape" (Just 88) (BS.length <$> BS.stripPrefix "cache.example.org-1:" first)+              `andThen` assertEqual "different" True (first /= second),+        -- Push refuses a key whose second half is not its seed's public+        -- key, so loading it checks the halves of the generated key.+        runTestM "a generated key loads as push's secret key file, signs a narinfo, and the signature verifies under its converted public key" $ do+          secretKey <- generateSecretKey "cache.example.org-1"+          let keyFile = root </> "secret-key"+          BS.writeFile keyFile (renderSecretKey secretKey)+          loaded <- loadSecretKeyFile keyFile+          pure $+            assertRight "loaded" loaded $ \pushKey ->+              assertRight "signed" (signNarInfo pushKey narInfo) $ \signed ->+                assertRight "public key" (Signing.parsePublicKey (TE.decodeLatin1 (renderPublicKey secretKey))) $ \publicKey ->+                  assertEqual "verified" [True] (map (Signing.verify publicKey signed) (NarInfo.niSigs signed)),+        holds "a key's spelling reads back as itself, its public key its name and its last 32 bytes" $+          QC.forAll ((,) <$> keyName <*> QC.vectorOf 64 QC.arbitrary) $ \(name, bytes) ->+            let spelled = renderColonBase64 name (BS.pack bytes)+             in case parseSecretKey spelled of+                  Right secretKey ->+                    renderSecretKey secretKey QC.=== spelled+                      QC..&&. renderPublicKey secretKey QC.=== renderColonBase64 name (BS.pack (drop 32 bytes))+                  Left refusal -> QC.counterexample (show refusal) False,+        runTest "a spelling with no colon, no name or no bytes is corrupt, and a byte outside base64 is named" $+          assertEqual+            "read"+            [ Left ColonBase64Corrupt,+              Left ColonBase64Corrupt,+              Left ColonBase64Corrupt,+              Left ColonBase64Corrupt,+              Left ColonBase64Corrupt,+              Left (ColonBase64BadCharacter 0x40),+              Right ("k", "\0\0"),+              Right ("k", "\0\0")+            ]+            (map parseColonBase64 ["key", ":AAAA", "k:", "k:=AAAA", "k:A", "k:AA@A", "k:AAA=@", "k:A\nAA\n"]),+        runTest "a refused key is reported as upstream's command reports it, with the trace it adds while decoding" $+          assertEqual+            "messages"+            [ traced "key is corrupt",+              traced "key is corrupt",+              traced "invalid character in Base64 string: '\r'",+              traced "invalid character in Base64 string: ' '",+              "error: secret key is not valid",+              "error: secret key is not valid",+              "error: secret key is not valid"+            ]+            ( map+                (either keyRefusalMessage (const "read") . parseSecretKey)+                [ "no-colon",+                  ":" <> upstreamBase64,+                  "k:" <> BS.take 86 upstreamBase64 <> "\r\n",+                  "k:" <> BS.take 40 upstreamBase64 <> " " <> BS.drop 40 upstreamBase64,+                  "k:AAAA",+                  renderColonBase64 "k" (BS.replicate 63 0),+                  renderColonBase64 "k" (BS.replicate 65 0)+                ]+            ),+        runTest "what follows a padded key's base64 is not read, so a carriage return or a space after it is let be" $+          assertEqual+            "public keys"+            (replicate 2 (Right "cache.example.org-0:tVeHVMaFaKi8lieGBErmScEOuxlSJLA7eO6IPrT1VGc="))+            (map (fmap renderPublicKey . parseSecretKey) [upstreamSecret <> "\r\n", upstreamSecret <> " x"]),+        runTest "a key of the wrong size is refused as such, not as an unreadable one" $+          assertEqual "refusal" (Left SecretKeyNotValid) (void (parseSecretKey "k:AAAA"))+      ]+  where+    upstreamBase64 = "E7lAO+MsPwTFfPXsdPtW8GKui/5ho4KQHVcAGnX+Tti1V4dUxoVoqLyWJ4YESuZJwQ67GVIksDt47og+tPVUZw=="+    upstreamSecret = "cache.example.org-0:" <> upstreamBase64+    traced message = "error:\n       " <> TE.encodeUtf8 (T.singleton '\x2026') <> " while decoding key named ''\n\n       error: " <> message+    keyName = BS8.pack <$> QC.listOf1 (QC.elements (['a' .. 'z'] <> ['0' .. '9'] <> ".-"))+    holds label prop = runTestM label $ do+      result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} prop+      pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))+    narInfo =+      NarInfo.NarInfo+        { NarInfo.niStorePath = "/nix/store/" <> T.replicate 32 "a" <> "-signed",+          NarInfo.niUrl = "nar/a.nar",+          NarInfo.niCompression = "none",+          NarInfo.niFileHash = Nothing,+          NarInfo.niFileSize = Nothing,+          NarInfo.niNarHash = "sha256:1b8m03r63zqhnjf7l5wnldhh7c134ap5vpj0850ymkq1iyzicy5s",+          NarInfo.niNarSize = 120,+          NarInfo.niReferences = [],+          NarInfo.niDeriver = Nothing,+          NarInfo.niSigs = [],+          NarInfo.niCA = Nothing+        }
+ test/Test/Parser.hs view
@@ -0,0 +1,1371 @@+{-# LANGUAGE LambdaCase #-}++-- | Tests of the lexer, the parser and scope resolution.+module Test.Parser+  ( testExprTypes,+    testLexer,+    testLineEndings,+    testParserExprs,+    testParserErrors,+    testSourceBytes,+    testStringAttrKeys,+    testParserIntegration,+    testCurPos,+    testStaticGlobalsSync,+    testUndefinedVariables,+    testUndefinedVariablesIO,+    testSourceBytesIO,+  )+where++import Control.Exception (bracket_, evaluate)+import Control.Monad (when)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BS8+import Data.Maybe (fromMaybe)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import qualified Data.Text.IO as TIO+import Data.Word (Word8)+import Foreign.Ptr (castPtr)+import Nix.Builtins (builtinEnv, rootScopeNames)+import Nix.Eval (NixValue (..), currentSystemStr, emptyContext, unrestrictedPolicy)+import Nix.Eval.CEnv (cenvNameTable)+import Nix.Eval.Types (AttrSet (..), Env (..), attrSetKeys)+import Nix.Expr.Resolve (impureOnlyGlobalNames, staticGlobalNames)+import Nix.Expr.Types+import Nix.Parser (ParseError (..), SourceError (..), parseNix, parsedExpr, parsedNames)+import Nix.Parser.Lexer (Located (..), Token (..), tokenize)+import System.Directory (createDirectoryIfMissing, doesDirectoryExist, getTemporaryDirectory, removeDirectoryRecursive)+import System.FilePath ((</>))+import System.Timeout (timeout)+import Test.Harness (TestResult (..), andThen, assertEqual, assertEval, assertEvalError, assertEvalFail, assertLeft, assertParse, assertParseFail, assertParseIn, assertRight, emits, evalNix, evalNixBytes, evalNixIO, evalNixWith, jsonInFile, nixQuotedPath, positionJson, positionsFile, purePolicy, runTest, runTestIO, runTestM, testBaseDir, testOrigin, testPos, upstreamBaseEnvNames, walkWatchdogMicros)+import qualified Test.QuickCheck as QC++-- ---------------------------------------------------------------------------+-- Test harness+-- ---------------------------------------------------------------------------++-- | Helper: extract just token types from Located list (drop positions and EOF).+tokenTypes :: [Located] -> [Token]+tokenTypes = filter (/= TokEOF) . map locToken++-- | The syntax error a source fails to parse with.+syntaxErrorOf :: Text -> Either Text ParseError+syntaxErrorOf = syntaxErrorOfBytes . TE.encodeUtf8++-- | 'syntaxErrorOf' over source bytes, which need not be UTF-8.+syntaxErrorOfBytes :: BS.ByteString -> Either Text ParseError+syntaxErrorOfBytes source = case parseNix testBaseDir testOrigin source of+  Left (SyntaxError err) -> Right err+  Left other -> Left ("expected a syntax error, got " <> T.pack (show other))+  Right _ -> Left "parsed unexpectedly"++-- ---------------------------------------------------------------------------+-- Tests: Expr types (existing)+-- ---------------------------------------------------------------------------++testExprTypes :: IO [Bool]+testExprTypes = do+  putStrLn "expr/types"+  sequence+    [ runTest "int literal" $+        assertEqual "ELit NixInt" (ELit (NixInt 42)) (ELit (NixInt 42)),+      runTest "bool literal" $+        assertEqual "ELit NixBool" (ELit (NixBool True)) (ELit (NixBool True)),+      runTest "null literal" $+        assertEqual "ELit NixNull" (ELit NixNull) (ELit NixNull),+      runTest "var" $+        assertEqual "EVar" (EVar "x") (EVar "x"),+      runTest "string parts" $+        let parts = [StrLit "hello ", StrInterp (EVar "name")]+         in assertEqual "EStr" (EStr parts) (EStr parts),+      runTest "binary op" $+        let expr = EBinary OpAdd (ELit (NixInt 1)) (ELit (NixInt 2))+         in assertEqual "EBinary" expr expr,+      runTest "lambda" $+        let expr = ELambda (FormalName "x") (EVar "x") NoCaptureInfo+         in assertEqual "ELambda" expr expr,+      runTest "let binding" $+        let expr = ELet [NamedBinding (testPos 1 5) (StaticKey "x") (ELit (NixInt 1))] (EVar "x") NoCaptureInfo+         in assertEqual "ELet" expr expr,+      runTest "attrs" $+        let expr = EAttrs False [NamedBinding (testPos 1 3) (StaticKey "a") (ELit (NixInt 1))] NoCaptureInfo+         in assertEqual "EAttrs" expr expr,+      runTest "if-then-else" $+        let expr = EIf (ELit (NixBool True)) (ELit (NixInt 1)) (ELit (NixInt 2))+         in assertEqual "EIf" expr expr+    ]++-- ---------------------------------------------------------------------------+-- Tests: Lexer+-- ---------------------------------------------------------------------------++testLexer :: IO [Bool]+testLexer = do+  putStrLn "parser/lexer"+  sequence+    [ runTest "integer" $+        assertRight "lex int" (tokenize "<test>" "42") $ \toks ->+          assertEqual "tokens" [TokInt 42] (tokenTypes toks),+      runTest "float" $+        assertRight "lex float" (tokenize "<test>" "3.14") $ \toks ->+          assertEqual "tokens" [TokFloat 3.14] (tokenTypes toks),+      runTest "trailing-dot float lexes as one float token" $+        assertRight "lex trailing-dot" (tokenize "<test>" "12.") $ \toks ->+          assertEqual "tokens" [TokFloat 12.0] (tokenTypes toks),+      -- Maximal munch: a dot-led run with a /-segment is one PATH token+      -- (upstream's PATH regex), while a slashless dot-run is not.+      runTest "dot-relative path lexes as one token" $+        assertRight "lex dot-path" (tokenize "<test>" ".github/x") $ \toks ->+          assertEqual "tokens" [TokPath ".github/x"] (tokenTypes toks),+      runTest "leading-dot float still lexes as float" $+        assertRight "lex dot-float" (tokenize "<test>" ".5") $ \toks ->+          assertEqual "tokens" [TokFloat 0.5] (tokenTypes toks),+      runTest "trailing-dot float with exponent lexes as one float token" $+        assertRight "lex trailing-dot-exp" (tokenize "<test>" "12.e2") $ \toks ->+          assertEqual "tokens" [TokFloat 1200.0] (tokenTypes toks),+      -- Float literals convert with a single rounding (strtod semantics).+      -- The exact value here sits between representable ..992 and ..994,+      -- nearer ..994; rounding whole and fraction separately lands on ..992.+      runTest "float literal rounds once at the 2^53 boundary" $+        assertRight "lex float-tie" (tokenize "<test>" "9007199254740993.5") $ \toks ->+          assertEqual "tokens" [TokFloat 9007199254740994.0] (tokenTypes toks),+      -- A float 10 ^^ exponent overflows on subnormals and flushes to 0.+      runTest "subnormal float literal survives" $+        assertRight "lex float-subnormal" (tokenize "<test>" "1.0e-320") $ \toks ->+          assertEqual "tokens" [TokFloat 1.0e-320] (tokenTypes toks),+      -- Bounded number lexing: a literal's cost must follow its length,+      -- never its exponent's magnitude, and megadigit literals must+      -- resolve promptly.  The watchdog turns a cost regression into a+      -- FAIL instead of a stuck suite; the checks force full values.+      runTestM "huge positive exponent saturates to Infinity" $ do+        let saturated = case tokenize "<test>" "1.0e999999999" of+              Right toks | [TokFloat f] <- tokenTypes toks -> isInfinite f && f > 0+              _ -> False+        outcome <- timeout walkWatchdogMicros (evaluate saturated)+        pure $ case outcome of+          Just True -> Pass+          Just False -> Fail "wrong tokens for a huge positive exponent"+          Nothing -> Fail "lexing did not return promptly",+      runTestM "huge negative exponent saturates to zero" $ do+        let flushed = case tokenize "<test>" "1.0e-999999999" of+              Right toks -> tokenTypes toks == [TokFloat 0.0]+              Left _ -> False+        outcome <- timeout walkWatchdogMicros (evaluate flushed)+        pure $ case outcome of+          Just True -> Pass+          Just False -> Fail "wrong tokens for a huge negative exponent"+          Nothing -> Fail "lexing did not return promptly",+      runTestM "zero mantissa ignores a huge exponent" $ do+        let zeroed = case tokenize "<test>" "0.0e999999999" of+              Right toks -> tokenTypes toks == [TokFloat 0.0]+              Left _ -> False+        outcome <- timeout walkWatchdogMicros (evaluate zeroed)+        pure $ case outcome of+          Just True -> Pass+          Just False -> Fail "wrong tokens for a zero mantissa"+          Nothing -> Fail "lexing did not return promptly",+      runTestM "megadigit integer literal rejects promptly" $ do+        let rejected = case tokenize "<test>" (BS8.replicate 1000000 '9') of+              Left _ -> True+              Right _ -> False+        outcome <- timeout walkWatchdogMicros (evaluate rejected)+        pure $ case outcome of+          Just True -> Pass+          Just False -> Fail "megadigit literal was not rejected"+          Nothing -> Fail "range rejection did not return promptly",+      runTestM "megadigit mantissa still rounds correctly" $ do+        -- 1.999...9e5 sits within half an ulp of 200000.0; the kept-768+        -- digits plus the sticky digit must round it there.+        let rounded = case tokenize "<test>" ("1." <> BS8.replicate 1000000 '9' <> "e5") of+              Right toks -> tokenTypes toks == [TokFloat 200000.0]+              Left _ -> False+        outcome <- timeout walkWatchdogMicros (evaluate rounded)+        pure $ case outcome of+          Just True -> Pass+          Just False -> Fail "wrong rounding for a megadigit mantissa"+          Nothing -> Fail "lexing did not return promptly",+      runTest "true" $+        assertRight "lex true" (tokenize "<test>" "true") $ \toks ->+          assertEqual "tokens" [TokTrue] (tokenTypes toks),+      runTest "false" $+        assertRight "lex false" (tokenize "<test>" "false") $ \toks ->+          assertEqual "tokens" [TokFalse] (tokenTypes toks),+      runTest "null" $+        assertRight "lex null" (tokenize "<test>" "null") $ \toks ->+          assertEqual "tokens" [TokNull] (tokenTypes toks),+      runTest "identifier" $+        assertRight "lex ident" (tokenize "<test>" "foo") $ \toks ->+          assertEqual "tokens" [TokIdent "foo"] (tokenTypes toks),+      runTest "hyphened identifier" $+        assertRight "lex hyphened" (tokenize "<test>" "hello-world") $ \toks ->+          assertEqual "tokens" [TokIdent "hello-world"] (tokenTypes toks),+      runTest "path ./foo" $+        assertRight "lex path" (tokenize "<test>" "./foo") $ \toks ->+          assertEqual "tokens" [TokPath "./foo"] (tokenTypes toks),+      runTest "path ~/foo" $+        assertRight "lex path home" (tokenize "<test>" "~/foo") $ \toks ->+          assertEqual "tokens" [TokPath "~/foo"] (tokenTypes toks),+      runTest "search path" $+        assertRight "lex search path" (tokenize "<test>" "<nixpkgs>") $ \toks ->+          assertEqual "tokens" [TokSearchPath "nixpkgs"] (tokenTypes toks),+      runTest "URI" $+        assertRight "lex uri" (tokenize "<test>" "https://example.com") $ \toks ->+          assertEqual "tokens" [TokUri "https://example.com"] (tokenTypes toks),+      -- Upstream URI = [a-zA-Z][a-zA-Z0-9+.-]*:[uri-char]+ with flex+      -- maximal munch: no // required, and the URI beats identifiers,+      -- keywords, and the lambda colon when it matches more characters.+      runTest "scheme-only URI x:y" $+        assertRight "lex uri x:y" (tokenize "<test>" "x:y") $ \toks ->+          assertEqual "tokens" [TokUri "x:y"] (tokenTypes toks),+      runTest "scheme-only URI mailto" $+        assertRight "lex uri mailto" (tokenize "<test>" "mailto:foo@example.com") $ \toks ->+          assertEqual "tokens" [TokUri "mailto:foo@example.com"] (tokenTypes toks),+      runTest "URI scheme allows + . -" $+        assertRight "lex uri scheme" (tokenize "<test>" "a+b.c:d") $ \toks ->+          assertEqual "tokens" [TokUri "a+b.c:d"] (tokenTypes toks),+      runTest "URI beats keyword by maximal munch" $+        assertRight "lex uri keyword" (tokenize "<test>" "then:x") $ \toks ->+          assertEqual "tokens" [TokUri "then:x"] (tokenTypes toks),+      runTest "hash is not a URI char (starts a comment)" $+        assertRight "lex uri hash" (tokenize "<test>" "http://a#frag") $ \toks ->+          assertEqual "tokens" [TokUri "http://a"] (tokenTypes toks),+      runTest "apostrophe and star are URI chars" $+        assertRight "lex uri quote star" (tokenize "<test>" "http://e.com/a'b*c") $ \toks ->+          assertEqual "tokens" [TokUri "http://e.com/a'b*c"] (tokenTypes toks),+      runTest "lambda colon needs the space" $+        assertRight "lex lambda colon" (tokenize "<test>" "x: y") $ \toks ->+          assertEqual "tokens" [TokIdent "x", TokColon, TokIdent "y"] (tokenTypes toks),+      runTest "underscore cannot start a URI scheme" $+        assertRight "lex underscore colon" (tokenize "<test>" "_a:b") $ \toks ->+          assertEqual "tokens" [TokIdent "_a", TokColon, TokIdent "b"] (tokenTypes toks),+      -- Raw CR/CRLF normalizes to LF in double-quoted strings (upstream+      -- unescapeStr); an escaped CR survives; indented strings keep CR+      -- verbatim because upstream's IND_STRING chunks skip unescapeStr.+      runTest "CRLF in double-quoted string normalizes to LF" $+        assertRight "lex crlf string" (tokenize "<test>" "\"a\r\nb\"") $ \toks ->+          assertEqual "tokens" [TokStringOpen, TokStringLit "a\nb", TokStringClose] (tokenTypes toks),+      runTest "lone CR in double-quoted string normalizes to LF" $+        assertRight "lex cr string" (tokenize "<test>" "\"a\rb\"") $ \toks ->+          assertEqual "tokens" [TokStringOpen, TokStringLit "a\nb", TokStringClose] (tokenTypes toks),+      runTest "escaped CR stays a literal CR" $+        assertRight "lex escaped cr" (tokenize "<test>" "\"a\\\rb\"") $ \toks ->+          assertEqual "tokens" [TokStringOpen, TokStringLit "a\rb", TokStringClose] (tokenTypes toks),+      runTest "indented string keeps CRLF verbatim" $+        assertRight "lex ind crlf" (tokenize "<test>" "''a\r\nb''") $ \toks ->+          assertEqual "tokens" [TokIndStringOpen, TokStringLit "a\r\nb", TokIndStringClose] (tokenTypes toks),+      -- The opener is '' with an optional run of spaces and one newline+      -- (upstream lexer.l); a tab is not part of it.+      runTest "indented string opener consumes trailing spaces and newline" $+        assertRight "lex ind opener" (tokenize "<test>" "''  \n  a''") $ \toks ->+          assertEqual "tokens" [TokIndStringOpen, TokStringLit "  a", TokIndStringClose] (tokenTypes toks),+      runTest "indented string opener stops at a tab" $+        assertRight "lex ind opener tab" (tokenize "<test>" "''\t\na''") $ \toks ->+          assertEqual "tokens" [TokIndStringOpen, TokStringLit "\t\na", TokIndStringClose] (tokenTypes toks),+      runTest "multi-char operators" $+        assertRight "lex ops" (tokenize "<test>" "++ // -> == != && || <= >=") $ \toks ->+          assertEqual+            "tokens"+            [TokConcat, TokUpdate, TokImpl, TokEq, TokNeq, TokAnd, TokOr, TokLte, TokGte]+            (tokenTypes toks),+      runTest "single-char operators" $+        assertRight "lex single ops" (tokenize "<test>" "+ - * ! ? < >") $ \toks ->+          assertEqual+            "tokens"+            [TokPlus, TokMinus, TokStar, TokNot, TokQuestion, TokLt, TokGt]+            (tokenTypes toks),+      runTest "division vs path" $+        assertRight "lex div" (tokenize "<test>" "6 / 3") $ \toks ->+          assertEqual "tokens" [TokInt 6, TokSlash, TokInt 3] (tokenTypes toks),+      runTest "string tokens" $+        assertRight "lex string" (tokenize "<test>" "\"hello\"") $ \toks ->+          assertEqual+            "tokens"+            [TokStringOpen, TokStringLit "hello", TokStringClose]+            (tokenTypes toks),+      runTest "empty string" $+        assertRight "lex empty string" (tokenize "<test>" "\"\"") $ \toks ->+          assertEqual+            "tokens"+            [TokStringOpen, TokStringClose]+            (tokenTypes toks),+      runTest "string interpolation tokens" $+        assertRight "lex interp" (tokenize "<test>" "\"a${x}b\"") $ \toks ->+          assertEqual+            "tokens"+            [ TokStringOpen,+              TokStringLit "a",+              TokInterpOpen,+              TokIdent "x",+              TokInterpClose,+              TokStringLit "b",+              TokStringClose+            ]+            (tokenTypes toks),+      runTest "line comment" $+        assertRight "lex comment" (tokenize "<test>" "# comment\n42") $ \toks ->+          assertEqual "tokens" [TokInt 42] (tokenTypes toks),+      runTest "block comment" $+        assertRight "lex block comment" (tokenize "<test>" "/* comment */ 42") $ \toks ->+          assertEqual "tokens" [TokInt 42] (tokenTypes toks),+      runTest "ellipsis" $+        assertRight "lex ellipsis" (tokenize "<test>" "...") $ \toks ->+          assertEqual "tokens" [TokEllipsis] (tokenTypes toks),+      runTest "punctuation" $+        assertRight "lex punct" (tokenize "<test>" ". @ : ; = ,") $ \toks ->+          assertEqual+            "tokens"+            [TokDot, TokAt, TokColon, TokSemicolon, TokAssign, TokComma]+            (tokenTypes toks),+      runTest "delimiters" $+        assertRight "lex delimiters" (tokenize "<test>" "( ) { } [ ]") $ \toks ->+          assertEqual+            "tokens"+            [TokLParen, TokRParen, TokLBrace, TokRBrace, TokLBracket, TokRBracket]+            (tokenTypes toks),+      runTest "keywords" $+        assertRight "lex keywords" (tokenize "<test>" "if then else let in with assert rec inherit") $ \toks ->+          assertEqual+            "tokens"+            [TokIf, TokThen, TokElse, TokLet, TokIn, TokWith, TokAssert, TokRec, TokInherit]+            (tokenTypes toks),+      runTest "or is identifier" $+        assertRight "lex or" (tokenize "<test>" "or") $ \toks ->+          assertEqual "tokens" [TokIdent "or"] (tokenTypes toks),+      runTest "string escape sequences" $+        assertRight "lex escapes" (tokenize "<test>" "\"\\n\\t\\\\\\\"\"") $ \toks ->+          assertEqual+            "tokens"+            [TokStringOpen, TokStringLit "\n\t\\\"", TokStringClose]+            (tokenTypes toks),+      runTest "a string keeps bytes that are not UTF-8" $+        assertRight "lex invalid UTF-8" (tokenize "<test>" (BS.pack [0x22, 0x61, 0xFF, 0xC3, 0x28, 0x22])) $ \toks ->+          assertEqual "tokens" [TokStringOpen, TokStringLit (BS.pack [0x61, 0xFF, 0xC3, 0x28]), TokStringClose] (tokenTypes toks),+      -- Upstream's column is one past a position's byte offset from the+      -- start of its line (PosTable::operator[], nixexpr.cc at 2.24.9), so+      -- the e-acute's two bytes take two columns and x is at 6.+      runTest "columns count bytes" $+        assertRight "lex columns" (tokenize "<test>" (TE.encodeUtf8 "\"\233\" x")) $ \toks ->+          assertEqual "x" [(1, 6)] [(locLine tok, locCol tok) | tok <- toks, locToken tok == TokIdent "x"],+      runTest "a syntax error's column counts the bytes before it" $+        assertRight "error column" (syntaxErrorOf "\"\233\" )") $ \err ->+          assertEqual "position" (1, 6) (peLine err, peCol err),+      runTest "an escaped newline in an indented string ends a line" $+        assertRight "lex escaped newline" (tokenize "<test>" "''a''\\\n'' x") $ \toks ->+          assertEqual "x" [(2, 4)] [(locLine tok, locCol tok) | tok <- toks, locToken tok == TokIdent "x"],+      -- Upstream's ID class is ASCII (lexer.l), so a letter outside it is+      -- the character no rule but the catch-all takes.+      runTest "a letter outside ASCII starts no token" $+        assertEqual "message" (Left "unexpected character: \233") (lexOutcome (TE.encodeUtf8 "\233")),+      runTest "a byte that is no character is named as a byte" $+        assertEqual "message" (Left "unexpected byte 0xff") (lexOutcome (BS.pack [0xFF])),+      -- Upstream's whitespace is [ \t\r\n] (lexer.l).+      runTest "a vertical tab is not whitespace" $+        assertEqual "message" (Left "unexpected character: \v") (lexOutcome "1\v")+    ]+  where+    lexOutcome source = either (Left . peMessage) (Right . length) (tokenize "<test>" source)++-- ---------------------------------------------------------------------------+-- Tests: Line endings+-- ---------------------------------------------------------------------------++-- | A line ends at an LF, a CRLF or a bare CR, as upstream's position+-- table splits a source (@Pos::LinesIterator@, position.cc at 2.24.9), and+-- a line comment ends before the first CR or LF (@\#[^\\r\\n]*@, lexer.l).+testLineEndings :: IO [Bool]+testLineEndings = do+  putStrLn "parser/line-endings"+  let quickCheckPasses property = do+        result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} property+        pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))+      positionsIn label source expected =+        assertRight label (tokenize "<test>" source) $ \toks ->+          assertEqual label expected [(locLine tok, locCol tok) | tok <- toks, locToken tok /= TokEOF]+      xAt label source expected =+        assertRight label (tokenize "<test>" source) $ \toks ->+          assertEqual label [expected] [(locLine tok, locCol tok) | tok <- toks, locToken tok == TokIdent "x"]+  sequence+    [ runTest "a line comment ends at a carriage return" $+        assertEval "comment" "# c\r1" (VInt 1),+      runTest "a line comment's CRLF ends one line" $+        xAt "comment crlf" "# c\r\nx" (2, 1),+      runTest "an LF, a CRLF and a bare CR each end one line" $+        positionsIn "endings" "a\nb\r\nc\rd" [(1, 1), (2, 1), (3, 1), (4, 1)],+      runTest "an LF before a CR ends a line of its own" $+        xAt "lf cr" "\n\rx" (3, 1),+      runTest "a bare CR ends a line in a block comment" $+        xAt "block comment" "/* a\r */ x" (2, 5),+      runTest "a bare CR ends a line in a double-quoted string" $+        xAt "string" "\"a\rb\" x" (2, 4),+      runTest "a bare CR ends a line in an indented string" $+        xAt "indented string" "''a\rb'' x" (2, 5),+      runTest "an escaped bare CR ends a line" $+        xAt "escaped cr" "\"\\\r\" x" (2, 3),+      -- The escape takes the CR and the string's next run its LF; the two+      -- are still one line ending.+      runTest "an escaped CR and the LF after it end one line" $+        xAt "escaped crlf" "\"\\\r\n\" x" (2, 3),+      runTest "an indented string's escaped CR and the LF after it end one line" $+        xAt "indented escaped crlf" "''a''\\\r\n'' x" (2, 4),+      -- Upstream's opener is @''(\ *\n)?@ (lexer.l): its newline is an LF,+      -- so after a CR the opening line is content.+      runTest "a CRLF after an indented string's opener is content" $+        assertRight "opener crlf" (tokenize "<test>" "''\r\na''") $ \toks ->+          assertEqual "tokens" [TokIndStringOpen, TokStringLit "\r\na", TokIndStringClose] (tokenTypes toks),+      -- Upstream puts an end-of-file syntax error at the end of the input+      -- (yyerror, parser.y at 2.24.9), which a trailing comment runs to.+      runTest "the end of input after a line comment is past the comment" $+        assertRight "eof after comment" (syntaxErrorOf "(\n# c") $ \err ->+          assertEqual "position" (2, 4) (peLine err, peCol err),+      runTestM "a source's tokens stand on the same lines whichever line endings it uses" $+        quickCheckPasses $+          QC.forAll genLineEndingSource $ \pieces ->+            case tokensOutsideStrings (renderSource (map withLf pieces)) of+              Left err -> QC.counterexample (show err) False+              Right expected -> tokensOutsideStrings (renderSource pieces) QC.=== Right expected+    ]+  where+    -- A string's content is not compared: an indented string keeps its+    -- CRs, and the content after an opener starts on the opening line+    -- unless an LF ends it.+    tokensOutsideStrings source = do+      toks <- tokenize "<test>" source+      pure [(locToken tok, locLine tok, locCol tok) | tok <- toks, not (isStringContent (locToken tok))]+    isStringContent (TokStringLit _) = True+    isStringContent (TokStringEsc _) = True+    isStringContent _ = False+    withLf (SourceLineEnding _) = SourceLineEnding Lf+    withLf piece = piece++-- | A line ending of the kind upstream's position table splits at.+data LineEnding = Lf | CrLf | Cr+  deriving (Show)++-- | A piece of a generated source: bytes, or a line ending.+data SourcePiece = SourceBytes !BS.ByteString | SourceLineEnding !LineEnding+  deriving (Show)++-- | The bytes of a generated source.+renderSource :: [SourcePiece] -> BS.ByteString+renderSource = BS.concat . map pieceBytes+  where+    pieceBytes (SourceBytes bytes) = bytes+    pieceBytes (SourceLineEnding Lf) = "\n"+    pieceBytes (SourceLineEnding CrLf) = "\r\n"+    pieceBytes (SourceLineEnding Cr) = "\r"++-- | Sources whose line endings sit wherever the lexer can meet one:+-- between tokens, at a line comment's end, in a block comment, in a+-- double-quoted and an indented string, after an indented string's+-- opener, and escaped in either string.  Each fragment ends at a space,+-- so no two fragments run together into another token, and a byte other+-- than LF follows each line ending, so no bare CR and the LF after it+-- read as one CRLF.+genLineEndingSource :: QC.Gen [SourcePiece]+genLineEndingSource = concat <$> QC.listOf (QC.oneof (map sequence fragments))+  where+    ending = SourceLineEnding <$> QC.elements [Lf, CrLf, Cr]+    bytes = pure . SourceBytes+    fragments =+      [ [bytes "x "],+        [bytes "1 "],+        [bytes "+ "],+        [bytes "\"\195\169\" "],+        [ending, bytes " "],+        [bytes "# c", ending, bytes " "],+        [bytes "/* c", ending, bytes "c */ "],+        [bytes "\"s", ending, bytes "s\" "],+        [bytes "\"\\", ending, bytes "\" "],+        [bytes "''", ending, bytes "s'' "],+        [bytes "''s", ending, bytes "s'' "],+        [bytes "''s''\\", ending, bytes "'' "]+      ]++-- ---------------------------------------------------------------------------+-- Tests: Parser expressions+-- ---------------------------------------------------------------------------++testParserExprs :: IO [Bool]+testParserExprs = do+  putStrLn "parser/exprs"+  sequence+    [ -- Atoms+      runTest "parse int" $+        assertParse "int" "42" (ELit (NixInt 42)),+      runTest "parse float" $+        assertParse "float" "3.14" (ELit (NixFloat 3.14)),+      runTest "parse true" $+        assertParse "true" "true" (ELit (NixBool True)),+      runTest "parse false" $+        assertParse "false" "false" (ELit (NixBool False)),+      runTest "parse null" $+        assertParse "null" "null" (ELit NixNull),+      runTest "parse var" $+        assertParseIn ["x"] "var" "x" (EVar "x"),+      runTest "parse empty string" $+        assertParse "empty string" "\"\"" (EStr []),+      runTest "parse string literal" $+        assertParse "string" "\"hello\"" (EStr [StrLit "hello"]),+      runTest "parse string interpolation" $+        assertParseIn+          ["name"]+          "interp"+          "\"hello ${name}\""+          (EStr [StrLit "hello ", StrInterp (EVar "name")]),+      runTest "parse nested string interpolation" $+        assertParse+          "nested interp"+          "\"${\"inner\"}\""+          (EStr [StrInterp (EStr [StrLit "inner"])]),+      -- Arithmetic+      runTest "parse add" $+        assertParse "add" "1 + 2" (EBinary OpAdd (ELit (NixInt 1)) (ELit (NixInt 2))),+      runTest "parse sub" $+        assertParse "sub" "3 - 1" (EBinary OpSub (ELit (NixInt 3)) (ELit (NixInt 1))),+      runTest "parse mul" $+        assertParse "mul" "2 * 3" (EBinary OpMul (ELit (NixInt 2)) (ELit (NixInt 3))),+      runTest "parse left-assoc add" $+        assertParse+          "left-assoc"+          "1 + 2 + 3"+          (EBinary OpAdd (EBinary OpAdd (ELit (NixInt 1)) (ELit (NixInt 2))) (ELit (NixInt 3))),+      runTest "parse precedence mul over add" $+        assertParse+          "precedence"+          "1 + 2 * 3"+          (EBinary OpAdd (ELit (NixInt 1)) (EBinary OpMul (ELit (NixInt 2)) (ELit (NixInt 3)))),+      -- Unary+      runTest "parse negation" $+        assertParse "negate" "-1" (EUnary OpNegate (ELit (NixInt 1))),+      runTest "parse logical not" $+        assertParse "not" "!true" (EUnary OpNot (ELit (NixBool True))),+      -- Non-associative+      runTest "parse eq" $+        assertParse "eq" "1 == 2" (EBinary OpEq (ELit (NixInt 1)) (ELit (NixInt 2))),+      runTest "parse lt" $+        assertParse "lt" "1 < 2" (EBinary OpLt (ELit (NixInt 1)) (ELit (NixInt 2))),+      -- Right-associative+      runTest "parse implication" $+        assertParseIn+          ["a", "b", "c"]+          "impl"+          "a -> b -> c"+          (EBinary OpImpl (EVar "a") (EBinary OpImpl (EVar "b") (EVar "c"))),+      runTest "parse concat right" $+        assertParseIn+          ["a", "b", "c"]+          "concat"+          "a ++ b ++ c"+          (EBinary OpConcat (EVar "a") (EBinary OpConcat (EVar "b") (EVar "c"))),+      runTest "parse update right" $+        assertParseIn+          ["a", "b", "c"]+          "update"+          "a // b // c"+          (EBinary OpUpdate (EVar "a") (EBinary OpUpdate (EVar "b") (EVar "c"))),+      -- Upstream's grammar binds -, then ?, then ++ tighter than * and +.+      runTest "negation binds tighter than ?" $+        assertParseIn ["a"] "negate over has-attr" "-a ? b" (EHasAttr (EUnary OpNegate (EVar "a")) [StaticKey "b"]),+      runTest "negation's operand is an application" $+        assertParseIn ["f", "x"] "negate an application" "-f x ? y" (EHasAttr (EUnary OpNegate (EApp (EVar "f") (EVar "x"))) [StaticKey "y"]),+      runTest "? binds tighter than ++" $+        assertParseIn ["a", "b"] "has-attr over concat" "a ++ b ? c" (EBinary OpConcat (EVar "a") (EHasAttr (EVar "b") [StaticKey "c"])),+      runTest "++ binds tighter than * and +" $+        assertParseIn+          ["a", "b", "c", "d"]+          "concat over arithmetic"+          "a * b ++ c + d"+          (EBinary OpAdd (EBinary OpMul (EVar "a") (EBinary OpConcat (EVar "b") (EVar "c"))) (EVar "d")),+      -- A prefix operator's operand runs to the end of the operators+      -- tighter than it, wherever the prefix operator stands.+      runTest "! as the operand of a tighter operator takes in the operators tighter than !" $+        assertParseIn+          ["a", "b", "c"]+          "not under add"+          "a + !b + c"+          (EBinary OpAdd (EVar "a") (EUnary OpNot (EBinary OpAdd (EVar "b") (EVar "c")))),+      runTest "! binds tighter than //" $+        assertParseIn ["a", "b"] "not over update" "!a // b" (EBinary OpUpdate (EUnary OpNot (EVar "a")) (EVar "b")),+      runTest "negation of ! takes in what ! takes in" $+        assertParseIn ["a", "b"] "negate a not" "-!a + b" (EUnary OpNegate (EUnary OpNot (EBinary OpAdd (EVar "a") (EVar "b")))),+      runTest "operators that group neither way do not chain" $+        foldr+          andThen+          Pass+          [assertParseFail source source | source <- ["1 == 2 == 3", "1 == 2 != 3", "1 < 2 > 3", "1 == 2 < 3 == 4"]],+      runTest "a second ? applies to the first's whole" $+        assertParseIn ["a"] "has-attr twice" "a ? b ? c" (EHasAttr (EHasAttr (EVar "a") [StaticKey "b"]) [StaticKey "c"]),+      runTest "a negated number has no attribute, as upstream reads -5 ? a" $+        assertEval "negate has-attr" "-5 ? a" (VBool False),+      runTest "! under a tighter operator parses, and an unforced binding of it never fails" $+        assertEval "not under add, unforced" "let x = 1 + !true; in 2" (VInt 2),+      -- Lambda+      -- After variable resolution, lambda-bound vars become EResolvedVar.+      -- FormalName "x" maps to slot 0; FormalSet [a,b] maps to a=0, b=1;+      -- FormalNamedSet "args" [a] maps to args=0, a=1.+      runTest "parse simple lambda" $+        assertParse "lambda" "x: x" (ELambda (FormalName "x") (EResolvedVar 0 0) NoCaptureInfo),+      runTest "parse set pattern lambda" $+        assertParse+          "set pattern"+          "{ a, b }: a"+          ( ELambda+              (FormalSet [Formal "a" Nothing, Formal "b" Nothing] False)+              (EResolvedVar 0 0)+              NoCaptureInfo+          ),+      runTest "parse set pattern with defaults" $+        assertParse+          "defaults"+          "{ a ? 1 }: a"+          ( ELambda+              (FormalSet [Formal "a" (Just (ELit (NixInt 1)))] False)+              (EResolvedVar 0 0)+              NoCaptureInfo+          ),+      runTest "parse set pattern with ellipsis" $+        assertParse+          "ellipsis"+          "{ a, ... }: a"+          ( ELambda+              (FormalSet [Formal "a" Nothing] True)+              (EResolvedVar 0 0)+              NoCaptureInfo+          ),+      runTest "parse named set pattern (name@{...})" $+        assertParse+          "named set"+          "args@{ a }: a"+          ( ELambda+              (FormalNamedSet "args" [Formal "a" Nothing] False)+              (EResolvedVar 0 1)+              NoCaptureInfo+          ),+      runTest "parse named set pattern ({...}@name)" $+        assertParse+          "set@name"+          "{ a }@args: a"+          ( ELambda+              (FormalNamedSet "args" [Formal "a" Nothing] False)+              (EResolvedVar 0 1)+              NoCaptureInfo+          ),+      -- Application+      runTest "parse application" $+        assertParseIn ["f", "x"] "app" "f x" (EApp (EVar "f") (EVar "x")),+      runTest "parse left-assoc application" $+        assertParseIn ["f", "x", "y"] "app left" "f x y" (EApp (EApp (EVar "f") (EVar "x")) (EVar "y")),+      runTest "parse application with parens" $+        assertParseIn+          ["f"]+          "app parens"+          "f (1 + 2)"+          (EApp (EVar "f") (EBinary OpAdd (ELit (NixInt 1)) (ELit (NixInt 2)))),+      -- Select+      runTest "parse select" $+        assertParseIn ["a"] "select" "a.b" (ESelect (EVar "a") [StaticKey "b"] Nothing),+      runTest "parse nested select" $+        assertParseIn+          ["a"]+          "nested select"+          "a.b.c"+          (ESelect (EVar "a") [StaticKey "b", StaticKey "c"] Nothing),+      runTest "parse select or default" $+        assertParseIn+          ["a"]+          "select or"+          "a.b or 1"+          (ESelect (EVar "a") [StaticKey "b"] (Just (ELit (NixInt 1)))),+      runTest "parse has-attr" $+        assertParseIn ["a"] "has-attr" "a ? b" (EHasAttr (EVar "a") [StaticKey "b"]),+      -- Attr sets+      runTest "parse empty attrs" $+        assertParse "empty attrs" "{ }" (EAttrs False [] NoCaptureInfo),+      runTest "parse attrs with binding" $+        assertParse+          "attrs"+          "{ a = 1; }"+          (EAttrs False [NamedBinding (testPos 1 3) (StaticKey "a") (ELit (NixInt 1))] NoCaptureInfo),+      runTest "parse rec attrs" $+        assertParse+          "rec attrs"+          "rec { a = 1; }"+          (EAttrs True [NamedBinding (testPos 1 7) (StaticKey "a") (ELit (NixInt 1))] NoCaptureInfo),+      -- inherit x y; is one binding per name, each holding the variable it+      -- copies, which resolution binds like any other variable.+      runTest "parse inherit" $+        assertParseIn+          ["x", "y"]+          "inherit"+          "{ inherit x y; }"+          (EAttrs False [Inherit (testPos 1 11) "x" (EVar "x"), Inherit (testPos 1 13) "y" (EVar "y")] NoCaptureInfo),+      runTest "parse inherit from" $+        assertParseIn+          ["a"]+          "inherit from"+          "{ inherit (a) x; }"+          (EAttrs False [InheritFrom (EVar "a") [InheritedName (testPos 1 15) "x"]] NoCaptureInfo),+      -- Let/if/with/assert+      runTest "parse let" $+        assertParse+          "let"+          "let x = 1; in x"+          (ELet [NamedBinding (testPos 1 5) (StaticKey "x") (ELit (NixInt 1))] (EResolvedVar 0 0) NoCaptureInfo),+      runTest "parse if-then-else" $+        assertParse+          "if"+          "if true then 1 else 2"+          (EIf (ELit (NixBool True)) (ELit (NixInt 1)) (ELit (NixInt 2))),+      runTest "parse with" $+        assertParseIn+          ["a"]+          "with"+          "with a; b"+          (EWith (EVar "a") (EWithVar "b")),+      runTest "parse assert" $+        assertParse+          "assert"+          "assert true; 1"+          (EAssert (ELit (NixBool True)) (ELit (NixInt 1))),+      -- Lists+      runTest "parse empty list" $+        assertParse "empty list" "[ ]" (EList []),+      runTest "parse list elements" $+        assertParse+          "list"+          "[ 1 2 3 ]"+          (EList [ELit (NixInt 1), ELit (NixInt 2), ELit (NixInt 3)]),+      -- Parens+      runTest "parse parens" $+        assertParse "parens" "(42)" (ELit (NixInt 42)),+      -- 'or' as identifier+      runTest "or as identifier" $+        assertParseIn ["or"] "or ident" "or" (EVar "or"),+      -- 'or' as attr key+      runTest "or as attr key" $+        assertParse+          "or attr key"+          "{ or = 1; }"+          (EAttrs False [NamedBinding (testPos 1 3) (StaticKey "or") (ELit (NixInt 1))] NoCaptureInfo)+    ]++-- ---------------------------------------------------------------------------+-- Tests: Parser errors+-- ---------------------------------------------------------------------------++testParserErrors :: IO [Bool]+testParserErrors = do+  putStrLn "parser/errors"+  sequence+    [ runTest "empty input" $+        assertLeft "empty" (parseNix testBaseDir testOrigin ""),+      runTest "unclosed paren" $+        assertLeft "unclosed paren" (parseNix testBaseDir testOrigin "(1"),+      runTest "unclosed string" $+        assertLeft "unclosed string" (parseNix testBaseDir testOrigin "\"hello"),+      runTest "unclosed brace" $+        assertLeft "unclosed brace" (parseNix testBaseDir testOrigin "{ a = 1;"),+      runTest "missing semicolon" $+        assertLeft "missing semi" (parseNix testBaseDir testOrigin "{ a = 1 }"),+      runTest "unclosed bracket" $+        assertLeft "unclosed bracket" (parseNix testBaseDir testOrigin "[ 1 2"),+      runTest "unexpected token" $+        assertLeft "unexpected" (parseNix testBaseDir testOrigin ")"),+      -- A failure deep in a lambda body is reported where it happened:+      -- a parsed lambda header commits, instead of backtracking into+      -- the attr-set reading and reporting its early stumble (which would+      -- put a real error at line 410 of a nixpkgs file at line 2).+      runTest "deep formals-lambda body error reports its own line" $+        assertRight "deep body" (syntaxErrorOf "{ a, b }:\n{\n  x = 1;\n  y = (;\n}") $ \err ->+          assertEqual "error line" 4 (peLine err),+      runTest "simple-lambda body error reports its own line" $+        assertRight "simple body" (syntaxErrorOf "x:\n(;") $ \err ->+          assertEqual "error line" 2 (peLine err),+      -- The empty attr set is a successful PREFIX parse of "{ }: body",+      -- so without commitment the outer parser complained at the colon.+      runTest "empty-formals lambda body error reports its own line" $+        assertRight "empty formals body" (syntaxErrorOf "{ }:\n(;") $ \err ->+          assertEqual "error line" 2 (peLine err),+      -- When neither reading parses, the deeper failure wins: the+      -- malformed formal at column 7, not the attr-set branch's+      -- stumble over the first comma at column 4.+      runTest "a malformed formal beats the attr-set branch's earlier error" $+        assertRight "malformed formal" (syntaxErrorOf "{ a, b.c }: x") $ \err ->+          assertEqual "deeper than the attr-set stumble" True ((peLine err, peCol err) > (1, 4)),+      -- End-of-input failures carry no position and must rank as the+      -- furthest a branch can get.+      runTest "truncated lambda reports end of input" $+        assertRight "truncated lambda" (syntaxErrorOf "{ a, b }:") $ \err ->+          assertEqual "end of input" True ("end of input" `T.isInfixOf` peMessage err),+      -- Upstream's attribute name is an identifier or or (the attr rule of+      -- parser.y), so its grammar refuses any other keyword as one, at the+      -- keyword.+      runTest "a keyword other than or is no attribute name, refused where it stands" $+        let refusedAt source = (\err -> (peLine err, peCol err)) <$> syntaxErrorOf source+            cases keyword =+              [ ("{ a." <> keyword <> " = 1; }", (1, 5)),+                ("x." <> keyword, (1, 3)),+                ("x ? " <> keyword, (1, 5)),+                ("{ inherit " <> keyword <> "; }", (1, 11)),+                ("{ inherit (x) " <> keyword <> "; }", (1, 15))+              ]+                ++ [("{ " <> keyword <> " = 1; }", (1, 3)) | keyword /= "inherit"]+            sources = concatMap cases refusedAttrKeywords+         in assertEqual "positions" [(source, Right at) | (source, at) <- sources] [(source, refusedAt source) | (source, _) <- sources],+      runTest "or, true, false and null are attribute names" $+        assertEval "names" "let s = { or = 1; true = 2; false = 3; null = 4; }; in s.or + s.true + s.false + s.null" (VInt 10),+      runTest "or, true, false and null are inherited names" $+        assertEval "inherited" "let s = { inherit ({ or = 1; true = 2; false = 3; null = 4; }) or true false null; }; in s.or + s.true + s.false + s.null" (VInt 10),+      runTest "a keyword written as a string is an attribute name" $+        assertEval "quoted" "let s = { \"if\" = 1; inherit ({ \"rec\" = 2; }) \"rec\"; }; in s.\"if\" + s.\"rec\"" (VInt 3)+    ]++-- | The keywords upstream's lexer makes tokens of their own (its rules+-- from @if@ to @inherit@ in lexer.l), none of which its grammar takes as+-- an attribute name.+refusedAttrKeywords :: [Text]+refusedAttrKeywords = ["if", "then", "else", "assert", "with", "let", "in", "rec", "inherit"]++-- ---------------------------------------------------------------------------+-- Tests: Source bytes+-- ---------------------------------------------------------------------------++-- | A source is bytes, as upstream's lexer reads it (lexer.l at 2.24.9): a+-- string literal's bytes are its value's whether or not they are UTF-8,+-- every other token is ASCII, and a byte order mark selects UTF-16, read+-- as its UTF-8.+testSourceBytes :: IO [Bool]+testSourceBytes = do+  putStrLn "parser/source-bytes"+  let quickCheckPasses property = do+        result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} property+        pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))+      -- NUL is left out: upstream's unescapeStr stops at one (lexer.l), so+      -- a literal holding it is no round trip there.+      literalBytes = BS.pack <$> QC.listOf (QC.choose (1, maxBound :: Word8))+      literalText = T.pack <$> QC.listOf (QC.arbitrary `QC.suchThat` (/= '\NUL'))+      -- An LF would end the line; 'stringLiteralText' escapes a CR.+      lineText = T.pack <$> QC.listOf (QC.arbitrary `QC.suchThat` (/= '\n'))+      utf16Le = (BS.pack [0xFF, 0xFE] <>) . TE.encodeUtf16LE+      utf16Be = (BS.pack [0xFE, 0xFF] <>) . TE.encodeUtf16BE+      errorAt err = (peLine err, peCol err, peMessage err)+  sequence+    [ runTestM "a string literal's bytes are its value's" $+        quickCheckPasses $+          QC.forAll literalBytes $ \bytes ->+            evalNixBytes (stringLiteralBytes bytes) QC.=== Right (VStr bytes emptyContext),+      runTestM "a UTF-16 source is read as its UTF-8, in either byte order" $+        quickCheckPasses $+          QC.forAll literalText $ \text ->+            let expected = Right (VStr (TE.encodeUtf8 text) emptyContext)+             in evalNixBytes (utf16Le (stringLiteralText text)) QC.=== expected+                  QC..&&. evalNixBytes (utf16Be (stringLiteralText text)) QC.=== expected,+      runTest "an indented string keeps bytes that are not UTF-8" $+        assertEqual "value" (Right (VStr (BS.pack [0x61, 0xFF, 0x62]) emptyContext)) (evalNixBytes ("''" <> BS.pack [0x61, 0xFF, 0x62] <> "''")),+      runTest "a comment may hold bytes that are not UTF-8" $+        assertEqual "value" (Right (VInt 1)) (evalNixBytes ("# " <> BS.pack [0xFF] <> "\n/* " <> BS.pack [0xC3, 0x28] <> " */ 1")),+      -- Upstream's PATH_CHAR is ASCII (lexer.l): the byte ends the path+      -- and starts no token of its own.+      runTest "a byte outside ASCII ends a path" $+        assertEqual "error" (Right (1, 4, "unexpected byte 0xff")) (errorAt <$> syntaxErrorOfBytes ("./a" <> BS.pack [0xFF] <> "b")),+      runTest "a string attribute name must be UTF-8" $+        assertEqual "error" (Right (1, 3, "attribute name is not valid UTF-8")) (errorAt <$> syntaxErrorOfBytes ("{ \"" <> BS.pack [0xFF] <> "\" = 1; }")),+      -- A dot commits to the key after it, so the key's error is the one+      -- reported, not a complaint about the dot.+      runTest "a string attribute name after a dot must be UTF-8" $+        assertEqual "error" (Right (1, 5, "attribute name is not valid UTF-8")) (errorAt <$> syntaxErrorOfBytes ("{ a.\"" <> BS.pack [0xFF] <> "\" = 1; }")),+      runTest "a string name after a dot in a has-attribute path must be UTF-8" $+        assertEqual "error" (Right (1, 9, "attribute name is not valid UTF-8")) (errorAt <$> syntaxErrorOfBytes ("{ } ? a.\"" <> BS.pack [0xFF] <> "\"")),+      runTest "a quoted inherit name must be UTF-8" $+        assertEqual "error" (Right (1, 17, "attribute name is not valid UTF-8")) (errorAt <$> syntaxErrorOfBytes ("{ inherit ({ }) \"" <> BS.pack [0xFF] <> "\"; }")),+      runTest "a UTF-8 byte order mark is dropped" $+        assertEqual "value" (Right (VInt 1)) (evalNixBytes (BS.pack [0xEF, 0xBB, 0xBF] <> "1")),+      runTest "an unpaired UTF-16 surrogate is a syntax error where it stands" $+        assertEqual "error" (Right (2, 3, "unpaired UTF-16 surrogate")) (errorAt <$> syntaxErrorOfBytes (utf16Le "1\n +" <> BS.pack [0x00, 0xD8])),+      runTest "a bare CR ends a line for a UTF-16 source's error" $+        assertEqual "error" (Right (2, 3, "unpaired UTF-16 surrogate")) (errorAt <$> syntaxErrorOfBytes (utf16Le "1\r +" <> BS.pack [0x00, 0xD8])),+      runTest "a UTF-16 source with an odd byte at its end is a syntax error" $+        assertEqual "error" (Right (1, 2, "UTF-16 source with an odd number of bytes")) (errorAt <$> syntaxErrorOfBytes (utf16Be "1" <> BS.pack [0x41])),+      runTest "a UTF-16 source's error column counts the UTF-8 bytes before it" $+        assertEqual "error" (Right (1, 7, "unpaired UTF-16 surrogate")) (errorAt <$> syntaxErrorOfBytes (utf16Le "\"\233\" +" <> BS.pack [0x00, 0xD8])),+      -- Upstream's column is one past a position's byte offset from the+      -- start of its line (PosTable::operator[], nixexpr.cc at 2.24.9).+      runTestM "a token's column is one past the bytes before it on its line" $+        quickCheckPasses $+          QC.forAll lineText $ \text ->+            let literal = TE.encodeUtf8 (stringLiteralText text)+                columnsOfX = map (\tok -> (locLine tok, locCol tok)) . filter ((== TokIdent "x") . locToken)+             in (columnsOfX <$> tokenize "<test>" (literal <> " x")) QC.=== Right [(1, BS.length literal + 2)]+    ]++-- | Bytes as a double-quoted literal of them: each byte with a meaning+-- there escaped ('literalEscape'), every other kept as it is.+stringLiteralBytes :: BS.ByteString -> BS.ByteString+stringLiteralBytes bytes = "\"" <> BS8.concatMap escaped bytes <> "\""+  where+    escaped c = maybe (BS8.singleton c) TE.encodeUtf8 (literalEscape c)++-- | Text as a double-quoted literal of it, escaped as 'stringLiteralBytes'.+stringLiteralText :: Text -> Text+stringLiteralText text = "\"" <> T.concatMap escaped text <> "\""+  where+    escaped c = fromMaybe (T.singleton c) (literalEscape c)++-- | The escape a character needs in a double-quoted literal: the quote,+-- the backslash, the dollar, and the carriage return, which a raw literal+-- reads as a newline (unescapeStr, lexer.l at 2.24.9).+literalEscape :: Char -> Maybe Text+literalEscape '"' = Just "\\\""+literalEscape '\\' = Just "\\\\"+literalEscape '$' = Just "\\$"+literalEscape '\r' = Just "\\r"+literalEscape _ = Nothing++-- ---------------------------------------------------------------------------+-- Tests: String attribute keys+-- ---------------------------------------------------------------------------++-- | A key written as a string or as @${ expr }@ is a name when upstream's+-- parser builds its expression as a plain string, and dynamic otherwise+-- (the @attrpath@ and @attrs@ rules of parser.y).+testStringAttrKeys :: IO [Bool]+testStringAttrKeys = do+  putStrLn "parser/string-attr-keys"+  let quickCheckPasses property = do+        result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} property+        pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))+      parsedAs source = (\parsed -> (parsedNames parsed, parsedExpr parsed)) <$> parseNix testBaseDir testOrigin (TE.encodeUtf8 source)+      keyText = T.pack <$> QC.listOf (QC.arbitrary `QC.suchThat` (/= '\NUL'))+      errorAt err = (peLine err, peCol err, peMessage err)+      boundAt name = EAttrs False [NamedBinding (testPos 1 3) (StaticKey name) (ELit (NixInt 1))] NoCaptureInfo+  sequence+    [ runTest "a key of an interpolated plain string is a name" $+        assertParse "plain string" "{ ${\"a\"} = 1; }" (boundAt "a"),+      runTest "a key of a parenthesized plain string is a name" $+        assertParse "parenthesized" "{ ${(\"a\")} = 1; }" (boundAt "a"),+      runTest "a key of an interpolated URI is a name" $+        assertParse "uri" "{ ${a:b} = 1; }" (boundAt "a:b"),+      runTestM "a key interpolating a string literal is the key the literal is" $+        quickCheckPasses $+          QC.forAll keyText $ \text ->+            let literal = stringLiteralText text+             in parsedAs ("{ ${" <> literal <> "} = 1; }") QC.=== parsedAs ("{ " <> literal <> " = 1; }"),+      runTest "an interpolated name must be UTF-8" $+        assertEqual "error" (Right (1, 3, "attribute name is not valid UTF-8")) (errorAt <$> syntaxErrorOfBytes ("{ ${\"" <> BS.pack [0xFF] <> "\"} = 1; }")),+      runTest "a key of an interpolated plain string binds in a let" $+        assertEval "let" "let ${\"a\"} = 1; in a" (VInt 1),+      runTest "a key of a URI binds in a let" $+        assertEval "let uri" "let ${a:b} = 1; in 2" (VInt 2),+      runTest "a key of an interpolated plain string is inherited" $+        assertEval "inherit" "let a = 1; in { inherit ${\"a\"}; }.a" (VInt 1),+      runTest "a key of an interpolated plain string is inherited from a set" $+        assertEval "inherit from" "{ inherit ({ a = 1; }) ${\"a\"}; }.a" (VInt 1),+      runTest "a key of an interpolated plain string is in a rec set's scope" $+        assertEval "rec" "(rec { ${\"a\"} = 1; b = a; }).b" (VInt 1),+      runTest "a path through an interpolated plain string merges with the name written bare" $+        assertEval "merge" "{ ${\"a\"}.b = 1; a.c = 2; }.a.b" (VInt 1),+      runTest "an interpolated plain string naming an attribute twice is a parse error" $+        assertParseFail "duplicate" "{ b = 1; ${\"b\"} = 2; }",+      runTest "a key of an interpolated string with interpolation stays dynamic" $+        assertParseFail "interpolated" "let ${\"${\"a\"}\"} = 1; in a",+      runTest "an inherited key that is dynamic is refused at its start" $+        assertEqual "error" (Right (1, 25, "dynamic attributes not allowed in inherit")) (errorAt <$> syntaxErrorOf "let a = 1; in { inherit ${\"a\" + \"\"}; }"),+      runTest "an inherited string with interpolation is refused at its quote" $+        assertEqual "error" (Right (1, 11, "dynamic attributes not allowed in inherit")) (errorAt <$> syntaxErrorOf "{ inherit \"${\"a\"}\"; }")+    ]++-- ---------------------------------------------------------------------------+-- Tests: Parser integration+-- ---------------------------------------------------------------------------++testParserIntegration :: IO [Bool]+testParserIntegration = do+  putStrLn "parser/integration"+  sequence+    [ runTest "shell.nix pattern" $+        assertRight "shell.nix" (parsedExpr <$> parseNix testBaseDir testOrigin "{ pkgs ? import <nixpkgs> {} }: pkgs.mkShell { buildInputs = [ pkgs.ghc ]; }") $ \case+          ELambda {} -> Pass+          other -> Fail ("expected ELambda, got: " <> T.pack (show other)),+      runTest "let with multiple bindings" $+        assertParse+          "multi-let"+          "let x = 1; y = 2; in x + y"+          ( ELet+              [ NamedBinding (testPos 1 5) (StaticKey "x") (ELit (NixInt 1)),+                NamedBinding (testPos 1 12) (StaticKey "y") (ELit (NixInt 2))+              ]+              (EBinary OpAdd (EResolvedVar 0 0) (EResolvedVar 0 1))+              NoCaptureInfo+          ),+      runTest "nested attr set" $+        -- Normalization hoists a nested attrpath into nested literal sets+        -- (upstream parser.y addAttr), so a.b.c = 1 parses like+        -- a = { b = { c = 1; }; }, every level at the path's position.+        assertParse+          "nested attrs"+          "{ a.b.c = 1; d = { e = 2; }; }"+          ( EAttrs+              False+              [ NamedBinding+                  (testPos 1 3)+                  (StaticKey "a")+                  ( EAttrs+                      False+                      [ NamedBinding+                          (testPos 1 3)+                          (StaticKey "b")+                          (EAttrs False [NamedBinding (testPos 1 3) (StaticKey "c") (ELit (NixInt 1))] NoCaptureInfo)+                      ]+                      NoCaptureInfo+                  ),+                NamedBinding (testPos 1 14) (StaticKey "d") (EAttrs False [NamedBinding (testPos 1 20) (StaticKey "e") (ELit (NixInt 2))] NoCaptureInfo)+              ]+              NoCaptureInfo+          ),+      runTest "indented string" $+        assertRight "ind string" (parsedExpr <$> parseNix testBaseDir testOrigin "''hello''") $ \case+          EIndStr _ -> Pass+          other -> Fail ("expected EIndStr, got: " <> T.pack (show other)),+      runTest "indented string escape is its own part" $+        assertRight "ind string esc" (parsedExpr <$> parseNix testBaseDir testOrigin "''a'''b''") $ \case+          EIndStr [StrLit "a", StrEsc "''", StrLit "b"] -> Pass+          other -> Fail ("expected literal, escape, literal, got: " <> T.pack (show other)),+      -- Positional let/rec resolution tests+      runTest "let inherit from outer lambda" $+        assertRight "let-inherit-lambda" (parsedExpr <$> parseNix testBaseDir testOrigin "x: let inherit x; in x") $ \case+          -- x: let inherit x; in x+          -- The lambda formal x is at level 0, index 0.+          -- The let scope is level 0 (for the let body).+          -- The inherited variable resolves against the outer (lambda)+          -- scope, one level up from the let it is evaluated in.+          -- The body x resolves to level 0, index 0 (the let scope).+          ELambda _ (ELet [Inherit _ "x" _rhsExpr] (EResolvedVar 0 0) _) _ -> Pass+          other -> Fail ("expected ELambda with let-inherit, got: " <> T.pack (show other)),+      runTest "nested lambda in let" $+        assertEval+          "let-nested-lambda"+          "let f = x: x + 1; g = y: f y; in g 5"+          (VInt 6),+      runTest "rec attrs positional resolution" $+        assertEval+          "rec-positional"+          "let s = rec { a = 1; b = a + 1; }; in s.b"+          (VInt 2)+    ]++-- ---------------------------------------------------------------------------+-- Tests: __curPos+-- ---------------------------------------------------------------------------++-- | Each expected value is derived from upstream's source at 2.24.9: the+-- parser reads every @__curPos@ its @expr_simple@ rule reaches as an+-- @ExprPos@ at the identifier, whatever binds the name, while the+-- variable an @inherit@ copies is an @ExprVar@ built without that check+-- (parser.y); and @ExprPos::eval@ answers @EvalState::mkPos@ of that+-- position (eval.cc), the position set in a file and null in text with+-- no file behind it (@parseExprFromString@'s @Pos::String@).  The+-- expressions put every @__curPos@ under test past line 1, so the+-- @builtins.toJSON (@ 'jsonInFile' prefixes moves no column.+testCurPos :: IO [Bool]+testCurPos = do+  putStrLn "parse/curPos"+  sequence+    [ runTest "the parser reads __curPos as a position" $+        assertParse "position node" "__curPos" (EPos (SrcPos testOrigin 1 1)),+      inFile "a file gives the position it is written at" "\n  __curPos" (2, 3),+      inFile "a position in a set is at the identifier" "{\n  a = __curPos;\n}.a" (2, 7),+      inFile "a position in a function body is at the identifier" "(x:\n  __curPos) 1" (2, 3),+      inFile "a let binding the name does not shadow it" "let __curPos = 1; in\n  __curPos" (2, 3),+      inFile "a formal of the name does not shadow it" "(__curPos:\n  __curPos) 1" (2, 3),+      inFile "a with supplying the name does not shadow it" "with { __curPos = 1; };\n  __curPos" (2, 3),+      -- A column counts bytes (PosTable::operator[], nixexpr.cc), so the+      -- e-acute takes two.+      inFile "a column counts the bytes before it" "{\n  a = \"\233\"; b = __curPos;\n}.b" (2, 17),+      -- mkPos fills the set with buildBindings' alloc, whose attributes+      -- are at noPos, which mkPos answers null for.+      jsonInFile "a position's attributes have no position" "builtins.unsafeGetAttrPos \"line\" (\n  __curPos)" "null",+      runTest "text with no file gives null" $+        assertEval "text" "__curPos" VNull,+      runTest "a let binding the name in text gives null, not the binding" $+        assertEval "text let" "let __curPos = 1; in __curPos" VNull,+      runTest "an inherited __curPos is a variable" $+        assertEval "inherit" "let __curPos = 1; in { inherit __curPos; }.__curPos" (VInt 1),+      runTest "an inherited __curPos nothing binds is undefined" $+        assertUnbound "inherit unbound" "{ inherit __curPos; }" "__curPos",+      runTest "an attribute may be named __curPos" $+        assertEval "attribute" "{ __curPos = 1; }.__curPos" (VInt 1)+    ]+  where+    inFile label source (line, column) = jsonInFile label source (positionJson positionsFile line column)++-- ---------------------------------------------------------------------------+-- Tests: resolver static globals stay in sync with the root env+-- ---------------------------------------------------------------------------++-- | The two @addConstant@ calls marked @impureOnly@, which upstream skips+-- under @pure-eval@.+upstreamImpureOnlyNames :: Set.Set Text+upstreamImpureOnlyNames = Set.fromList ["__currentSystem", "__currentTime"]++-- | Binding accepts exactly the names upstream's base environment holds,+-- and the root environment binds exactly the names binding accepts, under+-- each policy, every one of them to a value that forces.+testStaticGlobalsSync :: IO [Bool]+testStaticGlobalsSync = do+  putStrLn "resolve/static-globals-sync"+  let pureNames = Set.difference upstreamBaseEnvNames upstreamImpureOnlyNames+  unrestrictedRoot <- rootEnvNames unrestrictedPolicy+  pureRoot <- rootEnvNames purePolicy+  sequence+    [ runTest "binding accepts upstream's base environment" $+        assertSameNames "static globals" upstreamBaseEnvNames staticGlobalNames,+      runTest "pure evaluation drops upstream's impure-only constants" $+        assertEqual "impure-only" upstreamImpureOnlyNames impureOnlyGlobalNames+          `andThen` assertSameNames "pure scope" pureNames (rootScopeNames purePolicy),+      runTest "the root env binds exactly those names" $+        assertSameNames "root env" upstreamBaseEnvNames unrestrictedRoot+          `andThen` assertSameNames "pure root env" pureNames pureRoot,+      runTest "every root env name forces" $+        assertEqual+          "names that fail to force"+          []+          [ name+          | name <- Set.toList upstreamBaseEnvNames,+            evalNix ("builtins.seq " <> name <> " true") /= Right (VBool True)+          ],+      -- A program's names are interned before the strings its root+      -- environment binds, which upstream never interns, so they keep the+      -- order the program gives them.  It runs in a process of its own,+      -- whose symbol table nothing else has filled.+      emits+        "a program's names are interned before the strings its root environment binds"+        ("({ }: null) { a = 1; \"" <> currentSystemStr <> "\" = 2; }")+        ["error: function 'anonymous lambda' called with unexpected argument 'a'"],+      -- Upstream's base environment holds one value per primop, which+      -- every file reads, so sets copied out of builtins in two files hold+      -- the same values, and == takes each pair as equal without+      -- comparing the functions.+      runTestM "a builtin read in an imported file is the same value as in the importer" $ do+        tmpBase <- getTemporaryDirectory+        let dir = tmpBase </> "nova-nix-test-builtin-cells"+        bracket_+          (createDirectoryIfMissing True dir >> TIO.writeFile (dir </> "b.nix") "builtins")+          (removeDirectoryRecursive dir)+          $ do+            result <- evalNixIO dir "builtins.intersectAttrs { map = 1; } builtins == builtins.intersectAttrs { map = 1; } (import ./b.nix)"+            pure (assertRight "builtin-cells" result (assertEqual "builtin-cells" (VBool True)))+    ]+  where+    rootEnvNames policy = do+      Env envPtr <- builtinEnv policy 0 []+      tablePtr <- cenvNameTable envPtr+      Set.fromList <$> attrSetKeys (AttrSet (castPtr tablePtr))+    assertSameNames label expected actual =+      assertEqual+        (label <> ": (missing, extra)")+        ([], [])+        (Set.toList (Set.difference expected actual), Set.toList (Set.difference actual expected))++-- ---------------------------------------------------------------------------+-- Tests: variables are bound before evaluation (upstream's bindVars)+-- ---------------------------------------------------------------------------++-- | Assert that binding rejects a source for the named variable, before+-- anything is evaluated.+assertUnbound :: Text -> Text -> Text -> TestResult+assertUnbound label source name = case parseNix testBaseDir testOrigin (TE.encodeUtf8 source) of+  Left err -> assertEqual label (UndefinedVariable name) err+  Right parsed -> Fail (label <> ": bound, got " <> T.pack (show (parsedExpr parsed)))++-- | Assert that every variable in a source binds.+assertBinds :: Text -> Text -> TestResult+assertBinds label source = assertRight label (parseNix testBaseDir testOrigin (TE.encodeUtf8 source)) (const Pass)++-- | Upstream rejects a variable no scope binds and no @with@ could supply+-- while binding (nixexpr.cc, ExprVar::bindVars), wherever it sits; only a+-- name under a @with@ waits for evaluation.  Each expectation here is+-- nix-instantiate 2.33.2's.+testUndefinedVariables :: IO [Bool]+testUndefinedVariables = do+  putStrLn "resolve/undefined-variables"+  sequence+    [ runTest "an unbound variable in an unused let binding is rejected" $+        assertUnbound "unused-let" "let x = y; in 1" "y",+      runTest "an unbound variable on a branch not taken is rejected" $+        assertUnbound "untaken-branch" "if true then 1 else y" "y",+      runTest "tryEval has nothing to catch: binding fails first" $+        assertUnbound "tryEval" "builtins.tryEval (let x = y; in 1)" "y",+      runTest "the failure reads as upstream's" $+        assertEvalError "message" "builtins.tryEval (let x = y; in 1)" "undefined variable 'y'",+      runTest "the first unbound variable in source order is reported" $+        assertUnbound "first" "let a = b; c = d; in 1" "b",+      runTest "a name under a with binds" $+        assertBinds "with-binds" "with {}; y",+      runTest "a name no with supplies fails when evaluated" $+        assertEvalError "with-eval" "with {}; y" "undefined variable 'y'",+      runTest "an unused binding may read a name only a with could supply" $+        assertEval "with-unused" "with {}; let x = y; in 1" (VInt 1),+      runTest "a with supplies a name a let binding reads" $+        assertEval "with-let" "with { y = 3; }; let x = y; in x" (VInt 3),+      runTest "a nested let shadows the enclosing one" $+        assertEval "let-shadow" "let y = 1; in let y = 2; x = y; in x" (VInt 2),+      runTest "a nested rec reads the enclosing rec" $+        assertEval "rec-nested" "rec { a = 1; b = rec { c = a; }.c; }.b" (VInt 1),+      runTest "a rec reading a name it does not define is rejected" $+        assertUnbound "rec-missing" "rec { a = b; }" "b",+      runTest "a lambda formal shadows a with" $+        assertEval "formal-over-with" "(x: with { x = 2; }; x) 1" (VInt 1),+      runTest "a formal default reads a sibling formal" $+        assertEval "formal-default" "({ a, b ? a }: b) { a = 3; }" (VInt 3),+      runTest "an unbound formal default is rejected" $+        assertUnbound "formal-default-unbound" "{ a ? b }: a" "b",+      runTest "inherit of an unbound name in a let is rejected" $+        assertUnbound "let-inherit" "let inherit x; in 1" "x",+      runTest "inherit of an unbound name in a set is rejected" $+        assertUnbound "set-inherit" "{ inherit x; }" "x",+      runTest "inherit of an unbound name in a rec is rejected" $+        assertUnbound "rec-inherit" "rec { inherit x; }" "x",+      runTest "inherit reads a name only a with supplies" $+        assertEval "with-inherit" "with { x = 5; }; rec { inherit x; }.x" (VInt 5),+      runTest "inherit under an empty with fails only when selected" $+        assertEvalError "with-inherit-missing" "with {}; { inherit x; }.x" "undefined variable 'x'",+      runTest "inherit in a rec reads the enclosing binding, not its own" $+        assertEval "rec-inherit-outer" "(x: rec { inherit x; y = x; }.y) 4" (VInt 4),+      runTest "inherit from an unbound source is rejected" $+        assertUnbound "inherit-from-unbound" "{ inherit (s) x; }" "s",+      runTest "inherit from selects lazily" $+        assertEval "inherit-from-lazy" "let s = {}; in builtins.attrNames { inherit (s) x; } == [ \"x\" ]" (VBool True),+      runTest "inherit from fails when the attribute is selected" $+        assertEvalFail "inherit-from-missing" "let s = {}; in { inherit (s) x; }.x",+      runTest "an inherit clause cannot repeat a name" $+        assertParseFail "inherit-repeat" "let x = 1; in { inherit x x; }",+      runTest "an inherit-from clause cannot repeat a name" $+        assertParseFail "inherit-from-repeat" "let s = { x = 1; }; in { inherit (s) x x; }",+      runTest "__curPos is upstream syntax, not a variable" $+        assertEval "curpos" "if false then __curPos else 1" (VInt 1),+      runTest "inherit in a static-key rec reads the enclosing rec" $+        assertEval "rec-inherit-static" "rec { q = 0; x = 1; y = rec { a = 1; inherit x; }; }.y.x" (VInt 1),+      runTest "a __-prefixed builtin on a branch not taken binds" $+        assertEval "prefixed-untaken" "if false then __typeOf 1 else 2" (VInt 2),+      runTest "a __-prefixed builtin is the builtin" $+        assertEval "prefixed-value" "__typeOf 1 == \"int\"" (VBool True),+      runTest "a global is not shadowed by a with" $+        assertEval "prefixed-over-with" "with { __typeOf = 1; }; __typeOf 2 == \"int\"" (VBool True),+      runTest "fetchMercurial binds as a builtin" $+        assertEval "fetchMercurial-binds" "builtins.typeOf fetchMercurial == \"lambda\"" (VBool True),+      runTest "calling fetchMercurial fails as a builtin nova-nix lacks" $+        assertEvalError "fetchMercurial-call" "fetchMercurial {}" "unknown builtin 'fetchMercurial'",+      runTest "pure evaluation leaves upstream's impure-only constants unbound" $+        assertEqual "pure-currentTime" (Left "undefined variable '__currentTime'") (evalNixWith purePolicy "if false then __currentTime else 1"),+      runTest "pure evaluation binds the other globals" $+        assertEqual "pure-typeOf" (Right (VInt 1)) (evalNixWith purePolicy "if false then __typeOf else 1")+    ]++-- | The same check for files: upstream binds each file as it parses it, so+-- an import fails on an unbound variable the importing code never reaches,+-- and @scopedImport@ binds its scope's names around the file.  The inherit+-- cases whose regression is a self-reference run here too.+testUndefinedVariablesIO :: IO [Bool]+testUndefinedVariablesIO = do+  putStrLn "resolve/undefined-variables-io"+  tmpBase <- getTemporaryDirectory+  let testDir = tmpBase </> "nova-nix-test-undefined-variables"+      branchFile = nixQuotedPath (testDir </> "branch.nix")+      scopedFile = nixQuotedPath (testDir </> "scoped.nix")+      scopedWithFile = nixQuotedPath (testDir </> "scoped-with.nix")+      expectError label source expected = do+        result <- evalNixIO testDir source+        runTest label $ case result of+          Left err -> assertEqual label expected err+          Right val -> Fail (label <> ": expected an error, got " <> T.pack (show val))+  bracket_+    ( do+        createDirectoryIfMissing True testDir+        TIO.writeFile (testDir </> "branch.nix") "{ flag }:\nif flag then 1 else unboundName\n"+        TIO.writeFile (testDir </> "scoped.nix") "if false then notInScope else fromScope\n"+        TIO.writeFile (testDir </> "scoped-with.nix") "with { fromScope = \"with\"; }; fromScope\n"+    )+    ( do+        exists <- doesDirectoryExist testDir+        when exists (removeDirectoryRecursive testDir)+    )+    $ sequence+      [ expectError+          "an import fails on an unbound variable on a branch not taken"+          ("(import " <> branchFile <> ") { flag = true; }")+          "undefined variable 'unboundName'",+        expectError+          "tryEval cannot catch an import that fails to bind"+          ("builtins.tryEval (import " <> branchFile <> ")")+          "undefined variable 'unboundName'",+        runTestIO+          "an import that is never forced does not fail"+          testDir+          ("let f = import " <> branchFile <> "; in 1")+          (VInt 1),+        expectError+          "scopedImport binds against its scope"+          ("builtins.scopedImport { fromScope = 7; } " <> scopedFile)+          "undefined variable 'notInScope'",+        runTestIO+          "scopedImport scope names bind"+          testDir+          ("builtins.scopedImport { fromScope = 7; notInScope = 1; } " <> scopedFile)+          (VInt 7),+        runTestIO+          "a scopedImport scope name is not shadowed by a with"+          testDir+          ("builtins.scopedImport { fromScope = 7; } " <> scopedWithFile)+          (VInt 7),+        -- Evaluated where a self-reference is caught as infinite recursion+        -- rather than looping, which is what reading the inherited name+        -- from the rec's own scope would do.+        runTestIO+          "inherit in a dynamic-key rec reads the enclosing rec, not its own"+          testDir+          "rec { ${\"q\" + \"\"} = 0; x = 1; y = rec { ${\"a\" + \"\"} = 1; inherit x; }; }.y.x"+          (VInt 1),+        expectError+          "inherit of a name no with supplies is undefined, not the rec's own"+          "with {}; rec { ${\"a\" + \"\"} = 1; inherit x; }.x"+          "undefined variable 'x'"+      ]++-- ---------------------------------------------------------------------------+-- Tests: byte-indexed string semantics+-- ---------------------------------------------------------------------------++-- | A file is lexed as its bytes, as upstream reads it (eval.cc,+-- @parseExprFromFile@ at 2.24.9): a string literal in one keeps a byte+-- that is not UTF-8.  A byte order mark selects UTF-16, read as its UTF-8,+-- or marks UTF-8.+testSourceBytesIO :: IO [Bool]+testSourceBytesIO = do+  putStrLn "parser/source-bytes-io"+  tmpDir <- getTemporaryDirectory+  let testDir = tmpDir </> "nova-nix-source-bytes-test"+      invalid = BS.pack [0x61, 0xFF, 0x62]+      named = "{ name = \"caf\233\"; }"+      name = VStr (TE.encodeUtf8 "caf\233") emptyContext+  bracket_+    ( do+        createDirectoryIfMissing True testDir+        BS.writeFile (testDir </> "invalid.nix") ("\"" <> invalid <> "\"")+        BS.writeFile (testDir </> "utf16le.nix") (BS.pack [0xFF, 0xFE] <> TE.encodeUtf16LE named)+        BS.writeFile (testDir </> "utf16be.nix") (BS.pack [0xFE, 0xFF] <> TE.encodeUtf16BE named)+        BS.writeFile (testDir </> "utf8mark.nix") (BS.pack [0xEF, 0xBB, 0xBF] <> TE.encodeUtf8 named)+    )+    ( do+        exists <- doesDirectoryExist testDir+        when exists (removeDirectoryRecursive testDir)+    )+    $ sequence+      [ runTestIO "a string literal in a file keeps a byte that is not UTF-8" testDir "import ./invalid.nix" (VStr invalid emptyContext),+        runTestIO "a UTF-16 LE file with a byte order mark is read" testDir "(import ./utf16le.nix).name" name,+        runTestIO "a UTF-16 BE file with a byte order mark is read" testDir "(import ./utf16be.nix).name" name,+        runTestIO "a UTF-8 file with a byte order mark is read" testDir "(import ./utf8mark.nix).name" name+      ]
+ test/Test/Pkgs.hs view
@@ -0,0 +1,4202 @@+{-# LANGUAGE ScopedTypeVariables #-}++-- | Tests of the package set, and that the CI workflows spell each value+-- they share one way.+module Test.Pkgs+  ( testPkgsFetchurl,+    testStage0Pe32Chain,+    testMesWindows,+    testTinyccWindows,+    testGnumakeWindows,+    testBusyboxWindows,+    testChecksForbidSubstitutes,+    testSeedStdenvWindows,+    testBinutilsWindows,+    testGccCoreWindows,+    testGcc46Windows,+    testGcc46CxxWindows,+    testGcc10Windows,+    testMingwW64LatestWindows,+    testGccLatestWindows,+    testBinutilsX8664Windows,+    testGccCoreX8664Windows,+    testMingwW64CrtX8664Windows,+    testGccX8664Windows,+    testBinutilsNativeX8664Windows,+    testGccNativeX8664Windows,+    testStdenvWindows,+    testBashWindows,+    testWindowsSources,+    testUnusedPrebuilt,+    testWindowsRungs,+    testWorkflowSpellings,+  )+where++import Control.Applicative ((<|>))+import Control.Exception (IOException, displayException, try)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BS8+import Data.Char (isAsciiLower, isAsciiUpper, isDigit)+import Data.Functor ((<&>))+import Data.IORef (readIORef)+import Data.List (mapAccumL, nub, sort)+import qualified Data.Map.Strict as Map+import Data.Maybe (catMaybes, fromMaybe, isJust, listToMaybe, mapMaybe, maybeToList)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Nix.Builder.Unpack (builtinUnpackBuilder, envOmit, envSrcs)+import Nix.Builtins (parseNixPath)+import Nix.Derivation (Derivation (..), DerivationOutput (..), Platform (..))+import Nix.Eval (MonadEval (..), NixValue (..), evalParsed, mkStr, typeName, unrestrictedPolicy)+import Nix.Eval.IO (EvalState (..), evalBaseEnv, newEvalStateWith, runEvalIO)+import Nix.Hash (hashPlaceholder, sha256Digest)+import qualified Nix.Hash as Hash+import Nix.Json (Json (..), parseJson)+import Nix.Parser (parseNix)+import Nix.Store.Path (StoreWriteMode (..), defaultStoreDir, defaultStoreDirText, parseStorePath, storePathToFilePath, storePathToText)+import Nix.Store.Path.Internal (StorePath (..))+import qualified NovaCache.NAR as NAR+import qualified System.Directory as Dir+import System.FilePath ((</>))+import Test.Harness (TestResult (..), assertEqual, bytesText, evalNixIO, evalNixIOStoreDir, nixQuotedPath, runTest, runTestIO, runTestM, sessionClosure, testLogger, testOrigin, testSessionStore)+import Text.Read (readMaybe)++-- ---------------------------------------------------------------------------+-- Tests: NAR and hash known-answer vectors+-- ---------------------------------------------------------------------------++-- | @pkgs/windows/fetchurl.nix@ evaluated from the checkout.  The+-- @mirror://@ expansion is what a source derivation records, so a+-- mirrors.nix refresh or a regex edit moves every drvPath built on it;+-- these pin the list against nixpkgs' order and the eval-time errors.+testPkgsFetchurl :: IO [Bool]+testPkgsFetchurl = do+  putStrLn "pkgs/fetchurl"+  cwd <- Dir.getCurrentDirectory+  let fetchurl = "(import " <> nixQuotedPath (cwd </> "pkgs" </> "windows" </> "fetchurl.nix") <> ")"+      urlsOf source = "builtins.concatStringsSep \"\\n\" (" <> fetchurl <> " { " <> source <> " sha256 = \"" <> hash <> "\"; }).urls"+      failsWith expected result = case result of+        Left err+          | expected `T.isInfixOf` err -> Pass+          | otherwise -> Fail ("expected an error naming " <> expected <> ", got: " <> err)+        Right val -> Fail ("expected an eval error, got: " <> T.pack (show val))+  sequence+    [ runTestIO+        "mirror://gnu expands to the https hosts of mirrors.nix, in nixpkgs' order"+        cwd+        (urlsOf "url = \"mirror://gnu/hello/hello-2.12.3.tar.gz\";")+        (mkStr (T.intercalate "\n" (map (<> "hello/hello-2.12.3.tar.gz") gnuHosts))),+      runTestIO+        "a plain URL in urls passes through beside an expanded one"+        cwd+        (urlsOf "urls = [ \"https://example.invalid/sed-4.10.tar.xz\" \"mirror://gnu/sed/sed-4.10.tar.xz\" ];")+        (mkStr (T.intercalate "\n" ("https://example.invalid/sed-4.10.tar.xz" : map (<> "sed/sed-4.10.tar.xz") gnuHosts))),+      runTestM "an unknown mirror site is an eval error naming the recipe's URL" $+        failsWith "fetchurl: unknown mirror site 'nope' in 'mirror://nope/x'" <$> evalNixIO cwd (urlsOf "url = \"mirror://nope/x\";"),+      runTestM "a mirror URL with no path is an eval error" $+        failsWith "fetchurl: malformed mirror URL 'mirror://gnu'" <$> evalNixIO cwd (urlsOf "url = \"mirror://gnu\";")+    ]+  where+    hash :: Text+    hash = "0d5f60154382fee10b114a1c34e785d8b1f492073ae2d3a6f7b147687b366aa0"+    -- The gnu set of pkgs/windows/mirrors.nix without its ftp:// host.+    gnuHosts :: [Text]+    gnuHosts =+      [ "https://ftpmirror.gnu.org/",+        "https://ftp.nluug.nl/pub/gnu/",+        "https://mirrors.kernel.org/gnu/",+        "https://mirror.ibcp.fr/pub/gnu/",+        "https://mirror.dogado.de/gnu/",+        "https://mirror.tochlab.net/pub/gnu/",+        "https://ftp.gnu.org/pub/gnu/"+      ]++-- | @pkgs/windows@'s stage0-pe32 chain, read back as the build driver reads+-- it: every derivation reachable from the seed, the ten links and+-- mescc-tools-extra's thirteen programs.  The chain is full-source only if+-- nothing reaches it but the seed and the sources, so the graph's leaves are+-- exactly those six fetches, no derivation takes a plain input source, and+-- each of the thirty commands of stage0-pe32's @x86\/mescc-tools-mini.cmd@,+-- and each of the five steps of every mescc-tools-extra program, is a step run+-- by a program the graph builds.  Every program built from C, hex2-new and kaem+-- included, is those five steps with the arguments the .cmd gives kaem.  hex0+-- carries the seed's hash as its own, so the build itself checks that the+-- seed reproduces itself.+--+-- The bin directories and @test\/data\/run-command.nix@'s writeText and+-- runCommand builds add derivations kaem builds and no leaf, and read nothing+-- but the scripts evaluation writes.  Each bin directory's script copies the+-- programs its variables name to @bin\/\<name\>.exe@, runCommand runs its+-- script from those directories on a PATH joined with @;@, and a store path+-- in that script is spelled from @NIX_STORE@.+testStage0Pe32Chain :: IO [Bool]+testStage0Pe32Chain = do+  putStrLn "pkgs/stage0-pe32"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  -- The package set's fetchurl hands a single URL to <nix/fetchurl.nix>,+  -- which resolves against the checkout's data directory as the installed+  -- binary resolves it against its own.+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let chain = "(import " <> nixQuotedPath (cwd </> "pkgs" </> "windows") <> ").stage0-pe32"+      runCommandTests = "import " <> nixQuotedPath (cwd </> "test" </> "data" </> "run-command.nix")+      quoted name = "\"" <> name <> "\""+      source =+        T.concat+          [ "let chain = ",+            chain,+            "; runs = ",+            runCommandTests,+            "; in builtins.concatStringsSep \" \" (map (name: chain.${name}.drvPath) [ ",+            T.unwords (map quoted ("seed" : links ++ bins)),+            " ] ++ map (name: chain.mescc-tools-extra.${name}.drvPath) [ ",+            T.unwords (map quoted extras),+            " ] ++ map (name: runs.${name}.drvPath) [ ",+            T.unwords (map quoted runs),+            " ])"+          ]+      chainAttrs = ("seed" : links) ++ map extraAttr extras+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> do+          let rootOf = Map.fromList (zip (("seed" : links ++ bins) ++ map extraAttr extras ++ map runAttr runs) (T.words (bytesText bytes)))+          graph <- sessionClosure (mapMaybe (`Map.lookup` rootOf) chainAttrs)+          full <- sessionClosure (Map.elems rootOf)+          pure (rootOf, graph, full)+        other -> throwEvalError ("expected the drvPaths as one string, got " <> typeName other)+  writes <- readIORef (esStoreWriteCache st)+  case outcome of+    Left err -> sequence [runTest instantiates (Fail err)]+    Right (rootOf, graph, full) -> do+      let derivations = Map.elems graph+          fetches = filter ((== fetchurlBuilder) . drvBuilder) derivations+          unpacks = filter ((== builtinUnpackBuilder) . drvBuilder) derivations+          steps = filter (\drv -> drvBuilder drv `notElem` [fetchurlBuilder, builtinUnpackBuilder]) derivations+          leaves = filter (Map.null . drvInputDrvs) derivations+          nameOf drv = maybe "" bytesText (Map.lookup "name" (drvEnv drv))+          isFixedOutput drv = not (all (T.null . doHash) (drvOutputs drv))+          outOf drv = [TE.encodeUtf8 (storePathToText defaultStoreDir (doPath o)) | o <- drvOutputs drv, doName o == "out"]+          inputsOf drv = mapMaybe ((`Map.lookup` full) . storePathToText defaultStoreDir) (Map.keys (drvInputDrvs drv))+          builtBy attr = Map.lookup attr rootOf >>= (`Map.lookup` full)+          builderNamesOf drv = [nameOf input | input <- inputsOf drv, drvBuilder drv `elem` outOf input]+          fixedHashOf drv = [(doHashAlgo o, doHash o) | o <- drvOutputs drv, doName o == "out"]+          isStep drv = drvBuilder drv `notElem` [fetchurlBuilder, builtinUnpackBuilder]+          -- A program's steps, last first: each step after the compile has+          -- one input that is a step and not the program it runs.+          stepsBack drv = drv : maybe [] stepsBack (listToMaybe [input | input <- inputsOf drv, isStep input, drvBuilder drv `notElem` outOf input])+          -- An argument as the .cmd spells it: the step's own output, which+          -- the .drv holds as its placeholder until the build, as $out,+          -- another step's output by that step's name, and a file in an+          -- unpacked repository as <repo>/<path>.+          spell drv arg+            | bytesText arg == hashPlaceholder "out" = "$out"+            | otherwise =+                fromMaybe (bytesText arg) $+                  listToMaybe ([nameOf input | input <- inputsOf drv, arg `elem` outOf input] ++ mapMaybe (inRepository arg) unpacks)+          inRepository arg unpack = do+            root <- listToMaybe (outOf unpack)+            rest <- BS.stripPrefix (root <> "/") arg+            let repo = T.dropEnd 1 (fst (T.breakOnEnd "-" (nameOf unpack)))+            pure (repo <> "/" <> bytesText (BS.drop 1 (BS8.dropWhile (/= '/') rest)))+          command drv = (nameOf drv, builderNamesOf drv, map (spell drv) (drvArgs drv))+          -- What the bin directories and run-command.nix add to the chain.+          added = Map.elems (Map.difference full graph)+          fullLeaves = filter (Map.null . drvInputDrvs) (Map.elems full)+          variableOf name drv = maybe "" bytesText (Map.lookup name (drvEnv drv))+          outText attr = maybe "" bytesText (builtBy attr >>= listToMaybe . outOf)+          -- Each variable of a bin directory that names a program, with the+          -- name of the program's derivation.+          installs drv = sort [(var, nameOf input) | (var, value) <- Map.toList (drvEnv drv), var /= "builder", input <- inputsOf drv, value `elem` outOf input]+          wroteAsText path = fmap snd (Map.lookup (storePathToText defaultStoreDir path) writes) == Just WriteText+          runsWith drv = (bytesText (drvBuilder drv), map (spell drv) (drvArgs drv), variableOf "PATH" drv)+          scriptOf drv = listToMaybe [input | input <- inputsOf drv, nameOf input == nameOf drv <> "-builder"]+          textFile drv = (bytesText (drvBuilder drv), variableOf "PATH" drv, variableOf "passAsFile" drv, variableOf "text" drv, sort (map nameOf (inputsOf drv)))+          kaemExe = outText "kaem" <> "/bin/kaem.exe"+          extraPath = outText "mescc-tools-extra" <> "/bin"+          hello = "${NIX_STORE}/" <> T.drop (T.length defaultStoreDirText + 1) (outText (runAttr "hello"))+      sequence+        [ runTest instantiates $+            assertEqual "steps, unpacks, fetches" (95, 5, 6) (length steps, length unpacks, length fetches),+          runTest "no derivation of the chain takes a plain input source" $+            case [nameOf drv | drv <- derivations, not (null (drvInputSrcs drv))] of+              [] -> Pass+              named -> Fail ("input sources in: " <> T.intercalate ", " named),+          runTest "the chain's leaves are the seed and the five source archives, all fixed-output" $+            assertEqual+              "leaves"+              (fetchNames, True)+              ( sort (map nameOf leaves),+                all (\drv -> drvBuilder drv == fetchurlBuilder && isFixedOutput drv) leaves+              ),+          runTest "each source archive is unpacked from its fetch alone" $+            assertEqual "unpack inputs" (replicate 5 [fetchurlBuilder]) [map drvBuilder (inputsOf drv) | drv <- unpacks],+          runTest "every step is an i686-windows derivation" $+            case [nameOf drv | drv <- steps, drvPlatform drv /= I686_Windows] of+              [] -> Pass+              named -> Fail ("not i686-windows: " <> T.intercalate ", " named),+          runTest "each step is run by an input, the program its command runs" $+            assertEqual+              "file written, program run"+              (sort ([(written, [program]) | (written, program) <- commands] ++ [(written, program) | (_, built) <- extraPrograms, (written, program, _) <- built]))+              (sort [(nameOf drv, builderNamesOf drv) | drv <- steps]),+          runTest "each program built from C is the five steps that build kaem, with their arguments" $+            assertEqual+              "file written, program run, arguments"+              (cmdPrograms ++ extraPrograms)+              [(attr, maybe [] (map command . reverse . stepsBack) (builtBy attr)) | (attr, _) <- cmdPrograms ++ extraPrograms],+          runTest "hex0 is fixed-output to the seed's own hash" $+            case (fixedHashOf <$> builtBy "seed", fixedHashOf <$> builtBy "hex0") of+              (Just seedHash@[(_, digest)], Just hex0Hash)+                | not (T.null digest) -> assertEqual "hex0's output hash" seedHash hex0Hash+              other -> Fail ("expected the seed's fixed-output hash on hex0: " <> T.pack (show other)),+          runTest "the bin directories and run-command.nix add ten derivations" $+            assertEqual+              "derivations added"+              (sort ["kaem", "mescc-tools", "mescc-tools-extra", "hello.txt", "run-command-copies", "run-command-copies-builder", "run-command-fails", "run-command-fails-builder", "run-command-marks", "run-command-marks-builder"])+              (sort (map nameOf added)),+          runTest "with them the leaves are still the seed and the five source archives" $+            assertEqual "leaves" fetchNames (sort (map nameOf fullLeaves)),+          runTest "they read no input source but the scripts evaluation writes as text" $+            assertEqual+              "derivation and its sources, all written as text"+              ( [ ("hello.txt", ["write-text.kaem"]),+                  ("kaem", ["kaem-bin.kaem"]),+                  ("mescc-tools", ["mescc-tools-bin.kaem"]),+                  ("mescc-tools-extra", ["mescc-tools-extra-bin.kaem"]),+                  ("run-command-copies-builder", ["write-text.kaem"]),+                  ("run-command-fails-builder", ["write-text.kaem"]),+                  ("run-command-marks-builder", ["write-text.kaem"])+                ],+                True+              )+              ( sort [(nameOf drv, sort (map spName (drvInputSrcs drv))) | drv <- added, not (null (drvInputSrcs drv))],+                all (all wroteAsText . drvInputSrcs) added+              ),+          runTest "every derivation they add is i686-windows" $+            case [nameOf drv | drv <- added, drvPlatform drv /= I686_Windows] of+              [] -> Pass+              named -> Fail ("not i686-windows: " <> T.intercalate ", " named),+          runTest "kaem lays out each bin directory from the programs its variables name" $+            assertEqual+              "bin directory, program run, variable and program"+              [ ("kaem", ["kaem.exe"], sort [("chmod", "chmod.exe"), ("cp", "cp.exe"), ("kaem", "kaem.exe"), ("mkdir", "mkdir.exe")]),+                ("mescc-tools", ["kaem.exe"], sort [("M1", "M1.exe"), ("M2-Planet", "M2.exe"), ("chmod", "chmod.exe"), ("cp", "cp.exe"), ("hex2", "hex2-new.exe"), ("mkdir", "mkdir.exe")]),+                ("mescc-tools-extra", ["kaem.exe"], sort [(name, name <> ".exe") | name <- extras])+              ]+              [(attr, maybe [] builderNamesOf (builtBy attr), maybe [] installs (builtBy attr)) | attr <- bins],+          runTestM "each bin directory's script copies its programs to bin/<name>.exe and chmods each 555, and writeText's copies the text" $ do+            let scriptsOf drv = map (storePathToFilePath storeDir) (drvInputSrcs drv)+            scripts <- traverse (traverse BS.readFile . maybe [] scriptsOf . builtBy) (bins ++ [runAttr "hello"])+            pure $+              assertEqual+                "scripts"+                [[installScript ["kaem"]], [installScript ["M1", "M2-Planet", "hex2"]], [installScript extras], ["cp ${textPath} ${out}\n"]]+                (map (map bytesText) scripts),+          runTest "runCommand runs its script with kaem from the bin directories, on PATH joined with ';'" $+            assertEqual+              "builder, arguments, PATH"+              [ (kaemExe, ["--verbose", "--strict", "--file", name <> "-builder"], T.intercalate ";" [outText attr <> "/bin" | attr <- bins])+              | name <- ["run-command-copies", "run-command-fails", "run-command-marks"]+              ]+              (mapMaybe (fmap runsWith . builtBy . runAttr) ["copies", "fails", "marks"]),+          runTest "marks is fixed-output to the NAR hash of its tree with bin/hello executable" $+            assertEqual+              "output hash"+              (Just [("r:sha256", "d7b2412a32f4ff4be9340e6bbd33e316c64fdf38623ba4e76ed8af570dfaee9a")])+              (fixedHashOf <$> builtBy (runAttr "marks")),+          runTest "writeText passes its text as a file, and runCommand's script spells a store path from NIX_STORE" $+            assertEqual+              "builder, PATH, passAsFile, text and inputs"+              [ (kaemExe, extraPath, "text", "stage0-pe32 runs a kaem script\n", ["kaem", "mescc-tools-extra"]),+                ( kaemExe,+                  extraPath,+                  "text",+                  T.unlines ["mkdir -p ${out}/a/b", "cp " <> hello <> " ${out}/a/b/hello.txt", "catm ${out}/twice.txt " <> hello <> " " <> hello],+                  ["hello.txt", "kaem", "mescc-tools-extra"]+                )+              ]+              (map textFile (catMaybes [builtBy (runAttr "hello"), builtBy (runAttr "copies") >>= scriptOf]))+        ]+  where+    instantiates :: Text+    instantiates = "the chain instantiates: ninety-five steps, five unpacks and six fetches"+    fetchurlBuilder :: BS.ByteString+    fetchurlBuilder = "builtin:fetchurl"+    links :: [Text]+    links = ["hex0", "hex1", "hex2", "catm", "M0", "cc_x86", "M2", "M1", "hex2-new", "kaem-unwrapped"]+    extras :: [Text]+    extras = ["sha256sum", "match", "mkdir", "untar", "ungz", "unbz2", "unxz", "catm", "cp", "chmod", "rm", "replace", "wrap"]+    extraAttr :: Text -> Text+    extraAttr = ("mescc-tools-extra." <>)+    bins :: [Text]+    bins = ["kaem", "mescc-tools", "mescc-tools-extra"]+    runs :: [Text]+    runs = ["hello", "copies", "fails", "marks"]+    runAttr :: Text -> Text+    runAttr = ("run-command." <>)+    -- The script kaem runs to lay out a bin directory of the programs named.+    installScript :: [Text] -> Text+    installScript names =+      T.unlines+        ( "${mkdir} -p ${out}/bin"+            : concat+              [ ["${cp} ${" <> name <> "} ${out}/bin/" <> name <> ".exe", "${chmod} 555 ${out}/bin/" <> name <> ".exe"]+              | name <- sort names+              ]+        )+    fetchNames :: [Text]+    fetchNames = sort ["M2-Planet-ee0bf91.tar.gz", "M2libc-ef9dfc2.tar.gz", "hex0-seed.exe", "mescc-tools-578ac99.tar.gz", "mescc-tools-extra-d1d8146.tar.gz", "stage0-pe32-a81c837.tar.gz"]+    -- The steps that build a C program on M2libc's POSIX layer, named for+    -- stem: the file each writes, the program it runs and its arguments.+    cProgram :: Text -> Text -> [Text] -> [(Text, [Text], [Text])]+    cProgram executable stem files =+      [ (stem <> ".M1", ["M2.exe"], ["--architecture", "x86", "-D", "__windows__=1"] ++ concatMap (\file -> ["-f", file]) files ++ ["-o", "$out"]),+        (stem <> "-0.M1", ["catm.exe"], ["$out", "M2libc/x86/x86_defs.M1", "M2libc/x86/windows/libc-core.M1", "M2libc/x86/windows/libc-full.M1", stem <> ".M1", "M2libc/x86/windows/pe-end-shim.M1"]),+        (stem <> ".hex2", ["M0.exe"], [stem <> "-0.M1", "$out"]),+        (stem <> "-0.hex2", ["catm.exe"], ["$out", "M2libc/x86/windows/PE32-i386.hex2", "M2libc/x86/windows/ntdll-i386.hex2", stem <> ".hex2"]),+        (executable, ["hex2.exe"], [stem <> "-0.hex2", "$out"])+      ]+    -- Phase-7's M2libc files, which are what <stdio.h> reaches on the+    -- x86/windows target and bootstrappable.c, and Phase-8's, which add the+    -- string.c that <string.h> reaches.  catm is the one program here that+    -- does not include <string.h>.+    libcPosix :: [Text]+    libcPosix = map ("M2libc/" <>) (libcBelowString ++ libcAboveString)+    libcString :: [Text]+    libcString = map ("M2libc/" <>) (libcBelowString ++ ["string.c"] ++ libcAboveString)+    libcBelowString :: [Text]+    libcBelowString = ["sys/types.h", "stddef.h", "sys/utsname.h", "x86/windows/ntdll.c", "x86/windows/unistd.c", "x86/windows/process.c", "x86/windows/fcntl.c", "fcntl.c", "x86/windows/sys/stat.c", "ctype.c", "stdlib.c"]+    libcAboveString :: [Text]+    libcAboveString = ["stdarg.h", "stdio.h", "stdio.c", "bootstrappable.c"]+    -- The .cmd's two programs built from C and mescc-tools-extra's, by+    -- attribute, with the steps that build each.+    cmdPrograms :: [(Text, [(Text, [Text], [Text])])]+    cmdPrograms =+      [ ("hex2-new", cProgram "hex2-new.exe" "hex2_linker" (libcPosix ++ map ("mescc-tools/" <>) ["hex2.h", "hex2_linker.c", "hex2_word.c", "hex2.c"])),+        ("kaem-unwrapped", cProgram "kaem.exe" "kaem" (libcString ++ map ("mescc-tools/Kaem/" <>) ["kaem.h", "variable.c", "kaem_globals.c", "kaem.c"]))+      ]+    extraPrograms :: [(Text, [(Text, [Text], [Text])])]+    extraPrograms =+      [ (extraAttr name, cProgram (name <> ".exe") name ((if name == "catm" then libcPosix else libcString) ++ ["mescc-tools-extra/" <> name <> ".c"]))+      | name <- extras+      ]+    -- Each command of the .cmd: the file it writes and the program it runs.+    commands :: [(Text, Text)]+    commands =+      [ ("hex0.exe", "hex0-seed.exe"),+        ("hex1.exe", "hex0.exe"),+        ("hex2.exe", "hex1.exe"),+        ("catm.exe", "hex2.exe"),+        ("M0.hex2", "catm.exe"),+        ("M0.exe", "hex2.exe"),+        ("cc_x86-0.hex2", "M0.exe"),+        ("cc_x86.hex2", "catm.exe"),+        ("cc_x86.exe", "hex2.exe"),+        ("M2-0.c", "catm.exe"),+        ("M2-0.M1", "cc_x86.exe"),+        ("M2-0-0.M1", "catm.exe"),+        ("M2-0.hex2", "M0.exe"),+        ("M2-0-0.hex2", "catm.exe"),+        ("M2.exe", "hex2.exe"),+        ("M1-macro.M1", "M2.exe"),+        ("M1-macro-0.M1", "catm.exe"),+        ("M1-macro.hex2", "M0.exe"),+        ("M1-macro-0.hex2", "catm.exe"),+        ("M1.exe", "hex2.exe"),+        ("hex2_linker.M1", "M2.exe"),+        ("hex2_linker-0.M1", "catm.exe"),+        ("hex2_linker.hex2", "M0.exe"),+        ("hex2_linker-0.hex2", "catm.exe"),+        ("hex2-new.exe", "hex2.exe"),+        ("kaem.M1", "M2.exe"),+        ("kaem-0.M1", "catm.exe"),+        ("kaem.hex2", "M0.exe"),+        ("kaem-0.hex2", "catm.exe"),+        ("kaem.exe", "hex2.exe")+      ]++-- | @pkgs/windows@'s Mes, read back as the build driver reads it: what its+-- source tree, libraries, compiler and C library sources, and+-- @test\/data\/mes.nix@'s checks, add to the closure of the stage0 tools+-- they run on.  The rung is full-source only if the leaves it adds are the+-- Mes and NYACC archives and it reads no input source but the scripts+-- evaluation writes.  The builder spells a store path with a backslash,+-- which starts an escape in a C or Scheme string, so no script writes a path+-- into Mes's source with replace, and every script that runs Mes sets the+-- paths and sizes it reads in its environment instead.  exec-bit is+-- fixed-output to the NAR hash of the files its program makes, with the+-- execute bits their modes set.+testMesWindows :: IO [Bool]+testMesWindows = do+  putStrLn "pkgs/mes"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let windows = "(import " <> nixQuotedPath (cwd </> "pkgs" </> "windows") <> ")"+      checks = "import " <> nixQuotedPath (cwd </> "test" </> "data" </> "mes.nix")+      quoted name = "\"" <> name <> "\""+      source =+        T.concat+          [ "let pkgs = ",+            windows,+            "; checks = ",+            checks,+            "; in builtins.concatStringsSep \" \" ([ pkgs.mes.srcPrefix ] ++ map (name: pkgs.stage0-pe32.${name}.drvPath) [ ",+            T.unwords (map quoted tools),+            " ] ++ map (name: pkgs.mes.${name}.drvPath) [ ",+            T.unwords (map quoted mesAttrs),+            " ] ++ map (name: checks.${name}.drvPath) [ ",+            T.unwords (map quoted checkAttrs),+            " ])"+          ]+      roots = tools ++ map ("mes." <>) mesAttrs ++ map ("checks." <>) checkAttrs+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> case T.words (bytesText bytes) of+          prefix : paths -> do+            let rootOf = Map.fromList (zip roots paths)+            toolGraph <- sessionClosure (mapMaybe (`Map.lookup` rootOf) tools)+            full <- sessionClosure (Map.elems rootOf)+            pure (prefix, rootOf, toolGraph, full)+          [] -> throwEvalError "expected srcPrefix and the drvPaths"+        other -> throwEvalError ("expected srcPrefix and the drvPaths as one string, got " <> typeName other)+  writes <- readIORef (esStoreWriteCache st)+  case outcome of+    Left err -> sequence [runTest instantiates (Fail err)]+    Right (prefix, rootOf, toolGraph, full) -> do+      let added = Map.elems (Map.difference full toolGraph)+          nameOf drv = maybe "" bytesText (Map.lookup "name" (drvEnv drv))+          variableOf name drv = maybe "" bytesText (Map.lookup name (drvEnv drv))+          outOf drv = [storePathToText defaultStoreDir (doPath o) | o <- drvOutputs drv, doName o == "out"]+          builtBy attr = Map.lookup attr rootOf >>= (`Map.lookup` full)+          outText attr = T.concat (maybe [] outOf (builtBy attr))+          fixedHashOf drv = [(doHashAlgo o, doHash o) | o <- drvOutputs drv, doName o == "out"]+          inputsOf drv = mapMaybe ((`Map.lookup` full) . storePathToText defaultStoreDir) (Map.keys (drvInputDrvs drv))+          scriptOf drv = listToMaybe [variableOf "text" input | input <- inputsOf drv, nameOf input == nameOf drv <> "-builder"]+          isFetch drv = drvBuilder drv == "builtin:fetchurl"+          isFixedOutput drv = not (all (T.null . doHash) (drvOutputs drv))+          addedLeaves = filter (Map.null . drvInputDrvs) added+          wroteAsText path = fmap snd (Map.lookup (storePathToText defaultStoreDir path) writes) == Just WriteText+          runsMes script = any (`T.isInfixOf` script) ["/bin/mes-m2.exe ", "/bin/mes.exe "]+          runners = [drv | drv <- added, Just script <- [scriptOf drv], runsMes script]+          quote dir = "\"" <> dir <> "\""+          mesEnv =+            [ ("MES_ARENA", "20000000"),+              ("MES_STACK", "60000"),+              ("MES_PREFIX", prefix),+              ("GUILE_LOAD_PATH", T.intercalate ":" (map quote [prefix <> "/mes/module", prefix <> "/module", outText "mes.nyacc" <> "/share/nyacc-1.09.1/module"])),+              ("M1", outText "mescc-tools" <> "/bin/M1.exe"),+              ("HEX2", outText "mescc-tools" <> "/bin/hex2.exe")+            ]+          -- What each replace line of a script writes into the file it edits.+          replacements script = [snd (T.breakOn "--replace-with" line) | line <- T.lines script, "replace " `T.isPrefixOf` T.stripStart line]+          written = concatMap replacements (mapMaybe scriptOf added)+      sequence+        [ runTest instantiates $+            assertEqual "derivations added" (sort addedNames) (sort (map nameOf added)),+          runTest "every derivation it adds but the two fetches is i686-windows" $+            case [nameOf drv | drv <- added, not (isFetch drv), drvPlatform drv /= I686_Windows] of+              [] -> Pass+              named -> Fail ("not i686-windows: " <> T.intercalate ", " named),+          runTest "the leaves it adds are the Mes and NYACC archives, both fetched fixed-output" $+            assertEqual+              "leaves added"+              (sort ["mes-77ff40b.tar.gz", "nyacc-1.09.1.tar.gz"], True)+              (sort (map nameOf addedLeaves), all (\drv -> isFetch drv && isFixedOutput drv) addedLeaves),+          runTest "it reads no input source but what evaluation writes as text" $+            assertEqual "input sources not written as text" [] [nameOf drv | drv <- added, not (all wroteAsText (drvInputSrcs drv))],+          runTest "every script that runs Mes sets its arena, MES_PREFIX, GUILE_LOAD_PATH, M1 and HEX2" $+            assertEqual+              "derivation and its environment"+              [(name, mesEnv) | name <- sort mesRunners]+              (sort [(nameOf drv, [(var, variableOf var drv) | (var, _) <- mesEnv]) | drv <- runners]),+          runTest "no script writes a path into Mes's source with replace" $+            assertEqual+              "replacements, and those that name a path"+              (3, [])+              (length written, filter (\with -> "/" `T.isInfixOf` with || "${" `T.isInfixOf` with) written),+          runTest "exec-bit is fixed-output to the NAR hash of the files its program makes, open-0755 and chmod-0755 executable" $+            assertEqual+              "output hash"+              [("r:sha256", Hash.bytesToHexText (sha256Digest (NAR.serialise execBitTree)))]+              (maybe [] fixedHashOf (builtBy "checks.exec-bit"))+        ]+  where+    instantiates :: Text+    instantiates = "the Mes derivations instantiate, adding thirty-two to the stage0 tools'"+    tools :: [Text]+    tools = ["kaem", "mescc-tools", "mescc-tools-extra"]+    mesAttrs :: [Text]+    mesAttrs = ["nyacc", "srcPost", "libs", "compiler", "libc"]+    checkAttrs :: [Text]+    checkAttrs = ["mes-m2", "mes", "hello", "exec-bit"]+    -- Each kaem.runCommand adds its script, written by writeText as+    -- <name>-builder; mes-libc-0.28 is both the libc MesCC compiles and+    -- the sources for TinyCC, as in nixpkgs.+    addedNames :: [Text]+    addedNames =+      ["mes-77ff40b.tar.gz", "nyacc-1.09.1.tar.gz", "hello.c", "exec-bit.c"]+        ++ concat [[name, name <> "-builder"] | name <- mesRunners ++ ["nyacc-1.09.1", "mes-src-0.28", "mes-m2-libs-0.28", "mes-libc-0.28"]]+    mesRunners :: [Text]+    mesRunners =+      [ "mes-crt1-0.28",+        "mes-libc-mini-0.28",+        "mes-libmescc-0.28",+        "mes-libc-0.28",+        "mes-libc+tcc-0.28",+        "mes-0.28",+        "mes-m2-get-version",+        "mes-get-version",+        "mes-hello",+        "mes-exec-bit"+      ]+    -- What test/data/mes.nix's exec-bit program makes: three files holding+    -- one line, the one open creates with mode 0755 and the one chmod+    -- gives 0755 executable, the one open creates with 0644 not.+    execBitTree :: NAR.NarEntry+    execBitTree =+      NAR.NarDirectory+        [ ("open-0755", NAR.NarRegular True execBitContents),+          ("open-0644", NAR.NarRegular False execBitContents),+          ("chmod-0755", NAR.NarRegular True execBitContents)+        ]+    execBitContents :: BS.ByteString+    execBitContents = "written by Mes libc\n"++-- | @pkgs/windows@'s TinyCC, read back as the build driver reads it: what+-- the rounds from tinycc-boot-mes to tinycc-native and+-- @test\/data\/tinycc.nix@'s checks add to the closure of the Mes rung they+-- run on.  The rung is full-source only if the leaves it adds are the two+-- TinyCC archives and it reads no input source but the scripts evaluation+-- writes.  The builder spells a store path with a backslash, which starts+-- an escape in a C string, so no script puts a store path between the+-- escaped quotes a @-D@ or a @replace@ turns into a C string literal, and+-- every script that runs tcc names the headers it compiles against in+-- @C_INCLUDE_PATH@ instead, then Mes's when the tcc it runs is on Mes libc.+testTinyccWindows :: IO [Bool]+testTinyccWindows = do+  putStrLn "pkgs/tinycc"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let windows = "(import " <> nixQuotedPath (cwd </> "pkgs" </> "windows") <> ")"+      checks = "import " <> nixQuotedPath (cwd </> "test" </> "data" </> "tinycc.nix")+      quoted name = "\"" <> name <> "\""+      source =+        T.concat+          [ "let pkgs = ",+            windows,+            "; checks = ",+            checks,+            "; in builtins.concatStringsSep \" \" ([ pkgs.mes.srcPrefix ] ++ map (name: pkgs.stage0-pe32.${name}.drvPath) [ ",+            T.unwords (map quoted tools),+            " ] ++ map (name: pkgs.mes.${name}.drvPath) [ ",+            T.unwords (map quoted mesAttrs),+            " ] ++ [ ",+            T.unwords ["pkgs." <> path <> ".drvPath" | path <- tinyccPaths],+            " ] ++ map (name: checks.${name}.drvPath) [ ",+            T.unwords (map quoted checkAttrs),+            " ])"+          ]+      mesRoots = tools ++ map ("mes." <>) mesAttrs+      roots = mesRoots ++ tinyccPaths ++ map ("checks." <>) checkAttrs+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> case T.words (bytesText bytes) of+          prefix : paths -> do+            let rootOf = Map.fromList (zip roots paths)+            mesGraph <- sessionClosure (mapMaybe (`Map.lookup` rootOf) mesRoots)+            full <- sessionClosure (Map.elems rootOf)+            pure (prefix, rootOf, mesGraph, full)+          [] -> throwEvalError "expected srcPrefix and the drvPaths"+        other -> throwEvalError ("expected srcPrefix and the drvPaths as one string, got " <> typeName other)+  writes <- readIORef (esStoreWriteCache st)+  case outcome of+    Left err -> sequence [runTest instantiates (Fail err)]+    Right (prefix, rootOf, mesGraph, full) -> do+      let added = Map.elems (Map.difference full mesGraph)+          nameOf drv = maybe "" bytesText (Map.lookup "name" (drvEnv drv))+          variableOf name drv = maybe "" bytesText (Map.lookup name (drvEnv drv))+          outOf drv = [storePathToText defaultStoreDir (doPath o) | o <- drvOutputs drv, doName o == "out"]+          builtBy attr = Map.lookup attr rootOf >>= (`Map.lookup` full)+          outText attr = T.concat (maybe [] outOf (builtBy attr))+          byOut = Map.fromList [(path, drv) | drv <- Map.elems full, path <- outOf drv]+          -- A kaem.runCommand's last argument is its script, which writeText+          -- writes.+          scriptOf drv = do+            path <- listToMaybe (reverse (drvArgs drv))+            writer <- Map.lookup (bytesText path) byOut+            pure (variableOf "text" writer)+          isFetch drv = drvBuilder drv == "builtin:fetchurl"+          isFixedOutput drv = not (all (T.null . doHash) (drvOutputs drv))+          addedLeaves = filter (Map.null . drvInputDrvs) added+          wroteAsText path = fmap snd (Map.lookup (storePathToText defaultStoreDir path) writes) == Just WriteText+          -- What a script runs: the first word of each of its lines, which+          -- for a line continuing a command is an argument.+          commandsOf script = mapMaybe (listToMaybe . T.words) (T.lines script)+          runners program = [drv | drv <- added, Just script <- [scriptOf drv], any (\command -> any (`T.isSuffixOf` command) program) (commandsOf script)]+          mesProgram = ["/bin/mes-m2.exe", "/bin/mes.exe"]+          quote dir = "\"" <> dir <> "\""+          mesEnv =+            [ ("MES_ARENA", "20000000"),+              ("MES_STACK", "60000"),+              ("MES_PREFIX", prefix),+              ("GUILE_LOAD_PATH", T.intercalate ":" (map quote [prefix <> "/mes/module", prefix <> "/module", outText "mes.nyacc" <> "/share/nyacc-1.09.1/module"])),+              ("M1", outText "mescc-tools" <> "/bin/M1.exe"),+              ("HEX2", outText "mescc-tools" <> "/bin/hex2.exe")+            ]+          -- A TinyCC source tree, and its include directory, then Mes's.+          treeOf name tree = T.concat [path | drv <- added, nameOf drv == name, path <- outOf drv] <> "/" <> tree+          mesInclude = prefix <> "/include"+          jannekeInclude = treeOf ("tinycc-bootstrappable-" <> version <> "-source") ("tinycc-" <> rev) <> "/include;" <> mesInclude+          upstreamTree = treeOf ("tinycc-" <> upstreamVersion <> "-source") ("tinycc-" <> upstreamRev)+          upstreamInclude = upstreamTree <> "/include;" <> mesInclude+          -- TinyCC's own headers, the C library's and the Windows API's.+          win32Include = T.intercalate ";" [upstreamTree <> "/include", upstreamTree <> "/win32/include", upstreamTree <> "/win32/include/winapi"]+          -- The text between each pair of kaem's escaped quotes, which a -D+          -- hands MesCC or tcc, or a replace writes into a source, as a C+          -- string literal.+          cStrings script = [text | (i, text) <- zip [0 :: Int ..] (T.splitOn "\\\"" script), odd i]+          strings = concatMap cStrings (Set.toList (Set.fromList (mapMaybe scriptOf added)))+      sequence+        [ runTest instantiates $+            assertEqual "derivations added" (sort addedNames) (sort (map nameOf added)),+          runTest "every derivation it adds but the fetch is i686-windows" $+            case [nameOf drv | drv <- added, not (isFetch drv), drvPlatform drv /= I686_Windows] of+              [] -> Pass+              named -> Fail ("not i686-windows: " <> T.intercalate ", " named),+          runTest "the two leaves it adds are the TinyCC archives, fetched fixed-output" $+            assertEqual+              "leaves added"+              (sort ["tinycc-" <> rev <> ".tar.gz", "tinycc-" <> upstreamRev <> ".tar.gz"], True)+              (sort (map nameOf addedLeaves), all (\drv -> isFetch drv && isFixedOutput drv) addedLeaves),+          runTest "it reads no input source but what evaluation writes as text" $+            assertEqual "input sources not written as text" [] [nameOf drv | drv <- added, not (all wroteAsText (drvInputSrcs drv))],+          runTest "every script that runs Mes sets its arena, MES_PREFIX, GUILE_LOAD_PATH, M1 and HEX2" $+            assertEqual+              "derivation and its environment"+              [(name, mesEnv) | name <- sort mesRunners]+              (sort [(nameOf drv, [(var, variableOf var drv) | (var, _) <- mesEnv]) | drv <- runners mesProgram]),+          runTest "every script that runs tcc names the headers it compiles against in C_INCLUDE_PATH, then Mes's for a tcc on Mes libc" $+            assertEqual+              "derivation and its C_INCLUDE_PATH"+              ( sort+                  ( [(name, jannekeInclude) | name <- jannekeRunners]+                      ++ [(name, upstreamInclude) | name <- upstreamRunners]+                      ++ [(name, win32Include <> ";" <> mesInclude) | name <- mesWin32Runners]+                      ++ [(name, win32Include) | name <- nativeRunners]+                  )+              )+              (sort [(nameOf drv, variableOf "C_INCLUDE_PATH" drv) | drv <- runners ["/bin/tcc.exe"]]),+          -- Nine per Mes round's compile, five per native round's, and three+          -- in the edits TinyCC's own source gets: the format of nixpkgs'+          -- i386-asm.c replacement, and the two PATHSEP values.+          runTest "no C string literal a script passes in a -D or writes with replace names a store path" $+            assertEqual+              "string literals, and those that name a store path"+              (9 * (length rounds + length mesRounds) + 5 * length nativeRounds + 3, [])+              (length strings, filter ("${NIX_STORE}" `T.isInfixOf`) strings)+        ]+  where+    instantiates :: Text+    instantiates = "the TinyCC derivations instantiate, adding a hundred and fifty-four to Mes's"+    version :: Text+    version = "unstable-2024-07-07"+    rev :: Text+    rev = "ea3900f6d5e71776c5cfabcabee317652e3a19ee"+    upstreamVersion :: Text+    upstreamVersion = "unstable-2025-12-03"+    upstreamRev :: Text+    upstreamRev = "cb41cbfe717e4c00d7bb70035cda5ee5f0ff9341"+    tools :: [Text]+    tools = ["kaem", "mescc-tools", "mescc-tools-extra"]+    mesAttrs :: [Text]+    mesAttrs = ["nyacc", "srcPost", "libs", "compiler", "libc"]+    -- The first round of janneke's source and the last, which is built from+    -- all the others, both rounds of TinyCC's own on Mes libc, and both+    -- native rounds.+    tinyccPaths :: [Text]+    tinyccPaths =+      [ "tinycc.boot-mes.compiler",+        "tinycc.boot-mes.libs",+        "tinycc.bootstrappable.compiler",+        "tinycc.bootstrappable.libs",+        "tinycc-mes.prev.compiler",+        "tinycc-mes.prev.libs",+        "tinycc-mes.compiler",+        "tinycc-mes.libs",+        "tinycc-native.prev.compiler",+        "tinycc-native.prev.libs",+        "tinycc-native.compiler",+        "tinycc-native.libs"+      ]+    checkAttrs :: [Text]+    checkAttrs =+      [ "boot-mes",+        "hello",+        "bootstrappable",+        "bootstrappable-hello",+        "bootstrappable-float",+        "mes",+        "mes-hello",+        "mes-float",+        "mes-printf-float",+        "native",+        "native-search-dirs",+        "native-mingw32",+        "native-hello",+        "native-float",+        "native-printf-float",+        "native-winsock",+        "native-math"+      ]+    -- Each round of janneke's source, in the order each compiles the next,+    -- and then each round of TinyCC's own.+    rounds :: [Text]+    rounds = ["tinycc-boot-mes", "tinycc-boot0", "tinycc-boot1", "tinycc-boot2", "tinycc-boot3", "tinycc-bootstrappable"]+    mesRounds :: [Text]+    mesRounds = ["tinycc-mes-boot", "tinycc-mes"]+    -- The native rounds, the first compiled by tinycc-mes.+    nativeRounds :: [Text]+    nativeRounds = ["tinycc-native-boot", "tinycc-native"]+    -- What a round's library is compiled in, each by that round's tcc.+    libraryParts :: [Text]+    libraryParts = ["crt", "libtcc1.a", "libc.a", "libgetopt.a"]+    -- Each kaem.runCommand adds its script, written by writeText as+    -- <name>-builder.+    addedNames :: [Text]+    addedNames =+      ["tinycc-" <> rev <> ".tar.gz", "tinycc-" <> upstreamRev <> ".tar.gz", "hello.c", "float.c", "printf-float.c", "mingw32.c", "winsock.c", "math.c"]+        ++ concat+          [ [name, name <> "-builder"]+          | name <-+              ("tinycc-bootstrappable-" <> version <> "-source")+                : concat [[pname <> "-" <> version, pname <> "-libs-" <> version] ++ libraryParts | pname <- rounds]+                ++ tccRunnerChecks+                ++ ("tinycc-" <> upstreamVersion <> "-source")+                : ("tccdefs-" <> upstreamVersion)+                : concat [[pname <> "-" <> upstreamVersion, pname <> "-libs-" <> upstreamVersion] ++ libraryParts | pname <- mesRounds]+                ++ mesRunnerChecks+                ++ ("tinycc-mes-win32-libs-" <> upstreamVersion)+                : concat [[pname <> "-" <> upstreamVersion, pname <> "-libs-" <> upstreamVersion] | pname <- nativeRounds]+                ++ nativeRunnerChecks+          ]+    mesRunners :: [Text]+    mesRunners = ["tinycc-boot-mes-" <> version]+    tccRunnerChecks :: [Text]+    tccRunnerChecks =+      [ "tinycc-boot-mes-get-version",+        "tinycc-boot-mes-hello",+        "tinycc-bootstrappable-get-version",+        "tinycc-bootstrappable-hello",+        "tinycc-bootstrappable-float"+      ]+    mesRunnerChecks :: [Text]+    mesRunnerChecks =+      [ "tinycc-mes-get-version",+        "tinycc-mes-hello",+        "tinycc-mes-float",+        "tinycc-mes-printf-float"+      ]+    -- The scripts a tcc of janneke's source runs in: every library part of+    -- its rounds, every round's tcc but the first, which MesCC compiles, the+    -- checks, and what tinycc-bootstrappable compiles of TinyCC's own+    -- source, c2str and tinycc-mes-boot's tcc.+    jannekeRunners :: [Text]+    jannekeRunners =+      concatMap (const libraryParts) rounds+        ++ [pname <> "-" <> version | pname <- drop 1 rounds]+        ++ tccRunnerChecks+        ++ ["tccdefs-" <> upstreamVersion, "tinycc-mes-boot-" <> upstreamVersion]+    nativeRunnerChecks :: [Text]+    nativeRunnerChecks =+      [ "tinycc-native-get-version",+        "tinycc-native-search-dirs",+        "tinycc-native-mingw32",+        "tinycc-native-hello",+        "tinycc-native-float",+        "tinycc-native-printf-float",+        "tinycc-native-winsock",+        "tinycc-native-math"+      ]+    -- The scripts a tcc of TinyCC's own source on Mes libc runs in to+    -- compile against Mes libc: its rounds' library parts, tinycc-mes's tcc+    -- and the checks.+    upstreamRunners :: [Text]+    upstreamRunners = concatMap (const libraryParts) mesRounds ++ ["tinycc-mes-" <> upstreamVersion] ++ mesRunnerChecks+    -- The scripts tinycc-mes runs in to compile against the Windows+    -- headers: the runtime the first native tcc links with, and that tcc.+    mesWin32Runners :: [Text]+    mesWin32Runners = ["tinycc-mes-win32-libs-" <> upstreamVersion, "tinycc-native-boot-" <> upstreamVersion]+    -- The scripts a native tcc runs in: each round's runtime, the second+    -- round's tcc and the checks.+    nativeRunners :: [Text]+    nativeRunners = [pname <> "-libs-" <> upstreamVersion | pname <- nativeRounds] ++ ["tinycc-native-" <> upstreamVersion] ++ nativeRunnerChecks++-- | @pkgs/windows@'s GNU make, read back as the build driver reads it:+-- what make and @test\/data\/gnumake.nix@'s checks add to the closure of+-- tinycc-native, which compiles it.  The rung is full-source only if the+-- one leaf it adds is make's archive and it reads no input source but the+-- scripts and the import library evaluation writes.  make's script runs+-- tinycc-native, so it names the headers that compiler reads in+-- @C_INCLUDE_PATH@, as tinycc-native's own library script does, and no C+-- string literal its edits write names a store path.+testGnumakeWindows :: IO [Bool]+testGnumakeWindows = do+  putStrLn "pkgs/gnumake"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let windows = "(import " <> nixQuotedPath (cwd </> "pkgs" </> "windows") <> ")"+      checks = "import " <> nixQuotedPath (cwd </> "test" </> "data" </> "gnumake.nix")+      source =+        T.concat+          [ "let pkgs = ",+            windows,+            "; checks = ",+            checks,+            "; in builtins.concatStringsSep \" \" [ ",+            T.unwords [path <> ".drvPath" | path <- roots],+            " ]"+          ]+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> do+          let rootOf = Map.fromList (zip roots (T.words (bytesText bytes)))+          tinyccGraph <- sessionClosure (mapMaybe (`Map.lookup` rootOf) tinyccRoots)+          full <- sessionClosure (Map.elems rootOf)+          pure (rootOf, tinyccGraph, full)+        other -> throwEvalError ("expected the drvPaths as one string, got " <> typeName other)+  writes <- readIORef (esStoreWriteCache st)+  case outcome of+    Left err -> sequence [runTest instantiates (Fail err)]+    Right (rootOf, tinyccGraph, full) -> do+      let added = Map.elems (Map.difference full tinyccGraph)+          nameOf drv = maybe "" bytesText (Map.lookup "name" (drvEnv drv))+          variableOf name drv = maybe "" bytesText (Map.lookup name (drvEnv drv))+          builtBy attr = Map.lookup attr rootOf >>= (`Map.lookup` full)+          inputsOf drv = mapMaybe ((`Map.lookup` full) . storePathToText defaultStoreDir) (Map.keys (drvInputDrvs drv))+          scriptOf drv = listToMaybe [variableOf "text" input | input <- inputsOf drv, nameOf input == nameOf drv <> "-builder"]+          isFetch drv = drvBuilder drv == "builtin:fetchurl"+          isFixedOutput drv = not (all (T.null . doHash) (drvOutputs drv))+          addedLeaves = filter (Map.null . drvInputDrvs) added+          wroteAsText path = fmap snd (Map.lookup (storePathToText defaultStoreDir path) writes) == Just WriteText+          runsTcc script = "/bin/tcc.exe " `T.isInfixOf` script+          -- The text between each pair of kaem's escaped quotes, which a+          -- replace writes into a source as a C string literal.+          cStrings script = [text | (i, text) <- zip [0 :: Int ..] (T.splitOn "\\\"" script), odd i]+          strings = concatMap cStrings (mapMaybe scriptOf added)+      sequence+        [ runTest instantiates $+            assertEqual "derivations added" (sort addedNames) (sort (map nameOf added)),+          runTest "every derivation it adds but the fetch is i686-windows" $+            case [nameOf drv | drv <- added, not (isFetch drv), drvPlatform drv /= I686_Windows] of+              [] -> Pass+              named -> Fail ("not i686-windows: " <> T.intercalate ", " named),+          runTest "the one leaf it adds is make's archive, fetched fixed-output" $+            assertEqual+              "leaves added"+              (["make-" <> version <> ".tar.gz"], True)+              (map nameOf addedLeaves, all (\drv -> isFetch drv && isFixedOutput drv) addedLeaves),+          runTest "it reads no input source but what evaluation writes as text" $+            assertEqual "input sources not written as text" [] [nameOf drv | drv <- added, not (all wroteAsText (drvInputSrcs drv))],+          runTest "make's script runs tinycc-native with the headers its library script names" $+            assertEqual+              "derivations that run tcc, and their C_INCLUDE_PATH"+              [("gnumake-" <> version, variableOf "C_INCLUDE_PATH" <$> builtBy "pkgs.tinycc-native.libs")]+              [(nameOf drv, Just (variableOf "C_INCLUDE_PATH" drv)) | drv <- added, Just script <- [scriptOf drv], runsTcc script],+          -- One per include or library directory the edits remove.+          runTest "no C string literal make's edits write names a store path" $+            assertEqual+              "string literals, and those that name a store path"+              (5, [])+              (length strings, filter ("${NIX_STORE}" `T.isInfixOf`) strings)+        ]+  where+    instantiates :: Text+    instantiates = "the make derivations instantiate, adding ten to tinycc-native's"+    version :: Text+    version = "4.4.1"+    tinyccRoots :: [Text]+    tinyccRoots = ["pkgs.tinycc-native.compiler", "pkgs.tinycc-native.libs"]+    roots :: [Text]+    roots = tinyccRoots ++ ["pkgs.gnumake", "checks.version", "checks.pattern-rule"]+    -- Each kaem.runCommand adds its script, written by writeText as+    -- <name>-builder.+    addedNames :: [Text]+    addedNames =+      ["make-" <> version <> ".tar.gz", "pattern-rule.mk", "greeting.in"]+        ++ concat [[name, name <> "-builder"] | name <- ["gnumake-" <> version, "gnumake-get-version", "gnumake-pattern-rule"]]++-- | @pkgs/windows@'s busybox-w32, read back as the build driver reads it:+-- what busybox-w32 and @test\/data\/busybox.nix@'s checks add to the+-- closure of tinycc-native, which compiles it.  The rung is full-source+-- only if the leaves it adds are busybox-w32's release archive and the+-- mingw-w64-crt sources it links, and it reads no input source but what+-- evaluation writes as text and the package's own compatibility headers+-- and generators.  Its script runs tinycc-native, so it names the headers+-- that compiler reads in @C_INCLUDE_PATH@, and no C string literal it+-- passes names a store path.  replace writes a file unchanged when its+-- match is missing, so every file an edit writes has a sum the script+-- checks after the last edit.+testBusyboxWindows :: IO [Bool]+testBusyboxWindows = do+  putStrLn "pkgs/busybox-w32"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let windows = "(import " <> nixQuotedPath (cwd </> "pkgs" </> "windows") <> ")"+      checks = "import " <> nixQuotedPath (cwd </> "test" </> "data" </> "busybox.nix")+      source =+        T.concat+          [ "let pkgs = ",+            windows,+            "; checks = ",+            checks,+            "; in builtins.concatStringsSep \" \" [ ",+            T.unwords [path <> ".drvPath" | path <- roots],+            " ]"+          ]+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> do+          let rootOf = Map.fromList (zip roots (T.words (bytesText bytes)))+          tinyccGraph <- sessionClosure (mapMaybe (`Map.lookup` rootOf) tinyccRoots)+          full <- sessionClosure (Map.elems rootOf)+          pure (rootOf, tinyccGraph, full)+        other -> throwEvalError ("expected the drvPaths as one string, got " <> typeName other)+  writes <- readIORef (esStoreWriteCache st)+  case outcome of+    Left err -> sequence [runTest instantiates (Fail err)]+    Right (rootOf, tinyccGraph, full) -> do+      let added = Map.elems (Map.difference full tinyccGraph)+          nameOf drv = maybe "" bytesText (Map.lookup "name" (drvEnv drv))+          variableOf name drv = maybe "" bytesText (Map.lookup name (drvEnv drv))+          builtBy attr = Map.lookup attr rootOf >>= (`Map.lookup` full)+          inputsOf drv = mapMaybe ((`Map.lookup` full) . storePathToText defaultStoreDir) (Map.keys (drvInputDrvs drv))+          scriptOf drv = listToMaybe [variableOf "text" input | input <- inputsOf drv, nameOf input == nameOf drv <> "-builder"]+          isFetch drv = drvBuilder drv == "builtin:fetchurl"+          isFixedOutput drv = not (all (T.null . doHash) (drvOutputs drv))+          addedLeaves = filter (Map.null . drvInputDrvs) added+          wroteAsText path = fmap snd (Map.lookup (storePathToText defaultStoreDir path) writes) == Just WriteText+          runsTcc script = "/bin/tcc.exe " `T.isInfixOf` script+          -- The text between each pair of kaem's escaped quotes, which a+          -- -D hands tcc as a C string literal.+          cStrings script = [text | (i, text) <- zip [0 :: Int ..] (T.splitOn "\\\"" script), odd i]+          strings = concatMap cStrings (mapMaybe scriptOf added)+          busyboxScript = fromMaybe "" (builtBy "pkgs.busybox-w32" >>= scriptOf)+          edited = Set.fromList [TE.encodeUtf8 file | line <- T.lines busyboxScript, "replace" : "--file" : file : _ <- [T.words line]]+          -- The sums reach the build through its script, whose writeText+          -- derivation reads them as an input source.+          sumsPath = listToMaybe [path | drv <- added, path <- drvInputSrcs drv, spName path == "busybox-w32-edits.sha256"]+          numbered = zip [0 :: Int ..] (T.lines busyboxScript)+          checkedAfterEdits = case [i | (i, line) <- numbered, "sha256sum --check " `T.isPrefixOf` line] of+            [check] -> all (< check) [i | (i, line) <- numbered, "replace " `T.isPrefixOf` line]+            _ -> False+      sums <- traverse (BS.readFile . storePathToFilePath storeDir) sumsPath+      let summed = Set.fromList [file | bytes <- maybeToList sums, line <- BS8.lines bytes, [_, file] <- [BS8.words line]]+      sequence+        [ runTest instantiates $+            assertEqual "derivations added" (sort addedNames) (sort (map nameOf added)),+          runTest "every derivation it adds but the fetches is i686-windows" $+            case [nameOf drv | drv <- added, not (isFetch drv), drvPlatform drv /= I686_Windows] of+              [] -> Pass+              named -> Fail ("not i686-windows: " <> T.intercalate ", " named),+          runTest "the leaves it adds are busybox-w32's archive and the mingw-w64-crt sources, fetched fixed-output" $+            assertEqual+              "leaves added"+              (sort (("busybox-w32-" <> version <> ".tgz") : crtSources), True)+              (sort (map nameOf addedLeaves), all (\drv -> isFetch drv && isFixedOutput drv) addedLeaves),+          runTest "it reads no input source but what evaluation writes as text and the package's own sources" $+            assertEqual+              "input sources not written as text"+              ["compat", "gen_build_files.c", "usage_compressed.c"]+              (sort [spName path | drv <- added, path <- drvInputSrcs drv, not (wroteAsText path)]),+          runTest "busybox-w32's script runs tinycc-native with the headers its library script names" $+            assertEqual+              "derivations that run tcc, and their C_INCLUDE_PATH"+              [("busybox-w32-" <> version, variableOf "C_INCLUDE_PATH" <$> builtBy "pkgs.tinycc-native.libs")]+              [(nameOf drv, Just (variableOf "C_INCLUDE_PATH" drv)) | drv <- added, Just text <- [scriptOf drv], runsTcc text],+          -- One per busybox-w32 source, the empty MINGW_VER Makefile.flags+          -- defines.+          runTest "no C string literal busybox-w32's script passes names a store path" $+            assertEqual+              "string literals, and those that name a store path"+              (sourceCount, [])+              (length strings, filter ("${NIX_STORE}" `T.isInfixOf`) strings),+          runTest "every file busybox-w32's edits write is checked against its sum, once they are all made" $+            assertEqual+              "files edited, and files summed, and the one check after the last edit"+              (edited, True, True)+              (summed, not (Set.null edited), checkedAfterEdits)+        ]+  where+    instantiates :: Text+    instantiates = "the busybox-w32 derivations instantiate, adding thirteen to tinycc-native's"+    version :: Text+    version = "FRP-6354-g5f09fb446"+    sourceCount :: Int+    sourceCount = 336+    crtSources :: [Text]+    crtSources = ["getopt.c", "mempcpy.c", "mingw_usleep.c", "strtok_r.c", "msvcr80plus_ftruncate64.c"]+    tinyccRoots :: [Text]+    tinyccRoots = ["pkgs.tinycc-native.compiler", "pkgs.tinycc-native.libs"]+    roots :: [Text]+    roots = tinyccRoots ++ ["pkgs.busybox-w32", "checks.version", "checks.configure-tools"]+    -- Each kaem.runCommand adds its script, written by writeText as+    -- <name>-builder.+    addedNames :: [Text]+    addedNames =+      ("busybox-w32-" <> version <> ".tgz")+        : "configure-tools.sh"+        : crtSources+        ++ concat [[name, name <> "-builder"] | name <- ["busybox-w32-" <> version, "busybox-w32-get-version", "busybox-w32-configure-tools"]]++-- | The checks under @test\/data@ that the ladder's CI jobs build, each of+-- which has to forbid substitutes: CI publishes what it builds on main, and+-- a check whose output a cache held would be downloaded where it is meant+-- to run, and would test nothing while its job stayed green.  The one+-- attribute that may be substituted is @run-command.nix@'s hello, a file+-- @writeText@ writes, which takes no attributes.+testChecksForbidSubstitutes :: IO [Bool]+testChecksForbidSubstitutes = do+  putStrLn "pkgs/checks"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let fileOf name = nixQuotedPath (cwd </> "test" </> "data" </> T.unpack name)+      source =+        T.concat+          [ "let substitutable = file: set: map (name: \"${file}:${name}\") (builtins.filter (name: (set.${name}.allowSubstitutes or true) != false) (builtins.attrNames set)); in builtins.concatStringsSep \" \" (",+            T.intercalate " ++ " ["substitutable \"" <> name <> "\" (import " <> fileOf name <> ")" | name <- checkFiles],+            ")"+          ]+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> pure (T.words (bytesText bytes))+        other -> throwEvalError ("expected the attributes as one string, got " <> typeName other)+  sequence+    [ runTest "every check forbids substitutes but the file writeText writes" $+        either Fail (assertEqual "checks that may be substituted" ["run-command.nix:hello"]) outcome+    ]+  where+    checkFiles :: [Text]+    checkFiles = ["bash.nix", "binutils.nix", "binutils-native-x86_64.nix", "binutils-x86_64.nix", "busybox.nix", "gcc-core.nix", "gcc-core-x86_64.nix", "gcc-latest.nix", "gcc-native-x86_64.nix", "gcc-x86_64.nix", "gcc10.nix", "gcc46.nix", "gcc46-cxx.nix", "gnumake.nix", "mes.nix", "mingw-w64-latest.nix", "mingw-w64-x86_64.nix", "run-command.nix", "seed-stdenv.nix", "stdenv.nix", "tinycc.nix"]++-- | @pkgs/windows@'s seed stdenv, read back as the build driver reads it:+-- what the stdenv and GNU Hello built with it, @test\/data\/seed-stdenv.nix@'s+-- hello, add to the closure of the tools it is made of, busybox-w32, GNU+-- make and tinycc-native.  The one leaf it adds is hello's archive, and it+-- reads no input source but the stdenv's own files and what evaluation+-- writes as text.  The leaves of hello's whole closure are the seed and+-- the sources the ladder fetches; MinGW-w64's files there are the five+-- mingw-w64-crt sources busybox-w32 compiles and the declarations its+-- compat headers and the stdenv's sdkddkver.h transcribe.+testSeedStdenvWindows :: IO [Bool]+testSeedStdenvWindows = do+  putStrLn "pkgs/seed-stdenv"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let windows = "(import " <> nixQuotedPath (cwd </> "pkgs" </> "windows") <> ")"+      checks = "import " <> nixQuotedPath (cwd </> "test" </> "data" </> "seed-stdenv.nix")+      source =+        T.concat+          [ "let pkgs = ",+            windows,+            "; checks = ",+            checks,+            "; in builtins.concatStringsSep \" \" [ ",+            T.unwords [path <> ".drvPath" | path <- roots],+            " ]"+          ]+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> do+          let rootOf = Map.fromList (zip roots (T.words (bytesText bytes)))+              closureOf attrs = sessionClosure (mapMaybe (`Map.lookup` rootOf) attrs)+          tools <- closureOf toolRoots+          seed <- closureOf [seedHello]+          pure (tools, seed)+        other -> throwEvalError ("expected the drvPaths as one string, got " <> typeName other)+  writes <- readIORef (esStoreWriteCache st)+  case outcome of+    Left err -> sequence [runTest instantiates (Fail err)]+    Right (tools, seed) -> do+      let added = Map.elems (Map.difference seed tools)+          nameOf drv = maybe "" bytesText (Map.lookup "name" (drvEnv drv))+          isFetch drv = drvBuilder drv == "builtin:fetchurl"+          isFixedOutput drv = not (all (T.null . doHash) (drvOutputs drv))+          leavesOf = filter (Map.null . drvInputDrvs)+          addedLeaves = leavesOf added+          seedLeaves = leavesOf (Map.elems seed)+          wroteAsText path = fmap snd (Map.lookup (storePathToText defaultStoreDir path) writes) == Just WriteText+      sequence+        [ runTest instantiates $+            assertEqual "derivations added" (sort addedNames) (sort (map nameOf added)),+          runTest "every derivation it adds but the fetch is i686-windows" $+            case [nameOf drv | drv <- added, not (isFetch drv), drvPlatform drv /= I686_Windows] of+              [] -> Pass+              named -> Fail ("not i686-windows: " <> T.intercalate ", " named),+          runTest "the one leaf it adds is hello's archive, fetched fixed-output" $+            assertEqual+              "leaves added"+              ([helloArchive], True)+              (map nameOf addedLeaves, all (\drv -> isFetch drv && isFixedOutput drv) addedLeaves),+          runTest "it reads no input source but what evaluation writes as text and the stdenv's own files" $+            assertEqual+              "input sources not written as text"+              ["applet.c", "config.site", "include", "setup.sh"]+              (sort [spName path | drv <- added, path <- drvInputSrcs drv, not (wroteAsText path)]),+          runTest "the leaves of hello's closure are the seed and the ladder's sources, all fetched fixed-output" $+            assertEqual+              "leaves"+              (sort closureLeaves, True)+              (sort (map nameOf seedLeaves), all (\drv -> isFetch drv && isFixedOutput drv) seedLeaves)+        ]+  where+    instantiates :: Text+    instantiates = "the seed stdenv and its hello instantiate, adding three to the closure of their tools"+    toolRoots :: [Text]+    toolRoots = ["pkgs.busybox-w32", "pkgs.gnumake", "pkgs.tinycc-native.compiler", "pkgs.tinycc-native.libs"]+    seedHello :: Text+    seedHello = "checks.hello"+    roots :: [Text]+    roots = toolRoots ++ [seedHello]+    helloArchive :: Text+    helloArchive = "hello-2.12.3.tar.gz"+    addedNames :: [Text]+    addedNames = [helloArchive, "busybox-w32-FRP-6354-g5f09fb446-applets", "hello"]+    -- stage0-pe32's seed and sources, Mes and NYACC, janneke's TinyCC and+    -- TinyCC's own, GNU make, busybox-w32 and the mingw-w64-crt sources it+    -- compiles, and hello.+    closureLeaves :: [Text]+    closureLeaves =+      [ "hex0-seed.exe",+        "stage0-pe32-a81c837.tar.gz",+        "M2-Planet-ee0bf91.tar.gz",+        "M2libc-ef9dfc2.tar.gz",+        "mescc-tools-578ac99.tar.gz",+        "mescc-tools-extra-d1d8146.tar.gz",+        "mes-77ff40b.tar.gz",+        "nyacc-1.09.1.tar.gz",+        "tinycc-ea3900f6d5e71776c5cfabcabee317652e3a19ee.tar.gz",+        "tinycc-cb41cbfe717e4c00d7bb70035cda5ee5f0ff9341.tar.gz",+        "make-4.4.1.tar.gz",+        "busybox-w32-FRP-6354-g5f09fb446.tgz",+        "getopt.c",+        "mempcpy.c",+        "mingw_usleep.c",+        "strtok_r.c",+        "msvcr80plus_ftruncate64.c",+        helloArchive+      ]++-- | @pkgs/windows@'s binutils, read back as the build driver reads it: what+-- binutils and @test\/data\/binutils.nix@'s checks add to the closure of+-- the seed stdenv's tools and applets, which build it.  The rung is+-- full-source only if the one leaf it adds is binutils' archive, and it+-- reads no input source but the stdenv's own files, the package's patches+-- and compatibility headers, and what evaluation writes as text.  The+-- stdenv's @setup.sh@ applies the patches and searches the headers only if+-- the derivation names them in the variables it reads, @patches@ and+-- @buildInputs@.  The target is the triple GCC is configured for on the+-- next rung, which finds these tools by its name.+testBinutilsWindows :: IO [Bool]+testBinutilsWindows = do+  putStrLn "pkgs/binutils"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let windows = "(import " <> nixQuotedPath (cwd </> "pkgs" </> "windows") <> ")"+      checks = "import " <> nixQuotedPath (cwd </> "test" </> "data" </> "binutils.nix")+      source =+        T.concat+          [ "let pkgs = ",+            windows,+            "; checks = ",+            checks,+            "; in builtins.concatStringsSep \" \" [ ",+            T.unwords [path <> ".drvPath" | path <- roots],+            " ]"+          ]+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> do+          let rootOf = Map.fromList (zip roots (T.words (bytesText bytes)))+          stdenvGraph <- sessionClosure (mapMaybe (`Map.lookup` rootOf) stdenvRoots)+          full <- sessionClosure (Map.elems rootOf)+          pure (rootOf, stdenvGraph, full)+        other -> throwEvalError ("expected the drvPaths as one string, got " <> typeName other)+  writes <- readIORef (esStoreWriteCache st)+  case outcome of+    Left err -> sequence [runTest instantiates (Fail err)]+    Right (rootOf, stdenvGraph, full) -> do+      let added = Map.elems (Map.difference full stdenvGraph)+          nameOf drv = maybe "" bytesText (Map.lookup "name" (drvEnv drv))+          variableOf name drv = maybe "" bytesText (Map.lookup name (drvEnv drv))+          isFetch drv = drvBuilder drv == "builtin:fetchurl"+          isFixedOutput drv = not (all (T.null . doHash) (drvOutputs drv))+          addedLeaves = filter (Map.null . drvInputDrvs) added+          wroteAsText path = fmap snd (Map.lookup (storePathToText defaultStoreDir path) writes) == Just WriteText+          binutils = Map.lookup binutilsRoot rootOf >>= (`Map.lookup` full)+          -- The input sources of binutils' derivation under a name, as its+          -- environment spells a store path.+          sourcesNamed name = [storePathToText defaultStoreDir path | drv <- maybeToList binutils, path <- drvInputSrcs drv, spName path == name]+          wordsOf name = maybe [] (T.words . variableOf name) binutils+      sequence+        [ runTest instantiates $+            assertEqual "derivations added" (sort addedNames) (sort (map nameOf added)),+          runTest "every derivation it adds but the fetch is i686-windows" $+            case [nameOf drv | drv <- added, not (isFetch drv), drvPlatform drv /= I686_Windows] of+              [] -> Pass+              named -> Fail ("not i686-windows: " <> T.intercalate ", " named),+          runTest "the one leaf it adds is binutils' archive, fetched fixed-output" $+            assertEqual+              "leaves added"+              ([archive], True)+              (map nameOf addedLeaves, all (\drv -> isFetch drv && isFixedOutput drv) addedLeaves),+          runTest "it reads no input source but what evaluation writes as text, the stdenv's files and the package's patches and headers" $+            assertEqual+              "input sources not written as text"+              (sort (["compat", "config.site", "include", "setup.sh"] ++ patches))+              (sort [spName path | drv <- added, path <- drvInputSrcs drv, not (wroteAsText path)]),+          runTest "binutils names its patches and its headers where setup.sh reads them" $+            assertEqual+              "patches and buildInputs"+              (concatMap sourcesNamed patches, sourcesNamed "compat", True)+              (wordsOf "patches", wordsOf "buildInputs", isJust binutils),+          runTest "binutils is configured for the target GCC is" $+            assertEqual "target flags" ["--target=" <> target] (filter ("--target=" `T.isPrefixOf`) (wordsOf "configureFlags"))+        ]+  where+    instantiates :: Text+    instantiates = "the binutils derivations instantiate, adding seven to the closure of the seed stdenv's tools"+    version :: Text+    version = "2.41"+    archive :: Text+    archive = "binutils-" <> version <> ".tar.xz"+    patches :: [Text]+    patches = ["fix-tinycc-attribute.patch", "temp-file-binary.patch"]+    target :: Text+    target = "i686-w64-mingw32"+    binutilsRoot :: Text+    binutilsRoot = "pkgs.binutils"+    stdenvRoots :: [Text]+    stdenvRoots = ["pkgs.busybox-w32", "pkgs.gnumake", "pkgs.tinycc-native.compiler", "pkgs.tinycc-native.libs", "pkgs.seedStdenv.applets"]+    roots :: [Text]+    roots = stdenvRoots ++ [binutilsRoot, "checks.version", "checks.answer"]+    -- Each kaem.runCommand adds its script, written by writeText as+    -- <name>-builder.+    addedNames :: [Text]+    addedNames =+      [archive, "binutils-" <> version, "answer.sh"]+        ++ concat [[name, name <> "-builder"] | name <- ["binutils-get-version", "binutils-answer"]]++-- | @pkgs/windows@'s GCC rung, read back as the build driver reads it: what+-- mingw-w64-headers, mingw-w64-dirent, gcc-core and+-- @test\/data\/gcc-core.nix@'s checks add to the closure of the seed+-- stdenv's tools and binutils, which build them.  The rung is full-source+-- only if the leaves it adds are the six sources it names, and it reads no+-- input source but the stdenv's own files, gcc-core's patch, the header+-- mingw-w64-dirent compiles its source against, and what evaluation writes+-- as text.  The stdenv's @setup.sh@ applies the patch only if the+-- derivation names it in @patches@, and gcc-core's @preConfigure@ unpacks+-- gmp, mpfr and mpc from the variables that name their archives.  GCC's+-- configure is told where the headers, the assembler, the linker and the+-- dirent library are by flags, so each has to name the output of the+-- derivation that builds it.  The headers are named with @--with-headers@+-- and never with @--with-sysroot@: GCC's top level hands its options to+-- mpc's configure, whose libtool has a @--with-sysroot@ of its own and+-- stops at a path that begins with a drive letter, as every store path on+-- Windows does.  @--with-headers@ names the @include@ directory of+-- mingw-w64-headers' output, where its configure installs them unless a+-- flag moves them.  libgcc is built and installed by the same make,+-- without debugging information, which reaches it through the target+-- libraries' CFLAGS and through a make variable of GCC's own.+testGccCoreWindows :: IO [Bool]+testGccCoreWindows = do+  putStrLn "pkgs/gcc-core"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let windows = "(import " <> nixQuotedPath (cwd </> "pkgs" </> "windows") <> ")"+      checks = "import " <> nixQuotedPath (cwd </> "test" </> "data" </> "gcc-core.nix")+      source =+        T.concat+          [ "let pkgs = ",+            windows,+            "; checks = ",+            checks,+            "; in builtins.concatStringsSep \" \" [ ",+            T.unwords [path <> ".drvPath" | path <- roots],+            " ]"+          ]+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> do+          let rootOf = Map.fromList (zip roots (T.words (bytesText bytes)))+          before <- sessionClosure (mapMaybe (`Map.lookup` rootOf) builtBefore)+          full <- sessionClosure (Map.elems rootOf)+          pure (rootOf, before, full)+        other -> throwEvalError ("expected the drvPaths as one string, got " <> typeName other)+  writes <- readIORef (esStoreWriteCache st)+  gmpPatchLines <- BS8.lines <$> BS.readFile (cwd </> "pkgs" </> "windows" </> "by-name" </> "gc" </> "gcc-core" </> T.unpack gmpPatch)+  case outcome of+    Left err -> sequence [runTest instantiates (Fail err)]+    Right (rootOf, before, full) -> do+      let added = Map.elems (Map.difference full before)+          nameOf drv = maybe "" bytesText (Map.lookup "name" (drvEnv drv))+          variableOf name drv = maybe "" bytesText (Map.lookup name (drvEnv drv))+          isFetch drv = drvBuilder drv == "builtin:fetchurl"+          isFixedOutput drv = not (all (T.null . doHash) (drvOutputs drv))+          addedLeaves = filter (Map.null . drvInputDrvs) added+          wroteAsText path = fmap snd (Map.lookup (storePathToText defaultStoreDir path) writes) == Just WriteText+          derivationAt root = Map.lookup root rootOf >>= (`Map.lookup` full)+          gccCore = derivationAt gccCoreRoot+          headers = derivationAt headersRoot+          -- The output of a root's derivation, as a flag spells a store+          -- path, or a word no flag holds where the root is missing.+          outputOf root = maybe "<no output>" (storePathToText defaultStoreDir . doPath) (derivationAt root >>= listToMaybe . drvOutputs)+          outputNamed name = [storePathToText defaultStoreDir (doPath out) | drv <- added, nameOf drv == name, out <- drvOutputs drv]+          sourcesNamed name = [storePathToText defaultStoreDir path | drv <- maybeToList gccCore, path <- drvInputSrcs drv, spName path == name]+          wordsOf name = maybe [] (T.words . variableOf name)+          flagsWith prefixes drv = [flag | flag <- wordsOf "configureFlags" drv, any (`T.isPrefixOf` flag) prefixes]+          -- gmp's patch: the file it changes, the lines it removes, and the+          -- digit strings among the lines it adds, each a quoted value to+          -- sixteen places.+          gmpPatchFiles = [rest | line <- gmpPatchLines, Just rest <- [BS.stripPrefix "+++ " line]]+          gmpPatchRemoved = [rest | line <- gmpPatchLines, Just rest <- [BS.stripPrefix "-" line], not ("-- " `BS.isPrefixOf` rest)]+          gmpPatchAdded = [rest | line <- gmpPatchLines, Just rest <- [BS.stripPrefix "+" line], not ("++ " `BS.isPrefixOf` rest)]+          quoted line = [part | (index, part) <- zip [0 :: Int ..] (BS8.split '"' line), odd index]+          isDigits text = case BS8.uncons text of+            Just (leading, rest) -> leading `elem` ("01" :: String) && BS.length rest == 17 && "." `BS.isPrefixOf` rest && BS8.all isDigit (BS.drop 1 rest)+            Nothing -> False+          gmpDigits = concatMap (filter isDigits . quoted) gmpPatchAdded+          -- Whether a base's digits, read as a number, are log 2 / log base+          -- as this host's double precision computes it, to within+          -- digitsTolerance.+          nearValue :: Int -> BS.ByteString -> Bool+          nearValue base text = maybe False (\value -> abs (value - logBase (fromIntegral base) 2) < digitsTolerance) (readMaybe (BS8.unpack text))+      sequence+        [ runTest instantiates $+            assertEqual "derivations added" (sort addedNames) (sort (map nameOf added)),+          runTest "every derivation it adds but the fetches is i686-windows" $+            case [nameOf drv | drv <- added, not (isFetch drv), drvPlatform drv /= I686_Windows] of+              [] -> Pass+              named -> Fail ("not i686-windows: " <> T.intercalate ", " named),+          runTest "the leaves it adds are its six sources, fetched fixed-output" $+            assertEqual+              "leaves added"+              (sort archives, True)+              (sort (map nameOf addedLeaves), all (\drv -> isFetch drv && isFixedOutput drv) addedLeaves),+          runTest "it reads no input source but what evaluation writes as text, the stdenv's files, its two patches and the dirent header" $+            assertEqual+              "input sources not written as text"+              ["config.site", "config.site", patch, gmpPatch, "include", "include", "include", "setup.sh", "setup.sh"]+              (sort [spName path | drv <- added, path <- drvInputSrcs drv, not (wroteAsText path)]),+          runTest "gcc-core names its patch, its build inputs and its three libraries' archives where setup.sh and preConfigure read them" $+            assertEqual+              "patches, buildInputs and the archives"+              (sourcesNamed patch, [outputOf direntRoot, outputOf binutilsRoot], map (outputNamed . snd) mathArchives, True)+              (wordsOf "patches" gccCore, wordsOf "buildInputs" gccCore, [wordsOf variable gccCore | (variable, _) <- mathArchives], isJust gccCore),+          runTest "gcc-core names gmp's patch and applies it once preConfigure has unpacked gmp" $+            assertEqual+              "gmpPatch and the preConfigure lines from gmp's unpacking"+              ( sourcesNamed gmpPatch,+                ["tar xf \"$gmpSrc\"", "mv gmp-4.3.2 gmp", "(cd gmp && patch -p1 -i \"$gmpPatch\")"]+              )+              ( wordsOf "gmpPatch" gccCore,+                take 3 (dropWhile (/= "tar xf \"$gmpSrc\"") (maybe [] (map T.strip . T.lines . variableOf "preConfigure") gccCore))+              ),+          runTest "gmp's patch has gmp's base table written from fixed digits, log 2 / log base for each base from 2 to 256, in place of gmp's log, and changes nothing else" $+            assertEqual+              "the file it changes, the lines it removes, how many digit strings it adds, and whether each base's are its value"+              (["b/gen-bases.c"], removedByGmpPatch, length tableBases, [(base, True) | base <- tableBases])+              ( gmpPatchFiles,+                gmpPatchRemoved,+                length gmpDigits,+                [(base, nearValue base text) | (base, text) <- zip tableBases gmpDigits]+              ),+          runTest "gcc-core's flags name the target binutils is configured for and the outputs of the headers, binutils and the dirent library, and no sysroot" $+            assertEqual+              "flags"+              [ "--target=" <> target,+                "--with-headers=" <> outputOf headersRoot <> "/include",+                "--with-as=" <> outputOf binutilsRoot <> "/bin/" <> target <> "-as.exe",+                "--with-ld=" <> outputOf binutilsRoot <> "/bin/" <> target <> "-ld.exe",+                "--with-stage1-libs=" <> outputOf direntRoot <> "/lib/libdirent.a"+              ]+              (flagsWith ["--target=", "--with-headers", "--with-sysroot", "--with-build-sysroot", "--with-as=", "--with-ld=", "--with-stage1-libs="] gccCore),+          runTest "gcc-core builds and installs the compiler and libgcc, make running NIX_BUILD_CORES jobs with its makeFlags" $+            assertEqual+              "phases and parallelism"+              ( "make ${enableParallelBuilding:+-j$NIX_BUILD_CORES} $makeFlags all-gcc all-target-libgcc",+                "make ${enableParallelInstalling:+-j$NIX_BUILD_CORES} $makeFlags install-gcc install-target-libgcc",+                "1",+                "1"+              )+              ( maybe "" (variableOf "buildPhase") gccCore,+                maybe "" (variableOf "installPhase") gccCore,+                maybe "" (variableOf "enableParallelBuilding") gccCore,+                maybe "" (variableOf "enableParallelInstalling") gccCore+              ),+          runTestIO+            "the seed stdenv installs in parallel where a package builds in parallel and does not turn installing off"+            cwd+            ( "let mk = "+                <> windows+                <> ".seedStdenv.mkDerivation; installing = d: if d.drvAttrs ? enableParallelInstalling then (if d.drvAttrs.enableParallelInstalling then \"on\" else \"off\") else \"unset\"; in "+                <> "builtins.concatStringsSep \" \" (map installing [ (mk { name = \"a\"; enableParallelBuilding = true; }) (mk { name = \"b\"; enableParallelBuilding = true; enableParallelInstalling = false; }) (mk { name = \"c\"; }) ])"+            )+            (mkStr "on off unset"),+          runTest "gcc-core passes configure CFLAGS_FOR_TARGET=-O2 and make LIBGCC2_DEBUG_CFLAGS=-g0, the two settings that keep -g from libgcc" $+            assertEqual+              "the target's CFLAGS and makeFlags"+              (["CFLAGS_FOR_TARGET=-O2"], ["LIBGCC2_DEBUG_CFLAGS=-g0"])+              (flagsWith ["CFLAGS_FOR_TARGET="] gccCore, wordsOf "makeFlags" gccCore),+          runTest "mingw-w64-headers is configured in its own directory, for msvcrt, with no flag that moves the include directory gcc-core names" $+            assertEqual+              "preConfigure and flags"+              ("cd mingw-w64-headers", ["--with-default-msvcrt=msvcrt"])+              (maybe "" (variableOf "preConfigure") headers, wordsOf "configureFlags" headers)+        ]+  where+    instantiates :: Text+    instantiates = "the GCC rung's derivations instantiate, adding fifteen to the closure of the seed stdenv's tools and binutils"+    version :: Text+    version = "4.6.4"+    mingwVersion :: Text+    mingwVersion = "8.0.3"+    patch :: Text+    patch = "fix-tinycc-attribute.patch"+    gmpPatch :: Text+    gmpPatch = "gmp-bases-digits.patch"+    -- The lines gmp's patch takes out of its table generator: the math+    -- header, the double that holds each base's value, the value's+    -- computation with the build machine's log, and the two formats that+    -- print the double.+    removedByGmpPatch :: [BS.ByteString]+    removedByGmpPatch =+      [ "#include <math.h>",+        "",+        "double chars_per_bit_exactly;",+        "  chars_per_bit_exactly = 0.69314718055994530942 / log ((double) base);",+        "          printf (\"%u, %.16f, 0x%x },\\n\",",+        "          printf (\"%u, %.16f, CNST_LIMB(0x\","+      ]+    -- The bases gmp's table holds a value for, each with its digits.+    tableBases :: [Int]+    tableBases = [2 .. 256]+    -- How far a base's digits may be from the value this host computes:+    -- far outside their rounding to sixteen places and any host log's+    -- error, and far inside the gap between two bases' values.+    digitsTolerance :: Double+    digitsTolerance = 1.0e-15+    target :: Text+    target = "i686-w64-mingw32"+    -- The variable gcc-core's preConfigure unpacks each library from, and+    -- the archive it names.+    mathArchives :: [(Text, Text)]+    mathArchives = [("gmpSrc", "gmp-4.3.2.tar.gz"), ("mpfrSrc", "mpfr-2.4.2.tar.gz"), ("mpcSrc", "mpc-1.0.3.tar.gz")]+    archives :: [Text]+    archives = ["gcc-core-" <> version <> ".tar.gz", "mingw-w64-v" <> mingwVersion <> ".tar.bz2", "dirent.c"] ++ map snd mathArchives+    gccCoreRoot :: Text+    gccCoreRoot = "pkgs.gcc-core"+    headersRoot :: Text+    headersRoot = "pkgs.mingw-w64-headers"+    direntRoot :: Text+    direntRoot = "pkgs.mingw-w64-dirent"+    binutilsRoot :: Text+    binutilsRoot = "pkgs.binutils"+    builtBefore :: [Text]+    builtBefore = ["pkgs.busybox-w32", "pkgs.gnumake", "pkgs.tinycc-native.compiler", "pkgs.tinycc-native.libs", "pkgs.seedStdenv.applets", binutilsRoot]+    roots :: [Text]+    roots = builtBefore ++ [headersRoot, direntRoot, gccCoreRoot, "checks.version", "checks.answer"]+    -- Each kaem.runCommand adds its script, written by writeText as+    -- <name>-builder.+    addedNames :: [Text]+    addedNames =+      archives+        ++ ["mingw-w64-headers-" <> mingwVersion, "gcc-core-" <> version, "answer.sh"]+        ++ concat [[name, name <> "-builder"] | name <- ["mingw-w64-dirent-" <> mingwVersion, "gcc-core-get-version", "gcc-core-answer"]]++-- | @pkgs/windows@'s rung after GCC's core, read back as the build driver+-- reads it: what mingw-w64-crt, gcc46 and @test\/data\/gcc46.nix@'s checks+-- add to the closure of the GCC rung, which builds them.  The rung fetches+-- nothing: the runtime is compiled from mingw-w64-headers' archive, so it+-- adds no leaf, and it reads no input source but the stdenv's own files.+-- The runtime's configure takes the compiler and archiver the environment+-- names, and the stdenv's are tcc's, so its @preConfigure@ unsets them,+-- and @C_INCLUDE_PATH@, which GCC reads as well; its flags name the target+-- as the host and the headers' output as the sysroot, and its CFLAGS leave+-- out the @-g@ configure would add.  gcc46 compiles nothing: busybox's sh+-- copies gcc-core's output and the runtime's into one prefix, where the+-- driver, run from there, finds the start files and libraries every link+-- names.+testGcc46Windows :: IO [Bool]+testGcc46Windows = do+  putStrLn "pkgs/gcc46"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let windows = "(import " <> nixQuotedPath (cwd </> "pkgs" </> "windows") <> ")"+      checks = "import " <> nixQuotedPath (cwd </> "test" </> "data" </> "gcc46.nix")+      source =+        T.concat+          [ "let pkgs = ",+            windows,+            "; checks = ",+            checks,+            "; in builtins.concatStringsSep \" \" [ ",+            T.unwords [path <> ".drvPath" | path <- roots],+            " ]"+          ]+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> do+          let rootOf = Map.fromList (zip roots (T.words (bytesText bytes)))+          before <- sessionClosure (mapMaybe (`Map.lookup` rootOf) builtBefore)+          full <- sessionClosure (Map.elems rootOf)+          pure (rootOf, before, full)+        other -> throwEvalError ("expected the drvPaths as one string, got " <> typeName other)+  writes <- readIORef (esStoreWriteCache st)+  case outcome of+    Left err -> sequence [runTest instantiates (Fail err)]+    Right (rootOf, before, full) -> do+      let added = Map.elems (Map.difference full before)+          nameOf drv = maybe "" bytesText (Map.lookup "name" (drvEnv drv))+          variableOf name drv = maybe "" bytesText (Map.lookup name (drvEnv drv))+          addedLeaves = filter (Map.null . drvInputDrvs) added+          wroteAsText path = fmap snd (Map.lookup (storePathToText defaultStoreDir path) writes) == Just WriteText+          derivationAt root = Map.lookup root rootOf >>= (`Map.lookup` full)+          crt = derivationAt crtRoot+          gcc46 = derivationAt gcc46Root+          headers = derivationAt headersRoot+          -- The output of a root's derivation, as a flag spells a store+          -- path, or a word no flag holds where the root is missing.+          outputOf root = maybe "<no output>" (storePathToText defaultStoreDir . doPath) (derivationAt root >>= listToMaybe . drvOutputs)+          wordsOf name = maybe [] (T.words . variableOf name)+          -- What preConfigure runs before it moves to the build directory.+          firstLine = maybe "" (T.takeWhile (/= '\n') . variableOf "preConfigure")+      sequence+        [ runTest instantiates $+            assertEqual "derivations added" (sort addedNames) (sort (map nameOf added)),+          runTest "every derivation it adds is i686-windows" $+            case [nameOf drv | drv <- added, drvPlatform drv /= I686_Windows] of+              [] -> Pass+              named -> Fail ("not i686-windows: " <> T.intercalate ", " named),+          runTest "it adds no leaf: every source it builds from is the GCC rung's" $+            assertEqual "leaves added" [] (map nameOf addedLeaves),+          runTest "it reads no input source but what evaluation writes as text and the stdenv's files" $+            assertEqual+              "input sources not written as text"+              ["config.site", "include", "setup.sh"]+              (sort [spName path | drv <- added, path <- drvInputSrcs drv, not (wroteAsText path)]),+          runTest "mingw-w64-crt is built from mingw-w64-headers' archive by gcc-core and binutils, with tcc's variables unset" $+            assertEqual+              "src, buildInputs and preConfigure's first line"+              (wordsOf "src" headers, [outputOf gccCoreRoot, outputOf binutilsRoot], "unset CC AR C_INCLUDE_PATH", isJust headers)+              (wordsOf "src" crt, wordsOf "buildInputs" crt, firstLine crt, isJust crt),+          runTest "mingw-w64-crt's flags name the target as the host, mingw-w64-headers' output as the sysroot, msvcrt and the 32-bit runtime alone, and CFLAGS with no -g" $+            assertEqual+              "flags"+              [ "--host=" <> target,+                "--with-sysroot=" <> outputOf headersRoot,+                "--with-default-msvcrt=msvcrt",+                "--enable-lib32",+                "--disable-lib64",+                "--disable-dependency-tracking",+                "CFLAGS=-O2"+              ]+              (wordsOf "configureFlags" crt),+          runTest "mingw-w64-crt builds with NIX_BUILD_CORES jobs and installs with one" $+            assertEqual+              "parallelism"+              ("1", "")+              (maybe "" (variableOf "enableParallelBuilding") crt, maybe "" (variableOf "enableParallelInstalling") crt),+          runTest "gcc46 compiles nothing: busybox's sh runs its script over gcc-core's output, mingw-w64-crt's and the target's name" $+            assertEqual+              "builder, input derivations and the variables its script reads"+              ( outputOf busyboxRoot <> "/bin/busybox.exe",+                sort (mapMaybe (`Map.lookup` rootOf) [busyboxRoot, gccCoreRoot, crtRoot]),+                [outputOf gccCoreRoot, outputOf crtRoot, target]+              )+              ( maybe "" (bytesText . drvBuilder) gcc46,+                maybe [] (sort . map (storePathToText defaultStoreDir) . Map.keys . drvInputDrvs) gcc46,+                [maybe "" (variableOf name) gcc46 | name <- ["gccCore", "crt", "target"]]+              )+        ]+  where+    instantiates :: Text+    instantiates = "the rung's derivations instantiate, adding eight to the closure of the GCC rung"+    target :: Text+    target = "i686-w64-mingw32"+    crtRoot :: Text+    crtRoot = "pkgs.mingw-w64-crt"+    gcc46Root :: Text+    gcc46Root = "pkgs.gcc46"+    gccCoreRoot :: Text+    gccCoreRoot = "pkgs.gcc-core"+    headersRoot :: Text+    headersRoot = "pkgs.mingw-w64-headers"+    binutilsRoot :: Text+    binutilsRoot = "pkgs.binutils"+    busyboxRoot :: Text+    busyboxRoot = "pkgs.busybox-w32"+    builtBefore :: [Text]+    builtBefore = [busyboxRoot, "pkgs.gnumake", "pkgs.tinycc-native.compiler", "pkgs.tinycc-native.libs", "pkgs.seedStdenv.applets", binutilsRoot, headersRoot, "pkgs.mingw-w64-dirent", gccCoreRoot]+    roots :: [Text]+    roots = builtBefore ++ [crtRoot, gcc46Root, "checks.crt", "checks.hello"]+    -- Each kaem.runCommand adds its script, written by writeText as+    -- <name>-builder.+    addedNames :: [Text]+    addedNames =+      ["mingw-w64-crt-8.0.3", "gcc-4.6.4", "crt.sh", "hello.sh"]+        ++ concat [[name, name <> "-builder"] | name <- ["mingw-w64-crt-contents", "gcc46-hello"]]++-- | @pkgs\/windows@'s C++ rung, read back as the build driver reads it: what+-- gcc46-cxx and @test\/data\/gcc46-cxx.nix@'s checks add to the closure of+-- the rung before it, gcc46, which builds it.  The rung is full-source only+-- if the one leaf it adds is GCC's g++ archive and it reads no input source+-- but the stdenv's own files and what evaluation writes as text; the rest+-- of GCC's tree is gcc-core's four archives, which the stdenv's+-- @setup.sh@ (@src@) and its @preConfigure@ (the other three) unpack from+-- the variables that name them.  Its configure is told by+-- flags where MinGW-w64's headers and runtime, the assembler and the+-- linker are, and which compiler, archiver and linker the build runs, and+-- its install which strip, so each has to name the output of the+-- derivation that builds it, or the target's name binutils and gcc46+-- install their programs under.  Every flag that sets a compiler's options+-- leaves out the @-g@ whose debugging information would name the build+-- directory, and every link and strip is told to write no time stamp.+testGcc46CxxWindows :: IO [Bool]+testGcc46CxxWindows = do+  putStrLn "pkgs/gcc46-cxx"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let windows = "(import " <> nixQuotedPath (cwd </> "pkgs" </> "windows") <> ")"+      checks = "import " <> nixQuotedPath (cwd </> "test" </> "data" </> "gcc46-cxx.nix")+      source =+        T.concat+          [ "let pkgs = ",+            windows,+            "; checks = ",+            checks,+            "; in builtins.concatStringsSep \" \" [ ",+            T.unwords [path <> ".drvPath" | path <- roots],+            " ]"+          ]+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> do+          let rootOf = Map.fromList (zip roots (T.words (bytesText bytes)))+          before <- sessionClosure (mapMaybe (`Map.lookup` rootOf) builtBefore)+          full <- sessionClosure (Map.elems rootOf)+          pure (rootOf, before, full)+        other -> throwEvalError ("expected the drvPaths as one string, got " <> typeName other)+  writes <- readIORef (esStoreWriteCache st)+  case outcome of+    Left err -> sequence [runTest instantiates (Fail err)]+    Right (rootOf, before, full) -> do+      let added = Map.elems (Map.difference full before)+          nameOf drv = maybe "" bytesText (Map.lookup "name" (drvEnv drv))+          variableOf name drv = maybe "" bytesText (Map.lookup name (drvEnv drv))+          isFetch drv = drvBuilder drv == "builtin:fetchurl"+          isFixedOutput drv = not (all (T.null . doHash) (drvOutputs drv))+          addedLeaves = filter (Map.null . drvInputDrvs) added+          wroteAsText path = fmap snd (Map.lookup (storePathToText defaultStoreDir path) writes) == Just WriteText+          derivationAt root = Map.lookup root rootOf >>= (`Map.lookup` full)+          gccCxx = derivationAt gccCxxRoot+          gccCore = derivationAt gccCoreRoot+          -- The output of a root's derivation, as a flag spells a store+          -- path, or a word no flag holds where the root is missing.+          outputOf root = maybe "<no output>" (storePathToText defaultStoreDir . doPath) (derivationAt root >>= listToMaybe . drvOutputs)+          outputNamed name = [storePathToText defaultStoreDir (doPath out) | drv <- added, nameOf drv == name, out <- drvOutputs drv]+          wordsOf name = maybe [] (T.words . variableOf name)+          flagsWith prefixes drv = [flag | flag <- wordsOf "configureFlags" drv, any (`T.isPrefixOf` flag) prefixes]+      sequence+        [ runTest instantiates $+            assertEqual "derivations added" (sort addedNames) (sort (map nameOf added)),+          runTest "every derivation it adds but the fetch is i686-windows" $+            case [nameOf drv | drv <- added, not (isFetch drv), drvPlatform drv /= I686_Windows] of+              [] -> Pass+              named -> Fail ("not i686-windows: " <> T.intercalate ", " named),+          runTest "the one leaf it adds is GCC's g++ archive, fetched fixed-output" $+            assertEqual+              "leaves added"+              ([cxxArchive], True)+              (map nameOf addedLeaves, all (\drv -> isFetch drv && isFixedOutput drv) addedLeaves),+          runTest "it reads no input source but what evaluation writes as text, the stdenv's files and gmp's patch" $+            assertEqual+              "input sources not written as text"+              ["config.site", gmpPatch, "include", "setup.sh"]+              (sort [spName path | drv <- added, path <- drvInputSrcs drv, not (wroteAsText path)]),+          runTest "gcc46-cxx names gcc-core's four archives, gcc-core's patch of gmp and the g++ archive where setup.sh and preConfigure read them, with gcc46 and binutils as its build inputs and no patch of GCC's own" $+            assertEqual+              "the archives, gmp's patch, buildInputs and patches"+              ( [wordsOf variable gccCore | variable <- coreArchives] ++ [outputNamed cxxArchive],+                [outputOf gcc46Root, outputOf binutilsRoot],+                [],+                isJust gccCore+              )+              ( [wordsOf variable gccCxx | variable <- coreArchives ++ ["cxxSrc"]],+                wordsOf "buildInputs" gccCxx,+                wordsOf "patches" gccCxx,+                isJust gccCxx+              ),+          runTest "gcc46-cxx's flags name the target, the outputs of the headers, the runtime and binutils, and no sysroot" $+            assertEqual+              "flags"+              [ "--target=" <> target,+                "--with-headers=" <> outputOf headersRoot <> "/include",+                "--with-libs=" <> outputOf crtRoot <> "/lib",+                "--with-as=" <> outputOf binutilsRoot <> "/bin/" <> target <> "-as.exe",+                "--with-ld=" <> outputOf binutilsRoot <> "/bin/" <> target <> "-ld.exe"+              ]+              (flagsWith ["--target=", "--with-headers", "--with-libs", "--with-sysroot", "--with-build-sysroot", "--with-as=", "--with-ld="] gccCxx),+          runTest "gcc46-cxx builds with gcc46's driver and binutils' archiver and linker, by the target's names" $+            assertEqual+              "tools"+              ["CC=" <> target <> "-gcc", "AR=" <> target <> "-ar", "LD=" <> target <> "-ld"]+              (flagsWith ["CC=", "AR=", "LD=", "STRIP=", "CXX=", "RANLIB="] gccCxx),+          runTest "gcc46-cxx gives every link it makes --no-insert-timestamp, and LDFLAGS nothing else" $+            assertEqual+              "LDFLAGS"+              ["LDFLAGS=-Wl,--no-insert-timestamp"]+              (flagsWith ["LDFLAGS=", "LDFLAGS_FOR_BUILD="] gccCxx),+          runTest "gcc46-cxx's compiler options carry no -g, and libgcc's debugging flags are -g0" $+            assertEqual+              "the options and makeFlags"+              (["CFLAGS=-O1", "CXXFLAGS=-O1", "CFLAGS_FOR_TARGET=-O0", "CXXFLAGS_FOR_TARGET=-O0"], ["LIBGCC2_DEBUG_CFLAGS=-g0"])+              (flagsWith ["CFLAGS=", "CXXFLAGS=", "CFLAGS_FOR_TARGET=", "CXXFLAGS_FOR_TARGET="] gccCxx, wordsOf "makeFlags" gccCxx),+          runTest "gcc46-cxx builds C and C++, static, with no registry lookup" $+            assertEqual+              "languages, libraries and registry"+              ["--enable-languages=c,c++", "--disable-shared", "--disable-win32-registry"]+              (flagsWith ["--enable-languages=", "--enable-shared", "--disable-shared", "--enable-win32-registry", "--disable-win32-registry"] gccCxx),+          runTest "gcc46-cxx patches gmp's source with gmp's patch once preConfigure has unpacked it" $+            assertEqual+              "the preConfigure lines from gmp's unpacking"+              ["tar xf \"$gmpSrc\"", "mv gmp-4.3.2 gmp", "(cd gmp && patch -p1 -i \"$gmpPatch\")"]+              (take 3 (dropWhile (/= "tar xf \"$gmpSrc\"") (maybe [] (map T.strip . T.lines . variableOf "preConfigure") gccCxx))),+          runTest "gcc46-cxx unsets the stdenv's C_INCLUDE_PATH, and nothing else, before configure" $+            assertEqual+              "preConfigure's unset lines"+              ["unset C_INCLUDE_PATH"]+              (filter ("unset " `T.isPrefixOf`) (maybe [] (map T.strip . T.lines . variableOf "preConfigure") gccCxx)),+          runTest "gcc46-cxx builds all with NIX_BUILD_CORES jobs and installs with install-strip, whose strip keeps the zero time stamp ld writes" $+            assertEqual+              "phases and parallelism"+              ( "",+                "make ${enableParallelInstalling:+-j$NIX_BUILD_CORES} $makeFlags 'STRIP=" <> target <> "-strip -p' install-strip",+                "1",+                "1"+              )+              ( maybe "" (variableOf "buildPhase") gccCxx,+                maybe "" (variableOf "installPhase") gccCxx,+                maybe "" (variableOf "enableParallelBuilding") gccCxx,+                maybe "" (variableOf "enableParallelInstalling") gccCxx+              )+        ]+  where+    instantiates :: Text+    instantiates = "the C++ rung's derivations instantiate, adding eight to the closure of gcc46's rung"+    target :: Text+    target = "i686-w64-mingw32"+    cxxArchive :: Text+    cxxArchive = "gcc-g++-4.6.4.tar.gz"+    -- The variables gcc-core names its archives and gmp's patch in, which+    -- gcc46-cxx takes.+    coreArchives :: [Text]+    coreArchives = ["src", "gmpSrc", "gmpPatch", "mpfrSrc", "mpcSrc"]+    gmpPatch :: Text+    gmpPatch = "gmp-bases-digits.patch"+    gccCxxRoot :: Text+    gccCxxRoot = "pkgs.gcc46-cxx"+    gccCoreRoot :: Text+    gccCoreRoot = "pkgs.gcc-core"+    gcc46Root :: Text+    gcc46Root = "pkgs.gcc46"+    crtRoot :: Text+    crtRoot = "pkgs.mingw-w64-crt"+    headersRoot :: Text+    headersRoot = "pkgs.mingw-w64-headers"+    binutilsRoot :: Text+    binutilsRoot = "pkgs.binutils"+    builtBefore :: [Text]+    builtBefore = ["pkgs.busybox-w32", "pkgs.gnumake", "pkgs.tinycc-native.compiler", "pkgs.tinycc-native.libs", "pkgs.seedStdenv.applets", binutilsRoot, headersRoot, "pkgs.mingw-w64-dirent", gccCoreRoot, crtRoot, gcc46Root]+    roots :: [Text]+    roots = builtBefore ++ [gccCxxRoot, "checks.hello", "checks.stamps"]+    -- Each kaem.runCommand adds its script, written by writeText as+    -- <name>-builder.+    addedNames :: [Text]+    addedNames =+      [cxxArchive, "gcc-cxx-4.6.4", "hello.sh", "stamps.sh"]+        ++ concat [[name, name <> "-builder"] | name <- ["gcc46-cxx-hello", "gcc46-cxx-stamps"]]++-- | @pkgs\/windows@'s GCC 10 rung, read back as the build driver reads it:+-- what gcc10 and @test\/data\/gcc10.nix@'s checks add to the closure of the+-- rung before it, gcc46-cxx, which builds it.  The rung is full-source only+-- if the four leaves it adds are the archives of GCC, GMP, MPFR and MPC and+-- it reads no input source but the stdenv's own files, its patch and what+-- evaluation writes as text; the stdenv's @setup.sh@ unpacks GCC's (@src@) and+-- @preConfigure@ the other three, into the directories of GCC's tree its+-- configure builds them from.  Its configure is told by flags where+-- MinGW-w64's headers and runtime, the assembler and the linker are, and+-- which compilers, archiver and linker the build runs, and its install+-- which strip, so each has to name the output of the derivation that+-- builds it, or the target's name binutils and gcc46-cxx install their+-- programs under.  Every flag that sets a compiler's options leaves out+-- the @-g@ whose debugging information would name the build directory,+-- libgcc's own @-g@ is stripped after the install, and every link and+-- strip is told to write no time stamp.+testGcc10Windows :: IO [Bool]+testGcc10Windows = do+  putStrLn "pkgs/gcc10"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let windows = "(import " <> nixQuotedPath (cwd </> "pkgs" </> "windows") <> ")"+      checks = "import " <> nixQuotedPath (cwd </> "test" </> "data" </> "gcc10.nix")+      source =+        T.concat+          [ "let pkgs = ",+            windows,+            "; checks = ",+            checks,+            "; in builtins.concatStringsSep \" \" [ ",+            T.unwords [path <> ".drvPath" | path <- roots],+            " ]"+          ]+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> do+          let rootOf = Map.fromList (zip roots (T.words (bytesText bytes)))+          before <- sessionClosure (mapMaybe (`Map.lookup` rootOf) builtBefore)+          full <- sessionClosure (Map.elems rootOf)+          pure (rootOf, before, full)+        other -> throwEvalError ("expected the drvPaths as one string, got " <> typeName other)+  writes <- readIORef (esStoreWriteCache st)+  case outcome of+    Left err -> sequence [runTest instantiates (Fail err)]+    Right (rootOf, before, full) -> do+      let added = Map.elems (Map.difference full before)+          nameOf drv = maybe "" bytesText (Map.lookup "name" (drvEnv drv))+          variableOf name drv = maybe "" bytesText (Map.lookup name (drvEnv drv))+          isFetch drv = drvBuilder drv == "builtin:fetchurl"+          isFixedOutput drv = not (all (T.null . doHash) (drvOutputs drv))+          addedLeaves = filter (Map.null . drvInputDrvs) added+          wroteAsText path = fmap snd (Map.lookup (storePathToText defaultStoreDir path) writes) == Just WriteText+          derivationAt root = Map.lookup root rootOf >>= (`Map.lookup` full)+          gcc10 = derivationAt gcc10Root+          -- The output of a root's derivation, as a flag spells a store+          -- path, or a word no flag holds where the root is missing.+          outputOf root = maybe "<no output>" (storePathToText defaultStoreDir . doPath) (derivationAt root >>= listToMaybe . drvOutputs)+          outputNamed name = [storePathToText defaultStoreDir (doPath out) | drv <- added, nameOf drv == name, out <- drvOutputs drv]+          sourcesNamed name = [storePathToText defaultStoreDir path | drv <- maybeToList gcc10, path <- drvInputSrcs drv, spName path == name]+          wordsOf name = maybe [] (T.words . variableOf name)+          linesOf name = maybe [] (map T.strip . T.lines . variableOf name)+          flagsWith prefixes drv = [flag | flag <- wordsOf "configureFlags" drv, any (`T.isPrefixOf` flag) prefixes]+      sequence+        [ runTest instantiates $+            assertEqual "derivations added" (sort addedNames) (sort (map nameOf added)),+          runTest "every derivation it adds but the fetches is i686-windows" $+            case [nameOf drv | drv <- added, not (isFetch drv), drvPlatform drv /= I686_Windows] of+              [] -> Pass+              named -> Fail ("not i686-windows: " <> T.intercalate ", " named),+          runTest "the four leaves it adds are the archives of GCC, GMP, MPFR and MPC, fetched fixed-output" $+            assertEqual+              "leaves added"+              (sort (map snd archives), True)+              (sort (map nameOf addedLeaves), all (\drv -> isFetch drv && isFixedOutput drv) addedLeaves),+          runTest "it reads no input source but what evaluation writes as text, the stdenv's files and its patch" $+            assertEqual+              "input sources not written as text"+              (sort ["config.site", "include", "setup.sh", patch])+              (sort [spName path | drv <- added, path <- drvInputSrcs drv, not (wroteAsText path)]),+          runTest "gcc10 names its patch and its four archives where setup.sh and preConfigure read them, with gcc46-cxx and binutils as its build inputs" $+            assertEqual+              "the archives, buildInputs and patches"+              ( [outputNamed archive | (_, archive) <- archives],+                [outputOf gccCxxRoot, outputOf binutilsRoot],+                sourcesNamed patch+              )+              ( [wordsOf variable gcc10 | (variable, _) <- archives],+                wordsOf "buildInputs" gcc10,+                wordsOf "patches" gcc10+              ),+          runTest "gcc10's preConfigure moves GMP, MPFR and MPC to the directories GCC's configure builds them from" $+            assertEqual+              "preConfigure's mv lines"+              ["mv " <> library <> "-" <> libraryVersion <> " " <> library | (library, libraryVersion) <- libraries]+              (filter ("mv " `T.isPrefixOf`) (linesOf "preConfigure" gcc10)),+          runTest "gcc10's flags name the target, the outputs of the headers, the runtime and binutils, and no sysroot" $+            assertEqual+              "flags"+              [ "--target=" <> target,+                "--with-headers=" <> outputOf headersRoot <> "/include",+                "--with-libs=" <> outputOf crtRoot <> "/lib",+                "--with-as=" <> outputOf binutilsRoot <> "/bin/" <> target <> "-as.exe",+                "--with-ld=" <> outputOf binutilsRoot <> "/bin/" <> target <> "-ld.exe"+              ]+              (flagsWith ["--target=", "--with-headers", "--with-libs", "--with-sysroot", "--with-build-sysroot", "--with-native-system-header-dir", "--with-as=", "--with-ld="] gcc10),+          runTest "gcc10 builds with gcc46-cxx's drivers and binutils' archiver and linker, by the target's names" $+            assertEqual+              "tools"+              ["CC=" <> target <> "-gcc", "CXX=" <> target <> "-g++", "AR=" <> target <> "-ar", "LD=" <> target <> "-ld"]+              (flagsWith ["CC=", "CXX=", "AR=", "LD=", "STRIP=", "RANLIB="] gcc10),+          runTest "gcc10 gives every link it makes --no-insert-timestamp, and LDFLAGS nothing else" $+            assertEqual+              "LDFLAGS"+              ["LDFLAGS=-Wl,--no-insert-timestamp"]+              (flagsWith ["LDFLAGS=", "LDFLAGS_FOR_BUILD="] gcc10),+          runTest "gcc10's compiler options carry no -g, and it gives make no flags" $+            assertEqual+              "the options and makeFlags"+              (["CFLAGS=-O1", "CXXFLAGS=-O1", "CFLAGS_FOR_TARGET=-O2", "CXXFLAGS_FOR_TARGET=-O0"], [])+              (flagsWith ["CFLAGS=", "CXXFLAGS=", "CFLAGS_FOR_TARGET=", "CXXFLAGS_FOR_TARGET="] gcc10, wordsOf "makeFlags" gcc10),+          runTest "gcc10 builds C and C++, static, with no registry lookup" $+            assertEqual+              "languages, libraries and registry"+              ["--enable-languages=c,c++", "--disable-shared", "--disable-win32-registry"]+              (flagsWith ["--enable-languages=", "--enable-shared", "--disable-shared", "--enable-win32-registry", "--disable-win32-registry"] gcc10),+          runTest "gcc10 unsets the stdenv's C_INCLUDE_PATH, and nothing else, before configure" $+            assertEqual+              "preConfigure's unset lines"+              ["unset C_INCLUDE_PATH"]+              (filter ("unset " `T.isPrefixOf`) (linesOf "preConfigure" gcc10)),+          runTest "gcc10 builds all with NIX_BUILD_CORES jobs, installs with install-strip, whose strip keeps the zero time stamp ld writes, and strips libgcc's debugging information" $+            assertEqual+              "phases and parallelism"+              ( "",+                [ "make ${enableParallelInstalling:+-j$NIX_BUILD_CORES} 'STRIP=" <> target <> "-strip -p' install-strip",+                  "libgccDir=$out/lib/gcc/" <> target <> "/" <> version,+                  target <> "-strip -p --strip-debug \"$libgccDir/libgcc.a\" \"$libgccDir/libgcov.a\" \"$libgccDir/crtfastmath.o\""+                ],+                "1",+                "1"+              )+              ( maybe "" (variableOf "buildPhase") gcc10,+                linesOf "installPhase" gcc10,+                maybe "" (variableOf "enableParallelBuilding") gcc10,+                maybe "" (variableOf "enableParallelInstalling") gcc10+              )+        ]+  where+    instantiates :: Text+    instantiates = "the GCC 10 rung's derivations instantiate, adding fourteen to the closure of gcc46-cxx's rung"+    target :: Text+    target = "i686-w64-mingw32"+    version :: Text+    version = "10.4.0"+    -- GMP, MPFR and MPC, each with the release of it the rung builds in+    -- GCC's tree.+    libraries :: [(Text, Text)]+    libraries = [("gmp", "6.2.1"), ("mpfr", "4.2.2"), ("mpc", "1.4.1")]+    -- The variable the rung names each archive in, with the archive's+    -- name.+    archives :: [(Text, Text)]+    archives =+      ("src", "gcc-" <> version <> ".tar.xz")+        : [(library <> "Src", library <> "-" <> libraryVersion <> ".tar.xz") | (library, libraryVersion) <- libraries]+    -- GCC's commit that has libcpp's configure look the archiver up.+    patch :: Text+    patch = "libcpp-configure-ar.patch"+    gcc10Root :: Text+    gcc10Root = "pkgs.gcc10"+    gccCxxRoot :: Text+    gccCxxRoot = "pkgs.gcc46-cxx"+    crtRoot :: Text+    crtRoot = "pkgs.mingw-w64-crt"+    headersRoot :: Text+    headersRoot = "pkgs.mingw-w64-headers"+    binutilsRoot :: Text+    binutilsRoot = "pkgs.binutils"+    builtBefore :: [Text]+    builtBefore = ["pkgs.busybox-w32", "pkgs.gnumake", "pkgs.tinycc-native.compiler", "pkgs.tinycc-native.libs", "pkgs.seedStdenv.applets", binutilsRoot, headersRoot, "pkgs.mingw-w64-dirent", "pkgs.gcc-core", crtRoot, "pkgs.gcc46", gccCxxRoot]+    roots :: [Text]+    roots = builtBefore ++ [gcc10Root, "checks.hello-c", "checks.hello-cxx", "checks.stamps"]+    -- Each kaem.runCommand adds its script, written by writeText as+    -- <name>-builder.+    addedNames :: [Text]+    addedNames =+      map snd archives+        ++ ["gcc-" <> version, "hello-c.sh", "hello-cxx.sh", "stamps.sh"]+        ++ concat [[name, name <> "-builder"] | name <- ["gcc10-hello-c", "gcc10-hello-cxx", "gcc10-stamps"]]++-- | @pkgs\/windows@'s current MinGW-w64, read back as the build driver+-- reads it: what mingw-w64-headers-latest, mingw-w64-crt-latest and+-- @test\/data\/mingw-w64-latest.nix@'s checks add to the closure of gcc10,+-- which compiles the runtime.  The rung is full-source only if the one+-- leaf it adds is the release's archive and it reads no input source but+-- the stdenv's own files and what evaluation writes as text.  The headers+-- install from the archive's own directory, for msvcrt.dll.  The runtime+-- is compiled from the headers' archive, against the headers' output,+-- which its flags name as the sysroot; its configure takes the compiler+-- and archiver the environment names, and the stdenv's are tcc's, so its+-- @preConfigure@ unsets them, and @C_INCLUDE_PATH@, which GCC reads as+-- well; and its CFLAGS leave out the @-g@ configure would add.+testMingwW64LatestWindows :: IO [Bool]+testMingwW64LatestWindows = do+  putStrLn "pkgs/mingw-w64-latest"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let windows = "(import " <> nixQuotedPath (cwd </> "pkgs" </> "windows") <> ")"+      checks = "import " <> nixQuotedPath (cwd </> "test" </> "data" </> "mingw-w64-latest.nix")+      source =+        T.concat+          [ "let pkgs = ",+            windows,+            "; checks = ",+            checks,+            "; in builtins.concatStringsSep \" \" [ ",+            T.unwords [path <> ".drvPath" | path <- roots],+            " ]"+          ]+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> do+          let rootOf = Map.fromList (zip roots (T.words (bytesText bytes)))+          before <- sessionClosure (mapMaybe (`Map.lookup` rootOf) builtBefore)+          full <- sessionClosure (Map.elems rootOf)+          pure (rootOf, before, full)+        other -> throwEvalError ("expected the drvPaths as one string, got " <> typeName other)+  writes <- readIORef (esStoreWriteCache st)+  case outcome of+    Left err -> sequence [runTest instantiates (Fail err)]+    Right (rootOf, before, full) -> do+      let added = Map.elems (Map.difference full before)+          nameOf drv = maybe "" bytesText (Map.lookup "name" (drvEnv drv))+          variableOf name drv = maybe "" bytesText (Map.lookup name (drvEnv drv))+          isFetch drv = drvBuilder drv == "builtin:fetchurl"+          isFixedOutput drv = not (all (T.null . doHash) (drvOutputs drv))+          addedLeaves = filter (Map.null . drvInputDrvs) added+          wroteAsText path = fmap snd (Map.lookup (storePathToText defaultStoreDir path) writes) == Just WriteText+          derivationAt root = Map.lookup root rootOf >>= (`Map.lookup` full)+          headers = derivationAt headersRoot+          crt = derivationAt crtRoot+          -- The output of a root's derivation, as a flag spells a store+          -- path, or a word no flag holds where the root is missing.+          outputOf root = maybe "<no output>" (storePathToText defaultStoreDir . doPath) (derivationAt root >>= listToMaybe . drvOutputs)+          wordsOf name = maybe [] (T.words . variableOf name)+          -- What preConfigure runs before it moves to the build directory.+          firstLine = maybe "" (T.takeWhile (/= '\n') . variableOf "preConfigure")+      sequence+        [ runTest instantiates $+            assertEqual "derivations added" (sort addedNames) (sort (map nameOf added)),+          runTest "every derivation it adds but the fetch is i686-windows" $+            case [nameOf drv | drv <- added, not (isFetch drv), drvPlatform drv /= I686_Windows] of+              [] -> Pass+              named -> Fail ("not i686-windows: " <> T.intercalate ", " named),+          runTest "the one leaf it adds is MinGW-w64's release archive, fetched fixed-output" $+            assertEqual+              "leaves added"+              ([archive], True)+              (map nameOf addedLeaves, all (\drv -> isFetch drv && isFixedOutput drv) addedLeaves),+          runTest "it reads no input source but what evaluation writes as text and the stdenv's files" $+            assertEqual+              "input sources not written as text"+              ["config.site", "include", "setup.sh"]+              (sort (map spName (nub [path | drv <- added, path <- drvInputSrcs drv, not (wroteAsText path)]))),+          runTest "mingw-w64-headers-latest is configured in its own directory, for msvcrt, from the archive" $+            assertEqual+              "preConfigure, flags and src"+              ("cd mingw-w64-headers", ["--with-default-msvcrt=msvcrt"], [archive])+              ( maybe "" (variableOf "preConfigure") headers,+                wordsOf "configureFlags" headers,+                [nameOf drv | drv <- addedLeaves, any ((`elem` wordsOf "src" headers) . storePathToText defaultStoreDir . doPath) (drvOutputs drv)]+              ),+          runTest "mingw-w64-crt-latest is built from mingw-w64-headers-latest's archive by gcc10 and binutils, with tcc's variables unset" $+            assertEqual+              "src, buildInputs and preConfigure's first line"+              (wordsOf "src" headers, [outputOf gcc10Root, outputOf binutilsRoot], "unset CC AR C_INCLUDE_PATH", isJust headers)+              (wordsOf "src" crt, wordsOf "buildInputs" crt, firstLine crt, isJust crt),+          runTest "mingw-w64-crt-latest's flags name the target as the host, mingw-w64-headers-latest's output as the sysroot, msvcrt and the 32-bit runtime alone, and CFLAGS with no -g" $+            assertEqual+              "flags"+              [ "--host=" <> target,+                "--with-sysroot=" <> outputOf headersRoot,+                "--with-default-msvcrt=msvcrt",+                "--enable-lib32",+                "--disable-lib64",+                "--disable-dependency-tracking",+                "CFLAGS=-O2"+              ]+              (wordsOf "configureFlags" crt),+          runTest "mingw-w64-crt-latest builds and installs with NIX_BUILD_CORES jobs" $+            assertEqual+              "parallelism"+              ("1", "1")+              (maybe "" (variableOf "enableParallelBuilding") crt, maybe "" (variableOf "enableParallelInstalling") crt)+        ]+  where+    instantiates :: Text+    instantiates = "the current MinGW-w64's derivations instantiate, adding nine to the closure of gcc10"+    target :: Text+    target = "i686-w64-mingw32"+    version :: Text+    version = "14.0.0"+    archive :: Text+    archive = "mingw-w64-v" <> version <> ".tar.bz2"+    headersRoot :: Text+    headersRoot = "pkgs.mingw-w64-headers-latest"+    crtRoot :: Text+    crtRoot = "pkgs.mingw-w64-crt-latest"+    gcc10Root :: Text+    gcc10Root = "pkgs.gcc10"+    binutilsRoot :: Text+    binutilsRoot = "pkgs.binutils"+    builtBefore :: [Text]+    builtBefore = ["pkgs.busybox-w32", "pkgs.gnumake", "pkgs.tinycc-native.compiler", "pkgs.tinycc-native.libs", "pkgs.seedStdenv.applets", binutilsRoot, gcc10Root]+    roots :: [Text]+    roots = builtBefore ++ [headersRoot, crtRoot, "checks.crt", "checks.hello"]+    -- Each kaem.runCommand adds its script, written by writeText as+    -- <name>-builder.+    addedNames :: [Text]+    addedNames =+      [archive, "mingw-w64-headers-" <> version, "mingw-w64-crt-" <> version, "crt.sh", "hello.sh"]+        ++ concat [[name, name <> "-builder"] | name <- ["mingw-w64-latest-crt", "mingw-w64-latest-hello"]]++-- | @pkgs\/windows@'s GCC 16 rung, read back as the build driver reads it:+-- what gcc-latest and @test\/data\/gcc-latest.nix@'s checks add to the+-- closure of the rungs before it, gcc10, which builds it, and the current+-- MinGW-w64, its target's headers and runtime.  The rung is full-source+-- only if the three leaves it adds are the archives of GCC, GMP and MPC,+-- MPFR's being gcc10's, and it reads no input source but the stdenv's own+-- files and what evaluation writes as text; the stdenv's @setup.sh@+-- unpacks GCC's (@src@) and @preConfigure@ the other three, into the+-- directories of GCC's tree its configure builds them from.  Its+-- configure is told by flags where MinGW-w64's headers and runtime, the+-- assembler and the linker are, and which compilers, archiver and linker+-- the build runs, and its install which strip, so each has to name the+-- output of the derivation that builds it, or the target's name binutils+-- and gcc10 install their programs under.  Every flag that sets a+-- compiler's options leaves out the @-g@ whose debugging information+-- would name the build directory, libgcc's own @-g@ is stripped after+-- the install, every link and strip is told to write no time stamp, and+-- the build leaves the configure arguments, which name store paths, out+-- of the compiler.+testGccLatestWindows :: IO [Bool]+testGccLatestWindows = do+  putStrLn "pkgs/gcc-latest"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let windows = "(import " <> nixQuotedPath (cwd </> "pkgs" </> "windows") <> ")"+      checks = "import " <> nixQuotedPath (cwd </> "test" </> "data" </> "gcc-latest.nix")+      source =+        T.concat+          [ "let pkgs = ",+            windows,+            "; checks = ",+            checks,+            "; in builtins.concatStringsSep \" \" [ ",+            T.unwords [path <> ".drvPath" | path <- roots],+            " ]"+          ]+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> do+          let rootOf = Map.fromList (zip roots (T.words (bytesText bytes)))+          before <- sessionClosure (mapMaybe (`Map.lookup` rootOf) builtBefore)+          full <- sessionClosure (Map.elems rootOf)+          pure (rootOf, before, full)+        other -> throwEvalError ("expected the drvPaths as one string, got " <> typeName other)+  writes <- readIORef (esStoreWriteCache st)+  case outcome of+    Left err -> sequence [runTest instantiates (Fail err)]+    Right (rootOf, before, full) -> do+      let added = Map.elems (Map.difference full before)+          nameOf drv = maybe "" bytesText (Map.lookup "name" (drvEnv drv))+          variableOf name drv = maybe "" bytesText (Map.lookup name (drvEnv drv))+          isFetch drv = drvBuilder drv == "builtin:fetchurl"+          isFixedOutput drv = not (all (T.null . doHash) (drvOutputs drv))+          addedLeaves = filter (Map.null . drvInputDrvs) added+          wroteAsText path = fmap snd (Map.lookup (storePathToText defaultStoreDir path) writes) == Just WriteText+          derivationAt root = Map.lookup root rootOf >>= (`Map.lookup` full)+          gccLatest = derivationAt gccLatestRoot+          -- The output of a root's derivation, as a flag spells a store+          -- path, or a word no flag holds where the root is missing.+          outputOf root = maybe "<no output>" (storePathToText defaultStoreDir . doPath) (derivationAt root >>= listToMaybe . drvOutputs)+          outputNamed name = [storePathToText defaultStoreDir (doPath out) | drv <- Map.elems full, nameOf drv == name, out <- drvOutputs drv]+          wordsOf name = maybe [] (T.words . variableOf name)+          linesOf name = maybe [] (map T.strip . T.lines . variableOf name)+          flagsWith prefixes drv = [flag | flag <- wordsOf "configureFlags" drv, any (`T.isPrefixOf` flag) prefixes]+      sequence+        [ runTest instantiates $+            assertEqual "derivations added" (sort addedNames) (sort (map nameOf added)),+          runTest "every derivation it adds but the fetches is i686-windows" $+            case [nameOf drv | drv <- added, not (isFetch drv), drvPlatform drv /= I686_Windows] of+              [] -> Pass+              named -> Fail ("not i686-windows: " <> T.intercalate ", " named),+          runTest "the three leaves it adds are the archives of GCC, GMP and MPC, fetched fixed-output" $+            assertEqual+              "leaves added"+              (sort [archive | (variable, archive) <- archives, variable /= "mpfrSrc"], True)+              (sort (map nameOf addedLeaves), all (\drv -> isFetch drv && isFixedOutput drv) addedLeaves),+          runTest "it reads no input source but what evaluation writes as text and the stdenv's files" $+            assertEqual+              "input sources not written as text"+              ["config.site", "include", "setup.sh"]+              (sort (map spName (nub [path | drv <- added, path <- drvInputSrcs drv, not (wroteAsText path)]))),+          runTest "gcc-latest names its four archives where setup.sh and preConfigure read them, with gcc10 and binutils as its build inputs and no patch" $+            assertEqual+              "the archives, buildInputs and patches"+              ( [outputNamed archive | (_, archive) <- archives],+                [outputOf gcc10Root, outputOf binutilsRoot],+                []+              )+              ( [wordsOf variable gccLatest | (variable, _) <- archives],+                wordsOf "buildInputs" gccLatest,+                wordsOf "patches" gccLatest+              ),+          runTest "gcc-latest's preConfigure moves GMP, MPFR and MPC to the directories GCC's configure builds them from" $+            assertEqual+              "preConfigure's mv lines"+              ["mv " <> library <> "-" <> libraryVersion <> " " <> library | (library, libraryVersion, _) <- libraries]+              (filter ("mv " `T.isPrefixOf`) (linesOf "preConfigure" gccLatest)),+          runTest "gcc-latest's flags name the target, the outputs of the current MinGW-w64's headers and runtime and of binutils, and no sysroot" $+            assertEqual+              "flags"+              [ "--target=" <> target,+                "--with-headers=" <> outputOf headersRoot <> "/include",+                "--with-libs=" <> outputOf crtRoot <> "/lib",+                "--with-as=" <> outputOf binutilsRoot <> "/bin/" <> target <> "-as.exe",+                "--with-ld=" <> outputOf binutilsRoot <> "/bin/" <> target <> "-ld.exe"+              ]+              (flagsWith ["--target=", "--with-headers", "--with-libs", "--with-sysroot", "--with-build-sysroot", "--with-native-system-header-dir", "--with-as=", "--with-ld="] gccLatest),+          runTest "gcc-latest builds with gcc10's drivers and binutils' archiver, linker and resource compiler, by the target's names, the resource compiler named in the environment and run with --use-temp-file" $+            assertEqual+              "tools, and WINDRES"+              (["CC=" <> target <> "-gcc", "CXX=" <> target <> "-g++", "AR=" <> target <> "-ar", "LD=" <> target <> "-ld"], target <> "-windres --use-temp-file")+              (flagsWith ["CC=", "CXX=", "AR=", "LD=", "STRIP=", "RANLIB=", "WINDRES="] gccLatest, maybe "" (variableOf "WINDRES") gccLatest),+          runTest "gcc-latest gives every link it makes --no-insert-timestamp, and LDFLAGS nothing else" $+            assertEqual+              "LDFLAGS"+              ["LDFLAGS=-Wl,--no-insert-timestamp"]+              (flagsWith ["LDFLAGS=", "LDFLAGS_FOR_BUILD="] gccLatest),+          runTest "gcc-latest's compiler options carry no -g, and it gives make no flags" $+            assertEqual+              "the options and makeFlags"+              (["CFLAGS=-O1", "CXXFLAGS=-O1", "CFLAGS_FOR_TARGET=-O2", "CXXFLAGS_FOR_TARGET=-O0"], [])+              (flagsWith ["CFLAGS=", "CXXFLAGS=", "CFLAGS_FOR_TARGET=", "CXXFLAGS_FOR_TARGET="] gccLatest, wordsOf "makeFlags" gccLatest),+          runTest "gcc-latest builds C and C++, static, with a build ID on every link, no default PIE and no registry lookup" $+            assertEqual+              "languages, libraries, links and registry"+              ["--enable-languages=c,c++", "--enable-linker-build-id", "--disable-shared", "--disable-win32-registry"]+              (flagsWith ["--enable-languages=", "--enable-linker-build-id", "--enable-default-pie", "--enable-shared", "--disable-shared", "--enable-win32-registry", "--disable-win32-registry"] gccLatest),+          runTest "gcc-latest unsets the stdenv's C_INCLUDE_PATH, and nothing else, before configure" $+            assertEqual+              "preConfigure's unset lines"+              ["unset C_INCLUDE_PATH"]+              (filter ("unset " `T.isPrefixOf`) (linesOf "preConfigure" gccLatest)),+          runTest "gcc-latest drops the configure arguments from the top-level Makefile, builds with NIX_BUILD_CORES jobs, installs with install-strip, whose strip keeps the zero time stamp ld writes, strips libgcc's debugging information, removes what ng.nix removes and libstdc++'s gdb script, and removes the directories that leaves empty" $+            assertEqual+              "phases and parallelism"+              ( [ "sed -e '/TOPLEVEL_CONFIGURE_ARGUMENTS=/d' -i Makefile",+                  "make ${enableParallelBuilding:+-j$NIX_BUILD_CORES}"+                ],+                [ "make ${enableParallelInstalling:+-j$NIX_BUILD_CORES} 'STRIP=" <> target <> "-strip -p' install-strip",+                  "libgccDir=$out/lib/gcc/" <> target <> "/" <> version,+                  target <> "-strip -p --strip-debug \"$libgccDir\"/*.a \"$libgccDir\"/*.o",+                  "rm -r \"$out/libexec/gcc/" <> target <> "/" <> version <> "/install-tools\" \"$libgccDir/install-tools\"",+                  "rm -rf \"$out/share/gcc-" <> version <> "/python\" \"$out/share/man\" \"$out/share/info\"",+                  "rm \"$out/" <> target <> "/lib/libstdc++.a-gdb.py\"",+                  "rmdir \"$out/share/gcc-" <> version <> "\" \"$out/share\""+                ],+                "1",+                "1"+              )+              ( linesOf "buildPhase" gccLatest,+                linesOf "installPhase" gccLatest,+                maybe "" (variableOf "enableParallelBuilding") gccLatest,+                maybe "" (variableOf "enableParallelInstalling") gccLatest+              )+        ]+  where+    instantiates :: Text+    instantiates = "the GCC 16 rung's derivations instantiate, adding thirteen to the closure of gcc10 and the current MinGW-w64"+    target :: Text+    target = "i686-w64-mingw32"+    version :: Text+    version = "16.2.0"+    -- GMP, MPFR and MPC, each with the release of it the rung builds in+    -- GCC's tree and the compression of its archive.+    libraries :: [(Text, Text, Text)]+    libraries = [("gmp", "6.3.0", "xz"), ("mpfr", "4.2.2", "xz"), ("mpc", "1.3.1", "gz")]+    -- The variable the rung names each archive in, with the archive's+    -- name.+    archives :: [(Text, Text)]+    archives =+      ("src", "gcc-" <> version <> ".tar.xz")+        : [(library <> "Src", library <> "-" <> libraryVersion <> ".tar." <> compression) | (library, libraryVersion, compression) <- libraries]+    gccLatestRoot :: Text+    gccLatestRoot = "pkgs.gcc-latest"+    gcc10Root :: Text+    gcc10Root = "pkgs.gcc10"+    crtRoot :: Text+    crtRoot = "pkgs.mingw-w64-crt-latest"+    headersRoot :: Text+    headersRoot = "pkgs.mingw-w64-headers-latest"+    binutilsRoot :: Text+    binutilsRoot = "pkgs.binutils"+    builtBefore :: [Text]+    builtBefore = ["pkgs.busybox-w32", "pkgs.gnumake", "pkgs.tinycc-native.compiler", "pkgs.tinycc-native.libs", "pkgs.seedStdenv.applets", binutilsRoot, gcc10Root, headersRoot, crtRoot]+    roots :: [Text]+    roots = builtBefore ++ [gccLatestRoot, "checks.hello-c", "checks.hello-cxx", "checks.stamps"]+    -- Each kaem.runCommand adds its script, written by writeText as+    -- <name>-builder.+    addedNames :: [Text]+    addedNames =+      [archive | (variable, archive) <- archives, variable /= "mpfrSrc"]+        ++ ["gcc-" <> version, "hello-c.sh", "hello-cxx.sh", "stamps.sh"]+        ++ concat [[name, name <> "-builder"] | name <- ["gcc-latest-hello-c", "gcc-latest-hello-cxx", "gcc-latest-stamps"]]++-- | @pkgs\/windows@'s x86_64 binutils, read back as the build driver reads+-- it: what binutils-x86_64 and @test\/data\/binutils-x86_64.nix@'s checks+-- add to the closure of gcc-latest and binutils, which build it.  The+-- rung is full-source only if the one leaf it adds is the archive nixpkgs+-- fetches and it reads no input source but the stdenv's own files and+-- what evaluation writes as text.  Its configure is told the target the+-- x86_64 compilers are built for, so the tools install under the name+-- they look them up by; the build runs gcc-latest's compiler and+-- binutils' archiver and linker by the name of their target, since the+-- stdenv's CC, AR and LD are tcc's; its CFLAGS leave out the @-g@+-- configure would add, and every link is told to write no time stamp.+testBinutilsX8664Windows :: IO [Bool]+testBinutilsX8664Windows = do+  putStrLn "pkgs/binutils-x86_64"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let windows = "(import " <> nixQuotedPath (cwd </> "pkgs" </> "windows") <> ")"+      checks = "import " <> nixQuotedPath (cwd </> "test" </> "data" </> "binutils-x86_64.nix")+      source =+        T.concat+          [ "let pkgs = ",+            windows,+            "; checks = ",+            checks,+            "; in builtins.concatStringsSep \" \" [ ",+            T.unwords [path <> ".drvPath" | path <- roots],+            " ]"+          ]+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> do+          let rootOf = Map.fromList (zip roots (T.words (bytesText bytes)))+          before <- sessionClosure (mapMaybe (`Map.lookup` rootOf) builtBefore)+          full <- sessionClosure (Map.elems rootOf)+          pure (rootOf, before, full)+        other -> throwEvalError ("expected the drvPaths as one string, got " <> typeName other)+  writes <- readIORef (esStoreWriteCache st)+  case outcome of+    Left err -> sequence [runTest instantiates (Fail err)]+    Right (rootOf, before, full) -> do+      let added = Map.elems (Map.difference full before)+          nameOf drv = maybe "" bytesText (Map.lookup "name" (drvEnv drv))+          variableOf name drv = maybe "" bytesText (Map.lookup name (drvEnv drv))+          isFetch drv = drvBuilder drv == "builtin:fetchurl"+          isFixedOutput drv = not (all (T.null . doHash) (drvOutputs drv))+          addedLeaves = filter (Map.null . drvInputDrvs) added+          wroteAsText path = fmap snd (Map.lookup (storePathToText defaultStoreDir path) writes) == Just WriteText+          derivationAt root = Map.lookup root rootOf >>= (`Map.lookup` full)+          binutils = derivationAt binutilsX8664Root+          -- The output of a root's derivation, as a flag spells a store+          -- path, or a word no flag holds where the root is missing.+          outputOf root = maybe "<no output>" (storePathToText defaultStoreDir . doPath) (derivationAt root >>= listToMaybe . drvOutputs)+          outputNamed name = [storePathToText defaultStoreDir (doPath out) | drv <- added, nameOf drv == name, out <- drvOutputs drv]+          wordsOf name = maybe [] (T.words . variableOf name)+          linesOf name = maybe [] (map T.strip . T.lines . variableOf name)+          flagsWith prefixes drv = [flag | flag <- wordsOf "configureFlags" drv, any (`T.isPrefixOf` flag) prefixes]+      sequence+        [ runTest instantiates $+            assertEqual "derivations added" (sort addedNames) (sort (map nameOf added)),+          runTest "every derivation it adds but the fetch is i686-windows" $+            case [nameOf drv | drv <- added, not (isFetch drv), drvPlatform drv /= I686_Windows] of+              [] -> Pass+              named -> Fail ("not i686-windows: " <> T.intercalate ", " named),+          runTest "the one leaf it adds is nixpkgs' binutils archive, fetched fixed-output" $+            assertEqual+              "leaves added"+              ([archive], True)+              (map nameOf addedLeaves, all (\drv -> isFetch drv && isFixedOutput drv) addedLeaves),+          runTest "it reads no input source but what evaluation writes as text and the stdenv's files" $+            assertEqual+              "input sources not written as text"+              ["config.site", "include", "setup.sh"]+              (sort (map spName (nub [path | drv <- added, path <- drvInputSrcs drv, not (wroteAsText path)]))),+          runTest "binutils-x86_64 names its archive where setup.sh reads it, with gcc-latest and binutils as its build inputs and no patch" $+            assertEqual+              "src, buildInputs and patches"+              (outputNamed archive, [outputOf gccLatestRoot, outputOf binutilsRoot], [])+              (wordsOf "src" binutils, wordsOf "buildInputs" binutils, wordsOf "patches" binutils),+          runTest "binutils-x86_64 is configured for x86_64-w64-mingw32 with no sysroot, and builds with gcc-latest's driver and binutils' archiver and linker, by their target's name" $+            assertEqual+              "target and tools"+              ["--target=" <> target, "CC=" <> host <> "-gcc", "AR=" <> host <> "-ar", "LD=" <> host <> "-ld"]+              (flagsWith ["--target=", "--host=", "--with-sysroot", "CC=", "CXX=", "AR=", "LD=", "RANLIB=", "STRIP="] binutils),+          runTest "binutils-x86_64's CFLAGS carry no -g, and LDFLAGS gives every link --no-insert-timestamp and nothing else" $+            assertEqual+              "CFLAGS and LDFLAGS"+              ["CFLAGS=-O2", "LDFLAGS=-Wl,--no-insert-timestamp"]+              (flagsWith ["CFLAGS=", "CXXFLAGS=", "LDFLAGS="] binutils),+          runTest "binutils-x86_64 unsets the stdenv's C_INCLUDE_PATH, configures from a build directory beside the source, and builds with NIX_BUILD_CORES jobs and nixpkgs' MAKEINFO" $+            assertEqual+              "preConfigure, makeFlags and parallelism"+              ( [ "unset C_INCLUDE_PATH",+                  "mkdir ../build",+                  "cd ../build",+                  "configureScript=../binutils-with-gold-" <> version <> "/configure"+                ],+                ["MAKEINFO=true"],+                "1"+              )+              (linesOf "preConfigure" binutils, wordsOf "makeFlags" binutils, maybe "" (variableOf "enableParallelBuilding") binutils)+        ]+  where+    instantiates :: Text+    instantiates = "the x86_64 binutils derivations instantiate, adding eight to the closure of gcc-latest and binutils"+    version :: Text+    version = "2.46"+    archive :: Text+    archive = "binutils-with-gold-" <> version <> ".tar.bz2"+    target :: Text+    target = "x86_64-w64-mingw32"+    -- The target of the compiler and tools the build runs.+    host :: Text+    host = "i686-w64-mingw32"+    binutilsX8664Root :: Text+    binutilsX8664Root = "pkgs.binutils-x86_64"+    gccLatestRoot :: Text+    gccLatestRoot = "pkgs.gcc-latest"+    binutilsRoot :: Text+    binutilsRoot = "pkgs.binutils"+    builtBefore :: [Text]+    builtBefore = ["pkgs.busybox-w32", "pkgs.gnumake", "pkgs.tinycc-native.compiler", "pkgs.tinycc-native.libs", "pkgs.seedStdenv.applets", binutilsRoot, gccLatestRoot]+    roots :: [Text]+    roots = builtBefore ++ [binutilsX8664Root, "checks.link", "checks.stamps"]+    -- Each kaem.runCommand adds its script, written by writeText as+    -- <name>-builder.+    addedNames :: [Text]+    addedNames =+      [archive, target <> "-binutils-" <> version, "link.sh", "stamps.sh"]+        ++ concat [[name, name <> "-builder"] | name <- ["binutils-x86_64-link", "binutils-x86_64-stamps"]]++-- | @pkgs\/windows@'s x86_64 GCC core, read back as the build driver reads+-- it: what gcc-core-x86_64 and @test\/data\/gcc-core-x86_64.nix@'s checks+-- add to the closure of gcc-latest, binutils-x86_64 and the current+-- MinGW-w64's headers, which build it.  It fetches nothing: its four+-- archives are gcc-latest's, which @setup.sh@ and @preConfigure@ unpack+-- from the variables that name them, so it adds no leaf, and it reads no+-- input source but the stdenv's own files and what evaluation writes as+-- text.  Its configure is told by flags where the headers, the assembler+-- and the linker are, and which compilers, archiver, linker and resource+-- compiler the build runs, so each has to name the output of the+-- derivation that builds it, or the target's name binutils and gcc-latest+-- install their programs under.  The compiler is C alone, with a static,+-- single-threaded libgcc, which is what compiling the runtime needs; no+-- compiler option carries @-g@, every link and strip is told to write no+-- time stamp, and the build leaves the configure arguments, which name+-- store paths, out of the compiler.+testGccCoreX8664Windows :: IO [Bool]+testGccCoreX8664Windows = do+  putStrLn "pkgs/gcc-core-x86_64"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let windows = "(import " <> nixQuotedPath (cwd </> "pkgs" </> "windows") <> ")"+      checks = "import " <> nixQuotedPath (cwd </> "test" </> "data" </> "gcc-core-x86_64.nix")+      source =+        T.concat+          [ "let pkgs = ",+            windows,+            "; checks = ",+            checks,+            "; in builtins.concatStringsSep \" \" [ ",+            T.unwords [path <> ".drvPath" | path <- roots],+            " ]"+          ]+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> do+          let rootOf = Map.fromList (zip roots (T.words (bytesText bytes)))+          before <- sessionClosure (mapMaybe (`Map.lookup` rootOf) builtBefore)+          full <- sessionClosure (Map.elems rootOf)+          pure (rootOf, before, full)+        other -> throwEvalError ("expected the drvPaths as one string, got " <> typeName other)+  writes <- readIORef (esStoreWriteCache st)+  case outcome of+    Left err -> sequence [runTest instantiates (Fail err)]+    Right (rootOf, before, full) -> do+      let added = Map.elems (Map.difference full before)+          nameOf drv = maybe "" bytesText (Map.lookup "name" (drvEnv drv))+          variableOf name drv = maybe "" bytesText (Map.lookup name (drvEnv drv))+          isFetch drv = drvBuilder drv == "builtin:fetchurl"+          addedLeaves = filter (Map.null . drvInputDrvs) added+          wroteAsText path = fmap snd (Map.lookup (storePathToText defaultStoreDir path) writes) == Just WriteText+          derivationAt root = Map.lookup root rootOf >>= (`Map.lookup` full)+          gccCore = derivationAt gccCoreRoot+          gccLatest = derivationAt gccLatestRoot+          -- The output of a root's derivation, as a flag spells a store+          -- path, or a word no flag holds where the root is missing.+          outputOf root = maybe "<no output>" (storePathToText defaultStoreDir . doPath) (derivationAt root >>= listToMaybe . drvOutputs)+          wordsOf name = maybe [] (T.words . variableOf name)+          linesOf name = maybe [] (map T.strip . T.lines . variableOf name)+          flagsWith prefixes drv = [flag | flag <- wordsOf "configureFlags" drv, any (`T.isPrefixOf` flag) prefixes]+      sequence+        [ runTest instantiates $+            assertEqual "derivations added" (sort addedNames) (sort (map nameOf added)),+          runTest "every derivation it adds but the fetches is i686-windows" $+            case [nameOf drv | drv <- added, not (isFetch drv), drvPlatform drv /= I686_Windows] of+              [] -> Pass+              named -> Fail ("not i686-windows: " <> T.intercalate ", " named),+          runTest "it adds no leaf, fetching nothing gcc-latest does not" $+            assertEqual "leaves added" [] (map nameOf addedLeaves),+          runTest "it reads no input source but what evaluation writes as text and the stdenv's files" $+            assertEqual+              "input sources not written as text"+              ["config.site", "include", "setup.sh"]+              (sort (map spName (nub [path | drv <- added, path <- drvInputSrcs drv, not (wroteAsText path)]))),+          runTest "gcc-core-x86_64 names gcc-latest's four archives where setup.sh and preConfigure read them, with gcc-latest, binutils and binutils-x86_64 as its build inputs and no patch" $+            assertEqual+              "the archives, buildInputs and patches"+              ( [wordsOf variable gccLatest | variable <- archiveVariables],+                [outputOf gccLatestRoot, outputOf binutilsRoot, outputOf binutilsX8664Root],+                [],+                True+              )+              ( [wordsOf variable gccCore | variable <- archiveVariables],+                wordsOf "buildInputs" gccCore,+                wordsOf "patches" gccCore,+                isJust gccLatest+              ),+          runTest "gcc-core-x86_64's preConfigure moves GMP, MPFR and MPC to the directories GCC's configure builds them from, and unsets the stdenv's C_INCLUDE_PATH" $+            assertEqual+              "preConfigure's mv and unset lines"+              (["mv gmp-6.3.0 gmp", "mv mpfr-4.2.2 mpfr", "mv mpc-1.3.1 mpc"], ["unset C_INCLUDE_PATH"])+              (filter ("mv " `T.isPrefixOf`) (linesOf "preConfigure" gccCore), filter ("unset " `T.isPrefixOf`) (linesOf "preConfigure" gccCore)),+          runTest "gcc-core-x86_64's flags name the target, the outputs of the current MinGW-w64's headers and of binutils-x86_64, and no sysroot" $+            assertEqual+              "flags"+              [ "--target=" <> target,+                "--with-headers=" <> outputOf headersRoot <> "/include",+                "--with-as=" <> outputOf binutilsX8664Root <> "/bin/" <> target <> "-as.exe",+                "--with-ld=" <> outputOf binutilsX8664Root <> "/bin/" <> target <> "-ld.exe"+              ]+              (flagsWith ["--target=", "--with-headers", "--with-libs", "--with-sysroot", "--with-build-sysroot", "--with-native-system-header-dir", "--with-as=", "--with-ld="] gccCore),+          runTest "gcc-core-x86_64 builds with gcc-latest's drivers and binutils' archiver, linker and resource compiler, by their target's names, the resource compiler named in the environment and run with --use-temp-file" $+            assertEqual+              "tools, and WINDRES"+              (["CC=" <> host <> "-gcc", "CXX=" <> host <> "-g++", "AR=" <> host <> "-ar", "LD=" <> host <> "-ld"], host <> "-windres --use-temp-file")+              (flagsWith ["CC=", "CXX=", "AR=", "LD=", "STRIP=", "RANLIB=", "WINDRES="] gccCore, maybe "" (variableOf "WINDRES") gccCore),+          runTest "gcc-core-x86_64 gives every link it makes --no-insert-timestamp, and LDFLAGS nothing else" $+            assertEqual+              "LDFLAGS"+              ["LDFLAGS=-Wl,--no-insert-timestamp"]+              (flagsWith ["LDFLAGS=", "LDFLAGS_FOR_BUILD=", "LDFLAGS_FOR_TARGET="] gccCore),+          runTest "gcc-core-x86_64's compiler options carry no -g, and it gives make no flags" $+            assertEqual+              "the options and makeFlags"+              (["CFLAGS=-O2", "CXXFLAGS=-O2", "CFLAGS_FOR_TARGET=-O2"], [])+              (flagsWith ["CFLAGS=", "CXXFLAGS=", "CFLAGS_FOR_TARGET=", "CXXFLAGS_FOR_TARGET="] gccCore, wordsOf "makeFlags" gccCore),+          runTest "gcc-core-x86_64 builds C alone, static and single-threaded, with no registry lookup" $+            assertEqual+              "languages, libraries, threads and registry"+              ["--enable-languages=c", "--disable-shared", "--disable-threads", "--disable-win32-registry"]+              (flagsWith ["--enable-languages=", "--enable-shared", "--disable-shared", "--enable-threads", "--disable-threads", "--enable-win32-registry", "--disable-win32-registry"] gccCore),+          runTest "gcc-core-x86_64 drops the configure arguments from the top-level Makefile, builds the compiler and libgcc with NIX_BUILD_CORES jobs, installs them stripped of debugging information and time stamps, and removes what gcc-latest's install removes and the directory that leaves empty" $+            assertEqual+              "phases and parallelism"+              ( [ "sed -e '/TOPLEVEL_CONFIGURE_ARGUMENTS=/d' -i Makefile",+                  "make ${enableParallelBuilding:+-j$NIX_BUILD_CORES} all-gcc all-target-libgcc"+                ],+                [ "make ${enableParallelInstalling:+-j$NIX_BUILD_CORES} 'STRIP=" <> host <> "-strip -p' install-strip-gcc install-strip-target-libgcc",+                  "libgccDir=$out/lib/gcc/" <> target <> "/" <> version,+                  target <> "-strip -p --strip-debug \"$libgccDir\"/*.a \"$libgccDir\"/*.o",+                  "rm -r \"$out/libexec/gcc/" <> target <> "/" <> version <> "/install-tools\" \"$libgccDir/install-tools\"",+                  "rm -r \"$out/share/man\" \"$out/share/info\"",+                  "rmdir \"$out/share\""+                ],+                "1",+                "1"+              )+              ( linesOf "buildPhase" gccCore,+                linesOf "installPhase" gccCore,+                maybe "" (variableOf "enableParallelBuilding") gccCore,+                maybe "" (variableOf "enableParallelInstalling") gccCore+              )+        ]+  where+    instantiates :: Text+    instantiates = "the x86_64 GCC core's derivations instantiate, adding seven to the closure of gcc-latest, binutils-x86_64 and the current MinGW-w64's headers"+    target :: Text+    target = "x86_64-w64-mingw32"+    -- The target of the compiler and tools the build runs.+    host :: Text+    host = "i686-w64-mingw32"+    version :: Text+    version = "16.2.0"+    -- The variables that name GCC's archive and the three it builds in its+    -- tree.+    archiveVariables :: [Text]+    archiveVariables = ["src", "gmpSrc", "mpfrSrc", "mpcSrc"]+    gccCoreRoot :: Text+    gccCoreRoot = "pkgs.gcc-core-x86_64"+    gccLatestRoot :: Text+    gccLatestRoot = "pkgs.gcc-latest"+    headersRoot :: Text+    headersRoot = "pkgs.mingw-w64-headers-latest"+    binutilsRoot :: Text+    binutilsRoot = "pkgs.binutils"+    binutilsX8664Root :: Text+    binutilsX8664Root = "pkgs.binutils-x86_64"+    builtBefore :: [Text]+    builtBefore = ["pkgs.busybox-w32", "pkgs.gnumake", "pkgs.tinycc-native.compiler", "pkgs.tinycc-native.libs", "pkgs.seedStdenv.applets", binutilsRoot, gccLatestRoot, headersRoot, binutilsX8664Root]+    roots :: [Text]+    roots = builtBefore ++ [gccCoreRoot, "checks.link", "checks.stamps"]+    -- Each kaem.runCommand adds its script, written by writeText as+    -- <name>-builder.+    addedNames :: [Text]+    addedNames =+      [target <> "-gcc-core-" <> version, "link.sh", "stamps.sh"]+        ++ concat [[name, name <> "-builder"] | name <- ["gcc-core-x86_64-link", "gcc-core-x86_64-stamps"]]++-- | @pkgs\/windows@'s x86_64 MinGW-w64 runtime, read back as the build+-- driver reads it: what mingw-w64-crt-x86_64 and+-- @test\/data\/mingw-w64-x86_64.nix@'s checks add to the closure of+-- gcc-core-x86_64, which compiles it.  It fetches nothing: the runtime is+-- compiled from mingw-w64-headers-latest's archive, so it adds no leaf,+-- and it reads no input source but the stdenv's own files and what+-- evaluation writes as text.  Its configure takes the compiler and+-- archiver the environment names, and the stdenv's are tcc's, so its+-- @preConfigure@ unsets them, and @C_INCLUDE_PATH@, which GCC reads as+-- well; its flags name x86_64 as the host, the headers' output as the+-- sysroot, msvcrt and the 64-bit runtime alone, and CFLAGS with no @-g@.+testMingwW64CrtX8664Windows :: IO [Bool]+testMingwW64CrtX8664Windows = do+  putStrLn "pkgs/mingw-w64-crt-x86_64"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let windows = "(import " <> nixQuotedPath (cwd </> "pkgs" </> "windows") <> ")"+      checks = "import " <> nixQuotedPath (cwd </> "test" </> "data" </> "mingw-w64-x86_64.nix")+      source =+        T.concat+          [ "let pkgs = ",+            windows,+            "; checks = ",+            checks,+            "; in builtins.concatStringsSep \" \" [ ",+            T.unwords [path <> ".drvPath" | path <- roots],+            " ]"+          ]+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> do+          let rootOf = Map.fromList (zip roots (T.words (bytesText bytes)))+          before <- sessionClosure (mapMaybe (`Map.lookup` rootOf) builtBefore)+          full <- sessionClosure (Map.elems rootOf)+          pure (rootOf, before, full)+        other -> throwEvalError ("expected the drvPaths as one string, got " <> typeName other)+  writes <- readIORef (esStoreWriteCache st)+  case outcome of+    Left err -> sequence [runTest instantiates (Fail err)]+    Right (rootOf, before, full) -> do+      let added = Map.elems (Map.difference full before)+          nameOf drv = maybe "" bytesText (Map.lookup "name" (drvEnv drv))+          variableOf name drv = maybe "" bytesText (Map.lookup name (drvEnv drv))+          isFetch drv = drvBuilder drv == "builtin:fetchurl"+          addedLeaves = filter (Map.null . drvInputDrvs) added+          wroteAsText path = fmap snd (Map.lookup (storePathToText defaultStoreDir path) writes) == Just WriteText+          derivationAt root = Map.lookup root rootOf >>= (`Map.lookup` full)+          headers = derivationAt headersRoot+          crt = derivationAt crtRoot+          -- The output of a root's derivation, as a flag spells a store+          -- path, or a word no flag holds where the root is missing.+          outputOf root = maybe "<no output>" (storePathToText defaultStoreDir . doPath) (derivationAt root >>= listToMaybe . drvOutputs)+          wordsOf name = maybe [] (T.words . variableOf name)+          -- What preConfigure runs before it moves to the build directory.+          firstLine = maybe "" (T.takeWhile (/= '\n') . variableOf "preConfigure")+      sequence+        [ runTest instantiates $+            assertEqual "derivations added" (sort addedNames) (sort (map nameOf added)),+          runTest "every derivation it adds but the fetches is i686-windows" $+            case [nameOf drv | drv <- added, not (isFetch drv), drvPlatform drv /= I686_Windows] of+              [] -> Pass+              named -> Fail ("not i686-windows: " <> T.intercalate ", " named),+          runTest "it adds no leaf, fetching nothing mingw-w64-headers-latest does not" $+            assertEqual "leaves added" [] (map nameOf addedLeaves),+          runTest "it reads no input source but what evaluation writes as text and the stdenv's files" $+            assertEqual+              "input sources not written as text"+              ["config.site", "include", "setup.sh"]+              (sort (map spName (nub [path | drv <- added, path <- drvInputSrcs drv, not (wroteAsText path)]))),+          runTest "mingw-w64-crt-x86_64 is built from mingw-w64-headers-latest's archive by gcc-core-x86_64 and binutils-x86_64, with tcc's variables unset" $+            assertEqual+              "src, buildInputs and preConfigure's first line"+              (wordsOf "src" headers, [outputOf gccCoreRoot, outputOf binutilsX8664Root], "unset CC AR C_INCLUDE_PATH", isJust headers)+              (wordsOf "src" crt, wordsOf "buildInputs" crt, firstLine crt, isJust crt),+          runTest "mingw-w64-crt-x86_64's flags name x86_64 as the host, mingw-w64-headers-latest's output as the sysroot, msvcrt and the 64-bit runtime alone, and CFLAGS with no -g" $+            assertEqual+              "flags"+              [ "--host=" <> target,+                "--with-sysroot=" <> outputOf headersRoot,+                "--with-default-msvcrt=msvcrt",+                "--disable-lib32",+                "--enable-lib64",+                "--disable-dependency-tracking",+                "CFLAGS=-O2"+              ]+              (wordsOf "configureFlags" crt),+          runTest "mingw-w64-crt-x86_64 builds and installs with NIX_BUILD_CORES jobs" $+            assertEqual+              "parallelism"+              ("1", "1")+              (maybe "" (variableOf "enableParallelBuilding") crt, maybe "" (variableOf "enableParallelInstalling") crt)+        ]+  where+    instantiates :: Text+    instantiates = "the x86_64 runtime's derivations instantiate, adding seven to the closure of gcc-core-x86_64"+    target :: Text+    target = "x86_64-w64-mingw32"+    version :: Text+    version = "14.0.0"+    headersRoot :: Text+    headersRoot = "pkgs.mingw-w64-headers-latest"+    crtRoot :: Text+    crtRoot = "pkgs.mingw-w64-crt-x86_64"+    gccCoreRoot :: Text+    gccCoreRoot = "pkgs.gcc-core-x86_64"+    binutilsX8664Root :: Text+    binutilsX8664Root = "pkgs.binutils-x86_64"+    builtBefore :: [Text]+    builtBefore = ["pkgs.busybox-w32", "pkgs.gnumake", "pkgs.tinycc-native.compiler", "pkgs.tinycc-native.libs", "pkgs.seedStdenv.applets", headersRoot, binutilsX8664Root, gccCoreRoot]+    roots :: [Text]+    roots = builtBefore ++ [crtRoot, "checks.crt", "checks.hello"]+    -- Each kaem.runCommand adds its script, written by writeText as+    -- <name>-builder.+    addedNames :: [Text]+    addedNames =+      ["mingw-w64-crt-" <> target <> "-" <> version, "crt.sh", "hello.sh"]+        ++ concat [[name, name <> "-builder"] | name <- ["mingw-w64-x86_64-crt", "mingw-w64-x86_64-hello"]]++-- | @pkgs\/windows@'s x86_64 GCC, read back as the build driver reads it:+-- what gcc-x86_64 and @test\/data\/gcc-x86_64.nix@'s checks add to the+-- closure of gcc-latest, binutils-x86_64 and the x86_64 MinGW-w64+-- runtime, which build it.  It fetches nothing: its four archives are+-- gcc-latest's, so it adds no leaf, and it reads no input source but the+-- stdenv's own files and what evaluation writes as text.  Its configure+-- is told by flags where its target's headers and runtime, the assembler+-- and the linker are, and which compilers, archiver, linker and resource+-- compiler the build runs, so each has to name the output of the+-- derivation that builds it, or the target's name binutils and gcc-latest+-- install their programs under.  It builds C and C++ with static+-- libraries and the win32 thread model; no compiler option carries @-g@,+-- libgcc's own @-g@ is stripped after the install, every link and strip+-- is told to write no time stamp, and the build leaves the configure+-- arguments, which name store paths, out of the compiler.+testGccX8664Windows :: IO [Bool]+testGccX8664Windows = do+  putStrLn "pkgs/gcc-x86_64"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let windows = "(import " <> nixQuotedPath (cwd </> "pkgs" </> "windows") <> ")"+      checks = "import " <> nixQuotedPath (cwd </> "test" </> "data" </> "gcc-x86_64.nix")+      source =+        T.concat+          [ "let pkgs = ",+            windows,+            "; checks = ",+            checks,+            "; in builtins.concatStringsSep \" \" [ ",+            T.unwords [path <> ".drvPath" | path <- roots],+            " ]"+          ]+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> do+          let rootOf = Map.fromList (zip roots (T.words (bytesText bytes)))+          before <- sessionClosure (mapMaybe (`Map.lookup` rootOf) builtBefore)+          full <- sessionClosure (Map.elems rootOf)+          pure (rootOf, before, full)+        other -> throwEvalError ("expected the drvPaths as one string, got " <> typeName other)+  writes <- readIORef (esStoreWriteCache st)+  case outcome of+    Left err -> sequence [runTest instantiates (Fail err)]+    Right (rootOf, before, full) -> do+      let added = Map.elems (Map.difference full before)+          nameOf drv = maybe "" bytesText (Map.lookup "name" (drvEnv drv))+          variableOf name drv = maybe "" bytesText (Map.lookup name (drvEnv drv))+          isFetch drv = drvBuilder drv == "builtin:fetchurl"+          addedLeaves = filter (Map.null . drvInputDrvs) added+          wroteAsText path = fmap snd (Map.lookup (storePathToText defaultStoreDir path) writes) == Just WriteText+          derivationAt root = Map.lookup root rootOf >>= (`Map.lookup` full)+          gcc = derivationAt gccRoot+          gccLatest = derivationAt gccLatestRoot+          -- The output of a root's derivation, as a flag spells a store+          -- path, or a word no flag holds where the root is missing.+          outputOf root = maybe "<no output>" (storePathToText defaultStoreDir . doPath) (derivationAt root >>= listToMaybe . drvOutputs)+          wordsOf name = maybe [] (T.words . variableOf name)+          linesOf name = maybe [] (map T.strip . T.lines . variableOf name)+          flagsWith prefixes drv = [flag | flag <- wordsOf "configureFlags" drv, any (`T.isPrefixOf` flag) prefixes]+      sequence+        [ runTest instantiates $+            assertEqual "derivations added" (sort addedNames) (sort (map nameOf added)),+          runTest "every derivation it adds but the fetches is i686-windows" $+            case [nameOf drv | drv <- added, not (isFetch drv), drvPlatform drv /= I686_Windows] of+              [] -> Pass+              named -> Fail ("not i686-windows: " <> T.intercalate ", " named),+          runTest "it adds no leaf, fetching nothing gcc-latest does not" $+            assertEqual "leaves added" [] (map nameOf addedLeaves),+          runTest "it reads no input source but what evaluation writes as text and the stdenv's files" $+            assertEqual+              "input sources not written as text"+              ["config.site", "include", "setup.sh"]+              (sort (map spName (nub [path | drv <- added, path <- drvInputSrcs drv, not (wroteAsText path)]))),+          runTest "gcc-x86_64 names gcc-latest's four archives where setup.sh and preConfigure read them, with gcc-latest, binutils and binutils-x86_64 as its build inputs and no patch" $+            assertEqual+              "the archives, buildInputs and patches"+              ( [wordsOf variable gccLatest | variable <- archiveVariables],+                [outputOf gccLatestRoot, outputOf binutilsRoot, outputOf binutilsX8664Root],+                [],+                True+              )+              ( [wordsOf variable gcc | variable <- archiveVariables],+                wordsOf "buildInputs" gcc,+                wordsOf "patches" gcc,+                isJust gccLatest+              ),+          runTest "gcc-x86_64's preConfigure moves GMP, MPFR and MPC to the directories GCC's configure builds them from, and unsets the stdenv's C_INCLUDE_PATH" $+            assertEqual+              "preConfigure's mv and unset lines"+              (["mv gmp-6.3.0 gmp", "mv mpfr-4.2.2 mpfr", "mv mpc-1.3.1 mpc"], ["unset C_INCLUDE_PATH"])+              (filter ("mv " `T.isPrefixOf`) (linesOf "preConfigure" gcc), filter ("unset " `T.isPrefixOf`) (linesOf "preConfigure" gcc)),+          runTest "gcc-x86_64's flags name the target, the outputs of the current MinGW-w64's headers, of the x86_64 runtime and of binutils-x86_64, and no sysroot" $+            assertEqual+              "flags"+              [ "--target=" <> target,+                "--with-headers=" <> outputOf headersRoot <> "/include",+                "--with-libs=" <> outputOf crtRoot <> "/lib",+                "--with-as=" <> outputOf binutilsX8664Root <> "/bin/" <> target <> "-as.exe",+                "--with-ld=" <> outputOf binutilsX8664Root <> "/bin/" <> target <> "-ld.exe"+              ]+              (flagsWith ["--target=", "--with-headers", "--with-libs", "--with-sysroot", "--with-build-sysroot", "--with-native-system-header-dir", "--with-as=", "--with-ld="] gcc),+          runTest "gcc-x86_64 builds with gcc-latest's drivers and binutils' archiver, linker and resource compiler, by their target's names, the resource compiler named in the environment and run with --use-temp-file" $+            assertEqual+              "tools, and WINDRES"+              (["CC=" <> host <> "-gcc", "CXX=" <> host <> "-g++", "AR=" <> host <> "-ar", "LD=" <> host <> "-ld"], host <> "-windres --use-temp-file")+              (flagsWith ["CC=", "CXX=", "AR=", "LD=", "STRIP=", "RANLIB=", "WINDRES="] gcc, maybe "" (variableOf "WINDRES") gcc),+          runTest "gcc-x86_64 gives every link it makes --no-insert-timestamp, and LDFLAGS nothing else" $+            assertEqual+              "LDFLAGS"+              ["LDFLAGS=-Wl,--no-insert-timestamp"]+              (flagsWith ["LDFLAGS=", "LDFLAGS_FOR_BUILD=", "LDFLAGS_FOR_TARGET="] gcc),+          runTest "gcc-x86_64's compiler options carry no -g, and it gives make no flags" $+            assertEqual+              "the options and makeFlags"+              (["CFLAGS=-O2", "CXXFLAGS=-O2", "CFLAGS_FOR_TARGET=-O2", "CXXFLAGS_FOR_TARGET=-O2"], [])+              (flagsWith ["CFLAGS=", "CXXFLAGS=", "CFLAGS_FOR_TARGET=", "CXXFLAGS_FOR_TARGET="] gcc, wordsOf "makeFlags" gcc),+          runTest "gcc-x86_64 builds C and C++, static, with the win32 thread model, no LTO and no registry lookup" $+            assertEqual+              "languages, libraries, threads, LTO and registry"+              ["--enable-languages=c,c++", "--enable-threads=win32", "--disable-lto", "--disable-shared", "--disable-win32-registry"]+              (flagsWith ["--enable-languages=", "--enable-shared", "--disable-shared", "--enable-threads", "--disable-threads", "--enable-lto", "--disable-lto", "--enable-win32-registry", "--disable-win32-registry"] gcc),+          runTest "gcc-x86_64 drops the configure arguments from the top-level Makefile, builds with NIX_BUILD_CORES jobs, installs with install-strip, whose strip keeps the zero time stamp ld writes, strips libgcc's debugging information with the target's strip, and removes what gcc-latest's install removes" $+            assertEqual+              "phases and parallelism"+              ( [ "sed -e '/TOPLEVEL_CONFIGURE_ARGUMENTS=/d' -i Makefile",+                  "make ${enableParallelBuilding:+-j$NIX_BUILD_CORES}"+                ],+                [ "make ${enableParallelInstalling:+-j$NIX_BUILD_CORES} 'STRIP=" <> host <> "-strip -p' install-strip",+                  "libgccDir=$out/lib/gcc/" <> target <> "/" <> version,+                  target <> "-strip -p --strip-debug \"$libgccDir\"/*.a \"$libgccDir\"/*.o",+                  "rm -r \"$out/libexec/gcc/" <> target <> "/" <> version <> "/install-tools\" \"$libgccDir/install-tools\"",+                  "rm -rf \"$out/share/gcc-" <> version <> "/python\" \"$out/share/man\" \"$out/share/info\"",+                  "rm \"$out/" <> target <> "/lib/libstdc++.a-gdb.py\"",+                  "rmdir \"$out/share/gcc-" <> version <> "\" \"$out/share\""+                ],+                "1",+                "1"+              )+              ( linesOf "buildPhase" gcc,+                linesOf "installPhase" gcc,+                maybe "" (variableOf "enableParallelBuilding") gcc,+                maybe "" (variableOf "enableParallelInstalling") gcc+              )+        ]+  where+    instantiates :: Text+    instantiates = "the x86_64 GCC's derivations instantiate, adding ten to the closure of gcc-latest, binutils-x86_64 and the x86_64 runtime"+    target :: Text+    target = "x86_64-w64-mingw32"+    -- The target of the compiler and tools the build runs.+    host :: Text+    host = "i686-w64-mingw32"+    version :: Text+    version = "16.2.0"+    -- The variables that name GCC's archive and the three it builds in its+    -- tree.+    archiveVariables :: [Text]+    archiveVariables = ["src", "gmpSrc", "mpfrSrc", "mpcSrc"]+    gccRoot :: Text+    gccRoot = "pkgs.gcc-x86_64"+    gccLatestRoot :: Text+    gccLatestRoot = "pkgs.gcc-latest"+    headersRoot :: Text+    headersRoot = "pkgs.mingw-w64-headers-latest"+    crtRoot :: Text+    crtRoot = "pkgs.mingw-w64-crt-x86_64"+    binutilsRoot :: Text+    binutilsRoot = "pkgs.binutils"+    binutilsX8664Root :: Text+    binutilsX8664Root = "pkgs.binutils-x86_64"+    builtBefore :: [Text]+    builtBefore = ["pkgs.busybox-w32", "pkgs.gnumake", "pkgs.tinycc-native.compiler", "pkgs.tinycc-native.libs", "pkgs.seedStdenv.applets", binutilsRoot, gccLatestRoot, headersRoot, binutilsX8664Root, crtRoot]+    roots :: [Text]+    roots = builtBefore ++ [gccRoot, "checks.hello-c", "checks.hello-cxx", "checks.stamps"]+    -- Each kaem.runCommand adds its script, written by writeText as+    -- <name>-builder.+    addedNames :: [Text]+    addedNames =+      [target <> "-gcc-" <> version, "hello-c.sh", "hello-cxx.sh", "stamps.sh"]+        ++ concat [[name, name <> "-builder"] | name <- ["gcc-x86_64-hello-c", "gcc-x86_64-hello-cxx", "gcc-x86_64-stamps"]]++-- | @pkgs\/windows@'s native x86_64 binutils, read back as the build driver+-- reads it: what binutils-native-x86_64 and+-- @test\/data\/binutils-native-x86_64.nix@'s checks add to the closure of+-- gcc-latest, gcc-x86_64 and binutils-x86_64, which build it.  It fetches+-- nothing: its archive is binutils-x86_64's, so it adds no leaf, and it+-- reads no input source but the stdenv's own files and what evaluation+-- writes as text.  Its configure is told x86_64-w64-mingw32 as the host and+-- the target, so the tools install under their own names; the build runs+-- gcc-x86_64's compiler and binutils-x86_64's archiver and linker by the+-- name of their target, since the stdenv's CC, AR and LD are tcc's, and+-- gcc-latest's compiler for the build machine; and its other flags are+-- binutils-x86_64's, so its CFLAGS leave out @-g@ and every link is told to+-- write no time stamp.+testBinutilsNativeX8664Windows :: IO [Bool]+testBinutilsNativeX8664Windows = do+  putStrLn "pkgs/binutils-native-x86_64"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let windows = "(import " <> nixQuotedPath (cwd </> "pkgs" </> "windows") <> ")"+      checks = "import " <> nixQuotedPath (cwd </> "test" </> "data" </> "binutils-native-x86_64.nix")+      source =+        T.concat+          [ "let pkgs = ",+            windows,+            "; checks = ",+            checks,+            "; in builtins.concatStringsSep \" \" [ ",+            T.unwords [path <> ".drvPath" | path <- roots],+            " ]"+          ]+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> do+          let rootOf = Map.fromList (zip roots (T.words (bytesText bytes)))+          before <- sessionClosure (mapMaybe (`Map.lookup` rootOf) builtBefore)+          full <- sessionClosure (Map.elems rootOf)+          pure (rootOf, before, full)+        other -> throwEvalError ("expected the drvPaths as one string, got " <> typeName other)+  writes <- readIORef (esStoreWriteCache st)+  case outcome of+    Left err -> sequence [runTest instantiates (Fail err)]+    Right (rootOf, before, full) -> do+      let added = Map.elems (Map.difference full before)+          nameOf drv = maybe "" bytesText (Map.lookup "name" (drvEnv drv))+          variableOf name drv = maybe "" bytesText (Map.lookup name (drvEnv drv))+          isFetch drv = drvBuilder drv == "builtin:fetchurl"+          addedLeaves = filter (Map.null . drvInputDrvs) added+          wroteAsText path = fmap snd (Map.lookup (storePathToText defaultStoreDir path) writes) == Just WriteText+          derivationAt root = Map.lookup root rootOf >>= (`Map.lookup` full)+          binutilsNative = derivationAt binutilsNativeRoot+          binutilsCross = derivationAt binutilsX8664Root+          -- The output of a root's derivation, as a flag spells a store+          -- path, or a word no flag holds where the root is missing.+          outputOf root = maybe "<no output>" (storePathToText defaultStoreDir . doPath) (derivationAt root >>= listToMaybe . drvOutputs)+          wordsOf name = maybe [] (T.words . variableOf name)+          linesOf name = maybe [] (map T.strip . T.lines . variableOf name)+          flagsWith prefixes drv = [flag | flag <- wordsOf "configureFlags" drv, any (`T.isPrefixOf` flag) prefixes]+          sharedFlags drv = [flag | flag <- wordsOf "configureFlags" drv, not (any (`T.isPrefixOf` flag) hostAndToolPrefixes)]+      sequence+        [ runTest instantiates $+            assertEqual "derivations added" (sort addedNames) (sort (map nameOf added)),+          runTest "every derivation it adds but the fetches is i686-windows" $+            case [nameOf drv | drv <- added, not (isFetch drv), drvPlatform drv /= I686_Windows] of+              [] -> Pass+              named -> Fail ("not i686-windows: " <> T.intercalate ", " named),+          runTest "it adds no leaf, fetching nothing binutils-x86_64 does not" $+            assertEqual "leaves added" [] (map nameOf addedLeaves),+          runTest "it reads no input source but what evaluation writes as text and the stdenv's files" $+            assertEqual+              "input sources not written as text"+              ["config.site", "include", "setup.sh"]+              (sort (map spName (nub [path | drv <- added, path <- drvInputSrcs drv, not (wroteAsText path)]))),+          runTest "binutils-native-x86_64 builds binutils-x86_64's archive, with gcc-latest, gcc-x86_64 and binutils-x86_64 as its build inputs and no patch" $+            assertEqual+              "src, buildInputs and patches"+              (wordsOf "src" binutilsCross, [outputOf gccLatestRoot, outputOf gccX8664Root, outputOf binutilsX8664Root], [], True)+              (wordsOf "src" binutilsNative, wordsOf "buildInputs" binutilsNative, wordsOf "patches" binutilsNative, isJust binutilsCross),+          runTest "binutils-native-x86_64 is configured for x86_64-w64-mingw32 as its host and target with no sysroot, and builds with gcc-x86_64's driver and binutils-x86_64's archiver and linker by their target's name, and gcc-latest's driver for the build machine" $+            assertEqual+              "host, target and tools"+              [ "--host=" <> target,+                "--target=" <> target,+                "CC=" <> target <> "-gcc",+                "AR=" <> target <> "-ar",+                "LD=" <> target <> "-ld",+                "CC_FOR_BUILD=" <> buildTarget <> "-gcc"+              ]+              (flagsWith ["--target=", "--host=", "--with-sysroot", "--with-build-sysroot", "CC=", "CXX=", "AR=", "LD=", "RANLIB=", "STRIP=", "CC_FOR_BUILD=", "CXX_FOR_BUILD=", "AR_FOR_BUILD=", "RANLIB_FOR_BUILD="] binutilsNative),+          runTest "binutils-native-x86_64's other flags are binutils-x86_64's, so its CFLAGS carry no -g and LDFLAGS gives every link --no-insert-timestamp and nothing else" $+            assertEqual+              "the other flags, CFLAGS and LDFLAGS"+              (sharedFlags binutilsCross, ["CFLAGS=-O2", "LDFLAGS=-Wl,--no-insert-timestamp"])+              (sharedFlags binutilsNative, flagsWith ["CFLAGS=", "CXXFLAGS=", "LDFLAGS="] binutilsNative),+          runTest "binutils-native-x86_64 unsets the stdenv's C_INCLUDE_PATH, configures from a build directory beside the source, and builds with NIX_BUILD_CORES jobs and nixpkgs' MAKEINFO" $+            assertEqual+              "preConfigure, makeFlags and parallelism"+              ( [ "unset C_INCLUDE_PATH",+                  "mkdir ../build",+                  "cd ../build",+                  "configureScript=../binutils-with-gold-" <> version <> "/configure"+                ],+                ["MAKEINFO=true"],+                "1"+              )+              (linesOf "preConfigure" binutilsNative, wordsOf "makeFlags" binutilsNative, maybe "" (variableOf "enableParallelBuilding") binutilsNative)+        ]+  where+    instantiates :: Text+    instantiates = "the native x86_64 binutils derivations instantiate, adding seven to the closure of gcc-latest, gcc-x86_64 and binutils-x86_64"+    version :: Text+    version = "2.46"+    target :: Text+    target = "x86_64-w64-mingw32"+    -- The target of gcc-latest, the build machine's compiler.+    buildTarget :: Text+    buildTarget = "i686-w64-mingw32"+    -- What starts the flags that name the host or a tool the build runs,+    -- the flags in which the native and the cross binutils differ.+    hostAndToolPrefixes :: [Text]+    hostAndToolPrefixes = ["--host=", "CC=", "AR=", "LD=", "CC_FOR_BUILD="]+    binutilsNativeRoot :: Text+    binutilsNativeRoot = "pkgs.binutils-native-x86_64"+    binutilsX8664Root :: Text+    binutilsX8664Root = "pkgs.binutils-x86_64"+    gccLatestRoot :: Text+    gccLatestRoot = "pkgs.gcc-latest"+    gccX8664Root :: Text+    gccX8664Root = "pkgs.gcc-x86_64"+    builtBefore :: [Text]+    builtBefore = ["pkgs.busybox-w32", "pkgs.gnumake", "pkgs.tinycc-native.compiler", "pkgs.tinycc-native.libs", "pkgs.seedStdenv.applets", gccLatestRoot, binutilsX8664Root, gccX8664Root]+    roots :: [Text]+    roots = builtBefore ++ [binutilsNativeRoot, "checks.link", "checks.stamps"]+    -- Each kaem.runCommand adds its script, written by writeText as+    -- <name>-builder.+    addedNames :: [Text]+    addedNames =+      ["binutils-" <> version, "link.sh", "stamps.sh"]+        ++ concat [[name, name <> "-builder"] | name <- ["binutils-native-x86_64-link", "binutils-native-x86_64-stamps"]]++-- | @pkgs\/windows@'s native x86_64 GCC, read back as the build driver+-- reads it: what gcc-native-x86_64 and @test\/data\/gcc-native-x86_64.nix@'s+-- checks add to the closure of gcc-x86_64 and binutils-native-x86_64, which+-- build it and assemble and link for it.  It fetches nothing: its four+-- archives are gcc-latest's, so it adds no leaf, and it reads no input+-- source but the stdenv's own files, what evaluation writes as text, and+-- its patch, which takes @\/usr\/local\/include@ out of its search.+-- Its configure is told x86_64-w64-mingw32 as the host and the target,+-- where its target's headers are at build time, since a compiler whose+-- host is its target takes no @--with-headers@ or @--with-libs@, and which+-- assembler and linker it runs, so each has to name the output of the+-- derivation that builds it; the build runs gcc-x86_64's compilers and+-- binutils-x86_64's tools for the host by the name of their target, and+-- gcc-latest's and binutils' for the build machine by theirs.  It builds C+-- and C++ with static libraries and the win32 thread model, its other+-- flags are gcc-x86_64's, and its install copies the target's headers and+-- runtime where the installed driver finds them.+testGccNativeX8664Windows :: IO [Bool]+testGccNativeX8664Windows = do+  putStrLn "pkgs/gcc-native-x86_64"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let windows = "(import " <> nixQuotedPath (cwd </> "pkgs" </> "windows") <> ")"+      checks = "import " <> nixQuotedPath (cwd </> "test" </> "data" </> "gcc-native-x86_64.nix")+      source =+        T.concat+          [ "let pkgs = ",+            windows,+            "; checks = ",+            checks,+            "; in builtins.concatStringsSep \" \" [ ",+            T.unwords [path <> ".drvPath" | path <- roots],+            " ]"+          ]+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> do+          let rootOf = Map.fromList (zip roots (T.words (bytesText bytes)))+          before <- sessionClosure (mapMaybe (`Map.lookup` rootOf) builtBefore)+          full <- sessionClosure (Map.elems rootOf)+          pure (rootOf, before, full)+        other -> throwEvalError ("expected the drvPaths as one string, got " <> typeName other)+  writes <- readIORef (esStoreWriteCache st)+  patchLines <- BS8.lines <$> BS.readFile (cwd </> "pkgs" </> "windows" </> "by-name" </> "gc" </> "gcc-native-x86_64" </> T.unpack patch)+  case outcome of+    Left err -> sequence [runTest instantiates (Fail err)]+    Right (rootOf, before, full) -> do+      let added = Map.elems (Map.difference full before)+          nameOf drv = maybe "" bytesText (Map.lookup "name" (drvEnv drv))+          variableOf name drv = maybe "" bytesText (Map.lookup name (drvEnv drv))+          isFetch drv = drvBuilder drv == "builtin:fetchurl"+          addedLeaves = filter (Map.null . drvInputDrvs) added+          wroteAsText path = fmap snd (Map.lookup (storePathToText defaultStoreDir path) writes) == Just WriteText+          -- A unified diff's new file names, and the lines it adds and+          -- removes.+          patchFiles = [rest | line <- patchLines, Just rest <- [BS.stripPrefix "+++ " line]]+          patchAdded = [rest | line <- patchLines, Just rest <- [BS.stripPrefix "+" line], not ("++ " `BS.isPrefixOf` rest)]+          patchRemoved = [rest | line <- patchLines, Just rest <- [BS.stripPrefix "-" line], not ("-- " `BS.isPrefixOf` rest)]+          derivationAt root = Map.lookup root rootOf >>= (`Map.lookup` full)+          gccNative = derivationAt gccNativeRoot+          gccCross = derivationAt gccX8664Root+          gccLatest = derivationAt gccLatestRoot+          -- The output of a root's derivation, as a flag spells a store+          -- path, or a word no flag holds where the root is missing.+          outputOf root = maybe "<no output>" (storePathToText defaultStoreDir . doPath) (derivationAt root >>= listToMaybe . drvOutputs)+          wordsOf name = maybe [] (T.words . variableOf name)+          linesOf name = maybe [] (map T.strip . T.lines . variableOf name)+          flagsWith prefixes drv = [flag | flag <- wordsOf "configureFlags" drv, any (`T.isPrefixOf` flag) prefixes]+          sharedFlags drv = [flag | flag <- wordsOf "configureFlags" drv, not (any (`T.isPrefixOf` flag) hostAndToolPrefixes)]+      sequence+        [ runTest instantiates $+            assertEqual "derivations added" (sort addedNames) (sort (map nameOf added)),+          runTest "every derivation it adds but the fetches is i686-windows" $+            case [nameOf drv | drv <- added, not (isFetch drv), drvPlatform drv /= I686_Windows] of+              [] -> Pass+              named -> Fail ("not i686-windows: " <> T.intercalate ", " named),+          runTest "it adds no leaf, fetching nothing gcc-latest does not" $+            assertEqual "leaves added" [] (map nameOf addedLeaves),+          runTest "it reads no input source but what evaluation writes as text, the stdenv's files and its patch" $+            assertEqual+              "input sources not written as text"+              (sort ["config.site", "include", "setup.sh", patch])+              (sort (map spName (nub [path | drv <- added, path <- drvInputSrcs drv, not (wroteAsText path)]))),+          runTest "gcc-native-x86_64 names gcc-latest's four archives where setup.sh and preConfigure read them, with gcc-latest, binutils, gcc-x86_64 and binutils-x86_64 as its build inputs and its patch" $+            assertEqual+              "the archives, buildInputs and patches"+              ( [wordsOf variable gccLatest | variable <- archiveVariables],+                [outputOf gccLatestRoot, outputOf binutilsRoot, outputOf gccX8664Root, outputOf binutilsX8664Root],+                [storePathToText defaultStoreDir path | drv <- maybeToList gccNative, path <- drvInputSrcs drv, spName path == patch],+                True+              )+              ( [wordsOf variable gccNative | variable <- archiveVariables],+                wordsOf "buildInputs" gccNative,+                wordsOf "patches" gccNative,+                isJust gccLatest+              ),+          runTest "gcc-native-x86_64's preConfigure moves GMP, MPFR and MPC to the directories GCC's configure builds them from, and unsets the stdenv's C_INCLUDE_PATH" $+            assertEqual+              "preConfigure's mv and unset lines"+              (["mv gmp-6.3.0 gmp", "mv mpfr-4.2.2 mpfr", "mv mpc-1.3.1 mpc"], ["unset C_INCLUDE_PATH"])+              (filter ("mv " `T.isPrefixOf`) (linesOf "preConfigure" gccNative), filter ("unset " `T.isPrefixOf`) (linesOf "preConfigure" gccNative)),+          runTest "gcc-native-x86_64's flags name x86_64-w64-mingw32 as its host and target, the current MinGW-w64's headers' output as the build sysroot with /include as their directory, binutils-native-x86_64's assembler and linker, and no sysroot and no headers or runtime to copy" $+            assertEqual+              "flags"+              [ "--host=" <> target,+                "--target=" <> target,+                "--with-build-sysroot=" <> outputOf headersRoot,+                "--with-native-system-header-dir=/include",+                "--with-as=" <> outputOf binutilsNativeRoot <> "/bin/as.exe",+                "--with-ld=" <> outputOf binutilsNativeRoot <> "/bin/ld.exe"+              ]+              (flagsWith ["--host=", "--target=", "--with-headers", "--with-libs", "--with-sysroot", "--with-build-sysroot", "--with-native-system-header-dir", "--with-gxx-include-dir", "--with-as=", "--with-ld="] gccNative),+          runTest "gcc-native-x86_64 builds the host's programs with gcc-x86_64's drivers and binutils-x86_64's archiver, linker and resource compiler, and the build machine's with gcc-latest's drivers and binutils' archiver and ranlib, each by its target's name, the resource compiler named in the environment and run with --use-temp-file" $+            assertEqual+              "tools, and WINDRES"+              ( [ "CC=" <> target <> "-gcc",+                  "CXX=" <> target <> "-g++",+                  "AR=" <> target <> "-ar",+                  "LD=" <> target <> "-ld",+                  "CC_FOR_BUILD=" <> buildTarget <> "-gcc",+                  "CXX_FOR_BUILD=" <> buildTarget <> "-g++",+                  "AR_FOR_BUILD=" <> buildTarget <> "-ar",+                  "RANLIB_FOR_BUILD=" <> buildTarget <> "-ranlib"+                ],+                target <> "-windres --use-temp-file"+              )+              ( flagsWith ["CC=", "CXX=", "AR=", "LD=", "STRIP=", "RANLIB=", "WINDRES=", "CC_FOR_BUILD=", "CXX_FOR_BUILD=", "AR_FOR_BUILD=", "RANLIB_FOR_BUILD=", "LD_FOR_BUILD=", "NM_FOR_BUILD="] gccNative,+                maybe "" (variableOf "WINDRES") gccNative+              ),+          runTest "gcc-native-x86_64 gives every link it makes --no-insert-timestamp, and LDFLAGS nothing else" $+            assertEqual+              "LDFLAGS"+              ["LDFLAGS=-Wl,--no-insert-timestamp"]+              (flagsWith ["LDFLAGS=", "LDFLAGS_FOR_BUILD=", "LDFLAGS_FOR_TARGET="] gccNative),+          runTest "gcc-native-x86_64's compiler options carry no -g, and it gives make no flags" $+            assertEqual+              "the options and makeFlags"+              (["CFLAGS=-O2", "CXXFLAGS=-O2", "CFLAGS_FOR_TARGET=-O2", "CXXFLAGS_FOR_TARGET=-O2"], [])+              (flagsWith ["CFLAGS=", "CXXFLAGS=", "CFLAGS_FOR_TARGET=", "CXXFLAGS_FOR_TARGET=", "CFLAGS_FOR_BUILD=", "CXXFLAGS_FOR_BUILD="] gccNative, wordsOf "makeFlags" gccNative),+          runTest "gcc-native-x86_64 builds C and C++, static, with the win32 thread model, no LTO and no registry lookup" $+            assertEqual+              "languages, libraries, threads, LTO and registry"+              ["--enable-languages=c,c++", "--enable-threads=win32", "--disable-lto", "--disable-shared", "--disable-win32-registry"]+              (flagsWith ["--enable-languages=", "--enable-shared", "--disable-shared", "--enable-threads", "--disable-threads", "--enable-lto", "--disable-lto", "--enable-win32-registry", "--disable-win32-registry"] gccNative),+          runTest "gcc-native-x86_64's other flags are gcc-x86_64's" $+            assertEqual "the other flags" (sharedFlags gccCross, True) (sharedFlags gccNative, isJust gccCross),+          runTest "gcc-native-x86_64 hands configure, through the environment, the host's strip with -p, which install-strip runs on each program and which keeps the zero time stamp ld writes" $+            assertEqual "STRIP" (target <> "-strip -p") (maybe "" (variableOf "STRIP") gccNative),+          runTest "gcc-native-x86_64 drops the configure arguments from the top-level Makefile, builds with NIX_BUILD_CORES jobs, installs with install-strip, strips libgcc's debugging information, removes what gcc-x86_64's install removes, and copies the current MinGW-w64's headers and the x86_64 runtime into its tool directory" $+            assertEqual+              "phases and parallelism"+              ( [ "sed -e '/TOPLEVEL_CONFIGURE_ARGUMENTS=/d' -i Makefile",+                  "make ${enableParallelBuilding:+-j$NIX_BUILD_CORES}"+                ],+                [ "make ${enableParallelInstalling:+-j$NIX_BUILD_CORES} install-strip",+                  "libgccDir=$out/lib/gcc/" <> target <> "/" <> version,+                  target <> "-strip -p --strip-debug \"$libgccDir\"/*.a \"$libgccDir\"/*.o",+                  "rm -r \"$out/libexec/gcc/" <> target <> "/" <> version <> "/install-tools\" \"$libgccDir/install-tools\"",+                  "rm -rf \"$out/share/gcc-" <> version <> "/python\" \"$out/share/man\" \"$out/share/info\"",+                  "rm \"$out/lib/libstdc++.a-gdb.py\"",+                  "rmdir \"$out/share/gcc-" <> version <> "\" \"$out/share\"",+                  "mkdir -p \"$out/" <> target <> "/include\" \"$out/" <> target <> "/lib\"",+                  "cp -r \"" <> outputOf headersRoot <> "/include/.\" \"$out/" <> target <> "/include\"",+                  "cp -r \"" <> outputOf crtRoot <> "/lib/.\" \"$out/" <> target <> "/lib\""+                ],+                "1",+                "1"+              )+              ( linesOf "buildPhase" gccNative,+                linesOf "installPhase" gccNative,+                maybe "" (variableOf "enableParallelBuilding") gccNative,+                maybe "" (variableOf "enableParallelInstalling") gccNative+              ),+          runTest "no-local-include-dir.patch undefines LOCAL_INCLUDE_DIR in gcc/cppdefault.cc, and changes nothing else" $+            assertEqual+              "the files it changes, and the lines it adds and removes"+              (["b/gcc/cppdefault.cc"], ["#undef LOCAL_INCLUDE_DIR", ""], [])+              (patchFiles, patchAdded, patchRemoved)+        ]+  where+    patch :: Text+    patch = "no-local-include-dir.patch"+    instantiates :: Text+    instantiates = "the native x86_64 GCC's derivations instantiate, adding ten to the closure of gcc-x86_64 and binutils-native-x86_64"+    target :: Text+    target = "x86_64-w64-mingw32"+    -- The target of gcc-latest and binutils, the build machine's compilers+    -- and tools.+    buildTarget :: Text+    buildTarget = "i686-w64-mingw32"+    version :: Text+    version = "16.2.0"+    -- The variables that name GCC's archive and the three it builds in its+    -- tree.+    archiveVariables :: [Text]+    archiveVariables = ["src", "gmpSrc", "mpfrSrc", "mpcSrc"]+    -- What starts the flags that name the host, where the target's headers+    -- and runtime come from, the assembler and linker, or a tool the build+    -- runs, the flags in which the native and the cross GCC differ.+    hostAndToolPrefixes :: [Text]+    hostAndToolPrefixes =+      [ "--host=",+        "--with-headers=",+        "--with-libs=",+        "--with-build-sysroot=",+        "--with-native-system-header-dir=",+        "--with-as=",+        "--with-ld=",+        "CC=",+        "CXX=",+        "AR=",+        "LD=",+        "CC_FOR_BUILD=",+        "CXX_FOR_BUILD=",+        "AR_FOR_BUILD=",+        "RANLIB_FOR_BUILD="+      ]+    gccNativeRoot :: Text+    gccNativeRoot = "pkgs.gcc-native-x86_64"+    gccX8664Root :: Text+    gccX8664Root = "pkgs.gcc-x86_64"+    gccLatestRoot :: Text+    gccLatestRoot = "pkgs.gcc-latest"+    headersRoot :: Text+    headersRoot = "pkgs.mingw-w64-headers-latest"+    crtRoot :: Text+    crtRoot = "pkgs.mingw-w64-crt-x86_64"+    binutilsRoot :: Text+    binutilsRoot = "pkgs.binutils"+    binutilsX8664Root :: Text+    binutilsX8664Root = "pkgs.binutils-x86_64"+    binutilsNativeRoot :: Text+    binutilsNativeRoot = "pkgs.binutils-native-x86_64"+    builtBefore :: [Text]+    builtBefore = ["pkgs.busybox-w32", "pkgs.gnumake", "pkgs.tinycc-native.compiler", "pkgs.tinycc-native.libs", "pkgs.seedStdenv.applets", binutilsRoot, gccLatestRoot, headersRoot, binutilsX8664Root, crtRoot, gccX8664Root, binutilsNativeRoot]+    roots :: [Text]+    roots = builtBefore ++ [gccNativeRoot, "checks.hello-c", "checks.hello-cxx", "checks.stamps"]+    -- Each kaem.runCommand adds its script, written by writeText as+    -- <name>-builder.+    addedNames :: [Text]+    addedNames =+      ["gcc-" <> version, "hello-c.sh", "hello-cxx.sh", "stamps.sh"]+        ++ concat [[name, name <> "-builder"] | name <- ["gcc-native-x86_64-hello-c", "gcc-native-x86_64-hello-cxx", "gcc-native-x86_64-stamps"]]++-- | @pkgs\/windows@'s stdenv, read back as the build driver reads it:+-- what its wrappers and @test\/data\/stdenv.nix@'s checks, GNU Hello and+-- the set's other five packages built with it and flags, add to the+-- closure of the tools it is made of, busybox-w32, GNU make, the seed+-- stdenv's applets and the native x86_64 binutils and GCC.+-- The leaves it adds are the archives of Hello, sed and zlib, every+-- derivation but those fetches is x86_64-windows, and it reads no input+-- source but the stdenv's own files, the packages' source directories,+-- the flags check's sources and what evaluation writes as text.  Its+-- builds run its own @setup.sh@, which runs the seed stdenv's and then+-- the fixup phase, with the applets, GNU make and the wrappers on @PATH@ and+-- neither toolchain's bin directory, whose programs GNU make would run+-- before a wrapper of the same name; @CC@, @CXX@ and @LD@ name the+-- wrappers, @AR@ binutils' archiver, and nothing sets the+-- @C_INCLUDE_PATH@ the seed stdenv sets for TinyCC; @OBJDUMP@ and+-- @STRIP@ name binutils' programs, @WINDRES@ the windres wrapper, and the+-- fixup looks for a DLL in GCC's bin directory first.  The wrappers are+-- written from gcc-native-x86_64's drivers and binutils-native-x86_64's+-- linker.+testStdenvWindows :: IO [Bool]+testStdenvWindows = do+  putStrLn "pkgs/stdenv"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let windows = "(import " <> nixQuotedPath (cwd </> "pkgs" </> "windows") <> ")"+      checksOf name = "import " <> nixQuotedPath (cwd </> "test" </> "data" </> name)+      source =+        T.concat+          [ "let pkgs = ",+            windows,+            "; checks = ",+            checksOf "stdenv.nix",+            "; seedChecks = ",+            checksOf "seed-stdenv.nix",+            "; in builtins.concatStringsSep \" \" [ ",+            T.unwords [path <> ".drvPath" | path <- roots],+            " ]"+          ]+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> do+          let rootOf = Map.fromList (zip roots (T.words (bytesText bytes)))+              closureOf attrs = sessionClosure (mapMaybe (`Map.lookup` rootOf) attrs)+          tools <- closureOf toolRoots+          built <- closureOf ([wrappersRoot, helloRoot, flagsRoot] ++ packageRoots)+          full <- sessionClosure (Map.elems rootOf)+          pure (rootOf, tools, built, full)+        other -> throwEvalError ("expected the drvPaths as one string, got " <> typeName other)+  writes <- readIORef (esStoreWriteCache st)+  case outcome of+    Left err -> sequence [runTest instantiates (Fail err)]+    Right (rootOf, tools, built, full) -> do+      let added = Map.elems (Map.difference built tools)+          nameOf drv = maybe "" bytesText (Map.lookup "name" (drvEnv drv))+          variableOf name drv = maybe "" bytesText (Map.lookup name (drvEnv drv))+          isFetch drv = drvBuilder drv == "builtin:fetchurl"+          isFixedOutput drv = not (all (T.null . doHash) (drvOutputs drv))+          addedLeaves = filter (Map.null . drvInputDrvs) added+          wroteAsText path = fmap snd (Map.lookup (storePathToText defaultStoreDir path) writes) == Just WriteText+          derivationAt root = Map.lookup root rootOf >>= (`Map.lookup` full)+          -- The output of a root's derivation, as a variable spells a+          -- store path, or a word no variable holds where the root is+          -- missing.+          outputOf root = maybe "<no output>" (storePathToText defaultStoreDir . doPath) (derivationAt root >>= listToMaybe . drvOutputs)+          hello = derivationAt helloRoot+          seedHello = derivationAt seedHelloRoot+          wrappers = derivationAt wrappersRoot+          wordsOf name = maybe [] (T.words . variableOf name)+          storePathIn = parseStorePath defaultStoreDir+          -- The script a derivation's builder runs: the second argument,+          -- after busybox's applet name, sh.+          scriptOf drv = case drvArgs drv of+            [_, script] -> storePathIn (bytesText script)+            _ -> Nothing+          configSiteOf drv = storePathIn (variableOf "CONFIG_SITE" drv)+          binutilsProgram program = outputOf binutilsNativeRoot <> "/bin/" <> program <> ".exe"+      sequence+        [ runTest instantiates $+            assertEqual "derivations added" (sort addedNames) (sort (map nameOf added)),+          runTest "every derivation it adds but the fetch is x86_64-windows" $+            case [nameOf drv | drv <- added, not (isFetch drv), drvPlatform drv /= X86_64_Windows] of+              [] -> Pass+              named -> Fail ("not x86_64-windows: " <> T.intercalate ", " named),+          runTest "the leaves it adds are the archives of hello, sed and zlib, each fetched fixed-output" $+            assertEqual+              "leaves added"+              (sort archives, True)+              (sort (map nameOf addedLeaves), all (\drv -> isFetch drv && isFixedOutput drv) addedLeaves),+          -- Two scripts named setup.sh, the stdenv's and the seed+          -- stdenv's it runs, and the source directories of libgreet,+          -- zdemo and greeter.+          runTest "it reads no input source but what evaluation writes as text, the stdenv's own files, the packages' source directories and the flags check's sources" $+            assertEqual+              "input sources not written as text"+              (sort ["cc-wrapper.sh", "config.site", "ld-wrapper.sh", "link.specs", "setup.sh", "setup.sh", "src", "src", "src", "stdenv-flags", "windres-wrapper.sh", "wrap.sh"])+              (sort (map spName (nub [path | drv <- added, path <- drvInputSrcs drv, not (wroteAsText path)]))),+          runTest "hello built with it runs its own setup.sh under busybox's sh, which runs the seed stdenv's, with a config.site that is not the seed stdenv's" $+            assertEqual+              "the builder, the script and whether it is the seed stdenv's, whether seedSetup is the seed stdenv's script, and CONFIG_SITE and whether it is the seed stdenv's"+              (outputOf busyboxRoot <> "/bin/busybox.exe", Just "setup.sh", False, True, Just "config.site", False)+              ( maybe "" (bytesText . drvBuilder) hello,+                spName <$> (scriptOf =<< hello),+                (scriptOf =<< hello) == (scriptOf =<< seedHello),+                (storePathIn . variableOf "seedSetup" =<< hello) == (scriptOf =<< seedHello),+                spName <$> (configSiteOf =<< hello),+                (configSiteOf =<< hello) == (configSiteOf =<< seedHello)+              ),+          runTest "OBJDUMP and STRIP name binutils-native-x86_64's programs, WINDRES the windres wrapper, and the fixup looks in gcc-native-x86_64's bin directory first" $+            assertEqual+              "OBJDUMP, STRIP, WINDRES and dllSearchPath"+              (Just (binutilsProgram "objdump", binutilsProgram "strip", "windres", outputOf gccNativeRoot <> "/bin"))+              ( hello <&> \drv ->+                  (variableOf "OBJDUMP" drv, variableOf "STRIP" drv, variableOf "WINDRES" drv, variableOf "dllSearchPath" drv)+              ),+          runTest "its builds' PATH is the seed stdenv's applets, GNU make and the wrappers, with neither toolchain's bin directory on it" $+            assertEqual+              "initialPath and buildInputs"+              ([outputOf appletsRoot, outputOf gnumakeRoot, outputOf wrappersRoot], [])+              (wordsOf "initialPath" hello, wordsOf "buildInputs" hello),+          runTest "CC, CXX and LD name the wrappers, AR binutils-native-x86_64's archiver, configure's build is x86_64-w64-mingw32, and nothing sets C_INCLUDE_PATH" $+            assertEqual+              "CC, CXX, LD, AR, buildTriple, and whether C_INCLUDE_PATH is set"+              (Just ("gcc", "g++", "ld", outputOf binutilsNativeRoot <> "/bin/ar.exe", target, False))+              ( hello <&> \drv ->+                  ( variableOf "CC" drv,+                    variableOf "CXX" drv,+                    variableOf "LD" drv,+                    variableOf "AR" drv,+                    variableOf "buildTriple" drv,+                    Map.member "C_INCLUDE_PATH" (drvEnv drv)+                  )+              ),+          runTest "the wrappers are written from gcc-native-x86_64's drivers and binutils-native-x86_64's linker and resource compiler" $+            assertEqual+              "compilers, linker and windres"+              (Just (outputOf gccNativeRoot <> "/bin", outputOf binutilsNativeRoot <> "/bin/ld.exe", binutilsProgram "windres"))+              (wrappers <&> \drv -> (variableOf "compilers" drv, variableOf "linker" drv, variableOf "windres" drv))+        ]+  where+    instantiates :: Text+    instantiates = "the stdenv and its checks instantiate, adding eleven to the closure of their tools"+    target :: Text+    target = "x86_64-w64-mingw32"+    busyboxRoot :: Text+    busyboxRoot = "pkgs.busybox-w32"+    gnumakeRoot :: Text+    gnumakeRoot = "pkgs.gnumake"+    appletsRoot :: Text+    appletsRoot = "pkgs.seedStdenv.applets"+    binutilsNativeRoot :: Text+    binutilsNativeRoot = "pkgs.binutils-native-x86_64"+    gccNativeRoot :: Text+    gccNativeRoot = "pkgs.gcc-native-x86_64"+    toolRoots :: [Text]+    toolRoots = [busyboxRoot, gnumakeRoot, appletsRoot, binutilsNativeRoot, gccNativeRoot]+    wrappersRoot :: Text+    wrappersRoot = "pkgs.stdenv.cc"+    helloRoot :: Text+    helloRoot = "checks.hello"+    flagsRoot :: Text+    flagsRoot = "checks.flags"+    seedHelloRoot :: Text+    seedHelloRoot = "seedChecks.hello"+    roots :: [Text]+    roots = toolRoots ++ [wrappersRoot, helloRoot, flagsRoot, seedHelloRoot] ++ packageRoots+    -- The set's other five packages, built with the stdenv.+    packageRoots :: [Text]+    packageRoots = ["checks.sed", "checks.zlib", "checks.libgreet", "checks.zdemo", "checks.greeter"]+    archives :: [Text]+    archives = ["hello-2.12.3.tar.gz", "sed-4.10.tar.xz", "zlib-1.3.2.tar.gz"]+    addedNames :: [Text]+    addedNames = archives ++ ["gcc-wrapper-16.2.0", "hello", "stdenv-flags", "sed", "zlib", "libgreet", "zdemo", "greeter"]++-- | @pkgs\/windows@' bash, read back as the build driver reads it: what+-- it and @test\/data\/bash.nix@'s checks add to the closure of the+-- package set's stdenv.  The leaves it adds are bash's tarball and GNU's+-- twenty official patches, each fetched fixed-output.  A derivation runs+-- busybox's awk over the patches with @context-to-unified.awk@, and bash+-- applies its output, one patch for each in order, then @win32.patch@.+-- bash is configured without job control, line editing, history,+-- translations or network redirections, with its own malloc and the+-- cache answers the port gives configure.  The checks run bash itself as+-- the builder, with probe, which the stdenv builds, and a #! script whose+-- interpreter is bash.+testBashWindows :: IO [Bool]+testBashWindows = do+  putStrLn "pkgs/bash"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let source =+        T.concat+          [ "let pkgs = import ",+            nixQuotedPath (cwd </> "pkgs" </> "windows"),+            "; checks = import ",+            nixQuotedPath (cwd </> "test" </> "data" </> "bash.nix"),+            "; in builtins.concatStringsSep \" \" [ ",+            T.unwords [path <> ".drvPath" | path <- roots],+            " ]"+          ]+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> do+          let rootOf = Map.fromList (zip roots (T.words (bytesText bytes)))+          stdenv <- sessionClosure (maybeToList (Map.lookup stdenvRoot rootOf))+          full <- sessionClosure (Map.elems rootOf)+          pure (rootOf, stdenv, full)+        other -> throwEvalError ("expected the drvPaths as one string, got " <> typeName other)+  case outcome of+    Left err -> sequence [runTest instantiates (Fail err)]+    Right (rootOf, stdenv, full) -> do+      let added = Map.elems (Map.difference full stdenv)+          nameOf drv = maybe "" bytesText (Map.lookup "name" (drvEnv drv))+          variableOf name drv = maybe "" bytesText (Map.lookup name (drvEnv drv))+          wordsOf name = maybe [] (T.words . variableOf name)+          isFetch drv = drvBuilder drv == "builtin:fetchurl"+          isFixedOutput drv = not (all (T.null . doHash) (drvOutputs drv))+          addedLeaves = filter (Map.null . drvInputDrvs) added+          derivationAt root = Map.lookup root rootOf >>= (`Map.lookup` full)+          named name = listToMaybe [drv | drv <- added, nameOf drv == name]+          outputOf drv = maybe "<no output>" (storePathToText defaultStoreDir . doPath) (listToMaybe (drvOutputs drv))+          bash = derivationAt bashRoot+          unified = named "bash-5.3-patches"+          checks = derivationAt checksRoot+          scripts = derivationAt scriptsRoot+          fetchedPatches = [drv | n <- patchNumbers, drv <- maybeToList (named ("bash53-" <> n))]+          inputSourceNames drv = map spName (drvInputSrcs drv)+      sequence+        [ runTest instantiates $+            assertEqual "derivations added" (sort addedNames) (sort (map nameOf added)),+          runTest "the leaves it adds are bash's tarball and GNU's official patches, each fetched fixed-output" $+            assertEqual+              "leaves added"+              (sort ("bash-5.3.tar.gz" : map ("bash53-" <>) patchNumbers), True)+              (sort (map nameOf addedLeaves), all (\drv -> isFetch drv && isFixedOutput drv) addedLeaves),+          runTest "busybox's awk writes each official patch, in order, as a unified diff" $+            assertEqual+              "the patches it reads and the converter"+              (Just (map outputOf fetchedPatches, ["context-to-unified.awk"]))+              (unified <&> \drv -> (wordsOf "patches" (Just drv), filter (== "context-to-unified.awk") (inputSourceNames drv))),+          runTest "bash applies the unified official patches in order, then win32.patch" $+            assertEqual+              "patches"+              ([outputOf u <> "/bash53-" <> n <> ".patch" | u <- maybeToList unified, n <- patchNumbers], Just "win32.patch")+              ( take (length patchNumbers) (wordsOf "patches" bash),+                listToMaybe (drop (length patchNumbers) (wordsOf "patches" bash)) >>= fmap spName . parseStorePath defaultStoreDir+              ),+          runTest "bash is configured as a builder's shell, with the port's cache answers" $+            assertEqual "configureFlags" configureFlags (wordsOf "configureFlags" bash),+          runTest "the checks run bash itself as the builder, with probe and the #! scripts, whose interpreters are bash and probe" $+            assertEqual+              "the builder, the script, probe's and scripts' outputs, and the interpreters"+              ( Just (maybe "" outputOf bash <> "/bin/bash.exe"),+                ["checks.sh"],+                fmap outputOf (named "bash-probe"),+                fmap outputOf scripts,+                Just (maybe "" outputOf bash <> "/bin/bash"),+                fmap ((<> "/bin/probe") . outputOf) (named "bash-probe")+              )+              ( bytesText . drvBuilder <$> checks,+                [name | drv <- maybeToList checks, path <- drvArgs drv, Just sp <- [parseStorePath defaultStoreDir (bytesText path)], let name = spName sp, name == "checks.sh"],+                variableOf "probe" <$> checks,+                variableOf "scripts" <$> checks,+                variableOf "interpreter" <$> scripts,+                variableOf "relayInterpreter" <$> scripts+              )+        ]+  where+    instantiates :: Text+    instantiates = "bash and its checks instantiate, adding twenty-six to the stdenv's closure"+    stdenvRoot :: Text+    stdenvRoot = "pkgs.stdenv.cc"+    bashRoot :: Text+    bashRoot = "pkgs.bash"+    checksRoot :: Text+    checksRoot = "checks.checks"+    scriptsRoot :: Text+    scriptsRoot = "checks.scripts"+    roots :: [Text]+    roots = [stdenvRoot, bashRoot, checksRoot, scriptsRoot]+    patchNumbers :: [Text]+    patchNumbers = [T.justifyRight 3 '0' (T.pack (show n)) | n <- [1 :: Int .. 20]]+    addedNames :: [Text]+    addedNames =+      ["bash-5.3p20", "bash-5.3-patches", "bash-5.3.tar.gz", "bash-probe", "bash-scripts", "bash-checks"]+        ++ map ("bash53-" <>) patchNumbers+    configureFlags :: [Text]+    configureFlags =+      [ "--disable-job-control",+        "--disable-readline",+        "--disable-history",+        "--disable-nls",+        "--disable-net-redirections",+        "--without-curses",+        "--with-bash-malloc",+        "bash_cv_dev_fd=standard",+        "bash_cv_dev_stdin=present",+        "bash_cv_getcwd_malloc=yes",+        "bash_cv_getenv_redef=no",+        "ac_cv_func_strdup=no",+        "ac_cv_func_wcsdup=no",+        "ac_cv_sys_interpreter=no"+      ]++-- | @pkgs\/windows\/sources.nix@ against the package set whose sources it+-- lists: the fetches in the closure of every derivation in the set are the+-- list's, each fixed-output and listed once.  A package that fetches a+-- source and leaves it out of its @srcs@ fails here.  CI publishes the list+-- to the public cache, so a source missing from it is one every run fetches+-- from its upstream host.  A package's derivations are its value and the+-- attributes at most two sets below it, as @tinycc.boot0.libs@ is.+testWindowsSources :: IO [Bool]+testWindowsSources = do+  putStrLn "pkgs/sources"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let windows = cwd </> "pkgs" </> "windows"+      source =+        T.concat+          [ "let pkgs = import ",+            nixQuotedPath windows,+            "; sources = import ",+            nixQuotedPath (windows </> "sources.nix"),+            "; derivationsIn = depth: value:",+            " if !(builtins.isAttrs value) then [ ]",+            " else if (value.type or null) == \"derivation\" then [ value.drvPath ]",+            " else if depth == 0 then [ ]",+            " else builtins.concatMap (name: derivationsIn (depth - 1) value.${name}) (builtins.attrNames value);",+            " in builtins.concatStringsSep \" \" (map (source: source.drvPath) sources ++ [ \"",+            listEnd,+            "\" ] ++ derivationsIn ",+            T.pack (show packageDepth),+            " pkgs)"+          ]+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> do+          let (listed, roots) = break (== listEnd) (T.words (bytesText bytes))+          closure <- sessionClosure (listed ++ drop 1 roots)+          pure (listed, closure)+        other -> throwEvalError ("expected the drvPaths as one string, got " <> typeName other)+  case outcome of+    Left err -> sequence [runTest lists (Fail err)]+    Right (listed, closure) -> do+      let isFetch drv = drvBuilder drv == "builtin:fetchurl"+          isFixedOutput drv = not (all (T.null . doHash) (drvOutputs drv))+          fetches = Map.filter isFetch closure+          nameOf path = maybe path (maybe path bytesText . Map.lookup "name" . drvEnv) (Map.lookup path closure)+      sequence+        [ runTest lists $+            assertEqual "sources" (sort (map nameOf (Map.keys fetches))) (sort (map nameOf listed)),+          runTest "it lists the same derivations, not only the same names" $+            assertEqual "derivations" (Map.keys fetches) (sort listed),+          runTest "every source is fixed-output" $+            assertEqual "not fixed-output" [] [nameOf path | (path, drv) <- Map.toList fetches, not (isFixedOutput drv)],+          runTest "the set fetches the seed, the ladder's sources and its packages' sources" $+            assertEqual "sources missing" [] [name | name <- knownSources, name `notElem` map nameOf listed]+        ]+  where+    lists :: Text+    lists = "sources.nix lists every source the package set fetches, and no other"+    -- What ends the list's drvPaths in the string the expression returns: no+    -- store path is spelled so.+    listEnd :: Text+    listEnd = "|"+    packageDepth :: Int+    packageDepth = 3+    -- One source of each kind, so that an empty closure does not pass as an+    -- empty list: the seed, a rung's archive and a package's archive.+    knownSources :: [Text]+    knownSources = ["hex0-seed.exe", "busybox-w32-FRP-6354-g5f09fb446.tgz", "hello-2.12.3.tar.gz"]++-- | A group of @pkgs\/windows\/unused-prebuilt.json@: prebuilt files in+-- one source archive, unused for one reason.+data UnusedGroup = UnusedGroup+  { ugArchive :: !Text,+    ugWhy :: !Text,+    ugPaths :: ![Text]+  }++-- | The list's groups, each an object of exactly an @archive@, a @why@ and+-- its @paths@, none of them empty.+unusedGroups :: Json -> Either Text [UnusedGroup]+unusedGroups document = case document of+  JsonArray items -> traverse group items+  _ -> Left "the list is not an array"+  where+    group item = case item of+      JsonObject members+        | Map.keys members == ["archive", "paths", "why"],+          Just (JsonString archive) <- Map.lookup "archive" members,+          Just (JsonString why) <- Map.lookup "why" members,+          Just (JsonArray paths) <- Map.lookup "paths" members,+          Just texts <- traverse string paths,+          not (T.null archive || T.null why || null texts) ->+            Right (UnusedGroup archive why texts)+      _ -> Left ("a group is not an archive, why its files are unused and their paths: " <> T.pack (show item))+    string value = case value of+      JsonString text -> Just text+      _ -> Nothing++-- | Why a path the list names is not one an archive could name and both+-- unpackers read the same way, or 'Nothing': a file under the archive's+-- top-level directory, by a relative path of ASCII with no whitespace,+-- which the seed stdenv's setup.sh splits the list at, and no empty,+-- @.@ or @..@ component.+unusedPathFault :: Text -> Maybe Text+unusedPathFault path+  | T.any (\c -> c > '~' || c <= ' ') path = Just "is not printable ASCII without whitespace"+  | "/" `T.isPrefixOf` path = Just "is absolute"+  | any (`elem` ["", ".", ".."]) components = Just "has an empty, . or .. component"+  | length components < 2 = Just "is not under a top-level directory"+  | otherwise = Nothing+  where+    components = T.splitOn "/" path++-- | @pkgs\/windows\/unused-prebuilt.json@, the prebuilt files in the+-- source archives that no build uses, against the package set.  The list+-- is pinned by its shape and by its archives with how many files each, so+-- that a change to it shows here as well as in the list.  Each build in+-- the set that unpacks a listed archive removes exactly the archive's+-- files: the seed stdenv's unpack phase, for the stdenv and the seed+-- stdenv alike, those in @unusedPrebuilt@, and @builtin:unpack@ those in+-- @omit@.  CI's trust check holds the list to the prebuilt files trust+-- finds; this holds the builds to the list.+testUnusedPrebuilt :: IO [Bool]+testUnusedPrebuilt = do+  putStrLn "pkgs/unused-prebuilt"+  cwd <- Dir.getCurrentDirectory+  let windows = cwd </> "pkgs" </> "windows"+  contents <- try (BS.readFile (windows </> "unused-prebuilt.json"))+  let parsed = case contents of+        Left (err :: IOException) -> Left (T.pack (displayException err))+        Right bytes -> either (Left . T.pack . show) Right (TE.decodeUtf8' bytes) >>= parseJson >>= unusedGroups+  storeDir <- evalNixIOStoreDir+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let source =+        T.concat+          [ "let pkgs = import ",+            nixQuotedPath windows,+            "; derivationsIn = depth: value:",+            " if !(builtins.isAttrs value) then [ ]",+            " else if (value.type or null) == \"derivation\" then [ value.drvPath ]",+            " else if depth == 0 then [ ]",+            " else builtins.concatMap (name: derivationsIn (depth - 1) value.${name}) (builtins.attrNames value);",+            " in builtins.concatStringsSep \" \" (derivationsIn ",+            T.pack (show packageDepth),+            " pkgs)"+          ]+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right expression -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) expression+      case value of+        VStr bytes _ -> sessionClosure (T.words (bytesText bytes))+        other -> throwEvalError ("expected the drvPaths as one string, got " <> typeName other)+  case (parsed, outcome) of+    (Left err, _) -> sequence [runTest shaped (Fail err)]+    (_, Left err) -> sequence [runTest removes (Fail err)]+    (Right groups, Right closure) -> do+      let pathsOf archive = concat [ugPaths group | group <- groups, ugArchive group == archive]+          archives = nub (map ugArchive groups)+          allPaths = concatMap ugPaths groups+          -- Each fetch's output, as a derivation names it in src or srcs,+          -- with the fetch's name, the archive's name.+          fetched =+            Map.fromList+              [ (storePathToText defaultStoreDir (doPath output), bytesText name)+              | drv <- Map.elems closure,+                drvBuilder drv == "builtin:fetchurl",+                Just name <- [Map.lookup "name" (drvEnv drv)],+                output <- drvOutputs drv+              ]+          variable name drv = bytesText <$> Map.lookup name (drvEnv drv)+          -- Each build that unpacks a fetched archive: the archive's name,+          -- the derivation's name, and the files the build removes, or+          -- Nothing where it removes none by either variable.+          unpacks =+            [ (archive, bytesText (fromMaybe "" (Map.lookup "name" (drvEnv drv))), T.words <$> removed)+            | drv <- Map.elems closure,+              let (sourcesKey, removedKey) = unpackKeys drv+                  removed = variable removedKey drv,+              srcs <- maybeToList (variable sourcesKey drv),+              archive <- mapMaybe (`Map.lookup` fetched) (T.words srcs)+            ]+          -- builtin:unpack names its archives in srcs and what it leaves+          -- out in omit; a stdenv build its archive in src and what its+          -- unpack phase removes in unusedPrebuilt.+          unpackKeys drv+            | drvBuilder drv == builtinUnpackBuilder = (envSrcs, envOmit)+            | otherwise = ("src", "unusedPrebuilt")+      sequence+        [ runTest shaped Pass,+          runTest "it lists these archives, with these many files in each" $+            assertEqual "archives" pinnedArchives [(archive, length (pathsOf archive)) | archive <- sort archives],+          runTest "each path is a file under its archive's top-level directory, by a path both unpackers read" $+            assertEqual "paths" [] [(path, fault) | path <- allPaths, Just fault <- [unusedPathFault path]],+          runTest "no file is listed twice" $+            assertEqual "listed twice" [] [path | (path, count) <- Map.toList (Map.fromListWith (+) [(path, 1 :: Int) | path <- allPaths]), count > 1],+          runTest "each group says why its files are unused, once" $+            assertEqual "groups with a reason given twice for one archive" [] [archive | archive <- archives, let whys = [ugWhy group | group <- groups, ugArchive group == archive], length whys /= length (nub whys)],+          runTest removes $+            assertEqual "builds that unpack a listed archive and do not remove its files" [] [(archive, name, files) | (archive, name, files) <- unpacks, archive `elem` archives, files /= Just (pathsOf archive)],+          runTest "a build that unpacks an archive the list does not name removes nothing" $+            assertEqual "builds that remove files of an unlisted archive" [] [(archive, name, files) | (archive, name, files) <- unpacks, archive `notElem` archives, maybe False (not . null) files],+          runTest "a build in the set unpacks each listed archive" $+            assertEqual "listed archives no build unpacks" [] [archive | archive <- archives, archive `notElem` [unpacked | (unpacked, _, _) <- unpacks]]+        ]+  where+    shaped :: Text+    shaped = "the list is groups of an archive, why its files are unused and their paths"+    removes :: Text+    removes = "each build that unpacks a listed archive removes exactly its files"+    packageDepth :: Int+    packageDepth = 3+    pinnedArchives :: [(Text, Int)]+    pinnedArchives =+      [ ("binutils-2.41.tar.xz", 7),+        ("binutils-with-gold-2.46.tar.bz2", 7),+        ("gcc-10.4.0.tar.xz", 53),+        ("gcc-16.2.0.tar.xz", 57),+        ("gcc-core-4.6.4.tar.gz", 4),+        ("stage0-pe32-a81c837.tar.gz", 1)+      ]++-- | The workflow whose jobs build one leg of the seed ladder, a job for each+-- stage, from the repository root.+ladderWorkflowPath :: FilePath+ladderWorkflowPath = ".github" </> "workflows" </> "ladder.yml"++-- | The package set's file as a workflow step names it.+packageSetFile :: Text+packageSetFile = "pkgs/windows/default.nix"++-- | What precedes the attribute path where a step builds from the set.+packageSetBuild :: Text+packageSetBuild = "build " <> packageSetFile <> " -A "++-- | The attribute paths a job's steps build from the package set, in the+-- order the steps first name them, read from the workflow's lines.  A step+-- names one outright, or through its loop's variable, alone or inside a+-- path, the loop being one @for NAME in WORD ...; do@ line.  A line that+-- runs @nova-nix eval@ reads the set and builds nothing.  A build spelled+-- any other way is an error and not a build passed over, so the test fails+-- on a step it cannot read where it would otherwise miss a rung.+jobPackageSetBuilds :: Text -> [Text] -> Either Text [Text]+jobPackageSetBuilds jobId workflow = case dropWhile (/= jobKey) workflow of+  [] -> Left ("the workflow has no job " <> jobId)+  _ : rest -> nub . concat <$> sequence (snd (mapAccumL buildsOn Nothing (takeWhile (not . isJobKey) rest)))+  where+    jobKey = "  " <> jobId <> ":"+    -- Under @jobs:@ a line indented by exactly two spaces is a job's key or+    -- a comment.+    isJobKey line = case T.unpack (T.take 3 line) of+      [' ', ' ', next] -> next /= ' ' && next /= '#'+      _ -> False+    -- Each line's builds, with the loop the line is in: the last for line+    -- at or above it.+    buildsOn loop line =+      let current = forLoop line <|> loop+       in (current, lineBuilds current line)+    forLoop line = case T.words line of+      "for" : name : "in" : items+        | (leading, [final, "do"]) <- break (";" `T.isSuffixOf`) items -> Just (name, leading ++ [T.dropEnd 1 final])+      _ -> Nothing+    lineBuilds loop line+      | "#" `T.isPrefixOf` T.stripStart line = Right []+      | (_, found) <- T.breakOn packageSetBuild line,+        not (T.null found) =+          maybe (unread line) Right (expand loop (T.filter (/= '"') (T.takeWhile isArgumentChar (T.drop (T.length packageSetBuild) found))))+      | evaluation `T.isInfixOf` line = Right []+      | packageSetFile `T.isInfixOf` line = unread line+      | otherwise = Right []+    isArgumentChar c = isAsciiLower c || isAsciiUpper c || isDigit c || c `elem` ("._-$\"" :: String)+    -- The executable's path, which a step quotes, then the command.+    evaluation = "nova-nix.exe\" eval "+    -- The paths an argument names, or nothing where it is not a path and+    -- not the loop's variable in one.+    expand loop argument+      | T.null argument = Nothing+      | not ("$" `T.isInfixOf` argument) = Just [argument]+      | Just (name, items) <- loop,+        let variable = "$" <> name,+        variable `T.isInfixOf` argument,+        not ("$" `T.isInfixOf` T.replace variable "" argument) =+          Just [T.replace variable item argument | item <- items]+      | otherwise = Nothing+    unread line = Left ("a step of " <> jobId <> " builds from " <> packageSetFile <> " in a way this test does not read: " <> T.strip line)++-- | @pkgs\/windows\/rungs.nix@ against the CI jobs whose rungs it lists: each+-- stage's list is the attributes its job's steps build from the package+-- set, in the order the steps first name them, and each names a+-- derivation.  CI realises a stage's list before those steps from the+-- public cache in substitute mode, and in the next stage's job from the+-- stage's handoff, and fails on a listed rung that was built though the+-- cache holds it, so a rung a step builds and the list lacks is one those+-- checks never see.+testWindowsRungs :: IO [Bool]+testWindowsRungs = do+  putStrLn "pkgs/rungs"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  workflow <- try (BS.readFile ladderWorkflowPath)+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let windows = cwd </> "pkgs" </> "windows"+      source =+        T.concat+          [ "let pkgs = import ",+            nixQuotedPath windows,+            "; rungs = import ",+            nixQuotedPath (windows </> "rungs.nix"),+            "; stages = builtins.attrNames rungs;",+            " select = path: builtins.foldl' (set: name: set.${name}) pkgs (builtins.filter builtins.isString (builtins.split \"[.]\" path));",+            " isDerivation = path: let value = select path; in builtins.isAttrs value && (value.type or null) == \"derivation\";",+            " in builtins.concatStringsSep \" \" (builtins.concatMap (stage: [ stage ] ++ rungs.${stage} ++ [ \"",+            stageEnd,+            "\" ]) stages ++ builtins.filter (path: !(isDerivation path)) (builtins.concatMap (stage: rungs.${stage}) stages))"+          ]+      built jobId = case workflow of+        Left (err :: IOException) -> Left (T.pack (ladderWorkflowPath <> ": " <> displayException err))+        Right bytes -> jobPackageSetBuilds jobId (T.lines (bytesText bytes))+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> pure (stageLists (T.words (bytesText bytes)))+        other -> throwEvalError ("expected the stages as one string, got " <> typeName other)+  case outcome of+    Left err -> sequence [runTest lists (Fail err)]+    Right (stages, notDerivations) -> do+      let rungsOf stage = fromMaybe [] (lookup stage stages)+      sequence $+        [ runTest lists $+            assertEqual "stages" (sort (map fst stageJobs)) (map fst stages),+          runTest "every rung is a derivation of the package set" $+            assertEqual "not derivations" [] (nub notDerivations),+          runTest "each stage's list reaches its last rung" $+            assertEqual "rungs missing" [] [rung | (stage, rung) <- knownRungs, rung `notElem` rungsOf stage]+        ]+          ++ [ runTest ("the " <> stage <> " stage's rungs are what " <> jobId <> " builds from the package set, in order") $+                 either Fail (\named -> assertEqual "rungs" named (rungsOf stage)) (built jobId)+             | (stage, jobId) <- stageJobs+             ]+  where+    lists :: Text+    lists = "rungs.nix lists the ladder's stages"+    -- Each stage of rungs.nix with the job that builds its rungs.+    stageJobs :: [(Text, Text)]+    stageJobs =+      [ ("mes", "mes-windows"),+        ("tinycc", "tinycc-windows"),+        ("gcc46", "gcc46-windows"),+        ("gcc46-cxx", "gcc46-cxx-windows"),+        ("gcc10", "gcc10-windows"),+        ("gcc-latest", "gcc-latest-windows"),+        ("x86_64", "x86_64-windows"),+        ("gcc-x86_64", "gcc-x86_64-windows"),+        ("native-x86_64", "native-x86_64-windows"),+        ("stdenv", "stdenv-windows"),+        ("bash", "bash-windows")+      ]+    -- The rung each stage ends on, so that a workflow read as building+    -- nothing does not pass against an empty list.+    knownRungs :: [(Text, Text)]+    knownRungs = [("mes", "mes.libc"), ("tinycc", "seedStdenv.applets"), ("gcc46", "gcc46"), ("gcc46-cxx", "gcc46-cxx"), ("gcc10", "mingw-w64-crt-latest"), ("gcc-latest", "gcc-latest"), ("x86_64", "mingw-w64-crt-x86_64"), ("gcc-x86_64", "gcc-x86_64"), ("native-x86_64", "gcc-native-x86_64"), ("stdenv", "stdenv.cc"), ("bash", "bash")]+    -- What ends a stage's rungs in the string the expression returns: no+    -- attribute path is spelled so.+    stageEnd :: Text+    stageEnd = "|"+    -- The stages with their rungs, then the words after the last stage.+    stageLists :: [Text] -> ([(Text, [Text])], [Text])+    stageLists listed = case break (== stageEnd) listed of+      (stage : rungs, _ : rest) -> let (stages, others) = stageLists rest in ((stage, rungs) : stages, others)+      (others, _) -> ([], others)++-- | The workflows' directory, from the repository root.+workflowsDir :: FilePath+workflowsDir = ".github" </> "workflows"++-- | The values the lines of a workflow give a key as literals: @KEY: VALUE@,+-- the value bare or quoted.  An expression or an empty value is none.+literalValues :: Text -> [Text] -> [Text]+literalValues key = mapMaybe value+  where+    prefix = key <> ":"+    value line = T.stripPrefix prefix (T.stripStart line) >>= literal . T.dropAround (`elem` ("\"'" :: String)) . T.strip+    literal text+      | T.null text || "${{" `T.isPrefixOf` text = Nothing+      | otherwise = Just text++-- | The versions a line names as an @ormolu-VERSION@ package id: the digits+-- and dots after each @ormolu-@ that a digit follows.+ormoluVersions :: Text -> [Text]+ormoluVersions line =+  [ version+  | (_, after) <- T.breakOnAll ormoluPrefix line,+    let version = T.takeWhile (\c -> isDigit c || c == '.') (T.drop (T.length ormoluPrefix) after),+    maybe False (isDigit . fst) (T.uncons version)+  ]+  where+    ormoluPrefix = "ormolu-"++-- | The values that workflows spell in more than one place, and that have+-- to agree.  GHC's version is in every haskell-actions/setup step, and+-- ormolu's in CI's Ormolu job and in caches.yml: caches.yml saves the+-- caches the other workflows restore under keys that name these versions,+-- so a bump that missed it would leave every one of them unsaved.  The+-- public cache's address and signing key are the CACHE_URL and+-- CACHE_PUBLIC_KEY of CI, Seed ladder and Public cache, whose jobs take+-- from the cache or publish to it, and a cache move or a key rotation+-- that missed one would leave that workflow's jobs asking the old address+-- or trusting the old key.  Each value has one spelling, and the+-- workflows known to name it are among those found naming it, so a+-- reading that finds nothing fails.+testWorkflowSpellings :: IO [Bool]+testWorkflowSpellings = do+  putStrLn "ci/spellings"+  outcome <- try $ do+    names <- Dir.listDirectory workflowsDir+    let workflows = sort [name | name <- names, ".yml" `T.isSuffixOf` T.pack name]+    traverse (\name -> (,) name . T.lines . bytesText <$> BS.readFile (workflowsDir </> name)) workflows+  case outcome of+    Left (err :: IOException) -> sequence [runTest "the workflows read" (Fail (T.pack (workflowsDir <> ": " <> displayException err)))]+    Right workflows ->+      let code = [(name, line) | (name, ls) <- workflows, line <- ls, not ("#" `T.isPrefixOf` T.stripStart line)]+          ghc = [(name, version) | (name, line) <- code, version <- literalValues "ghc-version" [line]]+          ormolu =+            [(name, version) | (name, line) <- code, version <- ormoluVersions line]+              ++ [(name, version) | (name, line) <- code, version <- literalValues "ORMOLU_VERSION" [line]]+          cacheUrl = [(name, url) | (name, line) <- code, url <- literalValues "CACHE_URL" [line]]+          cacheKey = [(name, key) | (name, line) <- code, key <- literalValues "CACHE_PUBLIC_KEY" [line]]+       in sequence+            [ runTest "every workflow names one GHC version, ci.yml and caches.yml among them" $+                oneSpelling "GHC's version" ["caches.yml", "ci.yml"] ghc,+              runTest "every workflow names one ormolu version, ci.yml and caches.yml among them" $+                oneSpelling "ormolu's version" ["caches.yml", "ci.yml"] ormolu,+              runTest "every workflow names one public cache address, ci.yml, public-cache.yml and seed-ladder.yml among them" $+                oneSpelling "the public cache's address" cacheWorkflows cacheUrl,+              runTest "every workflow names one public cache key, ci.yml, public-cache.yml and seed-ladder.yml among them" $+                oneSpelling "the public cache's key" cacheWorkflows cacheKey+            ]+  where+    cacheWorkflows :: [FilePath]+    cacheWorkflows = ["ci.yml", "public-cache.yml", "seed-ladder.yml"]+    oneSpelling :: Text -> [FilePath] -> [(FilePath, Text)] -> TestResult+    oneSpelling value known found = case ([name | name <- known, name `notElem` map fst found], nub (map snd found)) of+      ([], [_]) -> Pass+      ([], _) -> Fail (value <> " is spelled more than one way: " <> T.pack (show found))+      (missing, _) -> Fail (value <> " is named in none of " <> T.pack (show missing))
+ test/Test/Push.hs view
@@ -0,0 +1,1074 @@+{-# LANGUAGE TupleSections #-}++-- | Tests of pushing to a binary cache.+module Test.Push+  ( testPushPure,+    testPushClosureIO,+    testPushSource,+    testPushMultipart,+    testPushDirectory,+    cacheListing,+  )+where++import CacheFixture (CacheSetup (..), Fault (..), Logged (..), Multipart (..), RequestKind (..), cacheSetup, requestLog, storedObject, withModelCache)+import Control.Exception (IOException, bracket, bracket_, try)+import Control.Monad (filterM, forM_, guard, (>=>))+import Control.Monad.Except (runExceptT)+import Control.Monad.State.Strict (evalStateT)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BS8+import Data.Char (isDigit)+import Data.Either (isLeft)+import Data.IORef (modifyIORef', newIORef, readIORef)+import Data.Int (Int32)+import Data.List (intercalate, nub, sort)+import qualified Data.Map.Strict as Map+import Data.Maybe (listToMaybe, mapMaybe)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import qualified Database.SQLite.Simple as SQL+import HttpFixture (withDirectoryServer)+import Nix.Builder (BuildConfig (..), BuildResult (..), buildWithDeps, defaultBuildConfig)+import Nix.CacheDirectory (CacheInfo (..), CacheOpenFailure (..), cacheFilePath, cacheInfoFileName, cacheInfoText, directoryUrl, fileUrlDirectory, parsePriority, readCacheInfo)+import qualified Nix.Cli.Args as Cli+import Nix.Derivation (Derivation (..), DerivationOutput (..), currentPlatform)+import qualified Nix.Hash as Hash+import Nix.Http (FetchRetryPolicy (..), RetryEffects (..), defaultFetchRetryPolicy)+import Nix.Logger (plainLogger)+import Nix.Push (PushArtifact (..), PushCompression (..), PushConfig (..), PushSummary (..), checkRecordedNarHash, computeClosure, defaultPartSize, isDerivationPath, loadKeyFile, mkNarInfo, mkPartSize, mkPushArtifact, narFileName, narHashMatches, outputPathsOnly, parsePushCompression, partSizeBytes, planMissing, preparePath, pushPaths, splitParts, storePathBasename, stripHashPrefix)+import Nix.Push.Directory (DirectoryPush (..), PushTarget (..), ed25519SeedBytes, loadSecretKeyFile, pushTarget, pushToDirectory, signNarInfo)+import Nix.Push.Source (PushSource (..), PushedPath (..), localPushSource)+import qualified Nix.Realise as Realise+import Nix.Store (Store (..), addToStore, closeStore, openStore, releasePathLock, writeDrv)+import Nix.Store.DB (PathRegistration (..), RegistrationTime (..), Ultimate (..), dbFileName, metaDirName, queryReferences, registerPaths)+import Nix.Store.Path (StoreDir (..), defaultStoreDir, parseStorePath, storePathToFilePath, storePathToText)+import Nix.Store.Path.Internal (StorePath (..))+import qualified Nix.Substituter as Subst+import NodeStatus (NodeStatus (..), nodeStatus)+import qualified NovaCache.Base64 as B64+import qualified NovaCache.Hash as CHash+import qualified NovaCache.NAR as NAR+import qualified NovaCache.NarInfo as NarInfo+import qualified NovaCache.Signing as Signing+import System.Directory (createDirectoryIfMissing, doesDirectoryExist, getTemporaryDirectory)+import qualified System.Directory as Dir+import System.FilePath (equalFilePath, (</>))+import qualified System.Info as SI+import Test.Harness (TestResult (..), andThen, assertEqual, assertRight, findTestShell, forceRemoveIfExists, offeredThenFetched, runTest, runTestM, testLogger, throwawayKey, withTempStore)+import qualified Test.QuickCheck as QC++-- ---------------------------------------------------------------------------+-- Tests: Push (pure narinfo construction + closure computation)+-- ---------------------------------------------------------------------------++testPushPure :: IO [Bool]+testPushPure = do+  putStrLn "push/narinfo"+  let hashA = T.replicate 32 "a"+      hashB = T.replicate 32 "b"+      spA = StorePath hashA "hello-1.0"+      spB = StorePath hashB "dep-2.0"+      narHash = "sha256:0123abcdef"+      narBytes = BS.replicate 1234 0x6e+      artifactNone = mkPushArtifact PushNone narHash narBytes+      artifactZstd = mkPushArtifact PushZstd narHash narBytes+      -- References deliberately unsorted; deriver present.+      ni = mkNarInfo artifactNone spA [spB, spA] (Just spB)+      niZstd = mkNarInfo artifactZstd spA [spB, spA] (Just spB)+  sequence+    [ runTest "narinfo StorePath is canonical /nix/store" $+        assertEqual "StorePath" ("/nix/store/" <> hashA <> "-hello-1.0") (NarInfo.niStorePath ni),+      runTest "narinfo URL is nar/<digest>.nar" $+        assertEqual "URL" "nar/0123abcdef.nar" (NarInfo.niUrl ni),+      runTest "compression none mirrors NAR fields into file fields" $+        assertEqual+          "file fields"+          ("none", Just (NarInfo.niNarHash ni), Just (NarInfo.niNarSize ni))+          (NarInfo.niCompression ni, NarInfo.niFileHash ni, NarInfo.niFileSize ni),+      runTest "narinfo sizes carry through" $+        assertEqual "NarSize" 1234 (NarInfo.niNarSize ni),+      -- The zstd artifact: file fields describe the compressed object,+      -- named by its own file hash, while the NAR fields stay the+      -- archive's - and the substituter's strict decoder round-trips+      -- the bytes under the declared NarSize bound.+      runTest "zstd artifact declares the compressed object" $+        assertEqual+          "zstd fields"+          ("zstd", Just (paFileHash artifactZstd), Just (fromIntegral (paFileSize artifactZstd)), 1234)+          (NarInfo.niCompression niZstd, NarInfo.niFileHash niZstd, NarInfo.niFileSize niZstd, NarInfo.niNarSize niZstd),+      -- Ground truth, not field copying: the file fields must equal+      -- independent computation over the artifact's actual bytes, and+      -- must NOT collapse into the NAR fields (the copy-paste hazard+      -- for a compressible input like this one).+      runTest "zstd file fields are computed from the compressed bytes" $+        let independentHash = CHash.formatNixHash (CHash.hashBytes (paBytes artifactZstd))+         in if paFileHash artifactZstd == independentHash+              && paFileSize artifactZstd == BS.length (paBytes artifactZstd)+              && paFileHash artifactZstd /= narHash+              && paFileSize artifactZstd /= BS.length narBytes+              then Pass+              else Fail "zstd file fields do not match the compressed bytes",+      runTest "none artifact IS the NAR" $+        if paBytes artifactNone == narBytes+          && paFileHash artifactNone == narHash+          && paFileSize artifactNone == BS.length narBytes+          then Pass+          else Fail "none artifact diverges from its NAR",+      runTest "zstd object is named by its independently computed file hash" $+        assertEqual+          "zstd URL"+          ("nar/" <> stripHashPrefix (CHash.formatNixHash (CHash.hashBytes (paBytes artifactZstd))) <> ".nar.zst")+          (NarInfo.niUrl niZstd),+      -- mkNarInfo cannot be handed NAR fields that disagree with the+      -- artifact: they come from the artifact itself.+      runTest "narinfo NAR fields come from the artifact" $+        assertEqual+          "NAR fields"+          (narHash, toInteger (BS.length narBytes))+          (NarInfo.niNarHash niZstd, NarInfo.niNarSize niZstd),+      runTestM "zstd artifact round-trips through the substituter decoder" $ do+        out <- Subst.decompressNar 1234 "zstd" (paBytes artifactZstd)+        pure (assertEqual "push-substitute roundtrip" (Right narBytes) out),+      -- The CLI vocabulary is the wire vocabulary, parsed in one place.+      runTest "parsePushCompression accepts the register and rejects by name" $+        case (parsePushCompression "none", parsePushCompression "zstd", parsePushCompression "brotli") of+          (Right PushNone, Right PushZstd, Left err)+            | "none, zstd" `T.isInfixOf` err -> Pass+          other -> Fail ("unexpected parse outcomes: " <> T.pack (show other)),+      runTest "references are sorted basenames" $+        assertEqual+          "References"+          [hashA <> "-hello-1.0", hashB <> "-dep-2.0"]+          (NarInfo.niReferences ni),+      runTest "deriver renders as a basename" $+        assertEqual "Deriver" (Just (hashB <> "-dep-2.0")) (NarInfo.niDeriver ni),+      runTest "no client-side signatures" $+        assertEqual "Sigs" ([] :: [Text]) (NarInfo.niSigs ni),+      -- The first main run of the cache job pushed a store's first valid+      -- path alphabetically, a .drv, and the cache refused its narinfo:+      -- a store registers recipes as valid paths, a cache serves outputs.+      runTest "outputPathsOnly drops derivations and keeps everything else" $+        assertEqual+          "outputs"+          ["hello", "hello.drv.tar", "src"]+          (map spName (outputPathsOnly [StorePath (T.replicate 32 "a") "hello", StorePath (T.replicate 32 "b") "hello.drv", StorePath (T.replicate 32 "c") "hello.drv.tar", StorePath (T.replicate 32 "d") "src"])),+      runTest "isDerivationPath is the .drv suffix on the name, not the hash" $+        assertEqual "drv" [True, False, False] (map isDerivationPath [StorePath (T.replicate 32 "a") "x.drv", StorePath (T.replicate 32 "b") "x", StorePath (T.replicate 32 "c") "drv"]),+      runTest "planMissing keeps only uncached paths" $+        assertEqual+          "missing"+          [hashB]+          (map spHash (planMissing (Set.singleton hashA) [spA, spB])),+      runTest "stripHashPrefix drops the algo tag" $+        assertEqual "tagged" "deadbeef" (stripHashPrefix "sha256:deadbeef"),+      runTest "stripHashPrefix tolerates a bare digest" $+        assertEqual "bare" "deadbeef" (stripHashPrefix "deadbeef"),+      runTest "storePathBasename joins hash and name" $+        assertEqual "basename" (hashA <> "-hello-1.0") (storePathBasename spA),+      runTest "narFileName appends .nar" $+        assertEqual "file" "0123abcdef.nar" (narFileName narHash),+      -- checkRecordedNarHash: the pre-upload integrity gate+      runTest "push gate accepts a registered matching path" $+        assertEqual+          "gate ok"+          (Right ())+          (checkRecordedNarHash (Just (pathInfoFor narHash)) narHash spA),+      runTest "push gate refuses an unregistered path" $+        case checkRecordedNarHash Nothing narHash spA of+          Left err+            | "not registered" `T.isInfixOf` err -> Pass+            | otherwise -> Fail ("wrong error: " <> err)+          Right () -> Fail "unregistered path must not be publishable",+      runTest "push gate refuses a changed-on-disk path" $+        case checkRecordedNarHash (Just (pathInfoFor "sha256:other")) narHash spA of+          Left err+            | "DB recorded" `T.isInfixOf` err -> Pass+            | otherwise -> Fail ("wrong error: " <> err)+          Right () -> Fail "hash mismatch must not be publishable",+      -- narHashMatches decodes both spellings before comparing.+      -- parseNixHash reads only the sha256:nix-base32 spelling, so a+      -- base16-recorded digest (both literals spell the empty-string+      -- sha256) falls back to text equality and refuses - the safe+      -- direction.  When the parser learns more spellings (foreign+      -- caches), this pin flips and the gate widens with it.+      runTest "push gate pins the accepted hash spellings" $+        if narHashMatches+          "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+          "sha256:0mdqa9w1p6cmli6976v4wi0sw9r4p5prkj7lzfd1877wk11c9c73"+          then Fail "base16 spelling unexpectedly matched - widen this pin"+          else Pass,+      runTest "push gate still refuses different digests" $+        if narHashMatches+          "sha256:0mdqa9w1p6cmli6976v4wi0sw9r4p5prkj7lzfd1877wk11c9c73"+          (Hash.formatNixHash (Hash.hashBytes "different"))+          then Fail "distinct digests must not match"+          else Pass+    ]+  where+    pathInfoFor recordedHash = PushedPath {ppNarHash = recordedHash, ppReferences = [], ppDeriver = Nothing}++-- | Closure computation against a real (temp) store database.+testPushClosureIO :: IO [Bool]+testPushClosureIO = do+  putStrLn "push/closure"+  withTempStore $ \store -> do+    let spTop = StorePath (T.replicate 32 "1") "top"+        spMid = StorePath (T.replicate 32 "2") "mid"+        spLeaf = StorePath (T.replicate 32 "3") "leaf"+        regFor sp refs =+          PathRegistration+            { prPath = sp,+              prNarHash = "sha256:" <> T.replicate 52 "0",+              prNarSize = 1,+              prDeriver = Nothing,+              prReferences = refs,+              prUltimate = NotUltimate,+              prSignatures = Set.empty,+              prContentAddress = Nothing,+              prRegistrationTime = RegisteredNow+            }+    registerPaths (stDB store) [regFor spTop [spMid], regFor spMid [spLeaf], regFor spLeaf []]+    fromTop <- computeClosure (localPushSource store) [spTop]+    fromBoth <- computeClosure (localPushSource store) [spTop, spLeaf]+    sequence+      [ runTest "closure walks transitive references" $+          assertRight "fromTop" fromTop $ \closure ->+            assertEqual+              "hashes"+              (Set.fromList (map spHash [spTop, spMid, spLeaf]))+              (Set.fromList (map spHash closure)),+        runTest "closure deduplicates across roots" $+          assertRight "fromBoth" fromBoth $ \closure ->+            assertEqual "count" (3 :: Int) (length closure),+        -- loadKeyFile: keys copied through Windows editors arrive with+        -- a BOM and CRLF; skipping the normalization turns every push+        -- into an auth rejection with no visible cause.+        runTestM "loadKeyFile strips BOM and CRLF" $ do+          tmpBase <- getTemporaryDirectory+          let keyFile = tmpBase </> "nova-nix-test-api-key"+          BS.writeFile keyFile (BS.pack [0xEF, 0xBB, 0xBF] <> "the-secret-key\r\n")+          loaded <- loadKeyFile keyFile+          Dir.removeFile keyFile+          pure (assertEqual "normalized key" (Right "the-secret-key") loaded),+        runTestM "loadKeyFile rejects an effectively-empty key file" $ do+          tmpBase <- getTemporaryDirectory+          let keyFile = tmpBase </> "nova-nix-test-api-key-empty"+          BS.writeFile keyFile (BS.pack [0xEF, 0xBB, 0xBF] <> "  \r\n")+          loaded <- loadKeyFile keyFile+          Dir.removeFile keyFile+          pure $ case loaded of+            Left err | "empty" `T.isInfixOf` err -> Pass+            other -> Fail ("expected empty-key rejection, got: " <> T.pack (show other)),+        runTestM "loadKeyFile reports a missing file" $ do+          tmpBase <- getTemporaryDirectory+          loaded <- loadKeyFile (tmpBase </> "nova-nix-test-no-such-key-file")+          pure $ case loaded of+            Left err | "cannot read key file" `T.isInfixOf` err -> Pass+            other -> Fail ("expected read error, got: " <> T.pack (show other))+      ]++-- | What a push reads from the 'PushSource' it is given, over real trees in+-- a directory and no store: the files are read from the source's store+-- directory, and every record is its answer.+testPushSource :: IO [Bool]+testPushSource = do+  putStrLn "push/source"+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-push-source"+  bracket_ (forceRemoveIfExists root) (forceRemoveIfExists root) $ do+    forM_ [leaf, top] $ \sp -> do+      let tree = storePathToFilePath (storeDirIn root) sp+      createDirectoryIfMissing True tree+      BS.writeFile (tree </> "data") (contentsOf sp)+    case throwawayKey (BS.replicate ed25519SeedBytes 9) >>= Signing.parseSecretKey . fst of+      Left err -> sequence [runTest "push/source key" (Fail (T.pack err))]+      Right secretKey -> sourceCases root secretKey+  where+    leaf = StorePath (T.replicate 32 "p") "leaf"+    top = StorePath (T.replicate 32 "q") "top"+    topDrv = StorePath (T.replicate 32 "r") "top.drv"+    contentsOf sp = TE.encodeUtf8 (spName sp) <> "\n"+    narHashOf sp = CHash.formatNixHash (CHash.hashBytes (NAR.serialise (NAR.NarDirectory [("data", NAR.NarRegular False (contentsOf sp))])))+    -- The files are under a store directory that holds no database.+    storeDirIn root = StoreDir (root </> "store")+    record sp references deriver = PushedPath {ppNarHash = narHashOf sp, ppReferences = references, ppDeriver = deriver}+    sourceWith root records =+      PushSource+        { psStoreDir = storeDirIn root,+          psCaseHack = NAR.CaseHackDisabled,+          psLogger = testLogger,+          psReferences = \sp -> pure (Right (maybe [] ppReferences (Map.lookup sp records))),+          psPathInfo = \sp -> pure (Right (Map.lookup sp records)),+          psAllValid = pure (Right (Map.keys records))+        }+    narInfoOf cache sp = NarInfo.parseNarInfo . TE.decodeUtf8 <$> BS.readFile (cache </> T.unpack (spHash sp) <> ".narinfo")+    pushWith root secretKey label = pushToDirectory (DirectoryPush (root </> label) secretKey PushNone)+    sourceCases root secretKey =+      let records = Map.fromList [(leaf, record leaf [] Nothing), (top, record top [leaf] (Just topDrv))]+          source = sourceWith root records+          wrongHash = "sha256:" <> T.replicate 52 "0"+       in sequence+            [ runTestM "a push reads each path's references, NAR hash and deriver from the source it is given" $ do+                pushed <- pushWith root secretKey "records" source [top]+                infos <- traverse (narInfoOf (root </> "records")) [leaf, top]+                let summary narInfo = (NarInfo.niReferences narInfo, NarInfo.niDeriver narInfo, NarInfo.niNarHash narInfo)+                pure $+                  assertEqual "push" (Right (PushSummary 2 0)) pushed+                    `andThen` assertEqual+                      "narinfos"+                      [ Right ([], Nothing, narHashOf leaf),+                        Right ([storePathBasename leaf], Just (storePathBasename topDrv), narHashOf top)+                      ]+                      (map (fmap summary) infos),+              runTestM "a push asks the source only for references as it walks the closure, and for a path's record as it prepares the path to send" $ do+                asked <- newIORef []+                let ask kind sp = modifyIORef' asked (++ [(kind :: Text, sp)])+                    counting =+                      source+                        { psReferences = \sp -> ask "references" sp >> psReferences source sp,+                          psPathInfo = \sp -> ask "record" sp >> psPathInfo source sp+                        }+                pushed <- pushWith root secretKey "counted" counting [top]+                calls <- readIORef asked+                pure (assertEqual "push" (Right (PushSummary 2 0)) pushed `andThen` assertEqual "asked" [("references", top), ("references", leaf), ("record", leaf), ("record", top)] calls),+              runTestM "a path the source does not hold is refused as not registered" $ do+                refused <- pushWith root secretKey "unregistered" (sourceWith root (Map.delete top records)) [top]+                pure (assertEqual "refused" (Left ("store integrity: " <> storePathBasename top <> " is on disk but not registered as valid; refusing to publish it with unknown references")) refused),+              runTestM "a NAR whose hash is not the one the source records is refused" $ do+                refused <- pushWith root secretKey "changed" (sourceWith root (Map.insert leaf ((record leaf [] Nothing) {ppNarHash = wrongHash}) records)) [top]+                pure (assertEqual "refused" (Left ("store integrity: " <> storePathBasename leaf <> " hashes to " <> narHashOf leaf <> " but the DB recorded " <> wrongHash)) refused),+              runTestM "a source that cannot give a path's references fails the push with its words" $ do+                refused <- pushWith root secretKey "no-references" source {psReferences = const (pure (Left "the daemon cannot be asked"))} [top]+                pure (assertEqual "refused" (Left "the daemon cannot be asked") refused),+              runTestM "a source that cannot give a path's record fails the push with its words" $ do+                refused <- pushWith root secretKey "no-record" source {psPathInfo = const (pure (Left "the daemon cannot be asked"))} [top]+                pure (assertEqual "refused" (Left "the daemon cannot be asked") refused)+            ]++-- | push sends a NAR over its part size through nova-cache's multipart+-- upload.  Each case pushes one registered path to a fresh+-- 'withModelCache': nova-cache's write endpoints behind a proxy that+-- refuses a body over the part size, as Cloudflare refuses one over+-- 100 MB in front of the public cache.  The cache records each request,+-- and a case reads back the requests and the NAR the cache stores.+testPushMultipart :: IO [Bool]+testPushMultipart = do+  putStrLn "push/multipart"+  tmpBase <- getTemporaryDirectory+  let source = tmpBase </> "nova-nix-test-push-multipart-src"+      topSource = tmpBase </> "nova-nix-test-push-multipart-top"+      goneSource = tmpBase </> "nova-nix-test-push-multipart-gone"+      sp = StorePath (T.replicate 32 "m") "large-output"+      -- A small path that references the large one, for a closure of two.+      spTop = StorePath (T.replicate 32 "n") "small-top"+      -- A registered path whose tree is gone, which a push cannot read.+      spGone = StorePath (T.replicate 32 "p") "gone"+  forceRemoveIfExists source+  forceRemoveIfExists topSource+  forceRemoveIfExists goneSource+  createDirectoryIfMissing True source+  createDirectoryIfMissing True topSource+  createDirectoryIfMissing True goneSource+  BS.writeFile (goneSource </> "payload") "gone"+  BS.writeFile (source </> "payload") (BS.pack (take payloadBytes (cycle [0 .. 250])))+  BS.writeFile (topSource </> "payload") "small"+  results <- withTempStore $ \store -> do+    addToStore store source sp Nothing []+    addToStore store topSource spTop Nothing [sp]+    addToStore store goneSource spGone Nothing []+    forceRemoveIfExists (storePathToFilePath (stDir store) spGone)+    prepared <- runExceptT (preparePath PushNone (localPushSource store) sp)+    case (prepared, mkPartSize testPartBytes) of+      (Right (artifact, narInfo), Just partSize) -> multipartCases store sp spTop spGone partSize (paBytes artifact) (TE.encodeUtf8 (NarInfo.niUrl narInfo))+      (Left err, _) -> sequence [runTest "push/multipart setup" (Fail err)]+      (Right _, Nothing) -> sequence [runTest "push/multipart setup" (Fail "the test part size is not one")]+  forceRemoveIfExists source+  forceRemoveIfExists topSource+  forceRemoveIfExists goneSource+  pure results+  where+    -- Large enough for a NAR of at least three parts, so a part has parts+    -- before and after it.+    payloadBytes = 3000+    testPartBytes = 1024+    multipartCases store sp spTop spGone partSize nar narObject =+      sequence+        [ runTest "the test NAR is at least three parts" $+            assertEqual "parts" True (count >= 3),+          -- The command that pushes words the failure; the push says only+          -- what went wrong.+          runTestM "a push that cannot read a path reports why, without the command's prefix" $ do+            (result, _) <- withModelCache behindProxy (\base -> pushPaths (config base partSize) (localPushSource store) [spGone])+            pure $ case result of+              Left err | not ("push failed" `T.isInfixOf` err), not (T.null err) -> Pass+              other -> Fail ("expected the failure without the command's prefix, got " <> T.pack (show other)),+          runTestM "a NAR over the part size goes up in parts under the proxy's limit, each request with the write key, and is completed" $ do+            outcome <- pushTo behindProxy partSize+            pure $+              delivered testPartBytes outcome+                `andThen` assertEqual "requests" ([HashList] ++ inParts ++ published) (kinds outcome),+          runTestM "a NAR of one part's size goes in one PUT, and one byte more goes in two parts" $+            case (mkPartSize (BS.length nar), mkPartSize (BS.length nar - 1)) of+              (Just whole, Just split) -> do+                oneRequest <- pushTo (cacheSetup (BS.length nar) key) whole+                twoParts <- pushTo (cacheSetup (BS.length nar - 1) key) split+                pure $+                  delivered (BS.length nar) oneRequest+                    `andThen` assertEqual "one request" ([HashList, NarPut] ++ published) (kinds oneRequest)+                    `andThen` delivered (BS.length nar - 1) twoParts+                    `andThen` assertEqual "two parts" ([HashList, Begin, Part 1, Part 2, Complete] ++ published) (kinds twoParts)+              _ -> pure (Fail "the NAR's size is no part size"),+          runTestM "a part whose response is lost is sent again" $ do+            outcome <- pushTo (once (Part 2) DropResponse) partSize+            pure $+              delivered testPartBytes outcome+                `andThen` assertEqual "requests" ([HashList, Begin, Part 1] ++ map Part (2 : [2 .. count]) ++ [Complete] ++ published) (kinds outcome),+          runTestM "a part answered 409 begins a new upload" $ do+            outcome <- pushTo (once (Part 2) LoseParts) partSize+            pure $+              delivered testPartBytes outcome+                `andThen` assertEqual "requests" ([HashList, Begin, Part 1, Part 2] ++ inParts ++ published) (kinds outcome),+          runTestM "a part answered 404 begins a new upload" $ do+            outcome <- pushTo (once (Part 3) ForgetUpload) partSize+            pure $+              delivered testPartBytes outcome+                `andThen` assertEqual "requests" ([HashList, Begin, Part 1, Part 2, Part 3] ++ inParts ++ published) (kinds outcome),+          runTestM "a completion whose response is lost leaves the narinfo to confirm the NAR" $ do+            outcome <- pushTo (once Complete DropResponse) partSize+            pure $+              delivered testPartBytes outcome+                `andThen` assertEqual "requests" ([HashList] ++ inParts ++ published) (kinds outcome),+          runTestM "a narinfo refused after a completion that failed uploads the NAR again" $ do+            outcome <- pushTo (once Complete (Refuse "502 Bad Gateway")) partSize+            pure $+              delivered testPartBytes outcome+                `andThen` assertEqual "requests" ([HashList] ++ inParts ++ [NarInfoPut] ++ inParts ++ published) (kinds outcome),+          runTestM "a cache that keeps losing parts fails the push after three uploads, naming the request and the server's message" $ do+            outcome@(result, _) <- pushTo (always (Part 2) LoseParts) partSize+            pure $+              assertEqual "uploads begun" 3 (countOf Begin outcome)+                `andThen` failsWith ["/2 returned HTTP 409: ", "holds 0 parts, so the next is part 1", "(3 uploads begun)"] result,+          runTestM "a part whose response is always lost fails the push after the retry policy's attempts" $ do+            outcome@(result, _) <- pushTo (always (Part 1) DropResponse) partSize+            pure $+              assertEqual "sends of part 1" (fromIntegral (frpAttempts retry)) (countOf (Part 1) outcome)+                `andThen` failsWith ["/1 failed: "] result,+          runTestM "a narinfo refused after every completion fails the push after three uploads, naming both answers" $ do+            outcome@(result, _) <- pushTo (always Complete (Refuse "502 Bad Gateway")) partSize+            pure $+              assertEqual "uploads begun" 3 (countOf Begin outcome)+                `andThen` assertEqual "narinfos sent" 3 (countOf NarInfoPut outcome)+                `andThen` failsWith [".narinfo returned HTTP 400: NAR nar/", "is not stored", "the NAR's last completion: POST nar/", "returned HTTP 502: ", "(3 uploads begun)"] result,+          runTestM "a cache without multipart upload takes a NAR over the part size in one PUT" $ do+            outcome <- pushTo ((cacheSetup maxBound key) {csMultipart = WithoutMultipart}) partSize+            pure $+              delivered maxBound outcome+                `andThen` assertEqual "requests" ([HashList, Begin, NarPut] ++ published) (kinds outcome),+          -- The narinfo that decides an unconfirmed NAR goes with the+          -- other narinfos, after every NAR: checked as soon as the+          -- completion went unanswered, it would announce the large path+          -- before the small one's NAR, and announce a path whose+          -- references are not all in place in a longer closure.+          runTestM "the narinfo that confirms a NAR goes after every NAR of the closure, in the closure's order" $ do+            (result, state) <- withModelCache (once Complete DropResponse) (\base -> pushPaths (config base partSize) (localPushSource store) [spTop])+            pure $+              assertEqual "push" (Right (PushSummary 2 0)) result+                `andThen` assertEqual "stored NAR" (Just nar) (storedObject narObject state)+                `andThen` assertEqual "requests" ([HashList] ++ inParts ++ [NarPut, NarInfoPut, NarInfoPut, NarInfoGet]) (map lgKind (requestLog state)),+          runTestM "a part answered with a status a retry could outlive is sent again" $ do+            outcome <- pushTo (once (Part 2) (Refuse "503 Service Unavailable")) partSize+            pure $+              delivered testPartBytes outcome+                `andThen` assertEqual "requests" ([HashList, Begin, Part 1] ++ map Part (2 : [2 .. count]) ++ [Complete] ++ published) (kinds outcome),+          runTestM "a part refused with a status no retry changes fails the push at once" $ do+            outcome@(result, _) <- pushTo (always (Part 1) (Refuse "413 Payload Too Large")) partSize+            pure $+              assertEqual "sends of part 1" 1 (countOf (Part 1) outcome)+                `andThen` failsWith ["/1 returned HTTP 413: refused by the fixture"] result,+          runTestM "an answer the upload does not define fails the push at once" $ do+            noId@(noIdResult, _) <- pushTo (once Begin (Refuse "201 Created")) partSize+            noError@(noErrorResult, _) <- pushTo (always (Part 1) (Refuse "204 No Content")) partSize+            pure $+              assertEqual "beginnings" 1 (countOf Begin noId)+                `andThen` failsWith ["/uploads answered with no upload id: refused by the fixture"] noIdResult+                `andThen` assertEqual "sends of part 1" 1 (countOf (Part 1) noError)+                `andThen` failsWith ["/1 returned HTTP 204"] noErrorResult,+          runTest "the default part size is 64 MiB, under the 100 MB a Cloudflare proxy allows" $+            assertEqual "default" (64 * 1024 * 1024, True) (partSizeBytes defaultPartSize, partSizeBytes defaultPartSize < cloudflareBodyLimit),+          runTest "a part size is at least one byte" $+            assertEqual "sizes" [Nothing, Nothing, Just 1] (map (fmap partSizeBytes . mkPartSize) [-1, 0, 1]),+          runTestM "splitting a NAR into parts keeps every byte in order, each part full but the last" $ do+            result <-+              QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} $+                QC.forAll ((,) <$> QC.choose (1, 40) <*> QC.resize 200 (QC.listOf QC.arbitrary)) $ \(size, bytes) ->+                  let input = BS.pack bytes+                      parts = maybe [] (`splitParts` input) (mkPartSize size)+                      (full, rest) = length bytes `divMod` size+                   in (BS.concat parts, map BS.length parts) QC.=== (input, replicate full size ++ [rest | rest > 0])+            pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))+        ]+      where+        key = TE.encodeUtf8 apiKey+        count = (BS.length nar + testPartBytes - 1) `div` testPartBytes+        inParts = [Begin] ++ map Part [1 .. count] ++ [Complete]+        published = [NarInfoPut, NarInfoGet]+        config base size =+          PushConfig+            { pcCacheUrl = base,+              pcApiKey = Just apiKey,+              pcCompression = PushNone,+              pcPartSize = size,+              pcRetry = retry+            }+        pushTo setup size = withModelCache setup (\base -> pushPaths (config base size) (localPushSource store) [sp])+        behindProxy = cacheSetup testPartBytes key+        once kind fault = behindProxy {csFault = \seenKind seen -> fault <$ guard (seenKind == kind && seen == 0)}+        always kind fault = behindProxy {csFault = \seenKind _ -> fault <$ guard (seenKind == kind)}+        kinds = map lgKind . requestLog . snd+        countOf kind = length . filter (== kind) . kinds+        -- The push published the path, the cache holds the NAR it was+        -- given, and no request carried a body past the proxy.+        delivered limit (result, state) =+          assertEqual "push" (Right (PushSummary 1 0)) result+            `andThen` assertEqual "stored NAR" (Just nar) (storedObject narObject state)+            `andThen` assertEqual "bodies over the limit" [] (filter ((> limit) . lgBodyBytes) (requestLog state))+        failsWith fragments result = case result of+          Left err | all (`T.isInfixOf` err) fragments -> Pass+          other -> Fail ("expected a failure naming " <> T.pack (show fragments) <> ", got " <> T.pack (show other))+    apiKey = "test-write-key"+    retry = defaultFetchRetryPolicy {frpBaseDelayMs = 1}+    -- Cloudflare's 100 MB, read as the smaller 10^8 bytes.+    cloudflareBodyLimit = 100 * 1000 * 1000++-- | push to a directory: the binary cache it writes, read back file by+-- file and substituted from by nova-nix's own substituter, as a static web+-- server serves it and through its @file:\/\/@ URL; what a second push+-- skips; the refusal of a cache for another store directory and of a key+-- file that holds no secret key; how @--cache@ and the key files select+-- where a push writes; and how a substitution opens and reads a+-- @file:\/\/@ cache.  The key is generated for the run, and each case that+-- pushes pushes top, which references leaf, from a store of its own.+testPushDirectory :: IO [Bool]+testPushDirectory = do+  putStrLn "push/directory"+  tmpBase <- getTemporaryDirectory+  seed <- BS.pack <$> QC.generate (QC.vectorOf ed25519SeedBytes QC.arbitrary)+  let root = tmpBase </> "nova-nix-test-push-directory"+  bracket_ (forceRemoveIfExists root) (forceRemoveIfExists root) $ do+    createDirectoryIfMissing True root+    let keyFile = root </> "secret-key"+    key <- case throwawayKey seed of+      Left err -> pure (Left (T.pack err))+      Right (keyText, publicKey) -> do+        BS.writeFile keyFile (TE.encodeUtf8 keyText)+        fmap (,publicKey) <$> loadSecretKeyFile keyFile+    case key of+      Left err -> sequence [runTest "push/directory key" (Fail err)]+      Right (secretKey, publicKey) -> concat <$> sequence [directoryCases root secretKey publicKey, substitutionCases root secretKey publicKey, targetCases root, cacheInfoCases]+  where+    leaf = StorePath (T.replicate 32 "p") "leaf"+    top = StorePath (T.replicate 32 "q") "top"+    contentsOf sp = TE.encodeUtf8 (spName sp) <> "\n"+    narOf sp = NAR.serialise (NAR.NarDirectory [("data", NAR.NarRegular False (contentsOf sp))])+    narInfoFile cache sp = cache </> T.unpack (spHash sp) <> ".narinfo"+    -- The directories the newest upstream release's file:// store makes in+    -- a cache it opens, sorted, which a substitution makes too.+    openedCacheDirectories = ["build-trace-v2", "log", "nar"]+    -- Those a push makes, sorted: the realisations directory under the+    -- name older upstream releases read as well.+    pushedCacheDirectories = sort ("realisations" : openedCacheDirectories)+    readMaybeFile path = either (const Nothing) Just <$> (try (BS.readFile path) :: IO (Either IOException BS.ByteString))+    -- A store holding top and leaf under the root, and the cache+    -- directory beside it.+    withSourceStore root label action = do+      let base = root </> label+      createDirectoryIfMissing True base+      bracket (openStore testLogger (StoreDir (base </> "store"))) closeStore $ \store -> do+        forM_ [(leaf, []), (top, [leaf])] $ \(sp, references) -> do+          let source = base </> T.unpack (spName sp)+          createDirectoryIfMissing True source+          BS.writeFile (source </> "data") (contentsOf sp)+          addToStore store source sp Nothing references+        action store (base </> "cache")+    -- A cache directory as a substitution reads it: served over loopback+    -- HTTP, or through its file:// URL.+    overHttp = withDirectoryServer+    directly cache use = use (directoryUrl cache)+    -- Build a derivation whose one output is top, with a builder that+    -- fails, in a fresh store whose one cache is the directory, served as+    -- given: the result, what leaf and top hold, and top's references+    -- there.+    substituteFrom serving root label cache publicKey = serving cache $ \base -> do+      shell <- findTestShell+      let dest = StoreDir (root </> label </> "dest")+          drvSP = StorePath (T.replicate 32 "r") "top.drv"+          drv =+            Derivation+              { drvOutputs = [DerivationOutput "out" top "" ""],+                drvInputDrvs = Map.empty,+                drvInputSrcs = [],+                drvPlatform = currentPlatform,+                drvBuilder = TE.encodeUtf8 shell,+                drvArgs = ["-c", "exit 1"],+                drvEnv = Map.singleton "name" "top"+              }+          config = (defaultBuildConfig dest) {bcCaches = [Subst.CacheConfig base [Signing.renderPublicKey publicKey] [] Subst.RequireSigs 40]}+      bracket (openStore testLogger dest) closeStore $ \store -> do+        writeDrv store drv drvSP+        result <- buildWithDeps config store drv drvSP+        held <- mapM (\sp -> readMaybeFile (storePathToFilePath (stDir store) sp </> "data")) [leaf, top]+        references <- map (parseStorePath (stDir store)) <$> queryReferences (stDB store) top+        pure (result, held, references)+    directoryCases root secretKey publicKey = do+      let pushTo cache compression = pushToDirectory (DirectoryPush cache secretKey compression) . localPushSource+          nar = narOf top+          narHash = CHash.formatNixHash (CHash.hashBytes nar)+          narUrl = "nar/" <> stripHashPrefix narHash <> ".nar"+          size = T.pack (show (BS.length nar))+      (pushed, directories, narInfoBytes, cacheInfo, storedNar, substituted, direct, again, before, after, modes) <-+        withSourceStore root "main" $ \store cache -> do+          pushed <- pushTo cache PushNone store [top]+          directories <- filterM (Dir.doesDirectoryExist . (cache </>)) pushedCacheDirectories+          narInfoBytes <- readMaybeFile (narInfoFile cache top)+          cacheInfo <- readMaybeFile (cache </> cacheInfoFileName)+          storedNar <- readMaybeFile (cache </> T.unpack narUrl)+          substituted <- substituteFrom overHttp root "main" cache publicKey+          listed <- cacheListing cache+          substitutedDirectly <- substituteFrom directly root "main-direct" cache publicKey+          listedAfter <- cacheListing cache+          let direct = (substitutedDirectly, listed == listedAfter)+          before <- cacheListing cache+          again <- pushTo cache PushNone store [top]+          after <- cacheListing cache+          let plain = root </> "main" </> "plain"+          BS.writeFile plain "plain"+          modes <- mapM (fmap (fmap nsPermissions) . nodeStatus) [plain, narInfoFile cache top, cache </> T.unpack narUrl, cache </> cacheInfoFileName]+          pure (pushed, directories, narInfoBytes, cacheInfo, storedNar, substituted, direct, again, before, after, modes)+      sequence+        [ runTest "a push to a directory writes the closure, and nova-nix substitutes it from the directory served over HTTP, building nothing" $+            assertEqual "push" (Right (PushSummary 2 0)) pushed+              `andThen` assertEqual "substitution" (BuildSuccess top, [Just (contentsOf leaf), Just (contentsOf top)], [Just leaf]) substituted,+          runTest "nova-nix substitutes the closure from the directory's file:// URL directly, file:///C:/... on Windows, building nothing, and writes nothing to the cache" $+            assertEqual "substitution" ((BuildSuccess top, [Just (contentsOf leaf), Just (contentsOf top)], [Just leaf]), True) direct,+          -- Upstream's file:// store creates these in every cache it opens,+          -- and a reader that cannot create a missing one drops the cache.+          runTest "a push makes the nar, log and realisations directories upstream's file:// store makes, the last as realisations and as build-trace-v2, so a reader of any pinned version that cannot write opens the cache" $+            assertEqual "directories" pushedCacheDirectories directories,+          runTest "the narinfo holds upstream's fields in upstream's order, names its NAR by the file's hash, and carries one signature the public key verifies" $+            case TE.decodeUtf8' <$> narInfoBytes of+              Just (Right text) ->+                let (fields, sigs) = break ("Sig: " `T.isPrefixOf`) (T.lines text)+                 in assertEqual+                      "fields"+                      [ "StorePath: /nix/store/" <> storePathBasename top,+                        "URL: " <> narUrl,+                        "Compression: none",+                        "FileHash: " <> narHash,+                        "FileSize: " <> size,+                        "NarHash: " <> narHash,+                        "NarSize: " <> size,+                        "References: " <> storePathBasename leaf+                      ]+                      fields+                      `andThen` assertEqual "signatures" 1 (length sigs)+                      `andThen` assertRight "parse" (NarInfo.parseNarInfo text) (\narInfo -> assertEqual "verified" True (all (Signing.verify publicKey narInfo) (NarInfo.niSigs narInfo)))+              other -> Fail ("no UTF-8 narinfo: " <> T.pack (show other)),+          runTest "the NAR is the path's archive, uncompressed, under nar/" $+            assertEqual "NAR" (Just nar) storedNar,+          runTest "nix-cache-info names the store directory alone, /nix/store, as upstream writes it" $+            assertEqual "nix-cache-info" (Just "StoreDir: /nix/store\n") cacheInfo,+          runTest "a second push skips every path the directory holds and changes no file" $+            assertEqual "push" (Right (PushSummary 0 2)) again+              `andThen` assertEqual "files" before after,+          runTest "the cache's files have the permissions a plain write leaves, so another user can read them" $+            case modes of+              Just plainMode : written+                | all (== Just plainMode) written -> Pass+              -- Windows has no mode.+              _ | SI.os == "mingw32" -> Pass+              other -> Fail ("modes, the plain file's first: " <> T.pack (show other)),+          runTestM "a NAR whose file is in the directory is not written again" $+            withSourceStore root "kept-nar" $ \store cache -> do+              initial <- pushTo cache PushNone store [top]+              Dir.removeFile (narInfoFile cache top)+              BS.writeFile (cache </> T.unpack narUrl) "kept"+              repeated <- pushTo cache PushNone store [top]+              kept <- readMaybeFile (cache </> T.unpack narUrl)+              rewritten <- Dir.doesFileExist (narInfoFile cache top)+              pure $+                assertEqual "pushes" [Right (PushSummary 2 0), Right (PushSummary 1 1)] [initial, repeated]+                  `andThen` assertEqual "NAR" (Just "kept") kept+                  `andThen` assertEqual "narinfo" True rewritten,+          runTestM "a push reads only the references of a path the cache holds, so a damaged row of it does not fail the push, and one that must be sent fails on it" $+            withSourceStore root "damaged-row" $ \store cache -> do+              initial <- pushTo cache PushNone store [top]+              conn <- SQL.open (unStoreDir (stDir store) </> metaDirName </> dbFileName)+              SQL.execute conn "UPDATE ValidPaths SET ca = ? WHERE path = ?" ("not a content address" :: Text, T.pack (storePathToFilePath (stDir store) leaf))+              SQL.close conn+              repeated <- pushTo cache PushNone store [top]+              sent <- pushTo (root </> "damaged-row" </> "other-cache") PushNone store [top]+              pure $+                assertEqual "pushes" [Right (PushSummary 2 0), Right (PushSummary 0 2)] [initial, repeated]+                  `andThen` assertEqual "sending the damaged path fails on its row" True (either ("invalid-path entry" `T.isInfixOf`) (const False) sent),+          -- Leaf comes first in the closure, so had its narinfo followed+          -- its NAR, the narinfo would be there when top's NAR failed.+          runTestM "a NAR that cannot be written fails the push before any narinfo is written, and leaves no partial file" $+            withSourceStore root "unwritable-nar" $ \store cache -> do+              createDirectoryIfMissing True (cache </> T.unpack narUrl)+              refused <- pushTo cache PushNone store [top]+              listing <- cacheListing cache+              let leafNar = narOf leaf+                  leafFile = "nar" </> T.unpack (stripHashPrefix (CHash.formatNixHash (CHash.hashBytes leafNar))) <> ".nar"+              pure $+                assertEqual "push failed" True (isLeft refused)+                  `andThen` assertEqual "files" [(leafFile, leafNar), (cacheInfoFileName, cacheInfoText)] listing,+          runTestM "with zstd the NAR is written compressed under its file's hash, and substitutes, over HTTP and from the directory, by its Compression field" $+            withSourceStore root "zstd" $ \store cache -> do+              zstdPushed <- pushTo cache PushZstd store [top]+              narInfo <- maybe (Left "no narinfo") (either (Left . show) Right . TE.decodeUtf8' >=> NarInfo.parseNarInfo) <$> readMaybeFile (narInfoFile cache top)+              stored <- either (const (pure Nothing)) (\found -> readMaybeFile (cache </> T.unpack (NarInfo.niUrl found))) narInfo+              decompressed <- maybe (pure (Left "no NAR")) (Subst.decompressNar (toInteger (BS.length nar)) "zstd") stored+              zstdSubstituted <- substituteFrom overHttp root "zstd" cache publicKey+              zstdDirect <- substituteFrom directly root "zstd-direct" cache publicKey+              pure $+                assertEqual "push" (Right (PushSummary 2 0)) zstdPushed+                  `andThen` assertRight+                    "narinfo"+                    narInfo+                    ( \found ->+                        assertEqual "compression" "zstd" (NarInfo.niCompression found)+                          `andThen` assertEqual "URL" ((\bytes -> "nar/" <> stripHashPrefix (CHash.formatNixHash (CHash.hashBytes bytes)) <> ".nar.zst") <$> stored) (Just (NarInfo.niUrl found))+                          `andThen` assertEqual "FileHash" (CHash.formatNixHash . CHash.hashBytes <$> stored) (NarInfo.niFileHash found)+                    )+                  `andThen` assertEqual "decompressed" (Right nar) decompressed+                  `andThen` assertEqual "substitution" (BuildSuccess top, [Just (contentsOf leaf), Just (contentsOf top)], [Just leaf]) zstdSubstituted+                  `andThen` assertEqual "direct substitution" (BuildSuccess top, [Just (contentsOf leaf), Just (contentsOf top)], [Just leaf]) zstdDirect,+          runTestM "a nix-cache-info for another store directory is refused in upstream's words, and the push leaves no file but it, only the empty directories the newest upstream's store also makes before it refuses" $+            withSourceStore root "foreign" $ \store cache -> do+              createDirectoryIfMissing True cache+              BS.writeFile (cache </> cacheInfoFileName) "StoreDir: /gnu/store\n"+              refused <- pushTo cache PushNone store [top]+              entries <- sort <$> Dir.listDirectory cache+              listing <- cacheListing cache+              pure $+                assertEqual "push" (Left ("binary cache '" <> directoryUrl cache <> "' is for Nix stores with prefix '/gnu/store', not '/nix/store'")) refused+                  `andThen` assertEqual "entries" (sort (cacheInfoFileName : openedCacheDirectories)) entries+                  `andThen` assertEqual "files" [(cacheInfoFileName, "StoreDir: /gnu/store\n")] listing,+          runTestM "signing a narinfo adds the key's signature to the sorted set of those it carries, so signing again changes nothing" $ do+            let unsigned =+                  NarInfo.NarInfo+                    { NarInfo.niStorePath = "/nix/store/" <> storePathBasename top,+                      NarInfo.niUrl = narUrl,+                      NarInfo.niCompression = "none",+                      NarInfo.niFileHash = Just narHash,+                      NarInfo.niFileSize = Just (toInteger (BS.length nar)),+                      NarInfo.niNarHash = narHash,+                      NarInfo.niNarSize = toInteger (BS.length nar),+                      NarInfo.niReferences = [storePathBasename leaf],+                      NarInfo.niDeriver = Nothing,+                      NarInfo.niSigs = [],+                      NarInfo.niCA = Nothing+                    }+            result <-+              QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} $+                QC.forAll (QC.shuffle =<< QC.sublistOf ["a-1:sig", "test-cache-1:other", "z-1:sig"]) $ \existing ->+                  case (signNarInfo secretKey unsigned, signNarInfo secretKey unsigned {NarInfo.niSigs = existing}) of+                    (Right alone, Right signed) ->+                      NarInfo.niSigs signed QC.=== sort (nub (NarInfo.niSigs alone <> existing))+                        QC..&&. signNarInfo secretKey signed QC.=== Right signed+                    other -> QC.counterexample (show other) False+            pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result))),+          -- Upstream's signer takes a key's second half as its public key,+          -- so a key whose second half is not its seed's signs for no key.+          runTestM "a key file that holds no secret key, or one whose second half is not its seed's public key, is refused without its contents, and one with a byte-order mark and CRLF loads" $ do+            let refusedFile = root </> "refused-key"+                markedFile = root </> "marked-key"+                mismatchedKey = B64.encode (BS.take ed25519SeedBytes (Signing.skBytes secretKey) <> BS.replicate ed25519SeedBytes 0)+            BS.writeFile refusedFile "test-cache-1:not!base64"+            refused <- loadSecretKeyFile refusedFile+            BS.writeFile refusedFile (TE.encodeUtf8 (Signing.renderPublicKey publicKey))+            public <- loadSecretKeyFile refusedFile+            BS.writeFile refusedFile (TE.encodeUtf8 ("test-cache-1:" <> mismatchedKey))+            halves <- loadSecretKeyFile refusedFile+            keyText <- BS.readFile (root </> "secret-key")+            BS.writeFile markedFile (BS.pack [0xEF, 0xBB, 0xBF] <> keyText <> "\r\n")+            marked <- loadSecretKeyFile markedFile+            pure $ case (refused, public, halves, marked) of+              (Left refusedErr, Left publicErr, Left halvesErr, Right loaded)+                | not ("not!base64" `T.isInfixOf` refusedErr),+                  "expected 64-byte secret key, got 32" `T.isInfixOf` publicErr,+                  "not the public key of its seed" `T.isInfixOf` halvesErr,+                  not (mismatchedKey `T.isInfixOf` halvesErr) ->+                    assertEqual "loaded" secretKey loaded+              other -> Fail ("unexpected loads: " <> T.pack (show other))+        ]+    -- What one run's queries for the paths find among the caches under the+    -- fallback: each offer's cache and the priority it was asked at, or+    -- the query's failure, with the warnings the run gave its logger.+    queried fallback caches paths = do+      messages <- newIORef []+      let logger = plainLogger (\_ message -> modifyIORef' messages (++ [message])) (const (pure ()))+      offers <- evalStateT (traverse (Subst.queryReferencesWith logger defaultFetchRetryPolicy quietEffects fallback caches) paths) Subst.emptyCacheMemo+      (,) (map offeredBy offers) . mapMaybe (T.stripPrefix "warning: ") <$> readIORef messages+    offeredBy offer = case offer of+      Realise.Offered substitute _ ->+        let cache = Subst.substituteCache substitute+         in Right (Just (Subst.ccUrl cache, Subst.ccPriority cache))+      Realise.NotOffered -> Right Nothing+      Realise.QueryFailed failure -> Left failure+    quietEffects = RetryEffects {reSleepMs = const (pure ()), reJitter = pure 0, reWarn = const (pure ())}+    -- A cache by its file:// URL, trusting the key, at the configured+    -- priority its nix-cache-info replaces.+    fileCache key cache = Subst.CacheConfig (directoryUrl cache) [Signing.renderPublicKey key] [] Subst.RequireSigs 50+    -- Fetch top as a build does, from the first of the caches to offer it,+    -- into a fresh store.+    fetchedInto root label caches =+      bracket (openStore testLogger (StoreDir (root </> label </> "dest"))) closeStore $ \store -> do+        result <- offeredThenFetched defaultFetchRetryPolicy quietEffects store caches top+        case result of+          Subst.SubstSuccess _ lock -> releasePathLock lock+          _ -> pure ()+        pure result+    substitutionCases root secretKey publicKey = do+      let pushTo cache = pushToDirectory (DirectoryPush cache secretKey PushNone) . localPushSource+          missing = StorePath (T.replicate 32 "m") "missing"+          offeredAt cache priority = Right (Just (directoryUrl cache, priority))+          otherKey = snd <$> throwawayKey (BS.replicate ed25519SeedBytes 7)+          withField name value narInfo = BS8.unlines [if (name <> ": ") `BS.isPrefixOf` line then name <> ": " <> value else line | line <- BS8.lines narInfo]+          unsigned = BS8.unlines . filter (not . BS.isPrefixOf "Sig: ") . BS8.lines+          rewrite path change = BS.readFile path >>= BS.writeFile path . change+          statePriority cache priority = BS.writeFile (cache </> cacheInfoFileName) (cacheInfoText <> "Priority: " <> priority <> "\n")+          narUrl = "nar/" <> stripHashPrefix (CHash.formatNixHash (CHash.hashBytes (narOf top))) <> ".nar"+          refusedWith ending result = case result of+            Subst.SubstError err | ending `T.isSuffixOf` err -> Pass+            other -> Fail ("expected a failure ending " <> ending <> ", got " <> T.pack (show other))+      sequence+        [ runTestM "a file:// cache offers what it holds at the priority it states, 0 when it states none, and a path it lacks is a miss, with no warning" $+            withSourceStore root "subst-miss" $ \store cache -> do+              _ <- pushTo cache store [top]+              found <- queried Realise.NoFallback [fileCache publicKey cache] [top, missing]+              pure (assertEqual "offers" ([offeredAt cache 0, Right Nothing], []) found),+          runTestM "a narinfo no trusted key signed is passed over, and so is one with no signature, as signatures are required, with upstream's warning" $+            withSourceStore root "subst-signatures" $ \store cache -> do+              _ <- pushTo cache store [top]+              signedOther <- either (const (pure ([], []))) (\key -> queried Realise.NoFallback [fileCache key cache] [top]) otherKey+              rewrite (narInfoFile cache top) unsigned+              withoutSignature <- queried Realise.NoFallback [fileCache publicKey cache] [top]+              let ignored = "ignoring substitute for '" <> storePathToText defaultStoreDir top <> "' from '" <> directoryUrl cache <> "', as it's not signed by any of the keys in 'trusted-public-keys'"+              pure $+                assertRight "other key" otherKey (const Pass)+                  `andThen` assertEqual "signed by another key" ([Right Nothing], [ignored]) signedOther+                  `andThen` assertEqual "unsigned" ([Right Nothing], [ignored]) withoutSignature,+          runTestM "a file:// cache whose nix-cache-info names another store directory is passed over for the run, after upstream's warning, given once" $+            withSourceStore root "subst-foreign" $ \store cache -> do+              _ <- pushTo cache store [top]+              BS.writeFile (cache </> cacheInfoFileName) "StoreDir: /gnu/store\n"+              found <- queried Realise.NoFallback [fileCache publicKey cache] [top, leaf]+              pure (assertEqual "offers" ([Right Nothing, Right Nothing], ["binary cache '" <> directoryUrl cache <> "' is for Nix stores with prefix '/gnu/store', not '/nix/store'"]) found),+          runTestM "a file:// cache is asked at the Priority its nix-cache-info states, among HTTP caches at theirs, and caches of one priority in the order given" $+            withSourceStore root "subst-priority" $ \store firstCache -> do+              let secondCache = root </> "subst-priority" </> "second"+              _ <- pushTo firstCache store [top]+              _ <- pushTo secondCache store [top]+              withDirectoryServer firstCache $ \base -> do+                let served = Subst.CacheConfig base [Signing.renderPublicKey publicKey] [] Subst.RequireSigs 40+                    both = [fileCache publicKey firstCache, fileCache publicKey secondCache]+                statePriority firstCache "30"+                statePriority secondCache "10"+                lower <- queried Realise.NoFallback both [top]+                statePriority firstCache "10"+                tied <- queried Realise.NoFallback both [top]+                BS.writeFile (secondCache </> cacheInfoFileName) cacheInfoText+                unstated <- queried Realise.NoFallback [served, fileCache publicKey secondCache] [top]+                statePriority secondCache "60"+                later <- queried Realise.NoFallback [fileCache publicKey secondCache, served] [top]+                pure $+                  assertEqual "the lower priority first" ([offeredAt secondCache 10], []) lower+                    `andThen` assertEqual "one priority in the order given" ([offeredAt firstCache 10], []) tied+                    `andThen` assertEqual "none stated, before HTTP's 40" ([offeredAt secondCache 0], []) unstated+                    `andThen` assertEqual "60, after HTTP's 40" ([Right (Just (base, 40))], []) later,+          runTestM "a Priority that is not a 32-bit integer fails the query whatever the fallback" $+            withSourceStore root "subst-bad-priority" $ \store cache -> do+              _ <- pushTo cache store [top]+              statePriority cache "high"+              refused <- traverse (\fallback -> queried fallback [fileCache publicKey cache] [top]) [Realise.NoFallback, Realise.BuildFromSource]+              let failure = Left ("binary cache '" <> directoryUrl cache <> "' gives the Priority 'high' in its nix-cache-info, which is not a 32-bit integer")+              pure (assertEqual "queries" [([failure], []), ([failure], [])] refused),+          runTestM "a file:// URL that names no directory, and a cache that cannot be opened, are passed over after a warning" $ do+            let base = root </> "subst-unopenable"+                plain = base </> "plain"+                underFile = plain </> "cache"+            createDirectoryIfMissing True base+            BS.writeFile plain "plain"+            (offers, warnings) <- queried Realise.NoFallback [Subst.CacheConfig (directoryUrl base <> "?priority=1") [Signing.renderPublicKey publicKey] [] Subst.RequireSigs 50, fileCache publicKey underFile] [top]+            pure $ case warnings of+              [urlWarning, openWarning]+                | "a file:// URL with a query" `T.isPrefixOf` urlWarning,+                  ("cannot open binary cache '" <> directoryUrl underFile <> "': ") `T.isPrefixOf` openWarning ->+                    assertEqual "offers" [Right Nothing] offers+              other -> Fail ("warnings: " <> T.pack (show other)),+          runTestM "opening a directory that holds no cache makes the directories and the nix-cache-info the newest upstream's store makes, and no realisations directory under its older name" $ do+            let cache = root </> "subst-empty" </> "cache"+            createDirectoryIfMissing True cache+            found <- queried Realise.NoFallback [fileCache publicKey cache] [top]+            entries <- sort <$> Dir.listDirectory cache+            cacheInfo <- readMaybeFile (cache </> cacheInfoFileName)+            pure $+              assertEqual "offers" ([Right Nothing], []) found+                `andThen` assertEqual "entries" (sort (cacheInfoFileName : openedCacheDirectories)) entries+                `andThen` assertEqual "nix-cache-info" (Just cacheInfoText) cacheInfo,+          runTestM "a cache without the realisations directory's older name, as the newest upstream writes one, opens where the substitution cannot write" $+            withSourceStore root "subst-read-only" $ \store cache -> do+              _ <- pushTo cache store [top]+              Dir.removeDirectory (cache </> "realisations")+              let writable allowed = Dir.getPermissions cache >>= Dir.setPermissions cache . Dir.setOwnerWritable allowed+              found <- bracket_ (writable False) (writable True) (queried Realise.NoFallback [fileCache publicKey cache] [top])+              pure (assertEqual "offers" ([offeredAt cache 0], []) found),+          runTestM "a NAR a narinfo names outside the cache is refused in upstream's words, and one that is gone is a miss" $+            withSourceStore root "subst-nar-files" $ \store cache -> do+              _ <- pushTo cache store [top]+              original <- BS.readFile (narInfoFile cache top)+              let caches = [fileCache publicKey cache]+              BS.writeFile (narInfoFile cache top) (withField "URL" "../escape.nar" original)+              escaping <- fetchedInto root "subst-nar-escaping" caches+              BS.writeFile (narInfoFile cache top) (withField "URL" "/escape.nar" original)+              absolute <- fetchedInto root "subst-nar-absolute" caches+              BS.writeFile (narInfoFile cache top) original+              Dir.removeFile (cache </> T.unpack narUrl)+              stillOffered <- queried Realise.NoFallback caches [top]+              gone <- fetchedInto root "subst-nar-gone" caches+              pure $+                refusedWith "local binary cache path '../escape.nar' must not contain '..' or '.' segments" escaping+                  `andThen` refusedWith "local binary cache path '/escape.nar' must not be absolute" absolute+                  `andThen` assertEqual "offered" ([offeredAt cache 0], []) stillOffered+                  `andThen` assertEqual "gone" Subst.SubstNotFound gone+        ]+    cacheInfoCases = do+      let windows = SI.os == "mingw32"+          foreignStore prefix = Left (CacheUnopenable ("binary cache 'file:///c' is for Nix stores with prefix '" <> prefix <> "', not '/nix/store'"))+          badPriority value = Left (CachePriorityInvalid ("binary cache 'file:///c' gives the Priority '" <> value <> "' in its nix-cache-info, which is not a 32-bit integer"))+          holds label prop = runTestM label $ do+            result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} prop+            pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))+          segment = QC.listOf1 (QC.elements (['a' .. 'z'] <> ['0' .. '9'] <> "-_.")) `QC.suchThat` (`notElem` [".", ".."])+          directory+            | windows = ("C:\\" <>) . intercalate "\\" <$> QC.listOf1 segment+            | otherwise = ("/" <>) . intercalate "/" <$> QC.listOf1 segment+          beforeNumber = QC.listOf (QC.elements " \t\n\v\f\r")+          afterNumber = QC.listOf (QC.elements ['\32' .. '\126']) `QC.suchThat` (maybe True (not . isDigit) . listToMaybe)+      sequence+        [ runTest "nix-cache-info is read as upstream reads it: each StoreDir trimmed and held to /nix/store, the last Priority the cache's, the first field refused the refusal, and WantMassQuery and fields named with spaces let be" $+            assertEqual+              "read"+              [ Right (CacheInfo Nothing),+                Right (CacheInfo (Just 40)),+                Right (CacheInfo (Just 40)),+                Right (CacheInfo (Just (-3))),+                Right (CacheInfo Nothing),+                foreignStore "/gnu/store",+                foreignStore "/nix/store/",+                badPriority "high",+                foreignStore "/gnu/store",+                badPriority "2147483648"+              ]+              ( map+                  (readCacheInfo "file:///c")+                  [ cacheInfoText,+                    "WantMassQuery: 1\nStoreDir: \t/nix/store \r\nPriority: 40\n",+                    "Priority: 10\nPriority:40",+                    "Priority: -3 lowest\n",+                    " StoreDir: /gnu/store\nStoreDir : /gnu/store\n",+                    "StoreDir: /nix/store\nStoreDir: /gnu/store\n",+                    "StoreDir: /nix/store/\n",+                    "Priority: high\nStoreDir: /gnu/store\n",+                    "StoreDir: /gnu/store\nPriority: high\n",+                    "Priority: 2147483648\n"+                  ]+              ),+          holds "a Priority reads as C reads an int: white space, a sign and digits, what follows them ignored" $+            QC.forAll ((,,) <$> beforeNumber <*> QC.arbitrary <*> afterNumber) $ \(before, number, after) ->+              parsePriority (BS8.pack (before <> show (number :: Int32) <> after)) QC.=== Just (fromIntegral number),+          runTest "a Priority without digits, or past a 32-bit int, does not read, and one with a plus sign or after a vertical tab does" $+            assertEqual+              "read"+              [Nothing, Nothing, Nothing, Nothing, Just 7, Just 12, Just 0, Just 2147483647, Just (-2147483648)]+              (map parsePriority ["", "-", "x1", "2147483648", "+7", "\v12", "0x10", "2147483647", "-2147483648"]),+          holds "the file:// URL directoryUrl spells names the directory again" $+            QC.forAll directory $ \dir ->+              case fileUrlDirectory "" (T.unpack (directoryUrl dir)) of+                Just (Right named) -> QC.counterexample named (equalFilePath named dir)+                other -> QC.counterexample (show other) False,+          runTest "directoryUrl puts a slash before a Windows drive and spells each separator a slash, and a URL of another scheme is no file:// one" $+            assertEqual "URL" (if windows then "file:///C:/srv/cache" else "file:///srv/cache") (directoryUrl (if windows then "C:\\srv\\cache" else "/srv/cache"))+              `andThen` assertEqual "https" Nothing (fileUrlDirectory "" "https://cache.example.org"),+          runTest "a file a narinfo names is held below the cache, in upstream's words" $+            assertEqual+              "paths"+              [ Right ("cache" </> "nar/x.nar"),+                Left "local binary cache path must not be empty",+                Left "local binary cache path '/x.nar' must not be absolute",+                Left "local binary cache path 'nar/../x.nar' must not contain '..' or '.' segments",+                Left "local binary cache path './x.nar' must not contain '..' or '.' segments",+                if windows then Left "local binary cache path 'C:\\x.nar' must not be absolute" else Right ("cache" </> "C:\\x.nar"),+                if windows then Left "local binary cache path 'nar\\..\\x.nar' must not contain '..' or '.' segments" else Right ("cache" </> "nar\\..\\x.nar")+              ]+              (map (cacheFilePath "cache") ["nar/x.nar", "", "/x.nar", "nar/../x.nar", "./x.nar", "C:\\x.nar", "nar\\..\\x.nar"])+        ]+    targetCases root = do+      let windows = SI.os == "mingw32"+          (absoluteUrl, absoluteDir)+            | windows = ("file:///C:/srv/cache", "C:/srv/cache")+            | otherwise = ("file:///srv/cache", "/srv/cache")+          refusedWith fragment result = case result of+            Left err | fragment `T.isInfixOf` err -> Pass+            other -> Fail ("expected a refusal naming " <> fragment <> ", got " <> T.pack (show other))+      sequence+        [ runTest "an http:// or https:// --cache is a nova-cache server, a file:// one a directory" $+            assertEqual "server" (Right (ServerTarget "https://cache.example.org" (Just "api-key"))) (pushTarget "https://cache.example.org//" (Just "api-key") Nothing)+              `andThen` assertEqual "plain http" (Right (ServerTarget "http://127.0.0.1:8080" Nothing)) (pushTarget "http://127.0.0.1:8080" Nothing Nothing)+              `andThen` assertEqual "directory" (Right (DirectoryTarget absoluteDir "secret")) (pushTarget absoluteUrl Nothing (Just "secret")),+          runTest "a Windows drive after file:/// names the drive's path on Windows, and a directory named for it elsewhere, and a drive's root is refused on Windows" $+            assertEqual+              "drive"+              (Right (DirectoryTarget (if windows then "C:/cache" else "/C:/cache") "secret"))+              (pushTarget "file:///C:/cache" Nothing (Just "secret"))+              `andThen` ( if windows+                            then refusedWith "filesystem root" (pushTarget "file:///C:/" Nothing (Just "secret"))+                            else assertEqual "drive root" (Right (DirectoryTarget "/C:/" "secret")) (pushTarget "file:///C:/" Nothing (Just "secret"))+                        ),+          runTest "a file:// cache needs --secret-key-file and refuses --key-file, and a server refuses --secret-key-file" $+            refusedWith "needs --secret-key-file" (pushTarget absoluteUrl Nothing Nothing)+              `andThen` refusedWith "--key-file is a nova-cache server's API key" (pushTarget absoluteUrl (Just "api-key") (Just "secret"))+              `andThen` refusedWith "a nova-cache server signs what it receives" (pushTarget "https://cache.example.org" Nothing (Just "secret")),+          runTest "a --cache that is no http://, https:// or file:// URL is refused" $+            refusedWith "--cache takes" (pushTarget (root </> "cache") Nothing (Just "secret"))+              `andThen` refusedWith "--cache takes" (pushTarget "s3://bucket" Nothing Nothing),+          runTest "a file:// URL naming a host, a relative path or the root, or with a query, a fragment or an escape, is refused" $+            foldr+              (andThen . refusedWith "file://")+              Pass+              [ pushTarget url Nothing (Just "secret")+              | url <- ["file://", "file:///", "file:////", "file://host/srv/cache", "file://srv/cache", "file://C:/cache", absoluteUrl <> "?secret-key=k", absoluteUrl <> "#top", absoluteUrl <> "%20x"]+              ],+          runTest "push takes --secret-key-file's value" $+            case Cli.optCommand <$> Cli.parseArgs ["push", "--cache", absoluteUrl, "--secret-key-file", "secret", "hash-name"] of+              Right (Cli.CmdPush args) -> assertEqual "secret key file" (Just "secret") (Cli.paSecretKeyFile args)+              other -> Fail ("unexpected parse: " <> T.pack (show other))+        ]++-- | Every file in a cache directory and in its @nar@ directory, by its+-- path below the cache, with its bytes, in order.+cacheListing :: FilePath -> IO [(FilePath, BS.ByteString)]+cacheListing cache = do+  names <- sort <$> Dir.listDirectory cache+  concat <$> mapM entry names+  where+    entry name = do+      let path = cache </> name+      isDirectory <- doesDirectoryExist path+      if isDirectory+        then (\inner -> [(name </> file, bytes) | (file, bytes) <- inner]) <$> cacheListing path+        else (\bytes -> [(name, bytes)]) <$> BS.readFile path
+ test/Test/Realise.hs view
@@ -0,0 +1,1625 @@+-- | Tests of realisation and of the dependency graph that orders its+-- builds.+module Test.Realise+  ( testRealise,+    testDepGraph,+  )+where++import Control.Exception (evaluate)+import Control.Monad.State.Strict (State, evalState, get, gets, modify', runState)+import qualified Data.ByteString as BS+import Data.Either (isLeft, isRight)+import Data.Functor.Identity (Identity (..))+import Data.List (find)+import Data.List.NonEmpty (NonEmpty (..))+import qualified Data.List.NonEmpty as NE+import qualified Data.Map.Strict as Map+import Data.Maybe (catMaybes)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Nix.DependencyGraph as DepGraph+import Nix.Derivation (Derivation (..), DerivationOutput (..), Platform (..))+import qualified Nix.Realise as Realise+import Nix.Store.Path (StoreDir (..), StorePath, defaultStoreDir, storePathToFilePath)+import Nix.Store.Path.Internal (StorePath (..))+import System.Timeout (timeout)+import Test.Harness (TestResult (..), andThen, assertEqual, genJson, pureDepGraph, runTest, runTestM, walkWatchdogMicros)+import qualified Test.QuickCheck as QC++-- ---------------------------------------------------------------------------+-- Tests: Realise+-- ---------------------------------------------------------------------------++-- | What the fake store and caches record, in order.+data RealiseEvent+  = EvQueried StorePath+  | EvQueriedNext StorePath+  | EvFetched [StorePath]+  | EvProbed [StorePath]+  | EvBuilt Text+  | EvChecked Text+  | EvReported Realise.Realised Text+  deriving (Eq, Show)++-- | A fake store and two caches, asked in order.  A cache entry maps a path+-- to its references, a fetch refuses a path whose references are not valid,+-- as the database's unregistered-referent guard does, and a build makes its+-- outputs valid.  The first cache fails to deliver the broken paths it+-- offers, no longer holds the gone ones, and cannot be asked about the+-- unreachable ones at all; the next cache is asked only about a path the+-- first did not deliver, and delivers what it offers.  A fetch that+-- registers nothing records what arrived as probed.  Building a derivation+-- again gives its unstable outputs other contents, and changes no path.+-- Each build is recorded with the outputs the request that led to it+-- asked.+data FakeWorld = FakeWorld+  { fwValid :: !(Set.Set StorePath),+    fwCache :: !(Map.Map StorePath [StorePath]),+    fwNextCache :: !(Map.Map StorePath [StorePath]),+    fwBroken :: !(Set.Set StorePath),+    fwGone :: !(Set.Set StorePath),+    fwUnreachable :: !(Set.Set StorePath),+    fwUnstable :: !(Set.Set StorePath),+    fwEvents :: ![RealiseEvent],+    -- | Each build's event name and the outputs its request asked,+    -- newest first.+    fwBuiltFor :: ![(Text, Set.Set Text)]+  }++-- | Which of the fake's caches offered a path.+data FakeCache = FirstCache | NextCache+  deriving (Eq, Show)++-- | A world with the given entries in the first cache and valid paths, and+-- no faults.+fakeWorld :: [(Text, [Text])] -> [Text] -> FakeWorld+fakeWorld cache valid =+  FakeWorld+    { fwValid = Set.fromList (map fakePath valid),+      fwCache = fakeCache cache,+      fwNextCache = Map.empty,+      fwBroken = Set.empty,+      fwGone = Set.empty,+      fwUnreachable = Set.empty,+      fwUnstable = Set.empty,+      fwEvents = [],+      fwBuiltFor = []+    }++-- | Cache entries by name.+fakeCache :: [(Text, [Text])] -> Map.Map StorePath [StorePath]+fakeCache cache = Map.fromList [(fakePath p, map fakePath refs) | (p, refs) <- cache]++fakeEvent :: RealiseEvent -> State FakeWorld ()+fakeEvent event = modify' (\world -> world {fwEvents = event : fwEvents world})++-- | What the fake cache says when it cannot be asked about a path.+fakeQueryFailure :: StorePath -> Text+fakeQueryFailure sp = "cannot ask about " <> spName sp++fakeSubst :: Realise.SubstEffects FakeCache (State FakeWorld)+fakeSubst =+  Realise.SubstEffects+    { Realise.seValid = \sp -> gets (Set.member sp . fwValid),+      Realise.seReferences = \sp -> do+        fakeEvent (EvQueried sp)+        unreachable <- gets (Set.member sp . fwUnreachable)+        offer <- gets (maybe Realise.NotOffered (Realise.Offered FirstCache) . Map.lookup sp . fwCache)+        pure (if unreachable then Realise.QueryFailed (fakeQueryFailure sp) else offer),+      Realise.seNextOffer = \sp offered -> case offered of+        FirstCache -> do+          fakeEvent (EvQueriedNext sp)+          gets (maybe Realise.NotOffered (Realise.Offered NextCache) . Map.lookup sp . fwNextCache)+        NextCache -> pure Realise.NotOffered,+      Realise.seFetch = \registration batch -> do+        world <- get+        let paths = map fst (NE.toList batch)+            incoming = Set.fromList paths+            landed sp = Set.member sp (fwValid world) || Set.member sp incoming+            declared (sp, FirstCache) = Map.findWithDefault [] sp (fwCache world)+            declared (sp, NextCache) = Map.findWithDefault [] sp (fwNextCache world)+            undelivered (sp, FirstCache)+              | Set.member sp (fwBroken world) = Just Realise.DeliveryFailed+              | Set.member sp (fwGone world) = Just Realise.Gone+            undelivered _ = Nothing+            short = [(sp, why) | each@(sp, _) <- NE.toList batch, Just why <- [undelivered each]]+            refused = registration == Realise.RegisterAll && not (all (all landed . declared) batch)+        case (NE.nonEmpty short, registration) of+          (Just undeliveredPaths, _) -> pure (Realise.NotFetched undeliveredPaths)+          (Nothing, _) | refused -> pure (Realise.NotFetched (fmap (\(sp, _) -> (sp, Realise.DeliveryFailed)) batch))+          (Nothing, Realise.RegisterNone) -> Realise.Fetched <$ fakeEvent (EvProbed paths)+          (Nothing, Realise.RegisterAll) -> do+            fakeEvent (EvFetched paths)+            modify' (\updated -> updated {fwValid = fwValid updated <> incoming})+            pure Realise.Fetched+    }++fakeRealiseEffects :: Set.Set Text -> Realise.RealiseEffects FakeCache (State FakeWorld)+fakeRealiseEffects failing =+  Realise.RealiseEffects+    { Realise.reSubst = fakeSubst,+      Realise.reBuild = \drv _ wanted -> do+        let name = fakeDrvName drv+        if Set.member name failing+          then pure (Left (Realise.BuilderStopped ("building " <> name <> " failed")))+          else do+            fakeEvent (EvBuilt name)+            modify' (\world -> world {fwValid = fwValid world <> Set.fromList (map doPath (drvOutputs drv)), fwBuiltFor = (name, wanted) : fwBuiltFor world})+            pure (Right ()),+      Realise.reCheck = \drv _ -> do+        let name = fakeDrvName drv+        fakeEvent (EvChecked name)+        unstable <- gets fwUnstable+        pure $+          if Set.member name failing+            then Left ("building " <> name <> " failed")+            else Right (maybe Realise.OutputsMatch (`Realise.OutputDiffers` Realise.RebuildDiscarded) (find (`Set.member` unstable) (map doPath (drvOutputs drv)))),+      Realise.reReport = \status drv -> fakeEvent (EvReported status (fakeDrvName drv))+    }++fakeDrvName :: Derivation -> Text+fakeDrvName drv = case drvOutputs drv of+  (out : _) -> spName (doPath out)+  [] -> ""++-- | A store path with a name-derived hash, so a failure reads as names.+fakePath :: Text -> StorePath+fakePath name = StorePath (T.take 32 (T.replicate 32 (T.take 1 name))) name++-- | A derivation with one output per name, depending on the named nodes+-- for the outputs named with each.+fakeNode :: Text -> [Text] -> [(Text, [Text])] -> (StorePath, DepGraph.DepNode)+fakeNode = fakeNodeWith Map.empty++-- | 'fakeNode' with an environment.+fakeNodeWith :: Map.Map Text BS.ByteString -> Text -> [Text] -> [(Text, [Text])] -> (StorePath, DepGraph.DepNode)+fakeNodeWith env name outputs deps =+  ( drvPath,+    DepGraph.DepNode+      { DepGraph.dnDrvPath = drvPath,+        DepGraph.dnDerivation =+          Derivation+            { drvOutputs = [DerivationOutput out (fakePath out) "" "" | out <- outputs],+              drvInputDrvs = Map.empty,+              drvInputSrcs = [],+              drvPlatform = X86_64_Linux,+              drvBuilder = "/bin/sh",+              drvArgs = [],+              drvEnv = env+            },+        DepGraph.dnDeps = Map.fromList [(fakePath (dep <> ".drv"), Set.fromList wanted) | (dep, wanted) <- deps]+      }+  )+  where+    drvPath = fakePath (name <> ".drv")++-- | Run 'Realise.realise' from a root over a graph and a cache, returning the+-- result, the events in order, and the final valid set.+runRealise ::+  Set.Set Text ->+  [(StorePath, DepGraph.DepNode)] ->+  [(Text, [Text])] ->+  [Text] ->+  Text ->+  (Either Realise.RealiseFailure (), [RealiseEvent], Set.Set StorePath)+runRealise failing nodes cache valid = runRealiseIn Realise.NoFallback (fakeWorld cache valid) failing nodes++-- | 'runRealise' in a given world, under a given fallback.+runRealiseIn ::+  Realise.Fallback ->+  FakeWorld ->+  Set.Set Text ->+  [(StorePath, DepGraph.DepNode)] ->+  Text ->+  (Either Realise.RealiseFailure (), [RealiseEvent], Set.Set StorePath)+runRealiseIn fallback = runRealiseUnder (Realise.RealiseSettings fallback Realise.HeedAllowSubstitutes) Realise.BuildNormal++-- | 'runRealiseIn' checking the root: under 'Realise.BuildCheck'.+runCheckIn ::+  Realise.Fallback ->+  FakeWorld ->+  Set.Set Text ->+  [(StorePath, DepGraph.DepNode)] ->+  Text ->+  (Either Realise.RealiseFailure (), [RealiseEvent], Set.Set StorePath)+runCheckIn fallback = runRealiseUnder (Realise.RealiseSettings fallback Realise.HeedAllowSubstitutes) Realise.BuildCheck++-- | 'runCheckIn' under 'Realise.NoFallback', in a world without faults.+runCheck ::+  Set.Set Text ->+  [(StorePath, DepGraph.DepNode)] ->+  [(Text, [Text])] ->+  [Text] ->+  Text ->+  (Either Realise.RealiseFailure (), [RealiseEvent], Set.Set StorePath)+runCheck failing nodes cache valid = runCheckIn Realise.NoFallback (fakeWorld cache valid) failing nodes++-- | 'runRealise' in a given world, under given settings and build mode.+runRealiseUnder ::+  Realise.RealiseSettings ->+  Realise.BuildMode ->+  FakeWorld ->+  Set.Set Text ->+  [(StorePath, DepGraph.DepNode)] ->+  Text ->+  (Either Realise.RealiseFailure (), [RealiseEvent], Set.Set StorePath)+runRealiseUnder settings mode world failing nodes root =+  let (result, final) = runRealiseWorld settings mode world failing nodes root+   in (result, reverse (fwEvents final), fwValid final)++-- | 'runRealiseUnder', answering the world it ends in.+runRealiseWorld ::+  Realise.RealiseSettings ->+  Realise.BuildMode ->+  FakeWorld ->+  Set.Set Text ->+  [(StorePath, DepGraph.DepNode)] ->+  Text ->+  (Either Realise.RealiseFailure (), FakeWorld)+runRealiseWorld settings mode world failing nodes root =+  runState+    (Realise.realise settings mode (fakeRealiseEffects failing) (DepGraph.DepGraph (Map.fromList nodes)) (fakePath (root <> ".drv")))+    world++-- | Run 'Realise.realiseRequests' under 'Realise.NoFallback' over a graph,+-- each request a node's name and the outputs it asks of it, in a world,+-- returning the result, the events in order, and the world it ends in.+runRequests ::+  FakeWorld ->+  Set.Set Text ->+  [(StorePath, DepGraph.DepNode)] ->+  [(Text, [Text])] ->+  (Either Realise.RequestsFailure (), [RealiseEvent], FakeWorld)+runRequests world failing nodes requests =+  let (result, final) =+        runState+          ( Realise.realiseRequests+              (Realise.RealiseSettings Realise.NoFallback Realise.HeedAllowSubstitutes)+              (fakeRealiseEffects failing)+              (DepGraph.DepGraph (Map.fromList nodes))+              [(fakePath (name <> ".drv"), Set.fromList outputs) | (name, outputs) <- requests]+          )+          world+   in (result, reverse (fwEvents final), final)++-- | Run 'Realise.realiseEach' under 'Realise.NoFallback' over a graph,+-- the builds of the derivations whose first outputs are named failing,+-- each request a node's name for its one output, in a world with nothing+-- valid and nothing cached.+runEach :: [Text] -> [(StorePath, DepGraph.DepNode)] -> [Text] -> (Either Realise.RealiseFailure (Map.Map StorePath Realise.RequestOutcome), FakeWorld)+runEach failing nodes requests =+  runState+    ( Realise.realiseEach+        (Realise.RealiseSettings Realise.NoFallback Realise.HeedAllowSubstitutes)+        Realise.BuildNormal+        (fakeRealiseEffects (Set.fromList failing))+        (DepGraph.DepGraph (Map.fromList nodes))+        [(fakePath (name <> ".drv"), Set.singleton (name <> "-out")) | name <- requests]+    )+    (fakeWorld [] [])++-- | Only the fetches, builds and checks of a run, the part that costs+-- anything.+realiseWork :: [RealiseEvent] -> [RealiseEvent]+realiseWork = filter isWork+  where+    isWork (EvFetched _) = True+    isWork (EvBuilt _) = True+    isWork (EvChecked _) = True+    isWork _ = False++-- | A random derivation graph to check.  Each node has one output or two+-- and depends only on lower nodes, for some of each one's outputs, so the+-- graph is acyclic and the highest node is the root.  With it: the nodes+-- that forbid substitutes, the references a cache declares for each+-- output it offers, the outputs that are valid, the ones a cache fails to+-- deliver and the ones it cannot be asked about, the nodes whose builder+-- fails, the outputs of the root that building it again gives other+-- contents, and what a failed substitute leads to.+data CheckCase = CheckCase+  { -- | Each node's dependencies, with the outputs it wants of each.+    ccDeps :: !(Map.Map Int [(Int, [Text])]),+    ccTwoOutputs :: ![Int],+    ccForbidding :: ![Int],+    ccCache :: !(Map.Map Text [Text]),+    ccValid :: ![Text],+    ccBroken :: ![Text],+    ccUnreachable :: ![Text],+    ccFailing :: ![Int],+    ccUnstable :: ![Text],+    ccFallback :: !Realise.Fallback+  }+  deriving (Show)++-- | The names of a node's outputs, given the nodes that have a second.+-- The first names the node in an event, as 'fakeDrvName' reads it.+checkCaseOutputs :: [Int] -> Int -> [Text]+checkCaseOutputs twoOutputs node = (stem <> "-out") : [stem <> "-dev" | node `elem` twoOutputs]+  where+    stem = "n" <> T.pack (show node)++-- | A 'CheckCase'.  A fault is drawn for a third of the cases and absent+-- from the rest, so that the cases reaching a rebuild are not rare; a+-- cache's declared references are an output's siblings and the outputs+-- of lower nodes.+genCheckCase :: QC.Gen CheckCase+genCheckCase = do+  size <- QC.chooseInt (1, 5)+  let nodes = [0 .. size - 1]+      root = size - 1+  twoOutputs <- QC.sublistOf nodes+  let outputsOf = checkCaseOutputs twoOutputs+      allOutputs = concatMap outputsOf nodes+      wanting dep = (,) dep <$> (QC.sublistOf (outputsOf dep) `QC.suchThat` (not . null))+      offered node output =+        QC.frequency+          [ (1, pure Nothing),+            (2, Just . (,) output <$> QC.sublistOf (filter (/= output) (outputsOf node) ++ concatMap outputsOf [0 .. node - 1]))+          ]+      seldom items = QC.frequency [(2, pure []), (1, QC.sublistOf items)]+  deps <- traverse (\node -> (,) node <$> (QC.sublistOf [0 .. node - 1] >>= traverse wanting)) nodes+  cache <- catMaybes <$> sequence [offered node output | node <- nodes, output <- outputsOf node]+  forbidding <- seldom nodes+  valid <- QC.sublistOf allOutputs+  broken <- seldom allOutputs+  unreachable <- seldom allOutputs+  failing <- seldom nodes+  unstable <- QC.sublistOf (outputsOf root)+  fallback <- QC.elements [Realise.NoFallback, Realise.BuildFromSource]+  pure+    CheckCase+      { ccDeps = Map.fromList deps,+        ccTwoOutputs = twoOutputs,+        ccForbidding = forbidding,+        ccCache = Map.fromList cache,+        ccValid = valid,+        ccBroken = broken,+        ccUnreachable = unreachable,+        ccFailing = failing,+        ccUnstable = unstable,+        ccFallback = fallback+      }++-- | What a 'CheckCase' runs in: the world, the names of the outputs whose+-- derivations fail to build, the graph's nodes, and the root's name.+data CheckSetup = CheckSetup+  { csWorld :: !FakeWorld,+    csFailing :: !(Set.Set Text),+    csNodes :: ![(StorePath, DepGraph.DepNode)],+    csRoot :: !Text+  }++-- | The 'CheckSetup' of a 'CheckCase'.  A failing node is named by its+-- first output, as 'fakeDrvName' names it.+checkSetup :: CheckCase -> CheckSetup+checkSetup checkCase =+  CheckSetup+    { csWorld =+        (fakeWorld [] (ccValid checkCase))+          { fwCache = Map.fromList [(fakePath output, map fakePath refs) | (output, refs) <- Map.toList (ccCache checkCase)],+            fwBroken = paths (ccBroken checkCase),+            fwUnreachable = paths (ccUnreachable checkCase),+            fwUnstable = paths (ccUnstable checkCase)+          },+      csFailing = Set.fromList (concatMap (take 1 . outputsOf) (ccFailing checkCase)),+      csNodes = [fakeNodeWith (env node) (name node) (outputsOf node) [(name dep, wanted) | (dep, wanted) <- below] | (node, below) <- Map.toList (ccDeps checkCase)],+      csRoot = name (maximum (0 : Map.keys (ccDeps checkCase)))+    }+  where+    name node = "n" <> T.pack (show node)+    outputsOf = checkCaseOutputs (ccTwoOutputs checkCase)+    paths = Set.fromList . map fakePath+    env node+      | node `elem` ccForbidding checkCase = Map.singleton "allowSubstitutes" ""+      | otherwise = Map.empty++-- | Run a 'CheckCase' from its root under a build mode: the result, the+-- events with the outputs that were valid before each, those valid at the+-- end, and each build's event name with the outputs its request asked, in+-- the order of the builds.+runCheckCase ::+  Realise.BuildMode ->+  CheckCase ->+  (Either Realise.RealiseFailure (), [(Set.Set StorePath, RealiseEvent)], Set.Set StorePath, [(Text, Set.Set Text)])+runCheckCase mode checkCase = (result, steps, fwValid ended, reverse (fwBuiltFor ended))+  where+    setup = checkSetup checkCase+    events = reverse (fwEvents ended)+    steps = zip (scanl landed (fwValid (csWorld setup)) events) events+    nodes = Map.keys (ccDeps checkCase)+    outputsOf = checkCaseOutputs (ccTwoOutputs checkCase)+    paths = Set.fromList . map fakePath+    (result, ended) =+      runRealiseWorld+        (Realise.RealiseSettings (ccFallback checkCase) Realise.HeedAllowSubstitutes)+        mode+        (csWorld setup)+        (csFailing setup)+        (csNodes setup)+        (csRoot setup)+    -- A build makes every output of its derivation valid, and its event+    -- names the first.+    builtOutputs = Map.fromList [(first, paths outputs) | node <- nodes, outputs@(first : _) <- [outputsOf node]]+    landed valid event = case event of+      EvFetched fetched -> valid <> Set.fromList fetched+      EvBuilt built -> valid <> Map.findWithDefault Set.empty built builtOutputs+      _ -> valid++-- | The law of a check, for one 'CheckCase'.  The root is never built in+-- the ordinary way.  It is built again at most once, and only when every+-- output of its own and every output it wants of each input is valid.  The+-- check's result is that rebuild's, and without a rebuild a failure.  A+-- root that cannot be checked builds nothing at all.  No output of the+-- root that was valid is fetched, and a root whose outputs were all valid+-- is not asked about.  A root that forbids substitutes and is short of an+-- output cannot be checked, and nothing at all is done for it.  A build+-- that is no check builds nothing again.+--+-- Each class the generator has to reach for those clauses to say anything+-- is covered: the property fails when one is rarer than its share.  The+-- shares are about a third of what 'genCheckCase' gives, measured over+-- 20000 cases (47%, 6%, 14% and 11% in this order).+checkLaw :: CheckCase -> QC.Property+checkLaw checkCase =+  QC.counterexample (show (result, events))+    . QC.cover 15 checked "the root was built again"+    . QC.cover 2 (checked && partlyValid) "a root with one output of two valid was built again"+    . QC.cover 5 (queryFailed result) "a cache could not be asked"+    . QC.cover 3 mustBuildShort "a root that forbids substitutes was short of an output"+    $ QC.conjoin+      [ QC.counterexample "the root was built" (EvBuilt rootName `notElem` events),+        QC.counterexample "another derivation was checked, or the root twice" ([name | EvChecked name <- events] `elem` [[], [rootName]]),+        QC.counterexample "checked before its outputs and inputs were valid" (all (needed `Set.isSubsetOf`) checks),+        QC.counterexample "the result is not the rebuild's" resultIsRebuilds,+        QC.counterexample "built something for a root it could not check" (not (unbuildable result) || null [() | EvBuilt _ <- events]),+        QC.counterexample "fetched an output of the root that was valid" (Set.null (Set.fromList (concat [fetched | EvFetched fetched <- events]) `Set.intersection` validAtStart)),+        QC.counterexample "asked a cache about a root whose outputs were valid" (not allValidAtStart || null [() | EvQueried asked <- events, asked `Set.member` rootOutputs]),+        QC.counterexample "did something for a root that forbids substitutes and lacks an output" (not mustBuildShort || (result, events) == (Left (Realise.OutputsNotValid rootDrv), [])),+        QC.counterexample "an ordinary build checked" (null [() | (_, EvChecked _) <- ordinary])+      ]+  where+    root = maximum (0 : Map.keys (ccDeps checkCase))+    outputsOf = checkCaseOutputs (ccTwoOutputs checkCase)+    rootDrv = fakePath ("n" <> T.pack (show root) <> ".drv")+    rootName = T.concat (take 1 (outputsOf root))+    rootOutputs = Set.fromList (map fakePath (outputsOf root))+    needed = Set.fromList (map fakePath (outputsOf root ++ concatMap snd (Map.findWithDefault [] root (ccDeps checkCase))))+    validAtStart = rootOutputs `Set.intersection` Set.fromList (map fakePath (ccValid checkCase))+    allValidAtStart = validAtStart == rootOutputs+    partlyValid = not (Set.null validAtStart) && not allValidAtStart+    mustBuildShort = root `elem` ccForbidding checkCase && not allValidAtStart+    (result, steps, _, _) = runCheckCase Realise.BuildCheck checkCase+    events = map snd steps+    checks = [valid | (valid, EvChecked _) <- steps]+    checked = not (null checks)+    rebuilt+      | root `elem` ccFailing checkCase = Left (Realise.BuildFailed ("building " <> rootName <> " failed"))+      | otherwise = maybe (Right ()) (\output -> Left (Realise.NotDeterministic rootDrv (fakePath output) Realise.RebuildDiscarded)) (find (`elem` ccUnstable checkCase) (outputsOf root))+    -- Without a rebuild the check can only have failed.+    resultIsRebuilds+      | checked = result == rebuilt+      | otherwise = either (const True) (const False) result+    unbuildable (Left (Realise.OutputsNotValid _)) = True+    unbuildable _ = False+    queryFailed (Left (Realise.CacheQueryFailed _)) = True+    queryFailed _ = False+    (_, ordinary, _, _) = runCheckCase Realise.BuildNormal checkCase++-- | The law of a build, for one 'CheckCase'.  A derivation builds only+-- while some output the request that led to the build asks of it is not+-- valid, and only once every output it wants of each of its inputs is+-- valid, so an input asked again for an output it has not realised is+-- realised again for it.  What is fetched is an output some request asks+-- for, or something such an output references, as the cache declares.  A+-- build that succeeds leaves every output of the root valid.+--+-- An input asked for one output of its two is what the first and third+-- clauses need to say anything.  An input that two dependents ask for+-- different outputs is what the second needs, and what the first needs to+-- tell the request that led to a build from the others made of the same+-- derivation.  Each is held to about a third of the share 'genCheckCase'+-- gives it, measured over 20000 cases (about 39% and 15% in this order).+realiseLaw :: CheckCase -> QC.Property+realiseLaw checkCase =+  QC.counterexample (show (result, steps, builtFor))+    . QC.cover 10 partlyWanted "an input was asked for one output of its two"+    . QC.cover 5 askedDifferently "an input was asked for different outputs by two dependents"+    $ QC.conjoin+      [ QC.counterexample "a build was not recorded with its request" (map fst builtFor == map snd buildSteps),+        QC.counterexample "built a derivation whose outputs the request asked were valid" (and [not (Set.map fakePath wanted `Set.isSubsetOf` valid) | ((valid, _), (_, wanted)) <- zip buildSteps builtFor]),+        QC.counterexample "built before the outputs it wants of its inputs were valid" (all inputsValid buildSteps),+        QC.counterexample "fetched what no request reaches" (all (all (`Set.member` reachable)) [fetched | (_, EvFetched fetched) <- steps]),+        QC.counterexample "succeeded short of an output of the root" (either (const True) (const (paths (outputsOf root) `Set.isSubsetOf` final)) result)+      ]+  where+    nodes = Map.keys (ccDeps checkCase)+    root = maximum (0 : nodes)+    outputsOf = checkCaseOutputs (ccTwoOutputs checkCase)+    paths = Set.fromList . map fakePath+    (result, steps, final, builtFor) = runCheckCase Realise.BuildNormal checkCase+    -- Each build, with the outputs valid before it.+    buildSteps = [(valid, built) | (valid, EvBuilt built) <- steps]+    edges = [(dep, wanted) | below <- Map.elems (ccDeps checkCase), (dep, wanted) <- below]+    -- The root is asked for every output, an input for what each of its+    -- dependents names.+    asked node+      | node == root = outputsOf root+      | otherwise = concat [wanted | (dep, wanted) <- edges, dep == node]+    -- A build's event names the node's first output.+    nodeBuilt = Map.fromList [(first, node) | node <- nodes, first : _ <- [outputsOf node]]+    wantedOfInputs node = paths (concatMap snd (Map.findWithDefault [] node (ccDeps checkCase)))+    inputsValid (valid, built) = maybe False ((`Set.isSubsetOf` valid) . wantedOfInputs) (Map.lookup built nodeBuilt)+    reachable = Set.map fakePath (closeUnder Set.empty (concatMap asked nodes))+    closeUnder seen pending = case pending of+      [] -> seen+      output : rest+        | Set.member output seen -> closeUnder seen rest+        | otherwise -> closeUnder (Set.insert output seen) (Map.findWithDefault [] output (ccCache checkCase) ++ rest)+    partlyWanted = or [length wanted < length (outputsOf dep) | (dep, wanted) <- edges]+    askedDifferently = or [Set.size (Set.fromList [Set.fromList wanted | (dep, wanted) <- edges, dep == node]) > 1 | node <- nodes]++-- | The law of a lone request, for one 'CheckCase': a request for every+-- output of the root realises the graph as 'Realise.realise' does under+-- 'Realise.BuildNormal', to the same result, through the same events and+-- builds, and to the same valid paths.  Cases that fail and cases that+-- succeed are each held to a share well under what 'genCheckCase' gives+-- them.+loneRequestLaw :: CheckCase -> QC.Property+loneRequestLaw checkCase =+  QC.cover 10 (isLeft requested) "the request failed"+    . QC.cover 10 (isRight requested) "the request was realised"+    $ alone QC.=== observed (either (Left . Realise.FailedWith) Right <$> Realise.realise settings Realise.BuildNormal effects graph rootDrv)+  where+    setup = checkSetup checkCase+    settings = Realise.RealiseSettings (ccFallback checkCase) Realise.HeedAllowSubstitutes+    effects = fakeRealiseEffects (csFailing setup)+    graph = DepGraph.DepGraph (Map.fromList (csNodes setup))+    rootDrv = fakePath (csRoot setup <> ".drv")+    everyOutput = Set.fromList (checkCaseOutputs (ccTwoOutputs checkCase) (maximum (0 : Map.keys (ccDeps checkCase))))+    alone@(requested, _, _, _) = observed (Realise.realiseRequests settings effects graph [(rootDrv, everyOutput)])+    observed action =+      let (result, final) = runState action (csWorld setup)+       in (result, reverse (fwEvents final), fwValid final, fwBuiltFor final)++-- | A random reference graph: each node references only lower nodes, so the+-- graph is acyclic, and some nodes are absent from the cache.+genClosureCase :: QC.Gen (Map.Map Int [Int], [Int])+genClosureCase = do+  size <- QC.chooseInt (1, 12)+  references <- traverse (\node -> (,) node <$> QC.sublistOf [0 .. node - 1]) [0 .. size - 1]+  absent <- QC.sublistOf [0 .. size - 1]+  pure (Map.fromList references, absent)++testRealise :: IO [Bool]+testRealise = do+  putStrLn "realise"+  sequence+    [ -- hello is on the cache, so nothing it was built from is touched, only+      -- what it references at runtime.+      runTest "a root on the cache fetches its runtime closure and nothing else" $+        let (result, events, _) =+              runRealise+                Set.empty+                [fakeNode "hello" ["hello-out"] [("gcc", ["gcc-out"])], fakeNode "gcc" ["gcc-out"] []]+                [("hello-out", ["glibc-out"]), ("glibc-out", []), ("gcc-out", [])]+                []+                "hello"+         in assertEqual+              "realise"+              (Right (), [EvFetched [fakePath "glibc-out"], EvFetched [fakePath "hello-out"]], False)+              (result, realiseWork events, EvQueried (fakePath "gcc-out") `elem` events),+      runTest "a root the cache lacks realises its inputs, then builds" $+        let (result, events, _) =+              runRealise+                Set.empty+                [fakeNode "hello" ["hello-out"] [("gcc", ["gcc-out"])], fakeNode "gcc" ["gcc-out"] []]+                [("gcc-out", [])]+                []+                "hello"+         in assertEqual "realise" (Right (), [EvFetched [fakePath "gcc-out"], EvBuilt "hello-out"]) (result, realiseWork events),+      runTest "a reference the cache lacks fails the substitution and builds" $+        let (result, events, valid) =+              runRealise+                Set.empty+                [fakeNode "hello" ["hello-out"] []]+                [("hello-out", ["gone-out"])]+                []+                "hello"+         in assertEqual+              "realise"+              (Right (), [EvBuilt "hello-out"], False)+              (result, realiseWork events, Set.member (fakePath "gone-out") valid),+      -- Upstream's retrySubstitution: the closure's hole is an input built+      -- here, and then the substitute is good, so hello is not built.+      runTest "an input that fills the closure's hole lets the substitute through" $+        let (result, events, _) =+              runRealise+                Set.empty+                [fakeNode "hello" ["hello-out"] [("lib", ["lib-out"])], fakeNode "lib" ["lib-out"] []]+                [("hello-out", ["lib-out"])]+                []+                "hello"+         in assertEqual "realise" (Right (), [EvBuilt "lib-out", EvFetched [fakePath "hello-out"]]) (result, realiseWork events),+      runTest "a root with a missing output is not retried when no reference was at fault" $+        let (_, events, _) =+              runRealise Set.empty [fakeNode "hello" ["hello-out"] []] [] [] "hello"+         in assertEqual "narinfo queries" (1 :: Int) (length [() | EvQueried _ <- events]),+      runTest "outputs arrive together, and one referencing another is no hole" $+        let (result, events, _) =+              runRealise+                Set.empty+                [fakeNode "pkg" ["pkg-bin", "pkg-lib"] [("gcc", ["gcc-out"])], fakeNode "gcc" ["gcc-out"] []]+                [("pkg-bin", ["pkg-lib"]), ("pkg-lib", [])]+                []+                "pkg"+         in assertEqual "realise" (Right (), [EvFetched [fakePath "pkg-bin", fakePath "pkg-lib"]]) (result, realiseWork events),+      runTest "one missing output of two builds rather than half substituting" $+        let (result, events, valid) =+              runRealise+                Set.empty+                [fakeNode "pkg" ["pkg-bin", "pkg-lib"] []]+                [("pkg-bin", [])]+                []+                "pkg"+         in assertEqual+              "realise"+              (Right (), [EvBuilt "pkg-bin"], True)+              (result, realiseWork events, Set.member (fakePath "pkg-lib") valid),+      runTest "a self-reference is no hole" $+        let (result, events, _) =+              runRealise Set.empty [fakeNode "hello" ["hello-out"] []] [("hello-out", ["hello-out"])] [] "hello"+         in assertEqual "realise" (Right (), [EvFetched [fakePath "hello-out"]]) (result, realiseWork events),+      -- The cycle ends at the visited set, and the registration it reaches+      -- refuses the unregistered referent: a failed substitute.+      runTest "a reference cycle a cache declares ends, and fails the substitution" $+        let (result, events, _) =+              runRealise+                Set.empty+                [fakeNode "hello" ["hello-out"] []]+                [("hello-out", ["a-out"]), ("a-out", ["b-out"]), ("b-out", ["a-out"])]+                []+                "hello"+         in assertEqual "realise" (Left (Realise.SubstitutesFailed (fakePath "hello.drv")), []) (result, realiseWork events),+      runTest "under fallback a reference cycle a cache declares builds" $+        let (result, events, _) =+              runRealiseIn+                Realise.BuildFromSource+                (fakeWorld [("hello-out", ["a-out"]), ("a-out", ["b-out"]), ("b-out", ["a-out"])] [])+                Set.empty+                [fakeNode "hello" ["hello-out"] []]+                "hello"+         in assertEqual "realise" (Right (), [EvBuilt "hello-out"]) (result, realiseWork events),+      -- Upstream's DerivationGoal::outputsSubstitutionTried: a substitute+      -- that fails is not a substitute the cache lacks.+      runTest "a substitute that fails stops the build, naming the derivation" $+        let (result, events, valid) =+              runRealiseIn+                Realise.NoFallback+                (fakeWorld [("hello-out", [])] []) {fwBroken = Set.singleton (fakePath "hello-out")}+                Set.empty+                [fakeNode "hello" ["hello-out"] [("gcc", ["gcc-out"])], fakeNode "gcc" ["gcc-out"] []]+                "hello"+         in assertEqual+              "realise"+              (Left (Realise.SubstitutesFailed (fakePath "hello.drv")), [], False, False)+              (result, realiseWork events, EvQueried (fakePath "gcc-out") `elem` events, Set.member (fakePath "hello-out") valid),+      runTest "under fallback a substitute that fails builds instead, and is not retried" $+        let (result, events, _) =+              runRealiseIn+                Realise.BuildFromSource+                (fakeWorld [("hello-out", []), ("gcc-out", [])] []) {fwBroken = Set.singleton (fakePath "hello-out")}+                Set.empty+                [fakeNode "hello" ["hello-out"] [("gcc", ["gcc-out"])], fakeNode "gcc" ["gcc-out"] []]+                "hello"+         in assertEqual+              "realise"+              (Right (), [EvFetched [fakePath "gcc-out"], EvBuilt "hello-out"], 1 :: Int)+              (result, realiseWork events, length [() | EvQueried sp <- events, sp == fakePath "hello-out"]),+      runTest "a reference whose substitute fails stops the build of what names it" $+        let (result, events, _) =+              runRealiseIn+                Realise.NoFallback+                (fakeWorld [("hello-out", ["lib-out"]), ("lib-out", [])] []) {fwBroken = Set.singleton (fakePath "lib-out")}+                Set.empty+                [fakeNode "hello" ["hello-out"] []]+                "hello"+         in assertEqual "realise" (Left (Realise.SubstitutesFailed (fakePath "hello.drv")), []) (result, realiseWork events),+      -- Upstream's goal moves on to its next substituter when a copy fails,+      -- and realises what that substituter's path info references first.+      runTest "a path the first cache fails to deliver comes from the next, after what that cache says it references" $+        let (result, events, _) =+              runRealiseIn+                Realise.NoFallback+                (fakeWorld [("hello-out", []), ("lib-out", [])] [])+                  { fwBroken = Set.singleton (fakePath "hello-out"),+                    fwNextCache = fakeCache [("hello-out", ["lib-out"])]+                  }+                Set.empty+                [fakeNode "hello" ["hello-out"] []]+                "hello"+         in assertEqual+              "realise"+              ( Right (),+                [ EvQueried (fakePath "hello-out"),+                  EvQueriedNext (fakePath "hello-out"),+                  EvQueried (fakePath "lib-out"),+                  EvFetched [fakePath "lib-out"],+                  EvFetched [fakePath "hello-out"],+                  EvReported Realise.Substituted "hello-out"+                ]+              )+              (result, events),+      runTest "only the output a cache failed to deliver is asked of the next cache" $+        let (result, events, _) =+              runRealiseIn+                Realise.NoFallback+                (fakeWorld [("pkg-bin", []), ("pkg-lib", [])] [])+                  { fwBroken = Set.singleton (fakePath "pkg-bin"),+                    fwNextCache = fakeCache [("pkg-bin", []), ("pkg-lib", [])]+                  }+                Set.empty+                [fakeNode "pkg" ["pkg-bin", "pkg-lib"] []]+                "pkg"+         in assertEqual+              "realise"+              (Right (), [fakePath "pkg-bin"], [EvFetched [fakePath "pkg-bin", fakePath "pkg-lib"]])+              (result, [sp | EvQueriedNext sp <- events], realiseWork events),+      -- Upstream's goal for each output runs its own course: dev's ends for+      -- want of a substitute and out's arrives from the next cache, so no+      -- goal failed and the derivation builds (outputsSubstitutionTried in+      -- derivation-goal.cc at 2.24.9, haveDerivation at 2.36.0).+      runTest "an output whose cache failed and that the next cache delivers fails nothing, though its sibling has no cache left" $+        let (result, events, _) =+              runRealiseIn+                Realise.NoFallback+                (fakeWorld [("pkg-out", []), ("pkg-dev", [])] [])+                  { fwBroken = Set.singleton (fakePath "pkg-out"),+                    fwGone = Set.singleton (fakePath "pkg-dev"),+                    fwNextCache = fakeCache [("pkg-out", [])]+                  }+                Set.empty+                [fakeNode "pkg" ["pkg-out", "pkg-dev"] []]+                "pkg"+         in assertEqual+              "realise"+              (Right (), [EvBuilt "pkg-out"], [[fakePath "pkg-out"]])+              (result, realiseWork events, [probed | EvProbed probed <- events]),+      runTest "an output whose every cache failed to deliver it stops the build, though its sibling is gone" $+        let (result, events, _) =+              runRealiseIn+                Realise.NoFallback+                (fakeWorld [("pkg-out", []), ("pkg-dev", [])] [])+                  { fwBroken = Set.singleton (fakePath "pkg-out"),+                    fwGone = Set.singleton (fakePath "pkg-dev")+                  }+                Set.empty+                [fakeNode "pkg" ["pkg-out", "pkg-dev"] []]+                "pkg"+         in assertEqual "realise" (Left (Realise.SubstitutesFailed (fakePath "pkg.drv")), []) (result, realiseWork events),+      -- Upstream rethrows a failed narinfo query, which ends the build+      -- before any other goal is asked anything.+      runTest "a cache that cannot be asked stops the build, and nothing after it is asked" $+        let (result, events, _) =+              runRealiseIn+                Realise.NoFallback+                (fakeWorld [("pkg-lib", [])] []) {fwUnreachable = Set.singleton (fakePath "pkg-bin")}+                Set.empty+                [fakeNode "pkg" ["pkg-bin", "pkg-lib"] [("gcc", ["gcc-out"])], fakeNode "gcc" ["gcc-out"] []]+                "pkg"+         in assertEqual+              "realise"+              (Left (Realise.CacheQueryFailed (fakeQueryFailure (fakePath "pkg-bin"))), [EvQueried (fakePath "pkg-bin")])+              (result, events),+      runTest "a substitution is retried once after the inputs, and not again" $+        let (_, events, _) =+              runRealise Set.empty [fakeNode "hello" ["hello-out"] []] [("hello-out", ["gone-out"])] [] "hello"+         in assertEqual "narinfo queries" (2 :: Int) (length [() | EvQueried sp <- events, sp == fakePath "hello-out"]),+      runTest "a reference that landed before another failed stays valid" $+        let (result, events, valid) =+              runRealise+                Set.empty+                [fakeNode "hello" ["hello-out"] []]+                [("hello-out", ["a-out", "z-out"]), ("a-out", [])]+                []+                "hello"+         in assertEqual+              "realise"+              (Right (), [EvFetched [fakePath "a-out"], EvBuilt "hello-out"], True)+              (result, realiseWork events, Set.member (fakePath "a-out") valid),+      runTestM "a closure lands exactly when all of it is cached, and stays closed" $ do+        result <-+          QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} $+            QC.forAll genClosureCase $ \(references, absent) ->+              let paths = Map.keys references+                  root = maximum (0 : paths)+                  closure seen node+                    | Set.member node seen = seen+                    | otherwise = foldl closure (Set.insert node seen) (Map.findWithDefault [] node references)+                  path = fakePath . ("p" <>) . T.pack . show+                  cache = Map.fromList [(path node, map path refs) | (node, refs) <- Map.toList references, node `notElem` absent]+                  (outcome, final) =+                    runState (Realise.substituteClosure fakeSubst [path root]) (fakeWorld [] []) {fwCache = cache}+                  valid = fwValid final+                  closed = all (\sp -> all (`Set.member` valid) (Map.findWithDefault [] sp cache)) valid+                  wholeOnCache = all (`notElem` absent) (closure Set.empty root)+               in (outcome == Realise.ClosureComplete, closed) QC.=== (wholeOnCache, True)+        pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result))),+      runTest "valid outputs need no cache at all" $+        let (result, events, _) =+              runRealise Set.empty [fakeNode "hello" ["hello-out"] [("gcc", ["gcc-out"])], fakeNode "gcc" ["gcc-out"] []] [] ["hello-out"] "hello"+         in assertEqual "realise" (Right (), [EvReported Realise.AlreadyValid "hello-out"]) (result, events),+      runTest "a dependency two others share is realised once" $+        let (result, events, _) =+              runRealise+                Set.empty+                [ fakeNode "top" ["top-out"] [("left", ["left-out"]), ("right", ["right-out"])],+                  fakeNode "left" ["left-out"] [("base", ["base-out"])],+                  fakeNode "right" ["right-out"] [("base", ["base-out"])],+                  fakeNode "base" ["base-out"] []+                ]+                []+                []+                "top"+         in assertEqual+              "realise"+              (Right (), [EvBuilt "base-out", EvBuilt "left-out", EvBuilt "right-out", EvBuilt "top-out"])+              (result, realiseWork events),+      -- An input is realised for the outputs its dependent names, which+      -- alone are checked and substituted (checkPathValidity and+      -- haveDerivation, derivation-goal.cc at 2.24.9).+      runTest "a dependency on one output fetches that output and its closure only" $+        let (result, events, valid) =+              runRealise+                Set.empty+                [fakeNode "app" ["app-out"] [("lib", ["lib-dev"])], threeOutputLib]+                [("lib-dev", ["lib-out"]), ("lib-out", []), ("lib-doc", [])]+                []+                "app"+         in assertEqual+              "realise"+              (Right (), [EvFetched [fakePath "lib-out"], EvFetched [fakePath "lib-dev"], EvBuilt "app-out"], False)+              (result, realiseWork events, Set.member (fakePath "lib-doc") valid),+      runTest "an output nothing wants and no cache holds builds nothing" $+        let (result, events, _) =+              runRealise+                Set.empty+                [fakeNode "app" ["app-out"] [("lib", ["lib-dev"])], threeOutputLib]+                [("lib-dev", ["lib-out"]), ("lib-out", [])]+                []+                "app"+         in assertEqual+              "realise"+              (Right (), [EvFetched [fakePath "lib-out"], EvFetched [fakePath "lib-dev"], EvBuilt "app-out"])+              (result, realiseWork events),+      -- lib.drv sorts before mid.drv, so app asks lib for lib-dev, and mid+      -- asks it for lib-out after that request is done.+      runTest "a later request for another output substitutes it" $+        let (result, events, _) = runRealise Set.empty laterRequest [("lib-dev", []), ("lib-out", [])] [] "app"+         in assertEqual+              "realise"+              (Right (), [EvFetched [fakePath "lib-dev"], EvFetched [fakePath "lib-out"], EvBuilt "mid-out", EvBuilt "app-out"])+              (result, realiseWork events),+      runTest "a later request for another output no cache holds builds the derivation" $+        let (result, events, _) = runRealise Set.empty laterRequest [("lib-dev", [])] [] "app"+         in assertEqual+              "realise"+              (Right (), [EvFetched [fakePath "lib-dev"], EvBuilt "lib-out", EvBuilt "mid-out", EvBuilt "app-out"])+              (result, realiseWork events),+      -- checkPathValidity refuses an output name the derivation does not+      -- have (derivation-goal.cc at 2.24.9), before anything is+      -- substituted for it.+      runTest "an output a derivation does not have fails the request, naming each in order" $+        let (result, events, _) =+              runRealise+                Set.empty+                [fakeNode "app" ["app-out"] [("lib", ["lib-out", "lib-man", "lib-bin"])], fakeNode "lib" ["lib-out"] []]+                [("lib-out", [])]+                []+                "app"+         in assertEqual+              "realise"+              (Left ("derivation '/nix/store/" <> T.replicate 32 "l" <> "-lib.drv' does not have wanted outputs 'lib-bin', 'lib-man'"), [])+              (messageOf result, realiseWork events),+      -- Upstream starts no goal for an input that names no output+      -- (DerivationGoal::gaveUpOnSubstitution in derivation-goal.cc at+      -- 2.24.9, DerivationResolutionGoal::realiseInputs in+      -- derivation-resolution-goal.cc at 2.36.0).+      runTest "an input asked for no output is not realised" $+        let (result, events, _) =+              runRealise Set.empty [fakeNode "app" ["app-out"] [("lib", [])], fakeNode "lib" ["lib-out"] []] [] [] "app"+         in assertEqual+              "realise"+              (Right (), [EvReported Realise.Built "app-out"])+              (result, [event | event@(EvReported _ _) <- events]),+      runTest "a later request for outputs already realised realises nothing again" $+        let (result, events, _) =+              runRealise+                Set.empty+                [ fakeNode "app" ["app-out"] [("lib", ["lib-dev"]), ("mid", ["mid-out"])],+                  fakeNode "mid" ["mid-out"] [("lib", ["lib-dev"])],+                  fakeNode "lib" ["lib-out", "lib-dev"] []+                ]+                [("lib-dev", [])]+                []+                "app"+         in assertEqual+              "realise"+              (Right (), [EvReported Realise.Substituted "lib-out", EvReported Realise.Built "mid-out", EvReported Realise.Built "app-out"])+              (result, [event | event@(EvReported _ _) <- events]),+      runTest "a failed input stops the build of what depends on it" $+        let (result, events, _) =+              runRealise+                (Set.singleton "gcc-out")+                [fakeNode "hello" ["hello-out"] [("gcc", ["gcc-out"])], fakeNode "gcc" ["gcc-out"] []]+                []+                []+                "hello"+         in assertEqual "realise" (Left (Realise.BuildFailed "building gcc-out failed"), []) (result, realiseWork events),+      -- Upstream's ParsedDerivation::substitutesAllowed, read where+      -- DerivationGoal::haveDerivation reads it: before any cache is asked+      -- about the derivation's own outputs.+      runTest "a derivation that forbids substitutes builds though a cache holds its output, and no cache is asked" $+        let (result, events, _) =+              runRealise Set.empty [fakeNodeWith forbidding "hello" ["hello-out"] []] [("hello-out", [])] [] "hello"+         in assertEqual+              "realise"+              (Right (), [EvBuilt "hello-out"], [])+              (result, realiseWork events, [path | EvQueried path <- events]),+      runTest "its inputs are substituted as any other derivation's are" $+        let (result, events, _) =+              runRealise+                Set.empty+                [fakeNodeWith forbidding "hello" ["hello-out"] [("gcc", ["gcc-out"])], fakeNode "gcc" ["gcc-out"] []]+                [("hello-out", []), ("gcc-out", [])]+                []+                "hello"+         in assertEqual "realise" (Right (), [EvFetched [fakePath "gcc-out"], EvBuilt "hello-out"]) (result, realiseWork events),+      -- Upstream's PathSubstitutionGoal knows paths, not the derivations+      -- that built them.+      runTest "its output is substituted as a path another substituted output references" $+        let (result, events, _) =+              runRealise+                Set.empty+                [fakeNode "app" ["app-out"] [("lib", ["lib-out"])], fakeNodeWith forbidding "lib" ["lib-out"] []]+                [("app-out", ["lib-out"]), ("lib-out", [])]+                []+                "app"+         in assertEqual "realise" (Right (), [EvFetched [fakePath "lib-out"], EvFetched [fakePath "app-out"]]) (result, realiseWork events),+      runTest "under always-allow-substitutes it is substituted" $+        let (result, events, _) =+              runRealiseUnder alwaysAllowing Realise.BuildNormal (fakeWorld [("hello-out", [])] []) Set.empty [fakeNodeWith forbidding "hello" ["hello-out"] []] "hello"+         in assertEqual "realise" (Right (), [EvFetched [fakePath "hello-out"]]) (result, realiseWork events),+      runTest "a structured allowSubstitutes that is no Boolean stops the build, naming the derivation as upstream does" $+        let (result, events, _) =+              runRealise Set.empty [fakeNodeWith mistyped "hello" ["hello-out"] []] [("hello-out", [])] [] "hello"+         in assertEqual+              "realise"+              (Left ("attribute 'allowSubstitutes' of derivation '" <> helloDrvName <> "' must be a Boolean"), [])+              (either (Left . Realise.realiseFailureMessage defaultStoreDir) Right result, realiseWork events),+      runTest "with several outputs it builds them all and asks no cache about any" $+        let (result, events, valid) =+              runRealise+                Set.empty+                [fakeNodeWith forbidding "pkg" ["pkg-bin", "pkg-lib"] []]+                [("pkg-bin", ["pkg-lib"]), ("pkg-lib", [])]+                []+                "pkg"+         in assertEqual+              "realise"+              (Right (), [EvBuilt "pkg-bin"], [], True)+              (result, realiseWork events, [path | EvQueried path <- events], Set.member (fakePath "pkg-lib") valid),+      runTest "it is not read for a derivation whose outputs are valid, nor under always-allow-substitutes" $+        let nodes = [fakeNodeWith mistyped "hello" ["hello-out"] []]+            (valid, _, _) = runRealise Set.empty nodes [] ["hello-out"] "hello"+            (always, _, _) = runRealiseUnder alwaysAllowing Realise.BuildNormal (fakeWorld [("hello-out", [])] []) Set.empty nodes "hello"+         in assertEqual "valid" (Right ()) valid `andThen` assertEqual "always" (Right ()) always,+      runTest "allowSubstitutes is read as upstream's getBoolAttr reads it" $+        let cases =+              [ ("absent", Map.empty, Realise.MaySubstitute),+                ("true as evaluation writes it", Map.singleton "allowSubstitutes" "1", Realise.MaySubstitute),+                ("false as evaluation writes it", forbidding, Realise.MustBuild),+                ("another string", Map.singleton "allowSubstitutes" "true", Realise.MustBuild),+                ("structured, absent", structured "{}", Realise.MaySubstitute),+                ("structured true", structured "{\"allowSubstitutes\":true}", Realise.MaySubstitute),+                ("structured false", structured "{\"allowSubstitutes\":false}", Realise.MustBuild),+                ("structured null", structured "null", Realise.MaySubstitute),+                ("structured, no object", structured "[false]", Realise.MaySubstitute),+                -- Structured attributes are read from the JSON alone.+                ("structured beside an environment entry", Map.union forbidding (structured "{}"), Realise.MaySubstitute)+              ] ::+                [(Text, Map.Map Text BS.ByteString, Realise.Substitutes)]+         in assertEqual+              "substitutes"+              [(label, Right allowed) | (label, _, allowed) <- cases]+              [(label, heeding env) | (label, env, _) <- cases],+      runTest "structured attributes that are not JSON are an error naming the derivation" $+        assertEqual "not-json" (Left True) (either (Left . T.isPrefixOf unreadable) Right (heeding (structured "{")))+          `andThen` assertEqual "not-utf8" (Left (unreadable <> "invalid UTF-8")) (heeding (structured "\xff")),+      -- Upstream's ParsedDerivation constructor runs for every derivation+      -- it has a goal for, before the outputs are looked at and whatever+      -- always-allow-substitutes says.+      runTest "they stop the build though the outputs are valid, and under always-allow-substitutes" $+        let nodes = [fakeNodeWith (structured "\xff") "hello" ["hello-out"] []]+            stopped (result, events, _) = (either (Left . Realise.realiseFailureMessage defaultStoreDir) Right result, events)+            refused = (Left (unreadable <> "invalid UTF-8"), [])+         in assertEqual "valid" refused (stopped (runRealise Set.empty nodes [] ["hello-out"] "hello"))+              `andThen` assertEqual+                "always"+                refused+                (stopped (runRealiseUnder alwaysAllowing Realise.BuildNormal (fakeWorld [("hello-out", [])] []) Set.empty nodes "hello")),+      runTestM "in the environment only 1 allows substitutes" $+        property $+          QC.forAll (QC.oneof [pure "1", BS.pack <$> QC.listOf QC.arbitrary]) $ \value ->+            heeding (Map.singleton "allowSubstitutes" value)+              QC.=== Right (if value == "1" then Realise.MaySubstitute else Realise.MustBuild),+      runTestM "always-allow-substitutes allows a derivation whatever its attributes hold" $+        property $+          QC.forAll genAttributes $ \attrs ->+            Realise.substitutesAllowed Realise.AlwaysAllowSubstitutes helloDrv attrs QC.=== Right Realise.MaySubstitute,+      -- Upstream's bmCheck.  A valid output's substitution goal ends at+      -- once (PathSubstitutionGoal::init), so the cache that holds hello+      -- is never asked about it, and gaveUpOnSubstitution gives the input+      -- an ordinary goal.+      runTest "a check realises the inputs of a valid root, builds the root again and asks no cache about it" $+        let (result, events, _) = runCheck Set.empty helloAndGcc [("hello-out", []), ("gcc-out", [])] ["hello-out"] "hello"+         in assertEqual+              "check"+              (Right (), [EvFetched [fakePath "gcc-out"], EvChecked "hello-out"], [EvReported Realise.Substituted "gcc-out", EvReported Realise.Checked "hello-out"], False)+              (result, realiseWork events, [event | event@(EvReported _ _) <- events], EvQueried helloOut `elem` events),+      runTest "a check builds an input no cache holds, and never the root" $+        let (result, events, _) = runCheck Set.empty helloAndGcc [] ["hello-out"] "hello"+         in assertEqual "check" (Right (), [EvBuilt "gcc-out", EvChecked "hello-out"]) (result, realiseWork events),+      runTest "an input that is valid is not built again" $+        let (result, events, _) = runCheck Set.empty helloAndGcc [] ["hello-out", "gcc-out"] "hello"+         in assertEqual "check" (Right (), [EvChecked "hello-out"]) (result, realiseWork events),+      -- registerOutputs raises NotDeterministic, and failingExitStatus+      -- gives the build that ends in it its own status.+      runTest "a rebuilt output that differs stops the check with upstream's message and status" $+        let (result, events, _) =+              runCheckIn Realise.NoFallback (fakeWorld [] ["hello-out"]) {fwUnstable = Set.singleton helloOut} Set.empty [fakeNode "hello" ["hello-out"] []] "hello"+            differs = Realise.NotDeterministic helloDrv helloOut Realise.RebuildDiscarded+         in assertEqual "check" (Left differs, [EvChecked "hello-out"], []) (result, realiseWork events, [status | EvReported status _ <- events])+              `andThen` assertEqual+                "message"+                ("derivation '" <> helloDrvText <> "' may not be deterministic: output \"" <> T.pack (storePathToFilePath defaultStoreDir helloOut) <> "\" differs")+                (Realise.realiseFailureMessage defaultStoreDir differs)+              `andThen` assertEqual "status" 104 (Realise.realiseFailureStatus differs),+      -- printStorePath for the derivation, toRealPath for the output.+      runTest "the output that differs is named where the store's files are, and the derivation under the store's own directory" $+        assertEqual+          "message"+          ("derivation '" <> helloDrvText <> "' may not be deterministic: output \"" <> T.pack (storePathToFilePath elsewhere helloOut) <> "\" differs")+          (Realise.realiseFailureMessage elsewhere (Realise.NotDeterministic helloDrv helloOut Realise.RebuildDiscarded)),+      -- Upstream under keep-failed moves the rebuild to the output's path+      -- with .check after it, which its message names, and the status is+      -- the same.+      runTest "a rebuild kept beside the output is named in the message as the output's path with .check after it" $+        let kept = Realise.NotDeterministic helloDrv helloOut Realise.RebuildKept+            outPath = T.pack (storePathToFilePath elsewhere helloOut)+         in assertEqual+              "message"+              ("derivation '" <> helloDrvText <> "' may not be deterministic: output \"" <> outPath <> "\" differs from \"" <> outPath <> ".check\"")+              (Realise.realiseFailureMessage elsewhere kept)+              `andThen` assertEqual "path" (T.unpack outPath <> ".check") (Realise.checkedOutputPath elsewhere helloOut)+              `andThen` assertEqual "status" 104 (Realise.realiseFailureStatus kept),+      -- Which output a rebuild finds different, and in what order it+      -- compares them, is the check effect's to say ("builder/check" pins+      -- the real one); the failure only passes its answer on.+      runTest "the output the check effect finds different is the one the failure names" $+        let (result, _, _) =+              runCheckIn+                Realise.NoFallback+                (fakeWorld [] ["pkg-bin", "pkg-lib"]) {fwUnstable = Set.singleton (fakePath "pkg-lib")}+                Set.empty+                [fakeNode "pkg" ["pkg-bin", "pkg-lib"] []]+                "pkg"+         in assertEqual "check" (Left (Realise.NotDeterministic (fakePath "pkg.drv") (fakePath "pkg-lib") Realise.RebuildDiscarded)) result,+      -- Upstream's goal for a derivation it cannot load fails; a check+      -- that built nothing again and compared nothing has not passed.+      runTest "a check of a root the graph does not hold fails, where a build of one realises nothing and succeeds" $+        let (checked, events, _) = runCheck Set.empty [] [] [] "hello"+            (built, _, _) = runRealise Set.empty [] [] [] "hello"+         in assertEqual "check" (Left ("cannot build missing derivation '" <> helloDrvText <> "'"), []) (messageOf checked, events)+              `andThen` assertEqual "failure" (Left (Realise.MissingDerivation helloDrv)) checked+              `andThen` assertEqual "build" (Right ()) built,+      -- haveDerivation starts the substitution goals whatever the mode,+      -- and the check goes on once they have made the outputs valid.+      runTest "a check substitutes a root that is not valid, realises its inputs, then builds it again" $+        let (result, events, _) = runCheck Set.empty helloAndGcc [("hello-out", []), ("gcc-out", [])] [] "hello"+         in assertEqual+              "check"+              (Right (), [EvFetched [helloOut], EvFetched [fakePath "gcc-out"], EvChecked "hello-out"], [Realise.Substituted, Realise.Substituted, Realise.Checked])+              (result, realiseWork events, [status | EvReported status _ <- events]),+      runTest "of two outputs only the one that is not valid is fetched before the check" $+        let (result, events, _) =+              runCheck Set.empty [fakeNode "pkg" ["pkg-bin", "pkg-lib"] []] [("pkg-bin", []), ("pkg-lib", [])] ["pkg-bin"] "pkg"+         in assertEqual "check" (Right (), [EvFetched [fakePath "pkg-lib"], EvChecked "pkg-bin"]) (result, realiseWork events),+      -- outputsSubstitutionTried throws before gaveUpOnSubstitution, so no+      -- input is looked at.+      runTest "a root no cache holds cannot be checked, and nothing is asked about its inputs or built" $+        let (result, events, _) = runCheck Set.empty helloAndGcc [("gcc-out", [])] [] "hello"+         in assertEqual+              "check"+              (Left notValid, [], False)+              (messageOf result, realiseWork events, EvQueried (fakePath "gcc-out") `elem` events)+              `andThen` assertEqual "status" (Left 1) (either (Left . Realise.realiseFailureStatus) Right result),+      runTest "one output of two that no cache holds leaves nothing to check" $+        let (result, events, _) = runCheck Set.empty [fakeNode "pkg" ["pkg-bin", "pkg-lib"] []] [] ["pkg-bin"] "pkg"+         in assertEqual "check" (Left (Realise.OutputsNotValid (fakePath "pkg.drv")), []) (result, realiseWork events),+      runTest "a root that forbids substitutes is not fetched to be checked" $+        let (result, events, _) =+              runCheck Set.empty [fakeNodeWith forbidding "hello" ["hello-out"] []] [("hello-out", [])] [] "hello"+         in assertEqual "check" (Left notValid, []) (messageOf result, events),+      runTest "a substitute that fails stops a check as it stops a build, and under fallback leaves nothing to check" $+        let broken = (fakeWorld [("hello-out", [])] []) {fwBroken = Set.singleton helloOut}+            stopped fallback =+              let (result, events, _) = runCheckIn fallback broken Set.empty helloAndGcc "hello"+               in (result, realiseWork events)+         in assertEqual "no fallback" (Left (Realise.SubstitutesFailed helloDrv), []) (stopped Realise.NoFallback)+              `andThen` assertEqual "fallback" (Left (Realise.OutputsNotValid helloDrv), []) (stopped Realise.BuildFromSource),+      runTest "a cache that cannot be asked stops a check" $+        let unreachable = (fakeWorld [] []) {fwUnreachable = Set.singleton helloOut}+            (result, events, _) = runCheckIn Realise.NoFallback unreachable Set.empty helloAndGcc "hello"+         in assertEqual "check" (Left (Realise.CacheQueryFailed (fakeQueryFailure helloOut)), []) (result, realiseWork events),+      -- The error for outputs that are not valid comes before the inputs,+      -- so the retry 'realise' makes after them never happens: lib is+      -- not built to fill the hole, and hello is asked about once.+      runTest "a substitute with a hole in its closure is not retried after the inputs" $+        let (result, events, _) =+              runCheck Set.empty [fakeNode "hello" ["hello-out"] [("lib", ["lib-out"])], fakeNode "lib" ["lib-out"] []] [("hello-out", ["lib-out"])] [] "hello"+         in assertEqual+              "check"+              (Left (Realise.OutputsNotValid helloDrv), [], 1 :: Int)+              (result, realiseWork events, length [() | EvQueried path <- events, path == helloOut]),+      runTest "a failed input stops the check before the root is built again" $+        let (result, events, _) = runCheck (Set.singleton "gcc-out") helloAndGcc [] ["hello-out"] "hello"+         in assertEqual "check" (Left (Realise.BuildFailed "building gcc-out failed"), []) (result, realiseWork events),+      runTest "a rebuild that fails stops the check with the builder's report, and the status of a failed build" $+        let (result, events, _) = runCheck (Set.singleton "hello-out") helloAndGcc [] ["hello-out", "gcc-out"] "hello"+            failed = Realise.BuildFailed "building hello-out failed"+         in assertEqual "check" (Left failed, [EvChecked "hello-out"]) (result, realiseWork events)+              `andThen` assertEqual "status" 1 (Realise.realiseFailureStatus failed),+      -- haveDerivation reads substitutesAllowed for a valid derivation+      -- too once the mode keeps it from returning early.+      runTest "a check reads allowSubstitutes though the outputs are valid, where a build leaves it unread" $+        let nodes = [fakeNodeWith mistyped "hello" ["hello-out"] []]+            (checked, events, _) = runCheck Set.empty nodes [] ["hello-out"] "hello"+            (built, _, _) = runRealise Set.empty nodes [] ["hello-out"] "hello"+         in assertEqual+              "check"+              (Left ("attribute 'allowSubstitutes' of derivation '" <> helloDrvName <> "' must be a Boolean"), [])+              (messageOf checked, events)+              `andThen` assertEqual "build" (Right ()) built,+      runTest "only a rebuilt output that differs has a status of its own" $+        assertEqual+          "statuses"+          [104, 1, 1, 1, 1, 1, 1, 1]+          ( map+              Realise.realiseFailureStatus+              [ Realise.NotDeterministic helloDrv helloOut Realise.RebuildDiscarded,+                Realise.BuildFailed "",+                Realise.CacheQueryFailed "",+                Realise.SubstitutesFailed helloDrv,+                Realise.InvalidDerivation "",+                Realise.OutputsNotValid helloDrv,+                Realise.MissingDerivation helloDrv,+                Realise.MissingOutputs helloDrv ("dev" :| [])+              ]+          ),+      -- realiseContext asks for one output of a derivation (primops.cc),+      -- and the goal it gets substitutes the outputs it wants alone+      -- (DerivationGoal::haveDerivation).+      runTest "a request for one output of three substitutes it alone, asks about no other, and builds nothing" $+        let (result, events, final) =+              runRequests (fakeWorld [("lib-out", []), ("lib-dev", []), ("lib-doc", [])] []) Set.empty [threeOutputLib] [("lib", ["lib-dev"])]+         in assertEqual+              "requests"+              (Right (), [EvFetched [fakePath "lib-dev"]], [fakePath "lib-dev"], Set.singleton (fakePath "lib-dev"))+              (result, realiseWork events, [path | EvQueried path <- events], fwValid final),+      -- One worker keeps one goal for a derivation, whichever request+      -- reaches it (Worker::makeDerivationGoalCommon in worker.cc at+      -- 2.24.9, Worker::initGoalIfNeeded at 2.36.0).+      runTest "an input two requests share is realised once" $+        let (result, events, _) =+              runRequests+                (fakeWorld [] [])+                Set.empty+                [ fakeNode "left" ["left-out"] [("base", ["base-out"])],+                  fakeNode "right" ["right-out"] [("base", ["base-out"])],+                  fakeNode "base" ["base-out"] []+                ]+                [("left", ["left-out"]), ("right", ["right-out"])]+         in assertEqual+              "requests"+              (Right (), [EvReported Realise.Built "base-out", EvReported Realise.Built "left-out", EvReported Realise.Built "right-out"])+              (result, [event | event@(EvReported _ _) <- events]),+      runTest "two requests for outputs of one derivation are realised as one request for both" $+        let (result, events, _) =+              runRequests+                (fakeWorld [("pkg-bin", []), ("pkg-lib", [])] [])+                Set.empty+                [fakeNode "pkg" ["pkg-bin", "pkg-lib"] []]+                [("pkg", ["pkg-lib"]), ("pkg", ["pkg-bin"])]+         in assertEqual+              "requests"+              (Right (), [EvFetched [fakePath "pkg-bin", fakePath "pkg-lib"]], [Realise.Substituted])+              (result, realiseWork events, [status | EvReported status _ <- events]),+      -- A failed goal ends every other unless keep-going is set+      -- (Worker::removeGoal in worker.cc), and buildPaths then names every+      -- request its worker did not finish (entry-points.cc).+      runTest "a request that fails leaves the ones after it unrealised, and the call names each" $+        let (result, events, _) =+              runRequests+                (fakeWorld [] [])+                (Set.singleton "a-out")+                [fakeNode "a" ["a-out"] [], fakeNode "b" ["b-out"] [], fakeNode "c" ["c-out"] []]+                [("c", ["c-out"]), ("a", ["a-out"]), ("b", ["b-out"])]+            leaving = Realise.FailedLeaving (Realise.BuildFailed "building a-out failed") (fakePath "a.drv") (fakePath "b.drv" :| [fakePath "c.drv"])+         in assertEqual "requests" (Left leaving, []) (result, realiseWork events)+              `andThen` assertEqual+                "message"+                ("build of " <> T.intercalate ", " ["'/nix/store/" <> T.replicate 32 name <> "-" <> name <> ".drv'" | name <- ["a", "b", "c"]] <> " failed")+                (Realise.requestsFailureMessage defaultStoreDir leaving)+              `andThen` assertEqual "status" 1 (Realise.requestsFailureStatus leaving),+      runTest "a request that fails once every other is realised is reported as its own failure" $+        let (result, events, _) =+              runRequests (fakeWorld [] []) (Set.singleton "b-out") [fakeNode "a" ["a-out"] [], fakeNode "b" ["b-out"] []] [("a", ["a-out"]), ("b", ["b-out"])]+         in assertEqual "requests" (Left (Realise.FailedWith (Realise.BuildFailed "building b-out failed")), [EvBuilt "a-out"]) (result, realiseWork events),+      -- The worker's first pass finishes a goal whose outputs are valid+      -- (Worker::run in worker.cc), before any build can fail.+      runTest "a request whose outputs are valid is realised before the others, and a failure does not name it" $+        let (result, events, _) =+              runRequests (fakeWorld [] ["z-out"]) (Set.singleton "a-out") [fakeNode "a" ["a-out"] [], fakeNode "z" ["z-out"] []] [("a", ["a-out"]), ("z", ["z-out"])]+         in assertEqual+              "requests"+              (Left (Realise.FailedWith (Realise.BuildFailed "building a-out failed")), [EvReported Realise.AlreadyValid "z-out"])+              (result, [event | event@(EvReported _ _) <- events]),+      -- c's goal is b's input goal, so it is done when d's build fails.+      runTest "a request realised as an input of one that fails is not named among those it leaves" $+        let (result, events, _) =+              runRequests+                (fakeWorld [] [])+                (Set.singleton "d-out")+                [fakeNode "b" ["b-out"] [("c", ["c-out"]), ("d", ["d-out"])], fakeNode "c" ["c-out"] [], fakeNode "d" ["d-out"] []]+                [("b", ["b-out"]), ("c", ["c-out"])]+         in assertEqual "requests" (Left (Realise.FailedWith (Realise.BuildFailed "building d-out failed")), [EvBuilt "c-out"]) (result, realiseWork events),+      -- A failed query is rethrown out of the worker+      -- (PathSubstitutionGoal::init in substitution-goal.cc at 2.24.9,+      -- PathSubstitutionGoal::substitute at 2.36.0), so buildPaths does+      -- not catch it.+      runTest "a cache that cannot be asked stops the call and is reported as it is, though requests are left" $+        let (result, events, _) =+              runRequests+                (fakeWorld [] []) {fwUnreachable = Set.singleton (fakePath "a-out")}+                Set.empty+                [fakeNode "a" ["a-out"] [], fakeNode "b" ["b-out"] []]+                [("a", ["a-out"]), ("b", ["b-out"])]+         in assertEqual+              "requests"+              (Left (Realise.FailedWith (Realise.CacheQueryFailed (fakeQueryFailure (fakePath "a-out")))), [])+              (result, realiseWork events),+      -- checkPathValidity throws in the worker's first pass+      -- (derivation-goal.cc), before any goal has built.+      runTest "a request for an output its derivation lacks stops the call before any request is realised" $+        let (result, events, _) =+              runRequests (fakeWorld [] []) Set.empty [fakeNode "a" ["a-out"] [], fakeNode "b" ["b-out"] []] [("a", ["a-out"]), ("b", ["b-man"])]+         in assertEqual "requests" (Left (Realise.FailedWith (Realise.MissingOutputs (fakePath "b.drv") ("b-man" :| []))), []) (result, realiseWork events)+              `andThen` assertEqual+                "message"+                (Left ("derivation '/nix/store/" <> T.replicate 32 "b" <> "-b.drv' does not have wanted outputs 'b-man'"))+                (either (Left . Realise.requestsFailureMessage defaultStoreDir) Right result),+      -- Upstream's worker takes its goals by key, the derivation's name+      -- and then its path (DerivationGoal::key in derivation-goal.cc):+      -- here the name and the path disagree.+      runTest "of two requests for outputs their derivations lack, the call reports the one named first, not the one whose path sorts first" $+        let first = StorePath (T.replicate 32 "z") "a.drv"+            second = StorePath (T.replicate 32 "b") "b.drv"+            at path (_, node) = (path, node)+            graph = DepGraph.DepGraph (Map.fromList [at first (fakeNode "a" ["a-out"] []), at second (fakeNode "b" ["b-out"] [])])+            settings = Realise.RealiseSettings Realise.NoFallback Realise.HeedAllowSubstitutes+            (result, _) = runState (Realise.realiseRequests settings (fakeRealiseEffects Set.empty) graph [(second, Set.singleton "b-man"), (first, Set.fromList ["a-man", "a-zed"])]) (fakeWorld [] [])+         in assertEqual "requests" (Left (Realise.FailedWith (Realise.MissingOutputs first ("a-man" :| ["a-zed"])))) result,+      -- A derivation's outputs are kept by output name, dev before out,+      -- where upstream's worker runs their substitution goals by key, the+      -- path's name and then the path (PathSubstitutionGoal::key in+      -- substitution-goal.hh).  An out path's name is the derivation's own,+      -- so it comes first, though its path sorts after dev's here.+      runTest "a derivation's missing outputs are asked of the caches in the order upstream's worker asks, by path name and then path" $+        let out = StorePath (T.replicate 32 "z") "two"+            dev = StorePath (T.replicate 32 "a") "two-dev"+            (drvPath, node) = fakeNode "two" [] []+            twoOutputs = node {DepGraph.dnDerivation = (DepGraph.dnDerivation node) {drvOutputs = [DerivationOutput "dev" dev "" "", DerivationOutput "out" out "" ""]}}+            settings = Realise.RealiseSettings Realise.NoFallback Realise.HeedAllowSubstitutes+            world = (fakeWorld [] []) {fwUnreachable = Set.fromList [out, dev]}+            (result, _) = runState (Realise.realiseRequests settings (fakeRealiseEffects Set.empty) (DepGraph.DepGraph (Map.singleton drvPath twoOutputs)) [(drvPath, Set.fromList ["dev", "out"])]) world+         in assertEqual "requests" (Left (Realise.FailedWith (Realise.CacheQueryFailed (fakeQueryFailure out)))) result,+      -- In name order: b builds z as its input, c is valid, e comes from+      -- the cache, x fails, and y is left; z, asked after x, was realised+      -- before x failed.+      runTest "each request says how it ended, one built as another's input built, and one left after a failure is not there" $+        let nodes = [fakeNode "b" ["b-out"] [("z", ["z-out"])], fakeNode "z" ["z-out"] [], fakeNode "c" ["c-out"] [], fakeNode "e" ["e-out"] [], fakeNode "x" ["x-out"] [], fakeNode "y" ["y-out"] []]+            settings = Realise.RealiseSettings Realise.NoFallback Realise.HeedAllowSubstitutes+            requests = [(fakePath (name <> ".drv"), Set.singleton (name <> "-out")) | name <- ["b", "z", "c", "e", "x", "y"]]+            (outcomes, _) = runState (Realise.realiseEach settings Realise.BuildNormal (fakeRealiseEffects (Set.singleton "x-out")) (DepGraph.DepGraph (Map.fromList nodes)) requests) (fakeWorld [("e-out", [])] ["c-out"])+         in assertEqual+              "outcomes"+              ( Right . Map.fromList $+                  [ (fakePath "b.drv", Realise.RequestRealised Realise.Built),+                    (fakePath "c.drv", Realise.RequestRealised Realise.AlreadyValid),+                    (fakePath "e.drv", Realise.RequestRealised Realise.Substituted),+                    (fakePath "x.drv", Realise.RequestFailed (Realise.BuildFailed "building x-out failed")),+                    (fakePath "z.drv", Realise.RequestRealised Realise.Built)+                  ]+              )+              outcomes,+      runTest "a request built as the input of one that then failed is reported built" $+        let (outcomes, _) = runEach ["x-out"] [fakeNode "x" ["x-out"] [("z", ["z-out"])], fakeNode "z" ["z-out"] []] ["x", "z"]+         in assertEqual "outcomes" (Right (Map.fromList [(fakePath "x.drv", Realise.RequestFailed (Realise.BuildFailed "building x-out failed")), (fakePath "z.drv", Realise.RequestRealised Realise.Built)])) outcomes,+      runTest "an input that fails is the failure of its own request, and the request that needed it is not reported" $+        let (outcomes, _) = runEach ["z-out"] [fakeNode "x" ["x-out"] [("z", ["z-out"])], fakeNode "z" ["z-out"] []] ["x", "z"]+         in assertEqual "outcomes" (Right (Map.singleton (fakePath "z.drv") (Realise.RequestFailed (Realise.BuildFailed "building z-out failed")))) outcomes,+      runTest "an input no request asked for that fails leaves the request that needed it not realised" $+        let (outcomes, _) = runEach ["z-out"] [fakeNode "x" ["x-out"] [("z", ["z-out"])], fakeNode "z" ["z-out"] []] ["x"]+         in assertEqual "outcomes" (Right (Map.singleton (fakePath "x.drv") (Realise.RequestDependencyFailed (fakePath "z.drv") (Realise.BuildFailed "building z-out failed")))) outcomes,+      runTest "a cache that cannot be asked ends the call, as upstream's goal throws then" $+        let settings = Realise.RealiseSettings Realise.NoFallback Realise.HeedAllowSubstitutes+            world = (fakeWorld [] []) {fwUnreachable = Set.singleton (fakePath "x-out")}+            (outcomes, _) = runState (Realise.realiseEach settings Realise.BuildNormal (fakeRealiseEffects Set.empty) (DepGraph.DepGraph (Map.fromList [fakeNode "x" ["x-out"] []])) [(fakePath "x.drv", Set.singleton "x-out")]) world+         in assertEqual "outcome" (Left (Realise.CacheQueryFailed (fakeQueryFailure (fakePath "x-out")))) outcomes,+      runTest "each request checked says it was checked, until one fails" $+        let nodes = [fakeNode "a" ["a-out"] [], fakeNode "b" ["b-out"] [], fakeNode "c" ["c-out"] []]+            settings = Realise.RealiseSettings Realise.NoFallback Realise.HeedAllowSubstitutes+            requests = [(fakePath (name <> ".drv"), Set.singleton (name <> "-out")) | name <- ["c", "b", "a"]]+            (outcomes, _) = runState (Realise.realiseEach settings Realise.BuildCheck (fakeRealiseEffects (Set.singleton "b-out")) (DepGraph.DepGraph (Map.fromList nodes)) requests) (fakeWorld [] ["a-out", "b-out", "c-out"])+         in assertEqual+              "outcomes"+              (Right (Map.fromList [(fakePath "a.drv", Realise.RequestRealised Realise.Checked), (fakePath "b.drv", Realise.RequestFailed (Realise.BuildFailed "building b-out failed"))]))+              outcomes,+      runTest "what realising would take: nothing for a valid path, a substitute with what it references, a build with its inputs, and the rest unknown" $+        let (_, topNode) = fakeNode "top" ["top-out"] []+            (_, libNode) = fakeNode "lib" ["lib-out"] []+            top = (DepGraph.dnDerivation topNode) {drvInputDrvs = Map.singleton (fakePath "lib.drv") ["lib-out"]}+            derivations = Map.fromList [(fakePath "top.drv", top), (fakePath "lib.drv", DepGraph.dnDerivation libNode)]+            effects =+              Realise.MissingEffects+                { Realise.meValid = Realise.seValid fakeSubst,+                  Realise.meDerivation = \path -> pure (maybe (Left ("no derivation at " <> spName path)) Right (Map.lookup path derivations)),+                  Realise.meOffer = Realise.seReferences fakeSubst,+                  Realise.meSizes = const (10, 20)+                }+            wanted = [Realise.WantedOutputs (fakePath "top.drv") Realise.EveryOutput, Realise.WantedPath (fakePath "here"), Realise.WantedPath (fakePath "ghost"), Realise.WantedOutputs (fakePath "absent.drv") Realise.EveryOutput]+            world = fakeWorld [("lib-out", ["dep-out"]), ("dep-out", [])] ["top.drv", "lib.drv", "here"]+            (planned, _) = runState (Realise.planMissing Realise.HeedAllowSubstitutes effects wanted) world+         in assertEqual+              "plan"+              (Right (Realise.MissingPaths (Set.singleton (fakePath "top.drv")) (Set.fromList [fakePath "lib-out", fakePath "dep-out"]) (Set.fromList [fakePath "ghost", fakePath "absent.drv"]) 20 40))+              planned,+      runTest "what realising would take stops at a cache that cannot be asked" $+        let effects =+              Realise.MissingEffects+                { Realise.meValid = Realise.seValid fakeSubst,+                  Realise.meDerivation = \path -> pure (Left ("no derivation at " <> spName path)),+                  Realise.meOffer = Realise.seReferences fakeSubst,+                  Realise.meSizes = const (0, 0)+                }+            world = (fakeWorld [] []) {fwUnreachable = Set.singleton (fakePath "far")}+         in assertEqual "plan" (Left (fakeQueryFailure (fakePath "far"))) (evalState (Realise.planMissing Realise.HeedAllowSubstitutes effects [Realise.WantedPath (fakePath "far")]) world),+      runTest "a call exits with its one failure's status, however it is reported" $+        let differs = Realise.NotDeterministic helloDrv helloOut Realise.RebuildDiscarded+         in assertEqual+              "statuses"+              [104, 104]+              (map Realise.requestsFailureStatus [Realise.FailedWith differs, Realise.FailedLeaving differs helloDrv (fakePath "other.drv" :| [])]),+      -- 'checkLaw', over random graphs of one- and two-output derivations,+      -- caches, valid sets and faults, with each class of case it speaks+      -- about held to a share of the cases generated.+      runTestM "a check builds the root again only once it and its inputs are valid, and never otherwise" $+        property (QC.checkCoverage (QC.forAll genCheckCase checkLaw)),+      -- 'realiseLaw', over the same graphs, where an input is asked for+      -- some of its outputs.+      runTestM "a build waits for the outputs it wants of its inputs and leaves the root's outputs valid" $+        property (QC.checkCoverage (QC.forAll genCheckCase realiseLaw)),+      -- 'loneRequestLaw', over the same graphs.+      runTestM "a request for every output of the root realises it as a build of the root does" $+        property (QC.checkCoverage (QC.forAll genCheckCase loneRequestLaw))+    ]+  where+    forbidding = Map.singleton "allowSubstitutes" ""+    structured = Map.singleton "__json"+    mistyped = structured "{\"allowSubstitutes\":\"no\"}"+    alwaysAllowing = Realise.RealiseSettings Realise.NoFallback Realise.AlwaysAllowSubstitutes+    helloDrv = fakePath "hello.drv"+    helloOut = fakePath "hello-out"+    helloAndGcc = [fakeNode "hello" ["hello-out"] [("gcc", ["gcc-out"])], fakeNode "gcc" ["gcc-out"] []]+    threeOutputLib = fakeNode "lib" ["lib-out", "lib-dev", "lib-doc"] []+    -- app asks lib for lib-dev, and mid, which app also asks for, asks it+    -- for lib-out.+    laterRequest =+      [ fakeNode "app" ["app-out"] [("lib", ["lib-dev"]), ("mid", ["mid-out"])],+        fakeNode "mid" ["mid-out"] [("lib", ["lib-out"])],+        fakeNode "lib" ["lib-out", "lib-dev"] []+      ]+    helloDrvText = "/nix/store/" <> helloDrvName+    notValid = "some outputs of '" <> helloDrvText <> "' are not valid, so checking is not possible"+    messageOf = either (Left . Realise.realiseFailureMessage defaultStoreDir) Right+    -- Where a store's files are when they are not under its logical+    -- directory.+    elsewhere = StoreDir "elsewhere"+    helloDrvName = T.replicate 32 "h" <> "-hello.drv"+    unreadable = "cannot process __json attribute of '" <> helloDrvName <> "': "+    drvWith env = DepGraph.dnDerivation (snd (fakeNodeWith env "hello" ["hello-out"] []))+    heeding env =+      Realise.derivationAttrs helloDrv (drvWith env) >>= Realise.substitutesAllowed Realise.HeedAllowSubstitutes helloDrv+    -- Attributes as either kind of derivation holds them: any JSON value,+    -- or an environment whose allowSubstitutes, when it has one, is any+    -- bytes.+    genAttributes =+      QC.oneof+        [ Realise.AttrsInJson <$> genJson 3,+          Realise.AttrsInEnvironment . maybe Map.empty (Map.singleton "allowSubstitutes" . BS.pack) <$> QC.arbitrary+        ]+    property :: (QC.Testable prop) => prop -> IO TestResult+    property prop = do+      result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} prop+      pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))++-- ---------------------------------------------------------------------------+-- Tests: DependencyGraph (Phase 3, Batch 5)+-- ---------------------------------------------------------------------------++testDepGraph :: IO [Bool]+testDepGraph = do+  putStrLn "dep-graph"+  let mkSP = StorePath+      spA = mkSP "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "a.drv"+      spB = mkSP "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "b.drv"+      spC = mkSP "cccccccccccccccccccccccccccccccccc" "c.drv"+      spD = mkSP "dddddddddddddddddddddddddddddddd" "d.drv"+      baseDrv =+        Derivation+          { drvOutputs = [],+            drvInputDrvs = Map.empty,+            drvInputSrcs = [],+            drvPlatform = X86_64_Linux,+            drvBuilder = "/bin/sh",+            drvArgs = [],+            drvEnv = Map.empty+          }+      -- Single node: A has no deps+      drvA = baseDrv+      -- Linear chain: B depends on C+      drvB = baseDrv {drvInputDrvs = Map.singleton spC ["out"]}+      -- C has no deps+      drvC = baseDrv+      -- Diamond: D depends on B and C, B depends on C+      drvD = baseDrv {drvInputDrvs = Map.fromList [(spB, ["out"]), (spC, ["out"])]}+      -- Cycle: A depends on B, B depends on A+      drvACycle = baseDrv {drvInputDrvs = Map.singleton spB ["out"]}+      drvBCycle = baseDrv {drvInputDrvs = Map.singleton spA ["out"]}+      readSingle _ = Left "not found"+      readChain sp+        | sp == spC = Right drvC+        | otherwise = Left ("unknown drv: " <> spName sp)+      readDiamond sp+        | sp == spB = Right drvB+        | sp == spC = Right drvC+        | otherwise = Left ("unknown drv: " <> spName sp)+      readCycle sp+        | sp == spB = Right drvBCycle+        | sp == spA = Right drvACycle+        | otherwise = Left ("unknown drv: " <> spName sp)+      -- Self-loop: A depends on itself+      drvSelf = baseDrv {drvInputDrvs = Map.singleton spA ["out"]}+      readSelf sp+        | sp == spA = Right drvSelf+        | otherwise = Left ("unknown drv: " <> spName sp)+      -- D and B read from one lookup, as a store holds every .drv.+      readStored sp+        | sp == spD = Right drvD+        | otherwise = readDiamond sp+      rootsGraph roots = runIdentity (DepGraph.buildDepGraphFrom (Identity . readStored) roots)+  sequence+    [ runTest "a graph from several roots reads each root and holds every derivation one of them reaches" $+        assertEqual+          "graph"+          (Right (Map.fromList [(spB, drvB), (spC, drvC), (spD, drvD)]))+          (Map.map DepGraph.dnDerivation . DepGraph.unDepGraph <$> rootsGraph [spD, spB, spD]),+      runTest "a graph from several roots fails on a root that cannot be read" $+        assertEqual "graph" (Left "unknown drv: a.drv") (DepGraph.unDepGraph <$> rootsGraph [spB, spA]),+      runTest "a graph from one root is the graph from that root read" $+        assertEqual "graph" (pureDepGraph readStored drvD spD) (rootsGraph [spD]),+      -- Single node+      runTest "single node graph" $ case pureDepGraph readSingle drvA spA of+        Right (DepGraph.DepGraph g) -> assertEqual "single-size" 1 (Map.size g)+        Left err -> Fail ("unexpected error: " <> err),+      -- Linear chain A to C: topoSort should give [C, A]+      runTest "linear chain topo" $ case pureDepGraph readChain drvB spB of+        Right graph -> case DepGraph.topoSort graph of+          DepGraph.TopoSorted order ->+            case order of+              [first, _] | first == spC -> Pass+              _ -> Fail ("bad order: " <> T.pack (show order))+          DepGraph.TopoCycle cyc -> Fail ("unexpected cycle: " <> T.pack (show cyc))+        Left err -> Fail ("graph build failed: " <> err),+      -- Diamond D to B,C; B to C: topoSort should have C first, D last+      runTest "diamond topo" $ case pureDepGraph readDiamond drvD spD of+        Right graph -> case DepGraph.topoSort graph of+          DepGraph.TopoSorted order ->+            case order of+              [first, _, lastElem] | first == spC, lastElem == spD -> Pass+              _ -> Fail ("bad diamond order: " <> T.pack (show order))+          DepGraph.TopoCycle cyc -> Fail ("unexpected cycle: " <> T.pack (show cyc))+        Left err -> Fail ("graph build failed: " <> err),+      runTest "each edge carries the outputs the dependent's .drv names" $+        let drvWanting = baseDrv {drvInputDrvs = Map.fromList [(spB, ["out", "dev", "out"]), (spC, ["lib"])]}+         in case pureDepGraph readDiamond drvWanting spD of+              Right (DepGraph.DepGraph g) ->+                assertEqual+                  "edges"+                  (Just (Map.fromList [(spB, Set.fromList ["dev", "out"]), (spC, Set.singleton "lib")]), Just (Map.singleton spC (Set.singleton "out")))+                  (DepGraph.dnDeps <$> Map.lookup spD g, DepGraph.dnDeps <$> Map.lookup spB g)+              Left err -> Fail ("graph build failed: " <> err),+      -- transitiveDeps+      runTest "transitiveDeps diamond" $ case pureDepGraph readDiamond drvD spD of+        Right graph ->+          let deps = DepGraph.transitiveDeps graph spD+           in if Set.size deps == 2 && Set.member spB deps && Set.member spC deps+                then Pass+                else Fail ("bad transitive deps: " <> T.pack (show deps))+        Left err -> Fail ("graph build failed: " <> err),+      -- directDeps+      runTest "directDeps diamond" $ case pureDepGraph readDiamond drvD spD of+        Right graph ->+          let deps = DepGraph.directDeps graph spD+           in assertEqual "direct-count" 2 (length deps)+        Left err -> Fail ("graph build failed: " <> err),+      -- Missing .drv causes failure+      runTest "missing drv fails" $ case pureDepGraph readSingle drvB spB of+        Left _ -> Pass+        Right _ -> Fail "expected failure for missing drv",+      -- Single node topoSort+      runTest "single node topoSort" $ case pureDepGraph readSingle drvA spA of+        Right graph -> case DepGraph.topoSort graph of+          DepGraph.TopoSorted [x] -> assertEqual "single-topo" spA x+          other -> Fail ("unexpected topo result: " <> T.pack (show other))+        Left err -> Fail ("graph build failed: " <> err),+      -- buildDepGraph with mock for cycle detection+      -- (Cycle detection happens at topoSort level, not buildDepGraph)+      runTest "cycle detection" $ case pureDepGraph readCycle drvACycle spA of+        Right graph -> case DepGraph.topoSort graph of+          DepGraph.TopoCycle _ -> Pass+          -- A "sorted" cyclic graph means Kahn's silently dropped the+          -- cycle: buildWithDeps would then loop or build with unbuilt+          -- inputs.+          DepGraph.TopoSorted order ->+            Fail ("cyclic graph topo-sorted as " <> T.pack (show (length order)) <> " nodes")+        -- A loud rejection at graph-build time also counts as detection.+        Left _ -> Pass,+      -- A root that depends on itself: the walk marks the root visited+      -- on enqueue, so it terminates - and per contract the result+      -- excludes the root, leaving nothing.+      runTestM "transitiveDeps terminates on a self-loop" $ do+        outcome <-+          timeout walkWatchdogMicros $+            evaluate $ case pureDepGraph readSelf drvSelf spA of+              Left _ -> Nothing+              Right graph -> Just $! DepGraph.transitiveDeps graph spA+        pure $ case outcome of+          Nothing -> Fail "did not terminate on a self-loop"+          Just Nothing -> Fail "graph build failed"+          Just (Just deps) -> assertEqual "self-loop deps" Set.empty deps,+      -- A two-node cycle already terminated; pin that the root stays+      -- excluded from its own transitive closure.+      runTestM "transitiveDeps two-node cycle excludes the root" $ do+        outcome <-+          timeout walkWatchdogMicros $+            evaluate $ case pureDepGraph readCycle drvACycle spA of+              Left _ -> Nothing+              Right graph -> Just $! DepGraph.transitiveDeps graph spA+        pure $ case outcome of+          Nothing -> Fail "did not terminate on a cycle"+          Just Nothing -> Fail "graph build failed"+          Just (Just deps) -> assertEqual "cycle deps" (Set.singleton spB) deps+    ]
+ test/Test/Store.hs view

5245 lines of diff, too many to show among the others: show this file

+ test/Test/StoreChoice.hs view
@@ -0,0 +1,400 @@+{-# LANGUAGE CPP #-}++-- | Which store a command uses ("Nix.Daemon.StoreChoice"): what a store+-- reference names, which of the three sources of one wins, what a daemon+-- is sent of it and how each command's @--store@ sets the setting, which+-- are pure; the choice @auto@ makes over a recording probe; and the two+-- questions it asks of the machine, whether this process can keep a+-- store's state directory ('probeStoreWriting') and whether anything is at+-- the daemon's address ('addressPresence'), asked of real directories,+-- sockets and pipes.+module Test.StoreChoice+  ( testStoreChoice,+    testStoreChoiceIO,+  )+where++import Control.Monad.State.Strict (State, modify', runState)+import DaemonLink (daemonAddress)+import qualified Data.ByteString as BS+import qualified Data.Map.Strict as Map+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Nix.Cli.Args (CliOpts (..), parseArgs, storeFlagOf)+import Nix.Daemon.ClientStore (DaemonAddress (..), daemonStoreName)+import Nix.Daemon.Dial (AddressPresence (..), addressPresence)+import qualified Nix.Daemon.Listen as Listen+import Nix.Daemon.StoreChoice (StoreChoice (..), StoreFlag (..), StoreProbe (..), StoreTarget (..), chooseStore, parseStoreTarget, parseStoreTargetOn, storeOverride, storeReference)+import Nix.Eval.Policy (PathRules (..))+import Nix.Store.Access (StoreWriting (..), probeStoreWriting)+import System.Directory (createDirectoryIfMissing, getTemporaryDirectory)+import System.FilePath ((</>))+import qualified System.Info as SI+import Test.Daemon (withSocketDaemon)+import Test.Harness (TestResult (..), allFailures, assertEqual, forceRemoveIfExists, runTest, runTestM)+import qualified Test.QuickCheck as QC++#if defined(mingw32_HOST_OS)+import DirDacl (processUserSid)+import Nix.Store.Access (createStateDirectory)+import Test.WindowsSandbox (makeDirectory)+#else+import Control.Exception (IOException, bracket_, try)+import qualified Data.ByteString.Char8 as BS8+import System.IO.Error (ioeGetErrorString)+import System.Posix.Files (createSymbolicLink, setFileMode)+import System.Posix.User (getEffectiveUserID)+#endif++-- ---------------------------------------------------------------------------+-- What a store reference names, and the choice+-- ---------------------------------------------------------------------------++-- | A question the machine was asked, as the recording probe notes it.+data Asked = AskedWriting | AskedPresence !BS.ByteString+  deriving (Eq, Show)++-- | A probe that answers as it is told and notes each question, the latest+-- first.+recordingProbe :: StoreWriting -> AddressPresence -> StoreProbe (State [Asked])+recordingProbe writing presence =+  StoreProbe+    { probeWriting = modify' (AskedWriting :) >> pure writing,+      probePresence = \address -> modify' (AskedPresence address :) >> pure presence+    }++-- | The daemon's default address, in these tests.+defaultAddress :: BS.ByteString+defaultAddress = "/run/default-socket"++-- | What 'chooseStore' answers over a recording probe, and what it asked.+choose :: StoreWriting -> AddressPresence -> StoreTarget -> (StoreChoice, [Asked])+choose writing presence target = runState (chooseStore (recordingProbe writing presence) defaultAddress target) []++-- | The pure part: the references, their precedence and the choice.+testStoreChoice :: IO [Bool]+testStoreChoice = do+  putStrLn "daemon/store-choice"+  sequence+    [ runTest "--store, the store setting and NIX_REMOTE name auto, the daemon, a socket, the local store or a directory, as upstream reads them" $+        allFailures+          [ assertEqual "nothing" (Right AutoStore) (posix ""),+            assertEqual "auto" (Right AutoStore) (posix "auto"),+            assertEqual "daemon" (Right (DaemonSocket Nothing)) (posix "daemon"),+            assertEqual "local" (Right (LocalStore Nothing)) (posix "local"),+            assertEqual "unix:// alone is the default socket" (Right (DaemonSocket Nothing)) (posix "unix://"),+            assertEqual "a socket" (Right (DaemonSocket (Just "/run/socket"))) (posix "unix:///run/socket"),+            assertEqual "percent-decoded" (Right (DaemonSocket (Just "/run/my socket"))) (posix "unix:///run/my%20socket"),+            assertEqual "a decoded slash splits" (Right (DaemonSocket (Just "/run/a/b"))) (posix "unix:///run/a%2Fb"),+            assertEqual "repeated separators and . fold" (Right (DaemonSocket (Just "/run/b"))) (posix "unix:///run//a/./../b"),+            assertEqual ".. at the root is dropped" (Right (DaemonSocket (Just "/b"))) (posix "unix:///../b"),+            assertEqual "a directory" (Right (LocalStore (Just "/srv/store"))) (posix "/srv/store"),+            assertEqual "a relative directory in the working directory" (Right (LocalStore (Just "./store"))) (posix "./store"),+            assertEqual "a relative directory" (Right (LocalStore (Just "srv/store"))) (posix "srv/store"),+            assertEqual "a path with a colon" (Right (LocalStore (Just "/srv/a:b"))) (posix "/srv/a:b")+          ],+      runTest "a word with no path separator that is none of the named forms is refused as a store that cannot be parsed" $+        allFailures+          [ assertEqual "a word" (Left "Cannot parse Nix store 'store'") (posix "store"),+            assertEqual "a misspelt daemon" (Left "Cannot parse Nix store 'daemno'") (posix "daemno"),+            assertEqual "a scheme with nothing after it" (Left "Cannot parse Nix store 'unix'") (posix "unix"),+            assertEqual "the names are case sensitive" (Left "Cannot parse Nix store 'Auto'") (posix "Auto"),+            assertEqual "a backslash separates nothing on POSIX" (Left "Cannot parse Nix store 'C:\\nix\\store'") (posix "C:\\nix\\store"),+            assertEqual "a word on Windows" (Left "Cannot parse Nix store 'store'") (windows "store")+          ],+      runTest "unix: with one slash is the socket, and a literal space in an address is refused, as upstream reads them" $+        allFailures+          [ assertEqual "one slash" (Right (DaemonSocket (Just "/run/socket"))) (posix "unix:/run/socket"),+            assertEqual "no path" (Right (DaemonSocket Nothing)) (posix "unix:"),+            assertEqual "a space in the path" (Left "Cannot parse Nix store 'unix:///run/my socket'") (posix "unix:///run/my socket"),+            assertEqual "a space in the authority" (Left "Cannot parse Nix store 'unix://my socket'") (posix "unix://my socket")+          ],+      runTest "a relative socket path is refused in upstream's words" $+        assertEqual "relative" (Left "not an absolute path: \"run/socket\"") (posix "unix://run/socket"),+      runTest "a store URL's settings and any other scheme are refused" $+        allFailures+          [ assertEqual "a query on daemon" (Left "store settings in a store's URL are not supported by nova-nix: 'daemon?trusted=1'") (posix "daemon?trusted=1"),+            assertEqual "a query on a socket" (Left "store settings in a store's URL are not supported by nova-nix: 'unix:///run/socket?x=y'") (posix "unix:///run/socket?x=y"),+            assertEqual "a query on a directory" (Left "store settings in a store's URL are not supported by nova-nix: '/srv/store?x=y'") (posix "/srv/store?x=y"),+            assertEqual "another scheme" (Left "store 'ssh://host' is not one nova-nix opens: it takes auto, daemon, local, unix://PATH or a store directory") (posix "ssh://host"),+            assertEqual "a file URL" (Left "store 'file:///srv/cache' is not one nova-nix opens: it takes auto, daemon, local, unix://PATH or a store directory") (posix "file:///srv/cache")+          ],+      runTest "on Windows a unix:// address is the pipe's path as written, and a drive path or an extended-length path is a directory" $+        allFailures+          [ assertEqual "a pipe" (Right (DaemonSocket (Just "\\\\.\\pipe\\nova-nix-daemon"))) (windows "unix://\\\\.\\pipe\\nova-nix-daemon"),+            assertEqual "no address" (Right (DaemonSocket Nothing)) (windows "unix://"),+            assertEqual "a drive path" (Right (LocalStore (Just "C:\\nix\\store"))) (windows "C:\\nix\\store"),+            assertEqual "a drive path with a slash, which is no URL" (Right (LocalStore (Just "C:/nix/store"))) (windows "C:/nix/store"),+            assertEqual "an extended-length path, whose prefix holds a ?" (Right (LocalStore (Just "\\\\?\\C:\\nix\\store"))) (windows "\\\\?\\C:\\nix\\store"),+            assertEqual "an extended-length UNC path" (Right (LocalStore (Just "\\\\?\\UNC\\host\\share"))) (windows "\\\\?\\UNC\\host\\share"),+            assertEqual "a relative path with a backslash" (Right (LocalStore (Just "srv\\store"))) (windows "srv\\store"),+            assertEqual "a query on a drive path" (Left "store settings in a store's URL are not supported by nova-nix: 'C:\\nix\\store?x=y'") (windows "C:\\nix\\store?x=y"),+            assertEqual "daemon" (Right (DaemonSocket Nothing)) (windows "daemon"),+            assertEqual "an address is not percent-decoded" (Right (DaemonSocket (Just "\\\\.\\pipe\\a%20b"))) (windows "unix://\\\\.\\pipe\\a%20b")+          ],+      runTest "--store overrides the store setting, which overrides NIX_REMOTE" $+        allFailures+          [ assertEqual "all three" "flag" (storeReference (Just "flag") (Just "setting") (Just "environment")),+            assertEqual "setting and environment" "setting" (storeReference Nothing (Just "setting") (Just "environment")),+            assertEqual "environment" "environment" (storeReference Nothing Nothing (Just "environment")),+            assertEqual "none" "auto" (storeReference Nothing Nothing Nothing),+            assertEqual "an empty setting overrides the environment" "" (storeReference Nothing (Just "") (Just "daemon")),+            assertEqual "an empty flag overrides both" "" (storeReference (Just "") (Just "daemon") (Just "local")),+            assertEqual "an empty setting reads as auto" (Right AutoStore) (parseStoreTarget (storeReference Nothing (Just "") (Just "daemon")))+          ],+      runTest "a daemon is told the store setting when a source set it, rendered as the setting renders it" $+        allFailures+          [ assertEqual "NIX_REMOTE only gives the setting's default" none (sent ValueFlag Nothing Nothing (Just "daemon")),+            assertEqual "nothing set" none (sent ValueFlag Nothing Nothing Nothing),+            assertEqual "an empty setting is auto" (told "auto") (sent ValueFlag Nothing (Just "") Nothing),+            assertEqual "auto" (told "auto") (sent ValueFlag Nothing (Just "auto") Nothing),+            assertEqual "daemon" (told "daemon") (sent ValueFlag Nothing (Just "daemon") Nothing),+            assertEqual "local" (told "local") (sent ValueFlag Nothing (Just "local") Nothing),+            assertEqual "the default socket" (told "unix://") (sent ValueFlag Nothing (Just "unix://") Nothing),+            assertEqual "a socket with one slash is rendered with three" (told "unix:///run/socket") (sent ValueFlag Nothing (Just "unix:/run/socket") Nothing),+            assertEqual "a socket's path is not folded" (told "unix:///run//a/../b") (sent ValueFlag Nothing (Just "unix:///run//a/../b") Nothing),+            assertEqual "a socket's path keeps its encoding" (told "unix:///run/my%20socket") (sent ValueFlag Nothing (Just "unix:///run/my%20socket") Nothing),+            assertEqual "a directory is opened directly, so nothing is sent" none (sent ValueFlag Nothing (Just "/srv/store") Nothing),+            assertEqual "a reference nova-nix does not open is refused, as it is where the store is chosen" (Left "store 'ssh://host' is not one nova-nix opens: it takes auto, daemon, local, unix://PATH or a store directory") (sent ValueFlag Nothing (Just "ssh://host") Nothing),+            assertEqual "a pipe on Windows is as written" (told "unix://\\\\.\\pipe\\x") (storeOverride WindowsPaths ValueFlag Nothing (Just "unix://\\\\.\\pipe\\x") Nothing)+          ],+      runTest "a value flag replaces the setting's value where a source set it, and a setting flag sets the setting itself" $+        allFailures+          [ assertEqual "a value flag over a setting" (told "daemon") (sent ValueFlag (Just "daemon") (Just "local") Nothing),+            assertEqual "an empty value flag over a setting" (told "auto") (sent ValueFlag (Just "") (Just "local") Nothing),+            assertEqual "a value flag alone sends nothing" none (sent ValueFlag (Just "daemon") Nothing Nothing),+            assertEqual "a value flag and NIX_REMOTE send nothing" none (sent ValueFlag (Just "daemon") Nothing (Just "local")),+            assertEqual "a setting flag alone is sent" (told "daemon") (sent SettingFlag (Just "daemon") Nothing Nothing),+            assertEqual "a setting flag over NIX_REMOTE is sent" (told "unix:///run/socket") (sent SettingFlag (Just "unix:///run/socket") Nothing (Just "local")),+            assertEqual "an empty setting flag is auto" (told "auto") (sent SettingFlag (Just "") Nothing Nothing),+            assertEqual "a setting flag over a setting" (told "local") (sent SettingFlag (Just "local") (Just "daemon") Nothing),+            assertEqual "a setting flag naming a directory sends nothing" none (sent SettingFlag (Just "/srv/store") Nothing Nothing),+            assertEqual "a setting flag, no flag given, and NIX_REMOTE send nothing" none (sent SettingFlag Nothing Nothing (Just "daemon"))+          ],+      runTest "--store sets the store setting itself for the commands that model upstream's nix command, and gives it a value only for the rest" $+        allFailures+          [ assertEqual (T.pack (unwords args)) (Right flag) (storeFlagOf . optCommand <$> parseArgs args)+          | (args, flag) <-+              [ (["develop", "--expr", "1"], SettingFlag),+                (["print-dev-env", "--expr", "1"], SettingFlag),+                (["profile", "add", "--expr", "1"], SettingFlag),+                (["profile", "remove", "hello"], SettingFlag),+                (["eval", "--expr", "1"], ValueFlag),+                (["build", "--expr", "1"], ValueFlag),+                (["profile", "list"], ValueFlag),+                (["store", "gc"], ValueFlag)+              ]+          ],+      runTest "auto opens the store when it can be written, goes through the daemon when it cannot and the socket is there, and asks nothing for a store named" $+        allFailures+          [ assertEqual "writable" (DirectStore Nothing, [AskedWriting]) (choose StoreWritable AddressPresent AutoStore),+            assertEqual "not writable, a socket" (ThroughDaemon (DefaultSocket defaultAddress), [AskedPresence defaultAddress, AskedWriting]) (choose StoreNotWritable AddressPresent AutoStore),+            assertEqual "not writable, no socket" (DirectStore Nothing, [AskedPresence defaultAddress, AskedWriting]) (choose StoreNotWritable AddressAbsent AutoStore),+            assertEqual "daemon" (ThroughDaemon (DefaultSocket defaultAddress), []) (choose StoreNotWritable AddressAbsent (DaemonSocket Nothing)),+            assertEqual "a socket" (ThroughDaemon (NamedSocket "/run/other"), []) (choose StoreWritable AddressAbsent (DaemonSocket (Just "/run/other"))),+            assertEqual "a socket at the default's path is the default" (ThroughDaemon (DefaultSocket defaultAddress), []) (choose StoreWritable AddressAbsent (DaemonSocket (Just defaultAddress))),+            assertEqual "local" (DirectStore Nothing, []) (choose StoreNotWritable AddressPresent (LocalStore Nothing)),+            assertEqual "a directory" (DirectStore (Just "/srv/store"), []) (choose StoreNotWritable AddressPresent (LocalStore (Just "/srv/store")))+          ],+      runTestM "the store setting a daemon is sent reads back as itself, so sending it again changes nothing" $+        if SI.os == "mingw32"+          then pure Pass+          else do+            result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} (QC.forAll absolutePath renderedSettingIsStable)+            pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result))),+      runTestM "a unix:// path read back from the name a store is given is the path" $+        if SI.os == "mingw32"+          then pure Pass+          else do+            result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} (QC.forAll absolutePath namedPathRoundTrips)+            pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))+    ]+  where+    posix = parseStoreTargetOn PosixPaths+    windows = parseStoreTargetOn WindowsPaths+    sent = storeOverride PosixPaths+    none = Right Map.empty+    told = Right . Map.singleton "store"++-- | An absolute POSIX path of any bytes a file name may hold, its+-- components none of them empty, @.@ or @..@, which a path folds.+absolutePath :: QC.Gen BS.ByteString+absolutePath = BS.cons slash . BS.intercalate (BS.singleton slash) <$> QC.listOf1 component+  where+    slash = 0x2f+    component = (BS.pack <$> QC.listOf1 byte) `QC.suchThat` (`notElem` [".", ".."])+    byte = QC.choose (1, 255) `QC.suchThat` (/= slash)++-- | The property: the store a path is named, as a message names it, reads+-- back as the daemon at that path.+namedPathRoundTrips :: BS.ByteString -> QC.Property+namedPathRoundTrips path =+  QC.counterexample (T.unpack name) (parseStoreTargetOn PosixPaths (TE.encodeUtf8 name) QC.=== Right (DaemonSocket (Just path)))+  where+    name = daemonStoreName (NamedSocket path)++-- | The property: the setting a daemon is sent for a socket, read as a+-- setting again, is sent as it was.+renderedSettingIsStable :: BS.ByteString -> QC.Property+renderedSettingIsStable path =+  QC.counterexample (show (first, second)) (first QC.=== second)+  where+    first = storeOverride PosixPaths ValueFlag Nothing (Just (TE.encodeUtf8 (daemonStoreName (NamedSocket path)))) Nothing+    second = first >>= maybe (Right Map.empty) (\rendered -> storeOverride PosixPaths ValueFlag Nothing (Just rendered) Nothing) . Map.lookup "store"++-- ---------------------------------------------------------------------------+-- What the machine is asked+-- ---------------------------------------------------------------------------++-- | The two questions @auto@ asks of the machine, asked of real+-- directories, sockets and pipes.+testStoreChoiceIO :: IO [Bool]+testStoreChoiceIO = do+  putStrLn "daemon/store-choice-machine"+  temporary <- getTemporaryDirectory+  let root = temporary </> "nova-nix-test-store-choice"+  sequence $+    [ runTestM "a store's state directory this process can write is writable, and one it cannot, or none, is not" $+        withRoot root (writingTests root),+      runTestM "a socket's path is present when anything is there and absent otherwise" $+        withSocketDaemon Listen.DefaultTrust id $ \_ address _ -> do+          listening <- addressPresence address+          unused <- daemonAddress (root </> "none")+          absent <- traverse addressPresence unused+          pure $+            allFailures+              [ assertEqual "a daemon's address" AddressPresent listening,+                assertEqual "an address nothing listens at" (Just AddressAbsent) absent+              ]+    ]+      ++ presenceTests root++-- | Run a test in a directory of its own, removed before and after.+withRoot :: FilePath -> IO a -> IO a+withRoot root action = do+  forceRemoveIfExists root+  createDirectoryIfMissing True root+  result <- action+  forceRemoveIfExists root+  pure result++#if defined(mingw32_HOST_OS)++-- | A state directory made as nova-nix makes one is writable, one that+-- grants this user only read is not, and a missing one is not; and of two+-- state directories this user may change, the one under a directory that+-- Authenticated Users may change is not writable, since no other process+-- may open a store whose way to it another account could alter, and the+-- one under a directory only this user may change is.+writingTests :: FilePath -> IO TestResult+writingTests root = do+  createStateDirectory made+  sid <- processUserSid >>= maybe (ioError (userError "the process's user has no SID")) pure+  makeDirectory readOnly ("D:P(A;;FR;;;" <> sid <> ")")+  makeStateDirectoryUnder sid keptByUser (fullControlFor sid)+  makeStateDirectoryUnder sid sharedWithUsers (fullControlFor sid <> fullControlFor "AU")+  writable <- probeStoreWriting made+  denied <- probeStoreWriting readOnly+  missing <- probeStoreWriting (root </> "missing")+  trusted <- probeStoreWriting (keptByUser </> ".nova-nix")+  distrusted <- probeStoreWriting (sharedWithUsers </> ".nova-nix")+  pure $+    allFailures+      [ assertEqual "made by nova-nix" StoreWritable writable,+        assertEqual "read only" StoreNotWritable denied,+        assertEqual "missing" StoreNotWritable missing,+        assertEqual "under a directory only this user may change" StoreWritable trusted,+        assertEqual "under a directory Authenticated Users may change" StoreNotWritable distrusted+      ]+  where+    made = root </> "made" </> ".nova-nix"+    readOnly = root </> "read-only"+    keptByUser = root </> "kept-by-user"+    sharedWithUsers = root </> "shared-with-users"+    -- An entry giving the account, a SID or an SDDL alias, full control,+    -- passed down.+    fullControlFor account = "(A;OICI;FA;;;" <> account <> ")"+    -- A directory with the entries given and, in it, a state directory this+    -- user alone may use.  The DACLs are protected, so nothing the test's+    -- own root grants is passed down.+    makeStateDirectoryUnder sid parent entries = do+      makeDirectory parent ("D:P" <> entries)+      makeDirectory (parent </> ".nova-nix") ("D:P" <> fullControlFor sid)++-- | A path under a file or one that cannot be looked at is a POSIX+-- matter: a pipe's name has neither.+presenceTests :: FilePath -> [IO Bool]+presenceTests _ = []++#else++-- | Whether this process is root, who is let through whatever the modes+-- say.+runsAsRoot :: IO Bool+runsAsRoot = (== 0) <$> getEffectiveUserID++-- | A state directory this user owns with the usual modes is writable, one+-- that has lost its write mode is not, and a missing one is not.  Root is+-- let through whatever the modes say, so for root the mode is not tried.+writingTests :: FilePath -> IO TestResult+writingTests root = do+  createDirectoryIfMissing True stateDir+  setFileMode stateDir 0o755+  writable <- probeStoreWriting stateDir+  missing <- probeStoreWriting (root </> "missing" </> ".nova-nix")+  asRoot <- runsAsRoot+  denied <-+    if asRoot+      then pure StoreNotWritable+      else bracket_ (setFileMode stateDir 0o555) (setFileMode stateDir 0o755) (probeStoreWriting stateDir)+  pure $+    allFailures+      [ assertEqual "writable" StoreWritable writable,+        assertEqual "missing" StoreNotWritable missing,+        assertEqual "without the write mode" StoreNotWritable denied+      ]+  where+    stateDir = root </> ".nova-nix"++-- | A file is present, a path under one and a missing one are absent, and+-- a path that cannot be looked at, as one under a directory this user may+-- not search, is a failure and not an answer.+presenceTests :: FilePath -> [IO Bool]+presenceTests root =+  [ runTestM "a file is present, and a path under a file, or nothing, is absent" $+      withRoot root $ do+        writeFile file ""+        present <- addressPresence (BS8.pack file)+        under <- addressPresence (BS8.pack (file </> "child"))+        missing <- addressPresence (BS8.pack (root </> "missing"))+        pure $+          allFailures+            [ assertEqual "a file" AddressPresent present,+              assertEqual "under a file" AddressAbsent under,+              assertEqual "missing" AddressAbsent missing+            ],+    runTestM "a link is present whatever it leads to, as it is looked at and not followed" $+      withRoot root $ do+        createSymbolicLink (root </> "nowhere") link+        dangling <- addressPresence (BS8.pack link)+        pure (assertEqual "a link to nothing" AddressPresent dangling),+    runTestM "a path that cannot be looked at is a failure in upstream's words, not an answer" $+      withRoot root $ do+        asRoot <- runsAsRoot+        if asRoot+          then pure Pass+          else do+            createDirectoryIfMissing True closed+            tried <- bracket_ (setFileMode closed 0o000) (setFileMode closed 0o755) (tryIO (addressPresence (BS8.pack (closed </> "socket"))))+            pure $ case tried of+              Left failure -> assertEqual "the failure" ("getting status of \"" <> closed </> "socket\": Permission denied") (ioeGetErrorString failure)+              Right answer -> Fail ("answered " <> T.pack (show answer))+  ]+  where+    file = root </> "file"+    link = root </> "link"+    closed = root </> "closed"+    tryIO :: IO a -> IO (Either IOException a)+    tryIO = try++#endif
+ test/Test/Substituter.hs view
@@ -0,0 +1,2401 @@+{-# LANGUAGE LambdaCase #-}++-- | Tests of substitution from binary caches.+module Test.Substituter+  ( testSubstituter,+    testSubstituterRetry,+    testStatedContentAddress,+    testVerifySigs,+    testNarInfoValidation,+  )+where++import Control.Exception (ErrorCall (..), SomeAsyncException (..), SomeException, asyncExceptionToException, bracket, bracket_, fromException, throwIO, try)+import Control.Monad (void)+import Control.Monad.State.Strict (evalStateT)+import qualified Data.ByteString as BS+import Data.Functor ((<&>))+import Data.IORef (atomicModifyIORef', newIORef, readIORef)+import Data.List.NonEmpty (NonEmpty (..))+import qualified Data.Map.Strict as Map+import Data.Maybe (catMaybes, fromMaybe)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import GHC.IO.Encoding (getFileSystemEncoding, mkTextEncoding, setFileSystemEncoding)+import HttpFixture (Reply (..), httpResponse, withHttpServer)+import qualified Network.HTTP.Client as HTTP+import Nix.Builder (BuildConfig (..), BuildResult (..), buildWithDeps, defaultBuildConfig, substitutePaths)+import Nix.Daemon.Protocol (ContentAddress, ContentAddressMethod (..), contentAddressFromParts, parseContentAddress, parseSignature, renderContentAddress)+import Nix.Derivation (Derivation (..), DerivationOutput (..), currentPlatform)+import Nix.Environment (argumentBytes)+import Nix.Hash (FileIngestionMethod (..), makeSourcePath, moduloHashFinalize, moduloHashInit, moduloHashUpdate, rawHashWithAlgo)+import Nix.Http (FetchRetryPolicy (..), RetryEffects (..), defaultFetchRetryPolicy, ioRetryEffects)+import Nix.Logger (Level (..), plainLogger)+import qualified Nix.Realise as Realise+import Nix.Store (ArchiveEnd (..), SignatureRequirement (..), Store (..), caseHackDiskNames, closeStore, isValid, newNarUnpackSink, onDiskNameKey, openStore, releasePathLock, sinkNarStream, tryAcquirePathLock, unpackNarEntry, writeDrv)+import Nix.Store.CaseSensitive (CaseSensitivity (..), probeCaseSensitivity, trySetCaseSensitiveDir, volumeCaseHack)+import Nix.Store.DB (PathInfo (..), PathRegistration (..), Ultimate (..), queryPathInfo)+import qualified Nix.Store.ExecBit as ExecBit+import Nix.Store.Metadata (executablePermissions, readOnlyPermissions)+import Nix.Store.Path (StoreDir (..), defaultStoreDir, storePathToFilePath, storePathToText)+import Nix.Store.Path.Internal (StorePath (..))+import qualified Nix.Substituter as Subst+import qualified NovaCache.Base32 as Nix32+import qualified NovaCache.Base64 as B64+import qualified NovaCache.Hash as CHash+import qualified NovaCache.NAR as NAR+import qualified NovaCache.NarInfo as NarInfo+import qualified NovaCache.Signing as Signing+import qualified NovaCache.Zstd as CZstd+import System.Directory (createDirectoryIfMissing, doesDirectoryExist, getPermissions, getTemporaryDirectory, removeDirectoryRecursive)+import qualified System.Directory as Dir+import System.FilePath ((</>))+import qualified System.Info as SI+import Test.Harness (TestResult (..), andThen, assertEqual, assertLeft, canonicalAs, chunkReader, forceRemoveIfExists, narInfoRequest, narRequest, offeredSubstitute, offeredThenFetched, posixOnlyEntries, quotedAsCxx, runTest, runTestM, servedPaths, sigTestKeyText, sigTestSecretKeyFile, sigTestWrongKeyText, signedTestNarInfo, testLogger)+import qualified Test.QuickCheck as QC++-- ---------------------------------------------------------------------------+-- Tests: Substituter (Phase 3, Batch 6)+-- ---------------------------------------------------------------------------++-- | Drain a chunk source to its byte count - the shape of a streaming+-- consumer, for tests that only care whether the pipeline fails.+drainChunkSource :: IO BS.ByteString -> IO (Either Subst.AttemptFailure Int)+drainChunkSource pull = go 0+  where+    go n = do+      chunk <- pull+      if BS.null chunk+        then pure (Right n)+        else let total = n + BS.length chunk in total `seq` go total++testSubstituter :: IO [Bool]+testSubstituter = do+  putStrLn "substituter"+  -- Every tree this group materializes under the temp directory keys+  -- sibling names the way a store on that volume would.+  tmpSensitivity <- tempCaseSensitivity+  sequence+    [ -- readBodyCapped: the client-side body cap (mirror of the server's+      -- readBodyLimited).  A body reader is just IO ByteString yielding+      -- chunks then empty.+      runTestM "readBodyCapped concatenates under the cap" $ do+        reader <- chunkReader ["abc", "def", "g"]+        body <- Subst.readBodyCapped 10 reader+        pure (assertEqual "under cap" (Just "abcdefg") body),+      runTestM "readBodyCapped allows exactly the cap" $ do+        reader <- chunkReader ["abcde", "fghij"]+        body <- Subst.readBodyCapped 10 reader+        pure (assertEqual "at cap" (Just "abcdefghij") body),+      runTestM "readBodyCapped aborts past the cap" $ do+        reader <- chunkReader ["abcdef", "ghijkl"]+        body <- Subst.readBodyCapped 10 reader+        pure (assertEqual "over cap" Nothing body),+      -- decompressorFor decides support from the narinfo's declared+      -- values alone, so unsupported compression rejects before any+      -- NAR download; xz resolves a bounded decompressor.+      runTest "decompressorFor xz resolves" $+        case Subst.decompressorFor 1024 "xz" of+          Right _ -> Pass+          Left err -> Fail ("xz rejected: " <> err),+      runTestM "decompressorFor none is identity" $+        case Subst.decompressorFor 5 "none" of+          Right decompress -> assertEqual "identity" (Right "bytes") <$> decompress "bytes"+          Left err -> pure (Fail ("expected none to be supported, got: " <> err)),+      -- verifyNarSize: the declared NarSize is a claim that flows into+      -- the store DB, so it must equal the downloaded byte count.+      runTest "verifyNarSize accepts matching size" $+        assertEqual+          "narsize-match"+          (Right ())+          (Subst.verifyNarSize ((sampleNarInfo sampleNarHash) {NarInfo.niNarSize = toInteger (BS.length sampleNarBytes)}) sampleNarBytes),+      runTest "verifyNarSize rejects mismatched size" $+        case Subst.verifyNarSize ((sampleNarInfo sampleNarHash) {NarInfo.niNarSize = toInteger (BS.length sampleNarBytes) + 1}) sampleNarBytes of+          Left err | "size mismatch" `T.isInfixOf` err -> Pass+          other -> Fail ("expected size mismatch, got: " <> T.pack (show other)),+      -- decompressNar: "none" passes through+      runTestM "decompressNar none" $+        let input = "fake nar data"+         in assertEqual "decompress-none" (Right input) <$> Subst.decompressNar (toInteger (BS.length input)) "none" input,+      -- decompressNar: an empty Compression field means bzip2 upstream+      -- (the field's historical default), never identity, so the empty+      -- spelling must decode a real bzip2 body exactly as the named+      -- one does.+      runTestM "decompressNar empty means bzip2" $+        case B64.decode bzip2FixtureB64 of+          Left err -> pure (Fail ("fixture base64 does not decode: " <> T.pack err))+          Right compressed -> do+            out <- Subst.decompressNar xzFixtureSize "" compressed+            pure $ case out of+              Right decoded -> assertEqual "empty-is-bzip2" xzFixturePayload decoded+              Left err -> Fail ("empty Compression failed to decode as bzip2: " <> err),+      -- decompressNar: bzip2 decodes under the same declared-NarSize+      -- bound as the other codecs; the fixture comes from the bzip2+      -- CLI, so the decoder is checked against the format's own+      -- reference encoder rather than its own library.+      runTestM "decompressNar bzip2 bounded roundtrip" $+        case B64.decode bzip2FixtureB64 of+          Left err -> pure (Fail ("fixture base64 does not decode: " <> T.pack err))+          Right compressed -> do+            out <- Subst.decompressNar xzFixtureSize "bzip2" compressed+            pure $ case out of+              Right decoded -> assertEqual "bzip2-roundtrip" xzFixturePayload decoded+              Left err -> Fail ("bzip2 roundtrip failed: " <> err),+      runTestM "decompressNar bzip2 over-bound rejects" $+        case B64.decode bzip2FixtureB64 of+          Left err -> pure (Fail ("fixture base64 does not decode: " <> T.pack err))+          Right compressed -> do+            out <- Subst.decompressNar (xzFixtureSize - 1) "bzip2" compressed+            pure $ case out of+              Left err | "NarSize" `T.isInfixOf` err -> Pass+              other -> Fail ("expected over-bound rejection, got: " <> T.pack (show other)),+      -- decompressNar: xz decodes under the declared-NarSize bound+      -- (the fixture is a real 112-byte xz stream of 1792 payload+      -- bytes, embedded base64 to keep the source ASCII).+      runTestM "decompressNar xz bounded roundtrip" $+        case B64.decode xzFixtureB64 of+          Left err -> pure (Fail ("fixture base64 does not decode: " <> T.pack err))+          Right compressed -> do+            out <- Subst.decompressNar xzFixtureSize "xz" compressed+            pure $ case out of+              Right decoded -> assertEqual "xz-roundtrip" xzFixturePayload decoded+              Left err -> Fail ("xz roundtrip failed: " <> err),+      -- The output bound is exact: one byte under the real size must+      -- refuse, naming the declared NarSize.+      runTestM "decompressNar xz over-bound rejects" $+        case B64.decode xzFixtureB64 of+          Left err -> pure (Fail ("fixture base64 does not decode: " <> T.pack err))+          Right compressed -> do+            out <- Subst.decompressNar (xzFixtureSize - 1) "xz" compressed+            pure $ case out of+              Left err | "NarSize" `T.isInfixOf` err -> Pass+              other -> Fail ("expected over-bound rejection, got: " <> T.pack (show other)),+      -- decompressNar: bytes that are not an xz stream are an error,+      -- never silently passed through+      runTestM "decompressNar xz garbage rejects" $ do+        out <- Subst.decompressNar 64 "xz" "not an xz stream"+        pure $ case out of+          Left _ -> Pass+          Right _ -> Fail "garbage decoded as xz",+      -- decompressNar: zstd decodes under the same declared-NarSize+      -- bound; the fixture compresses with the sublibrary's own+      -- encoder, the same pairing the push path ships.+      runTestM "decompressNar zstd bounded roundtrip" $ do+        out <- Subst.decompressNar xzFixtureSize "zstd" zstdFixtureCompressed+        pure $ case out of+          Right decoded -> assertEqual "zstd-roundtrip" xzFixturePayload decoded+          Left err -> Fail ("zstd roundtrip failed: " <> err),+      runTestM "decompressNar zstd over-bound rejects" $ do+        out <- Subst.decompressNar (xzFixtureSize - 1) "zstd" zstdFixtureCompressed+        pure $ case out of+          Left err | "NarSize" `T.isInfixOf` err -> Pass+          other -> Fail ("expected over-bound rejection, got: " <> T.pack (show other)),+      -- decompressNar: unknown compression+      runTestM "decompressNar unknown" $ do+        out <- Subst.decompressNar 4 "brotli" "data"+        pure $ case out of+          Left _ -> Pass+          Right _ -> Fail "expected error for unknown",+      -- parseReferences: narinfo references are wire-format basenames+      runTest "parseReferences basenames" $+        let refs = ["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-hello", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-dep-2.0"]+            expected =+              [ StorePath "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "hello",+                StorePath "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "dep-2.0"+              ]+         in assertEqual "parse-refs" (Right expected) (Subst.parseReferences refs),+      -- parseReferences: a malformed token is a loud error, never dropped+      runTest "parseReferences malformed rejected" $+        case Subst.parseReferences ["not-a-store-path"] of+          Left _ -> Pass+          Right refs -> Fail ("expected rejection, got: " <> T.pack (show refs)),+      -- parseDeriver: basename becomes the DB's full path text+      runTest "parseDeriver basename" $+        let sp = StorePath "cccccccccccccccccccccccccccccccc" "hello.drv"+            expected = Just (T.pack (storePathToFilePath defaultStoreDir sp))+         in assertEqual "parse-deriver" (Right expected) (Subst.parseDeriver defaultStoreDir (Just "cccccccccccccccccccccccccccccccc-hello.drv")),+      -- parseDeriver: upstream's unknown-deriver sentinel means no deriver+      runTest "parseDeriver unknown sentinel" $+        assertEqual "parse-deriver-unknown" (Right Nothing) (Subst.parseDeriver defaultStoreDir (Just "unknown-deriver")),+      -- parseDeriver: absent stays absent, malformed is an error+      runTest "parseDeriver absent and malformed" $+        case (Subst.parseDeriver defaultStoreDir Nothing, Subst.parseDeriver defaultStoreDir (Just "bogus")) of+          (Right Nothing, Left _) -> Pass+          other -> Fail ("unexpected: " <> T.pack (show other)),+      -- Recorded production narinfos from cache.nixos.org (paths this+      -- codebase did not produce): the parse -> validate -> signature+      -- pipeline against real cache data, the production ed25519+      -- signature verified offline with the shipped public key.+      runTest "recorded cache.nixos.org narinfo verifies end to end" $+        case NarInfo.parseNarInfo recordedHelloNarInfo of+          Left err -> Fail ("parse failed: " <> T.pack err)+          Right ni ->+            case Subst.validateNarInfoFields ni >> signedUnder defaultCacheKeys ni of+              Left err -> Fail ("validate/verify failed: " <> err)+              Right () -> assertEqual "compression" "xz" (NarInfo.niCompression ni),+      -- References of a path built by Hydra, including the self+      -- reference, and its Deriver - both produced by upstream Nix.+      runTest "recorded narinfo references and deriver parse" $+        case NarInfo.parseNarInfo recordedHelloNarInfo of+          Left err -> Fail ("parse failed: " <> T.pack err)+          Right ni ->+            case (Subst.parseReferences (NarInfo.niReferences ni), Subst.parseDeriver defaultStoreDir (NarInfo.niDeriver ni)) of+              (Right refs, Right (Just _)) ->+                assertEqual+                  "reference hashes"+                  ["dska0s3gxxd8azbsn85pwm6xcqhivldw", "jppkr0h8aap5z7m4xy4vg5yrwlly9h2v"]+                  (map spHash refs)+              other -> Fail ("references/deriver did not parse: " <> T.pack (show other)),+      -- The empty References line ("References: " with a trailing+      -- space) production caches emit for leaf paths.+      runTest "recorded no-reference narinfo verifies" $+        case NarInfo.parseNarInfo recordedHelloDocNarInfo of+          Left err -> Fail ("parse failed: " <> T.pack err)+          Right ni ->+            case Subst.validateNarInfoFields ni >> signedUnder defaultCacheKeys ni >> Subst.parseReferences (NarInfo.niReferences ni) of+              Right [] -> Pass+              other -> Fail ("expected verified empty references, got: " <> T.pack (show other)),+      -- The fingerprint covers NarSize: altering the signed claim must+      -- break the production signature.+      runTest "tampered recorded narinfo fails signature" $+        case NarInfo.parseNarInfo recordedHelloNarInfo of+          Left err -> Fail ("parse failed: " <> T.pack err)+          Right ni ->+            case signedUnder defaultCacheKeys (ni {NarInfo.niNarSize = NarInfo.niNarSize ni + 1}) of+              Left _ -> Pass+              Right () -> Fail "signature verified over an altered NarSize",+      -- Streaming pipeline: the chunk-fed download materializes,+      -- hashes, and verifies without ever holding the NAR.  The tree+      -- carries the interesting shapes: nesting, an executable, a+      -- symlink, and a sibling pair colliding on folding filesystems -+      -- the digest equality proves the materialized tree re-serialises+      -- to its NAR on every platform strategy.+      -- Every length word, tag, and padding run must survive splitting+      -- across Await boundaries, so the whole materialization runs at+      -- several chunk sizes including single-byte feeds.+      runTestM "streaming unpack materializes and verifies across chunk sizes" $ do+        tmpBase <- getTemporaryDirectory+        let tmpDir = tmpBase </> "nova-nix-test-stream-unpack"+            chunkSizes = [1, 7, 8, 11] :: [Int]+            runAt n = do+              let dest = tmpDir </> ("out-" <> show n)+              source <- chunkReader (streamChunks n streamTestNar)+              result <- Subst.consumeNarStream tmpSensitivity dest (streamTestNarInfo streamTestNar) streamTestDigest source+              onDisk <- ExecBit.serialiseFromPath (volumeCaseHack tmpSensitivity) dest+              pure $ case result of+                Left err ->+                  Just ("chunk size " <> T.pack (show n) <> ": " <> Subst.attemptFailureMessage err)+                Right narByteCount+                  | narByteCount == BS.length streamTestNar+                      && CHash.hashBytes (NAR.serialise onDisk) == streamTestDigest ->+                      Nothing+                  | otherwise ->+                      Just ("chunk size " <> T.pack (show n) <> ": streamed tree diverges from its NAR")+        forceRemoveIfExists tmpDir+        createDirectoryIfMissing True tmpDir+        outcomes <- mapM runAt chunkSizes+        forceRemoveIfExists tmpDir+        pure $ case catMaybes outcomes of+          [] -> Pass+          (msg : _) -> Fail msg,+      -- A truncated stream is a loud parse failure, never a short+      -- tree - and it retries: truncation and a torn transfer+      -- parse-fail the same way.+      runTestM "streaming unpack refuses a truncated stream as transient" $ do+        tmpBase <- getTemporaryDirectory+        let tmpDir = tmpBase </> "nova-nix-test-stream-trunc"+        forceRemoveIfExists tmpDir+        createDirectoryIfMissing True tmpDir+        source <- chunkReader (streamChunks 7 (BS.take (BS.length streamTestNar - 10) streamTestNar))+        result <- Subst.consumeNarStream tmpSensitivity (tmpDir </> "out") (streamTestNarInfo streamTestNar) streamTestDigest source+        forceRemoveIfExists tmpDir+        pure $ case result of+          Left (Subst.TransientFailure _) -> Pass+          Left (Subst.FatalFailure err) -> Fail ("truncation classified fatal: " <> err)+          Right _ -> Fail "truncated NAR stream was accepted",+      -- A digest mismatch reports before the tree is trusted, and it+      -- is fatal: the size matched, so the transfer completed.+      runTestM "streaming unpack refuses a digest mismatch as fatal" $ do+        tmpBase <- getTemporaryDirectory+        let tmpDir = tmpBase </> "nova-nix-test-stream-digest"+        forceRemoveIfExists tmpDir+        createDirectoryIfMissing True tmpDir+        source <- chunkReader (streamChunks 7 streamTestNar)+        result <- Subst.consumeNarStream tmpSensitivity (tmpDir </> "out") (streamTestNarInfo streamTestNar) (CHash.hashBytes "not the nar") source+        forceRemoveIfExists tmpDir+        pure $ case result of+          Left (Subst.FatalFailure err) | "hash mismatch" `T.isInfixOf` err -> Pass+          Left other -> Fail ("expected fatal hash mismatch, got: " <> Subst.attemptFailureMessage other)+          Right _ -> Fail "digest mismatch was accepted",+      -- The parser refuses what upstream's refuses past the grammar, so a+      -- cache's archive holding a name, a target or a nesting past the+      -- format's limits does not unpack, and the attempt fails with the+      -- parser's words, digest and size notwithstanding.+      runTestM "streaming unpack refuses an archive past upstream's NAR limits" $ do+        tmpBase <- getTemporaryDirectory+        let tmpDir = tmpBase </> "nova-nix-test-stream-limits"+            file = NAR.NarRegular False "x"+            nested depth = foldr (\_ inner -> NAR.NarDirectory [("d", inner)]) file [1 .. depth :: Int]+            refused (entry, refusal) = do+              forceRemoveIfExists tmpDir+              createDirectoryIfMissing True tmpDir+              let nar = NAR.serialise entry+              source <- chunkReader (streamChunks 7 nar)+              result <- Subst.consumeNarStream tmpSensitivity (tmpDir </> "out") (streamTestNarInfo nar) (CHash.hashBytes nar) source+              pure $ case result of+                Left failure -> assertEqual "refusal" ("NAR stream parse failed: " <> refusal) (Subst.attemptFailureMessage failure)+                Right _ -> Fail ("an archive past the limits was accepted: " <> refusal)+        results <-+          traverse+            refused+            [ (NAR.NarDirectory [(BS.replicate 256 0x61, file)], "entry name: declared length 256 exceeds the 255-byte limit"),+              (NAR.NarSymlink (BS.replicate 4096 0x61), "symlink target: declared length 4096 exceeds the 4095-byte limit"),+              (NAR.NarSymlink "", "empty NAR symlink target"),+              (NAR.NarSymlink "a\NULb", "NAR symlink target holds NUL: \"a\\NULb\""),+              (nested 64, "NAR directory nesting exceeds the maximum depth of 64: \"d\"")+            ]+        forceRemoveIfExists tmpDir+        pure (foldr andThen Pass results),+      -- Streamed to its root node's close, the archive's digest and size+      -- are of the archive alone, whatever follows it and wherever the+      -- chunks fall, since the input after that close is left unread.+      runTestM "a NAR streamed to its root's close is hashed and counted alone, whatever follows it" $ do+        tmpBase <- getTemporaryDirectory+        let tmpDir = tmpBase </> "nova-nix-test-stream-root-close"+            expected = Right (CHash.hashBytes streamTestNar, BS.length streamTestNar)+            genTrailing = BS.pack <$> QC.listOf QC.arbitrary+            streamedWith (trailing, chunkLen) = QC.ioProperty $ do+              forceRemoveIfExists tmpDir+              createDirectoryIfMissing True tmpDir+              sink <- newNarUnpackSink tmpSensitivity (tmpDir </> "out")+              source <- chunkReader (streamChunks chunkLen (streamTestNar <> trailing))+              streamed <- sinkNarStream AtRootClose sink source+              pure (streamed QC.=== expected)+        result <-+          QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} $+            QC.forAll ((,) <$> genTrailing <*> QC.choose (1, BS.length streamTestNar)) streamedWith+        forceRemoveIfExists tmpDir+        pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result))),+      -- Upstream's import of a substituted NAR stops reading at the root+      -- node's close and holds NarHash and NarSize to the bytes read to+      -- there, so a cache's NAR followed by bytes the archive does not+      -- hold substitutes as the archive alone.+      runTestM "a cache's NAR followed by extra bytes substitutes as the archive, under its NarHash and NarSize" $ do+        tmpBase <- getTemporaryDirectory+        let sp = StorePath (T.replicate 32 "g") "trailing"+            contents = "the archive\n"+            nar = NAR.serialise (NAR.NarRegular False contents)+            root = tmpBase </> "nova-nix-test-subst-trailing"+        case signedTestNarInfo sp [] "nar/trailing.nar" nar of+          Left err -> pure (Fail (T.pack err))+          Right (publicKey, narInfo) -> do+            let served = Map.fromList [(narInfoRequest sp, TE.encodeUtf8 narInfo), ("/nar/trailing.nar", nar <> "bytes after the archive")]+                route target _ = Send (maybe (httpResponse "404 Not Found" "") (httpResponse "200 OK") (Map.lookup target served))+            withHttpServer route $ \base _ _ ->+              bracket_ (forceRemoveIfExists root) (forceRemoveIfExists root) $+                bracket (openStore testLogger (StoreDir root)) closeStore $ \store -> do+                  result <- offeredThenFetched defaultFetchRetryPolicy (ioRetryEffects testLogger) store [Subst.CacheConfig base [publicKey] [] Subst.RequireSigs 40] sp+                  case result of+                    Subst.SubstSuccess reg lock -> do+                      releasePathLock lock+                      onDisk <- BS.readFile (storePathToFilePath (stDir store) sp)+                      pure+                        ( assertEqual+                            "NarHash, NarSize and the file"+                            (CHash.formatNixHash (CHash.hashBytes nar), BS.length nar, contents)+                            (prNarHash reg, prNarSize reg, onDisk)+                        )+                    other -> pure (Fail ("expected the archive substituted, got: " <> T.pack (show other))),+      -- Upstream holds an imported NAR's hash before its size and words+      -- each refusal as a mismatch importing the path, the hash in SRI+      -- form, and the streamed and the whole pipelines hold it the same.+      runTestM "a NAR's hash and then its size are held to its narinfo in upstream's words, by both pipelines" $ do+        tmpBase <- getTemporaryDirectory+        let tmpDir = tmpBase </> "nova-nix-test-stream-claim-words"+            honest = streamTestNarInfo streamTestNar+            path = NarInfo.niStorePath honest+            sri bytes = "sha256-" <> B64.encode (case CHash.hashBytes bytes of CHash.NixHash raw -> raw)+            lyingHash info = info {NarInfo.niNarHash = CHash.formatNixHash (CHash.hashBytes "not the nar")}+            lyingSize info = info {NarInfo.niNarSize = NarInfo.niNarSize info + 1}+            hashRefusal = "hash mismatch importing path '" <> path <> "';\n  specified: " <> sri "not the nar" <> "\n  got:       " <> sri streamTestNar+            sizeRefusal =+              "size mismatch importing path '"+                <> path+                <> "';\n  specified: "+                <> T.pack (show (BS.length streamTestNar + 1))+                <> "\n  got:       "+                <> T.pack (show (BS.length streamTestNar))+            heldBoth (label, info, declared, refusal) = do+              forceRemoveIfExists tmpDir+              createDirectoryIfMissing True tmpDir+              source <- chunkReader (streamChunks 7 streamTestNar)+              streamed <- Subst.consumeNarStream tmpSensitivity (tmpDir </> "out") info declared source+              pure+                ( assertEqual (label <> ", streamed") (Left refusal) (either (Left . Subst.attemptFailureMessage) Right streamed)+                    `andThen` assertEqual (label <> ", whole") (Left refusal) (void (Subst.verifyNar info streamTestNar))+                )+        results <-+          traverse+            heldBoth+            [ ("a wrong hash", lyingHash honest, CHash.hashBytes "not the nar", hashRefusal),+              ("a wrong size", lyingSize honest, streamTestDigest, sizeRefusal),+              ("both wrong, the hash first", lyingHash (lyingSize honest), CHash.hashBytes "not the nar", hashRefusal)+            ]+        forceRemoveIfExists tmpDir+        pure (foldr andThen Pass results),+      -- A narinfo lying about NarSize in either direction is refused+      -- at NarDone - the grammar completed, so the mismatch is the+      -- narinfo misdeclaring, and fatal.+      runTestM "streaming unpack refuses an overdeclared NarSize" $ do+        tmpBase <- getTemporaryDirectory+        let tmpDir = tmpBase </> "nova-nix-test-stream-oversize"+            lying = (streamTestNarInfo streamTestNar) {NarInfo.niNarSize = toInteger (BS.length streamTestNar) + 1}+        forceRemoveIfExists tmpDir+        createDirectoryIfMissing True tmpDir+        source <- chunkReader (streamChunks 7 streamTestNar)+        result <- Subst.consumeNarStream tmpSensitivity (tmpDir </> "out") lying streamTestDigest source+        forceRemoveIfExists tmpDir+        pure $ case result of+          Left (Subst.FatalFailure err) | "size mismatch" `T.isInfixOf` err -> Pass+          Left other -> Fail ("expected fatal size mismatch, got: " <> Subst.attemptFailureMessage other)+          Right _ -> Fail "overdeclared NarSize was accepted",+      runTestM "streaming unpack refuses an underdeclared NarSize" $ do+        tmpBase <- getTemporaryDirectory+        let tmpDir = tmpBase </> "nova-nix-test-stream-undersize"+            lying = (streamTestNarInfo streamTestNar) {NarInfo.niNarSize = toInteger (BS.length streamTestNar) - 1}+        forceRemoveIfExists tmpDir+        createDirectoryIfMissing True tmpDir+        source <- chunkReader (streamChunks 7 streamTestNar)+        result <- Subst.consumeNarStream tmpSensitivity (tmpDir </> "out") lying streamTestDigest source+        forceRemoveIfExists tmpDir+        pure $ case result of+          Left (Subst.FatalFailure err) | "size mismatch" `T.isInfixOf` err -> Pass+          Left other -> Fail ("expected fatal size mismatch, got: " <> Subst.attemptFailureMessage other)+          Right _ -> Fail "underdeclared NarSize was accepted",+      -- cappedBodySource: the streaming mirror of readBodyCapped -+      -- a body past the key-trusted declared size aborts mid-stream.+      runTestM "cappedBodySource aborts past the cap" $ do+        reader <- chunkReader ["abcdef", "ghijkl"]+        source <- Subst.cappedBodySource 10 reader+        firstChunk <- source+        overCap <- try source :: IO (Either SomeException BS.ByteString)+        pure $ case (firstChunk, overCap) of+          ("abcdef", Left _) -> Pass+          other -> Fail ("expected abort past the cap, got: " <> T.pack (show other)),+      -- withDecompressedSource: xz chunks decompress under the+      -- declared bound; the support decision mirrors decompressorFor.+      runTestM "withDecompressedSource xz chunked roundtrip" $+        case B64.decode xzFixtureB64 of+          Left err -> pure (Fail ("fixture base64 does not decode: " <> T.pack err))+          Right compressed -> do+            source <- chunkReader (streamChunks 7 compressed)+            result <- Subst.withDecompressedSource xzFixtureSize "xz" source $ \pull ->+              let go acc = do+                    chunk <- pull+                    if BS.null chunk+                      then pure (Right (BS.concat (reverse acc)))+                      else go (chunk : acc)+               in go []+            pure $ case result of+              Right out | out == xzFixturePayload -> Pass+              other -> Fail ("xz source roundtrip diverged: " <> T.pack (show (fmap BS.length other))),+      runTestM "withDecompressedSource zstd chunked roundtrip" $ do+        source <- chunkReader (streamChunks 7 zstdFixtureCompressed)+        result <- Subst.withDecompressedSource xzFixtureSize "zstd" source $ \pull ->+          let go acc = do+                chunk <- pull+                if BS.null chunk+                  then pure (Right (BS.concat (reverse acc)))+                  else go (chunk : acc)+           in go []+        pure $ case result of+          Right out | out == xzFixturePayload -> Pass+          other -> Fail ("zstd source roundtrip diverged: " <> T.pack (show (fmap BS.length other))),+      runTestM "withDecompressedSource xz single-byte chunks" $+        case B64.decode xzFixtureB64 of+          Left err -> pure (Fail ("fixture base64 does not decode: " <> T.pack err))+          Right compressed -> do+            source <- chunkReader (streamChunks 1 compressed)+            result <- Subst.withDecompressedSource xzFixtureSize "xz" source $ \pull ->+              let go acc = do+                    chunk <- pull+                    if BS.null chunk+                      then pure (Right (BS.concat (reverse acc)))+                      else go (chunk : acc)+               in go []+            pure $ case result of+              Right out | out == xzFixturePayload -> Pass+              other -> Fail ("xz 1-byte roundtrip diverged: " <> T.pack (show (fmap BS.length other))),+      -- The LIVE pipeline's defenses, not the strict oracle's: hostile+      -- compressed input through withDecompressedSource must land in+      -- the Left channel with the right retry class, never escape as+      -- an exception.+      runTestM "withDecompressedSource xz over-bound is fatal" $+        case B64.decode xzFixtureB64 of+          Left err -> pure (Fail ("fixture base64 does not decode: " <> T.pack err))+          Right compressed -> do+            source <- chunkReader (streamChunks 7 compressed)+            result <- Subst.withDecompressedSource (xzFixtureSize - 1) "xz" source drainChunkSource+            pure $ case result of+              Left (Subst.FatalFailure err) | "NarSize" `T.isInfixOf` err -> Pass+              other -> Fail ("expected fatal over-bound, got: " <> T.pack (show (void other))),+      runTestM "withDecompressedSource xz garbage is transient" $ do+        source <- chunkReader ["not an xz stream"]+        result <- Subst.withDecompressedSource 64 "xz" source drainChunkSource+        pure $ case result of+          Left (Subst.TransientFailure _) -> Pass+          other -> Fail ("expected transient stream error, got: " <> T.pack (show (void other))),+      runTestM "withDecompressedSource xz truncated is transient" $+        case B64.decode xzFixtureB64 of+          Left err -> pure (Fail ("fixture base64 does not decode: " <> T.pack err))+          Right compressed -> do+            source <- chunkReader (streamChunks 7 (BS.take 40 compressed))+            result <- Subst.withDecompressedSource xzFixtureSize "xz" source drainChunkSource+            pure $ case result of+              Left (Subst.TransientFailure _) -> Pass+              other -> Fail ("expected transient truncation, got: " <> T.pack (show (void other))),+      -- The failure contract of the post-download pipeline: every+      -- failing materialization removes the tree it wrote, and a+      -- clean one registers the verified metadata.+      runTestM "materialize registers a verified tree" $ do+        tmpBase <- getTemporaryDirectory+        let tmpStore = tmpBase </> "nova-nix-test-materialize-ok"+        forceRemoveIfExists tmpStore+        createDirectoryIfMissing True tmpStore+        store <- openStore testLogger (StoreDir tmpStore)+        let sp = StorePath sampleHash "stream"+            destPath = storePathToFilePath (StoreDir tmpStore) sp+        source <- chunkReader (streamChunks 7 streamTestNar)+        result <- Subst.materializeNarFromSource store sp (streamTestNarInfo streamTestNar) streamTestDigest [] Nothing source+        survived <- doesDirectoryExist destPath+        closeStore store+        forceRemoveIfExists tmpStore+        pure $ case result of+          Left err -> Fail ("materialize failed: " <> Subst.attemptFailureMessage err)+          Right reg+            | not survived -> Fail "verified tree missing after materialize"+            | prNarSize reg /= BS.length streamTestNar -> Fail "registration NarSize diverges"+            | prNarHash reg /= CHash.formatNixHash streamTestDigest -> Fail "registration NarHash diverges"+            | otherwise -> Pass,+      -- A substituted path keeps the signatures its narinfo carries and+      -- the content address its tree was held to, as upstream registers+      -- the path info it copies; a Sig line that does not parse is left+      -- out.+      runTestM "materialize registers the narinfo's signatures and the content address it checked" $ do+        tmpBase <- getTemporaryDirectory+        let tmpStore = tmpBase </> "nova-nix-test-materialize-trust"+            (address, made) = case streamTestDigest of+              CHash.NixHash digest -> ("fixed:r:sha256:" <> Nix32.encode digest, makeSourcePath "stream" digest Set.empty)+            signature = "cache.example.org-1:AQI="+            narInfo = (streamTestNarInfo streamTestNar) {NarInfo.niSigs = [signature, "not a signature"], NarInfo.niCA = Just address}+        case made of+          Left err -> pure (Fail ("the address makes no path: " <> T.pack (show err)))+          Right sp -> do+            forceRemoveIfExists tmpStore+            createDirectoryIfMissing True tmpStore+            store <- openStore testLogger (StoreDir tmpStore)+            source <- chunkReader (streamChunks 7 streamTestNar)+            result <- Subst.materializeNarFromSource store sp narInfo streamTestDigest [] Nothing source+            closeStore store+            forceRemoveIfExists tmpStore+            let expected = (NotUltimate, either (const Set.empty) Set.singleton (parseSignature (TE.encodeUtf8 signature)), either (const Nothing) Just (parseContentAddress address))+            pure $ case result of+              Left err -> Fail ("materialize failed: " <> Subst.attemptFailureMessage err)+              Right reg -> assertEqual "trust" expected (prUltimate reg, prSignatures reg, prContentAddress reg),+      runTestM "materialize removes the tree on a digest mismatch" $ do+        tmpBase <- getTemporaryDirectory+        let tmpStore = tmpBase </> "nova-nix-test-materialize-digest"+        forceRemoveIfExists tmpStore+        createDirectoryIfMissing True tmpStore+        store <- openStore testLogger (StoreDir tmpStore)+        let sp = StorePath sampleHash "stream"+            destPath = storePathToFilePath (StoreDir tmpStore) sp+        source <- chunkReader (streamChunks 7 streamTestNar)+        result <- Subst.materializeNarFromSource store sp (streamTestNarInfo streamTestNar) (CHash.hashBytes "not the nar") [] Nothing source+        survived <- doesDirectoryExist destPath+        closeStore store+        forceRemoveIfExists tmpStore+        pure $ case result of+          Right _ -> Fail "digest mismatch was accepted"+          Left (Subst.TransientFailure err) -> Fail ("mismatch classified transient: " <> err)+          Left (Subst.FatalFailure err)+            | not ("hash mismatch" `T.isInfixOf` err) -> Fail ("unexpected failure: " <> err)+            | survived -> Fail "tree survived a digest mismatch"+            | otherwise -> Pass,+      runTestM "materialize removes the tree on a truncated stream" $ do+        tmpBase <- getTemporaryDirectory+        let tmpStore = tmpBase </> "nova-nix-test-materialize-trunc"+        forceRemoveIfExists tmpStore+        createDirectoryIfMissing True tmpStore+        store <- openStore testLogger (StoreDir tmpStore)+        let sp = StorePath sampleHash "stream"+            destPath = storePathToFilePath (StoreDir tmpStore) sp+        source <- chunkReader (streamChunks 7 (BS.take (BS.length streamTestNar - 10) streamTestNar))+        result <- Subst.materializeNarFromSource store sp (streamTestNarInfo streamTestNar) streamTestDigest [] Nothing source+        survived <- doesDirectoryExist destPath+        closeStore store+        forceRemoveIfExists tmpStore+        pure $ case result of+          Right _ -> Fail "truncated stream was accepted"+          Left (Subst.FatalFailure err) -> Fail ("truncation classified fatal: " <> err)+          Left (Subst.TransientFailure _)+            | survived -> Fail "tree survived a truncated stream"+            | otherwise -> Pass,+      -- The download cap is the ceiling of the narinfo's NarSize, which+      -- a signature covers, so the FileSize, which none does, moves it+      -- in neither direction: one smaller than the body, as a narinfo+      -- records after its cache compressed the NAR again, and one+      -- inflated past the ceiling.+      runTest "downloadCapFor ignores FileSize" $+        let base = streamTestNarInfo streamTestNar+            narSize = NarInfo.niNarSize base+            ceilingCap = Subst.compressedBodyCeiling narSize+            capFor fileSize = Subst.downloadCapFor base {NarInfo.niFileSize = fileSize}+         in assertEqual+              "caps"+              (replicate 3 (Right (fromInteger ceilingCap)))+              (map capFor [Nothing, Just (narSize - 1), Just (ceilingCap * 1000)]),+      runTest "compressedBodyCeiling floors small and scales large" $+        let smallCeiling = Subst.compressedBodyCeiling 10+            largeSize = 64 * 1024 * 1024+            largeCeiling = Subst.compressedBodyCeiling largeSize+         in if smallCeiling == 10 + 64 * 1024 && largeCeiling == largeSize + largeSize `div` 64+              then Pass+              else Fail ("unexpected ceilings: " <> T.pack (show (smallCeiling, largeCeiling))),+      -- The zstd mirror of the xz hostile trio: over-bound output is+      -- deterministic, while a corrupt frame and a frame cut off+      -- mid-way both retry - the codec judges end of input by+      -- libzstd's own frame-boundary signal, so truncation refuses+      -- here instead of yielding a short output.+      runTestM "withDecompressedSource zstd over-bound is fatal" $ do+        source <- chunkReader (streamChunks 7 zstdFixtureCompressed)+        result <- Subst.withDecompressedSource (xzFixtureSize - 1) "zstd" source drainChunkSource+        pure $ case result of+          Left (Subst.FatalFailure err) | "NarSize" `T.isInfixOf` err -> Pass+          other -> Fail ("expected fatal over-bound, got: " <> T.pack (show (void other))),+      runTestM "withDecompressedSource zstd garbage is transient" $ do+        source <- chunkReader ["not a zstd frame"]+        result <- Subst.withDecompressedSource 64 "zstd" source drainChunkSource+        pure $ case result of+          Left (Subst.TransientFailure _) -> Pass+          other -> Fail ("expected transient stream error, got: " <> T.pack (show (void other))),+      runTestM "withDecompressedSource zstd truncated is transient" $ do+        source <- chunkReader (streamChunks 7 (BS.take (BS.length zstdFixtureCompressed - 8) zstdFixtureCompressed))+        result <- Subst.withDecompressedSource xzFixtureSize "zstd" source drainChunkSource+        pure $ case result of+          Left (Subst.TransientFailure _) -> Pass+          other -> Fail ("expected transient truncation, got: " <> T.pack (show (void other))),+      -- The codec refuses a truncated frame, and the whole pipeline+      -- must carry that refusal into the Left channel as retryable+      -- rather than let a short NAR reach the store.+      runTestM "zstd truncated body fails the pipeline as transient" $ do+        tmpBase <- getTemporaryDirectory+        let tmpDir = tmpBase </> "nova-nix-test-zstd-trunc"+            compressedNar = CZstd.compress CZstd.defaultCompressionLevel streamTestNar+        forceRemoveIfExists tmpDir+        createDirectoryIfMissing True tmpDir+        source <- chunkReader (streamChunks 7 (BS.take (BS.length compressedNar - 8) compressedNar))+        result <-+          Subst.withDecompressedSource (toInteger (BS.length streamTestNar)) "zstd" source $+            Subst.consumeNarStream tmpSensitivity (tmpDir </> "out") ((streamTestNarInfo streamTestNar) {NarInfo.niCompression = "zstd"}) streamTestDigest+        forceRemoveIfExists tmpDir+        pure $ case result of+          Left (Subst.TransientFailure _) -> Pass+          Left (Subst.FatalFailure err) -> Fail ("zstd truncation classified fatal: " <> err)+          Right _ -> Fail "truncated zstd body was accepted",+      -- The bzip2 mirror of the xz hostile trio, over a fixture the+      -- bzip2 CLI produced: over-bound output is deterministic, while+      -- garbage and a truncated stream retry.+      runTestM "withDecompressedSource bzip2 chunked roundtrip" $+        case B64.decode bzip2FixtureB64 of+          Left err -> pure (Fail ("fixture base64 does not decode: " <> T.pack err))+          Right compressed -> do+            source <- chunkReader (streamChunks 7 compressed)+            result <- Subst.withDecompressedSource xzFixtureSize "bzip2" source $ \pull ->+              let go acc = do+                    chunk <- pull+                    if BS.null chunk+                      then pure (Right (BS.concat (reverse acc)))+                      else go (chunk : acc)+               in go []+            pure $ case result of+              Right out | out == xzFixturePayload -> Pass+              other -> Fail ("bzip2 source roundtrip diverged: " <> T.pack (show (fmap BS.length other))),+      runTestM "withDecompressedSource bzip2 over-bound is fatal" $+        case B64.decode bzip2FixtureB64 of+          Left err -> pure (Fail ("fixture base64 does not decode: " <> T.pack err))+          Right compressed -> do+            source <- chunkReader (streamChunks 7 compressed)+            result <- Subst.withDecompressedSource (xzFixtureSize - 1) "bzip2" source drainChunkSource+            pure $ case result of+              Left (Subst.FatalFailure err) | "NarSize" `T.isInfixOf` err -> Pass+              other -> Fail ("expected fatal over-bound, got: " <> T.pack (show (void other))),+      runTestM "withDecompressedSource bzip2 garbage is transient" $ do+        source <- chunkReader ["not a bzip2 stream"]+        result <- Subst.withDecompressedSource 64 "bzip2" source drainChunkSource+        pure $ case result of+          Left (Subst.TransientFailure _) -> Pass+          other -> Fail ("expected transient stream error, got: " <> T.pack (show (void other))),+      runTestM "withDecompressedSource bzip2 truncated is transient" $+        case B64.decode bzip2FixtureB64 of+          Left err -> pure (Fail ("fixture base64 does not decode: " <> T.pack err))+          Right compressed -> do+            source <- chunkReader (streamChunks 7 (BS.take (BS.length compressed - 8) compressed))+            result <- Subst.withDecompressedSource xzFixtureSize "bzip2" source drainChunkSource+            pure $ case result of+              Left (Subst.TransientFailure _) -> Pass+              other -> Fail ("expected transient truncation, got: " <> T.pack (show (void other))),+      -- A bzip2-compressed NAR through the whole post-download+      -- pipeline: the format the historical caches serve decompresses,+      -- hashes, parses, and materializes in one bounded pass.+      runTestM "bzip2 NAR streams through the pipeline" $+        case B64.decode bzip2NarFixtureB64 of+          Left err -> pure (Fail ("fixture base64 does not decode: " <> T.pack err))+          Right compressed -> do+            tmpBase <- getTemporaryDirectory+            let tmpDir = tmpBase </> "nova-nix-test-bzip2-pipeline"+                destPath = tmpDir </> "out"+            forceRemoveIfExists tmpDir+            createDirectoryIfMissing True tmpDir+            source <- chunkReader (streamChunks 7 compressed)+            result <-+              Subst.withDecompressedSource (toInteger (BS.length bzip2NarFixture)) "bzip2" source $+                Subst.consumeNarStream+                  tmpSensitivity+                  destPath+                  ((streamTestNarInfo bzip2NarFixture) {NarInfo.niCompression = "bzip2"})+                  (CHash.hashBytes bzip2NarFixture)+            materialized <- Dir.doesFileExist (destPath </> "greeting")+            forceRemoveIfExists tmpDir+            pure $ case result of+              Left err -> Fail ("bzip2 pipeline failed: " <> Subst.attemptFailureMessage err)+              Right narBytes+                | narBytes /= BS.length bzip2NarFixture -> Fail "bzip2 pipeline counted the wrong NAR size"+                | not materialized -> Fail "bzip2 pipeline left no tree at the destination"+                | otherwise -> Pass,+      runTest "streaming compression support matches the strict set" $+        case (Subst.streamingDecompressionSupported "xz", Subst.streamingDecompressionSupported "zstd", Subst.streamingDecompressionSupported "bzip2", Subst.streamingDecompressionSupported "brotli") of+          (Right (), Right (), Right (), Left _) -> Pass+          other -> Fail ("unexpected support set: " <> T.pack (show other)),+      -- The support set is encoded twice - the strict decompressor and+      -- the streaming decision - so their agreement is pinned across+      -- the codecs either could plausibly grow, not left to comments.+      runTest "strict and streaming support sets agree" $+        let agrees compression =+              case (Subst.decompressorFor 1 compression, Subst.streamingDecompressionSupported compression) of+                (Right _, Right ()) -> True+                (Left _, Left _) -> True+                _ -> False+         in if all agrees ["none", "", "xz", "zstd", "bzip2", "brotli"]+              then Pass+              else Fail "strict and streaming compression support drifted",+      -- The strict path is the streaming path's differential oracle:+      -- the same NAR materialized by both must produce the same tree.+      runTestM "strict and streaming unpack agree" $ do+        tmpBase <- getTemporaryDirectory+        let tmpDir = tmpBase </> "nova-nix-test-stream-oracle"+        forceRemoveIfExists tmpDir+        createDirectoryIfMissing True tmpDir+        strictOutcome <- case NAR.deserialise streamTestNar of+          Left err -> pure (Left (T.pack err))+          Right entry -> unpackNarEntry tmpSensitivity (tmpDir </> "strict") entry+        source <- chunkReader (streamChunks 11 streamTestNar)+        streamOutcome <- Subst.consumeNarStream tmpSensitivity (tmpDir </> "streamed") (streamTestNarInfo streamTestNar) streamTestDigest source+        strictTree <- NAR.serialiseFromPath (tmpDir </> "strict")+        streamedTree <- NAR.serialiseFromPath (tmpDir </> "streamed")+        forceRemoveIfExists tmpDir+        pure $ case (strictOutcome, streamOutcome) of+          (Right (), Right _)+            | NAR.serialise strictTree == NAR.serialise streamedTree -> Pass+            | otherwise -> Fail "strict and streaming trees diverge"+          other -> Fail ("oracle setup failed: " <> T.pack (show other)),+      -- With no cache there is nothing to offer, so nothing is fetched.+      runTestM "a path asked of no cache is not offered, and nothing is fetched" $ do+        tmpBase <- getTemporaryDirectory+        let tmpStore = tmpBase </> "nova-nix-test-subst"+        createDirectoryIfMissing True tmpStore+        store <- openStore testLogger (StoreDir tmpStore)+        result <- offeredThenFetched defaultFetchRetryPolicy (ioRetryEffects testLogger) store [] (StorePath "test" "hello")+        closeStore store+        removeDirectoryRecursive tmpStore+        pure (assertEqual "no-caches" Subst.SubstNotFound result),+      -- defaultCacheConfig has correct URL+      runTest "defaultCacheConfig url" $+        assertEqual "default-url" "https://cache.nixos.org" (Subst.ccUrl Subst.defaultCacheConfig),+      -- defaultCacheConfig has priority 40+      runTest "defaultCacheConfig priority" $+        assertEqual "default-prio" 40 (Subst.ccPriority Subst.defaultCacheConfig),+      -- verifyNarHash: matching NAR hash accepted (HIGH#2 integrity gate);+      -- the returned digest is the declared hash, decoded.+      runTest "verifyNarHash accepts matching hash" $+        case Subst.verifyNarHash (sampleNarInfo sampleNarHash) sampleNarBytes of+          Right declared+            | CHash.formatNixHash declared == sampleNarHash -> Pass+            | otherwise -> Fail "returned digest does not match the declared hash"+          Left err -> Fail ("expected acceptance, got: " <> err),+      -- verifyNarHash: mismatched NAR hash rejected+      runTest "verifyNarHash rejects mismatched hash" $+        case Subst.verifyNarHash (sampleNarInfo wrongNarHash) sampleNarBytes of+          Left _ -> Pass+          Right _ -> Fail "expected mismatch rejection",+      -- verifyNarHash: malformed NAR hash rejected+      runTest "verifyNarHash rejects malformed hash" $+        case Subst.verifyNarHash (sampleNarInfo "not-a-hash") sampleNarBytes of+          Left _ -> Pass+          Right _ -> Fail "expected malformed-hash rejection",+      -- verifyNar: the only constructor of VerifiedNar carries the bytes+      -- unchanged and the declared digest decoded, so the unpack sink+      -- and the registration read both from the witness.+      runTest "verifyNar carries the bytes and the declared digest" $+        case Subst.verifyNar (sampleNarInfo sampleNarHash) sampleNarBytes of+          Right verified+            | Subst.verifiedNarBytes verified /= sampleNarBytes -> Fail "verified bytes differ from the input"+            | CHash.formatNixHash (Subst.verifiedNarDigest verified) /= sampleNarHash -> Fail "carried digest is not the declared hash"+            | otherwise -> Pass+          Left err -> Fail ("expected acceptance, got: " <> err),+      -- verifyNar: either claim failing yields no witness at all.+      runTest "verifyNar rejects a hash or size mismatch" $+        let wrongHash = Subst.verifyNar (sampleNarInfo wrongNarHash) sampleNarBytes+            wrongSize = Subst.verifyNar ((sampleNarInfo sampleNarHash) {NarInfo.niNarSize = toInteger (BS.length sampleNarBytes) + 1}) sampleNarBytes+         in case (wrongHash, wrongSize) of+              (Left _, Left _) -> Pass+              other -> Fail ("expected both rejections, got: " <> T.pack (show other)),+      -- narInfoMatchesPath: identity match accepted+      runTest "narInfoMatchesPath accepts matching identity" $+        if Subst.narInfoMatchesPath (StorePath sampleHash "hello") (sampleNarInfo sampleNarHash)+          then Pass+          else Fail "expected identity match",+      -- narInfoMatchesPath: identity mismatch rejected+      runTest "narInfoMatchesPath rejects mismatched identity" $+        if Subst.narInfoMatchesPath (StorePath (T.replicate 32 "b") "hello") (sampleNarInfo sampleNarHash)+          then Fail "expected identity mismatch"+          else Pass,+      -- Upstream holds the narinfo's name to the requested path's too, not+      -- its hash alone.+      runTest "narInfoMatchesPath rejects a narinfo naming another name under the same hash" $+        if Subst.narInfoMatchesPath (StorePath sampleHash "goodbye") (sampleNarInfo sampleNarHash)+          then Fail "a narinfo for another name was taken for the requested path"+          else Pass,+      -- catchSync, which a fetch and a query wrap each attempt in: a+      -- synchronous exception becomes the handler's value, and so a failed+      -- substitute the realisation passes to the next cache.+      runTestM "catchSync folds a synchronous exception into the handler's value" $ do+        result <- Subst.catchSync (throwIO (ErrorCall "disk full")) (pure . Subst.SubstError . T.pack . show)+        pure $ case result of+          Subst.SubstError err+            | "disk full" `T.isInfixOf` err -> Pass+          other -> Fail ("expected SubstError from sync exception, got " <> T.pack (show other)),+      -- catchSync: an asynchronous exception passes through untouched -+      -- cancellation must abort substitution, never be spent as a failed+      -- substitute and from there a local build.+      runTestM "catchSync passes an asynchronous exception through" $ do+        outcome <- try (Subst.catchSync (throwIO (asyncExceptionToException (ErrorCall "cancelled"))) (pure . Subst.SubstError . T.pack . show))+        pure $ case (outcome :: Either SomeException Subst.SubstResult) of+          Left escaped -> case fromException escaped of+            Just (SomeAsyncException _) -> Pass+            Nothing -> Fail ("wrong exception escaped: " <> T.pack (show escaped))+          Right result -> Fail ("async exception folded into " <> T.pack (show result)),+      -- clearStaleDestination: removes a read-only leftover tree (the+      -- crash-between-unpack-and-register wedge)+      runTestM "clearStaleDestination removes read-only leftovers" $ do+        tmpBase <- getTemporaryDirectory+        let staleRoot = tmpBase </> "nova-nix-test-stale-dest"+            staleFile = staleRoot </> "bin" </> "tool"+        createDirectoryIfMissing True (staleRoot </> "bin")+        writeFile staleFile "leftover"+        perms <- getPermissions staleFile+        Dir.setPermissions staleFile (Dir.setOwnerWritable False perms)+        Subst.clearStaleDestination staleRoot+        gone <- Dir.doesPathExist staleRoot+        pure (if gone then Fail "stale tree survived" else Pass),+      -- clearStaleDestination: a missing destination is a no-op+      runTestM "clearStaleDestination missing path no-op" $ do+        tmpBase <- getTemporaryDirectory+        outcome <- try (Subst.clearStaleDestination (tmpBase </> "nova-nix-test-no-such-dir"))+        pure $ case (outcome :: Either SomeException ()) of+          Right () -> Pass+          Left e -> Fail ("threw: " <> T.pack (show e)),+      -- unpackNarEntry: what the archive grammar refuses (traversal+      -- shapes, a NUL) is refused on every host before anything is+      -- written+      runTestM "unpackNarEntry rejects unsafe entry names" $ do+        tmpBase <- getTemporaryDirectory+        let dest = tmpBase </> "nova-nix-test-unpack-unsafe"+            evil name = NAR.NarDirectory [(name, NAR.NarRegular False "x")]+            -- Cleared before each: the root is created exclusively, so+            -- a leftover from the previous name would refuse for a+            -- different reason than the one under test.+            unpackFresh name = do+              Subst.clearStaleDestination dest+              unpackNarEntry tmpSensitivity dest (evil name)+        results <- mapM unpackFresh ["..", ".", "", "a/b", "a\NULb"]+        Subst.clearStaleDestination dest+        pure $+          if all (\case Left err -> "NAR directory entry name" `T.isInfixOf` err; Right () -> False) results+            then Pass+            else Fail ("accepted an unsafe name: " <> T.pack (show results)),+      -- Names upstream's restore writes on POSIX as it finds them+      -- (posixOnlyTree, compared against nix-store --restore 2.33.2)+      -- materialize byte for byte through both unpack paths there, and+      -- the tree re-serialises to the NAR it came from.  Windows refuses+      -- the first such name before writing any entry.+      runTestM "names upstream restores on POSIX materialize as their bytes" $ do+        tmpBase <- getTemporaryDirectory+        let refusal = "NAR directory entry name 'COM1' is a Windows device name"+        outcomes <- unpackedBothWays tmpSensitivity (tmpBase </> "nova-nix-test-unpack-posix-names") posixOnlyTree+        pure $+          if SI.os == "mingw32"+            then assertEqual "Windows refusals (strict, streamed)" (Left refusal, Left refusal) outcomes+            else assertEqual "trees read back (strict, streamed)" (Right posixOnlyTree, Right posixOnlyTree) outcomes,+      -- The same tree substituted into a temp store: the strict pipeline+      -- unpacks and seals it, then re-serialises the store path from disk+      -- against the narinfo's hash before it registers anything, so a+      -- success means the path's bytes reproduce the NAR.  Windows+      -- refuses it before writing.+      runTestM "a store path holding names upstream restores on POSIX substitutes" $ do+        tmpBase <- getTemporaryDirectory+        let tmpStore = tmpBase </> "nova-nix-test-unpack-posix-store"+            sp = StorePath (T.replicate 32 "c") "posix-names"+            rawNar = NAR.serialise posixOnlyTree+            info = (streamTestNarInfo rawNar) {NarInfo.niStorePath = storePathToText defaultStoreDir sp}+        forceRemoveIfExists tmpStore+        store <- openStore testLogger (StoreDir tmpStore)+        result <- Subst.unpackAndVerify store sp info rawNar+        onDisk <- case result of+          Subst.SubstSuccess _ lock -> do+            releasePathLock lock+            Right <$> NAR.serialiseFromPath (storePathToFilePath (stDir store) sp)+          other -> pure (Left (T.pack (show other)))+        closeStore store+        forceRemoveIfExists tmpStore+        pure $ case onDisk of+          Left shown+            | SI.os == "mingw32" && "is a Windows device name" `T.isInfixOf` shown -> Pass+          _ -> assertEqual "store path read back" (Right posixOnlyTree) onDisk,+      -- A name and a link target with no UTF-8 reading.  Linux holds+      -- both as bytes, as upstream restores them; a macOS volume cannot+      -- hold the name (APFS refuses it, HFS+ rewrites it) but keeps the+      -- target's bytes; Windows holds neither.+      runTestM "bytes with no UTF-8 reading materialize where the host holds them" $ do+        tmpBase <- getTemporaryDirectory+        let dest = tmpBase </> "nova-nix-test-unpack-raw-bytes"+            nameTree = NAR.NarDirectory [("caf\xE9", NAR.NarDirectory [("\xFF", NAR.NarRegular True "x")])]+            targetTree = NAR.NarDirectory [("link", NAR.NarSymlink "caf\xE9")]+            nameRefusal reason = "NAR directory entry name \"caf\\233\" is not valid UTF-8, " <> reason+            targetRefusal = "NAR symlink target \"caf\\233\" is not valid UTF-8, so it has no UTF-16 form for Windows"+            both outcome = (outcome, outcome)+        named <- unpackedBothWays tmpSensitivity dest nameTree+        targeted <- unpackedBothWays tmpSensitivity dest targetTree+        pure $ case SI.os of+          "mingw32" ->+            assertEqual+              "Windows refusals"+              (both (Left (nameRefusal "so it has no UTF-16 form for Windows")), both (Left targetRefusal))+              (named, targeted)+          "darwin" ->+            assertEqual+              "macOS refuses the name and keeps the target"+              (both (Left (nameRefusal "which a macOS filesystem cannot hold")), both (Right targetTree))+              (named, targeted)+          _ ->+            assertEqual+              "Linux keeps both"+              (both (Right nameTree), both (Right targetTree))+              (named, targeted),+      -- The bytes reach the filesystem without passing through the+      -- locale's codec: under an ASCII file-system encoding (a C locale)+      -- or a Latin-1 one a UTF-8 name still lands as its UTF-8 bytes.+      -- Spelled through 'FilePath', the first cannot encode the name and+      -- the second writes other bytes.+      runTestM "names land as their bytes whatever the file-system encoding" $ do+        tmpBase <- getTemporaryDirectory+        let dest = tmpBase </> "nova-nix-test-unpack-codec"+            tree =+              NAR.NarDirectory+                [ ("caf\xC3\xA9", NAR.NarRegular False "e"),+                  ("link", NAR.NarSymlink "\xE2\x9C\x93"),+                  ("\xE2\x9C\x93", NAR.NarRegular False "check")+                ]+            under encodingName = do+              encoding <- mkTextEncoding encodingName+              bracket getFileSystemEncoding setFileSystemEncoding $ \_ -> do+                setFileSystemEncoding encoding+                unpackedBothWays tmpSensitivity dest tree+        if SI.os == "mingw32"+          then Pass <$ putStrLn "  SKIP  a Windows path is UTF-16 and no locale codec spells it"+          else do+            outcomes <- mapM under ["ASCII//ROUNDTRIP", "ISO-8859-1//ROUNDTRIP"]+            pure (assertEqual "trees read back under ASCII and Latin-1 (strict, streamed)" (replicate 2 (Right tree, Right tree)) outcomes),+      -- unpackNarEntry: a NAR symlink materializes as a REAL link or fails+      -- loudly - never as a regular file holding the target text, which+      -- would silently diverge from the NAR hash+      runTestM "unpackNarEntry symlink is real or loud" $ do+        tmpBase <- getTemporaryDirectory+        let dest = tmpBase </> "nova-nix-test-unpack-symlink"+            tree =+              NAR.NarDirectory+                [ ("real", NAR.NarRegular False "contents"),+                  ("link", NAR.NarSymlink "real")+                ]+        Subst.clearStaleDestination dest+        result <- unpackNarEntry tmpSensitivity dest tree+        outcome <- case result of+          Right () -> do+            isLink <- Dir.pathIsSymbolicLink (dest </> "link")+            pure (if isLink then Pass else Fail "symlink materialized as a non-link")+          Left _ -> do+            leftBehind <- Dir.doesFileExist (dest </> "link")+            pure (if leftBehind then Fail "failed loudly but left a regular file behind" else Pass)+        Subst.clearStaleDestination dest+        pure outcome,+      -- unpackNarEntry: a directory-target symlink that sorts BEFORE its+      -- target still gets the directory link flavor (second-pass typing)+      runTestM "unpackNarEntry types forward dir symlink" $ do+        tmpBase <- getTemporaryDirectory+        let dest = tmpBase </> "nova-nix-test-unpack-dirlink"+            tree =+              NAR.NarDirectory+                [ ("alink", NAR.NarSymlink "zdir"),+                  ("zdir", NAR.NarDirectory [("f", NAR.NarRegular False "x")])+                ]+        Subst.clearStaleDestination dest+        result <- unpackNarEntry tmpSensitivity dest tree+        outcome <- case result of+          Left _ -> pure Pass -- symlinks unavailable here; the loud failure is the contract+          Right () -> do+            throughLink <- doesDirectoryExist (dest </> "alink")+            pure (if throughLink then Pass else Fail "dir symlink not traversable (wrong flavor)")+        Subst.clearStaleDestination dest+        pure outcome,+      -- Folding sibling names MATERIALIZE on every platform: true names+      -- via the NTFS per-directory flag on Windows and on any volume the+      -- probe reports sensitive (Linux, case-sensitive APFS), upstream's+      -- case-hack renaming on a folding volume.  The platform serialiser+      -- reverses whichever branch ran, so the tree re-serialises to its+      -- original NAR either way.+      runTestM "folding sibling names materialize and round-trip" $ do+        tmpBase <- getTemporaryDirectory+        let dest = tmpBase </> "nova-nix-test-unpack-fold"+            tree =+              NAR.NarDirectory+                [ ("Foo", NAR.NarRegular False "upper"),+                  ("foo", NAR.NarRegular False "lower")+                ]+        Subst.clearStaleDestination dest+        result <- unpackNarEntry tmpSensitivity dest tree+        outcome <- case result of+          Left err -> pure (Fail ("unpack failed: " <> err))+          Right () -> do+            onDisk <- NAR.serialiseFromPath dest+            if onDisk /= tree+              then pure (Fail "materialized tree does not re-serialise to its NAR")+              else+                if SI.os == "mingw32" || tmpSensitivity == CaseSensitive+                  then do+                    -- True names, not the hack: both spellings hold+                    -- distinct contents.+                    upper <- BS.readFile (dest </> "Foo")+                    lower <- BS.readFile (dest </> "foo")+                    pure (assertEqual "true names" ("upper", "lower") (upper, lower))+                  else do+                    -- The hack: the later variant carries the suffix.+                    lower <- BS.readFile (dest </> "foo~nix~case~hack~1")+                    pure (assertEqual "case-hacked name" "lower" lower)+        Subst.clearStaleDestination dest+        pure outcome,+      -- Every unpack creates exclusively, its root included, as+      -- upstream's restore does: a destination that already holds an+      -- entry is refused with upstream's wording and left as it was,+      -- not truncated or written into.  Callers clear a stale+      -- destination first.  Any volume answers this, so it is the+      -- exclusive create's check on every platform, Windows' CREATE_NEW+      -- included.+      runTestM "unpack refuses a destination that already exists" $ do+        tmpBase <- getTemporaryDirectory+        let dest = tmpBase </> "nova-nix-test-unpack-taken"+            fileTree = NAR.NarRegular False "new"+            dirTree = NAR.NarDirectory [("f", NAR.NarRegular False "new")]+            fileRefusal = "creating file '" <> quotedAsCxx dest <> "': File exists"+            dirOverFile = "creating directory '" <> T.pack dest <> "': File exists"+            dirOverDir = "path '" <> T.pack dest <> "' already exists"+            streamInto tree = do+              let raw = NAR.serialise tree+              source <- chunkReader [raw]+              outcome <- Subst.consumeNarStream tmpSensitivity dest (streamTestNarInfo raw) (CHash.hashBytes raw) source+              pure (either (Left . Subst.attemptFailureMessage) (const (Right ())) outcome)+            strictAndStreamed tree = (,) <$> unpackNarEntry tmpSensitivity dest tree <*> streamInto tree+        Subst.clearStaleDestination dest+        BS.writeFile dest "old"+        fileOnFile <- strictAndStreamed fileTree+        dirOnFile <- strictAndStreamed dirTree+        keptFile <- BS.readFile dest+        Subst.clearStaleDestination dest+        createDirectoryIfMissing True dest+        dirOnDir <- strictAndStreamed dirTree+        wroteInto <- Dir.doesPathExist (dest </> "f")+        Subst.clearStaleDestination dest+        let verdict+              | keptFile /= "old" = Fail "the existing file was written over"+              | wroteInto = Fail "the existing directory was written into"+              | otherwise =+                  assertEqual+                    "refusals, strict and streamed (a file over a file, a directory over a file, a directory over a directory)"+                    ((Left fileRefusal, Left fileRefusal), (Left dirOverFile, Left dirOverFile), (Left dirOverDir, Left dirOverDir))+                    (fileOnFile, dirOnFile, dirOnDir)+        pure verdict,+      -- std::quoted escapes a double quote and a backslash inside the+      -- path, so a name holding both pins upstream's exact text.  A+      -- Windows name can hold neither.+      runTestM "the file refusal quotes its path as std::quoted does" $ do+        tmpBase <- getTemporaryDirectory+        let plain = tmpBase </> "nova-nix-test-unpack-q"+            dest = plain <> "\"b\\s"+            expected = "creating file '\"" <> T.pack plain <> "\\\"b\\\\s\"': File exists"+            tree = NAR.NarRegular False "new"+            raw = NAR.serialise tree+        if SI.os == "mingw32"+          then Pass <$ putStrLn "  SKIP  a Windows name cannot hold a double quote"+          else do+            Subst.clearStaleDestination dest+            BS.writeFile dest "old"+            strict <- unpackNarEntry tmpSensitivity dest tree+            source <- chunkReader [raw]+            streamed <- Subst.consumeNarStream tmpSensitivity dest (streamTestNarInfo raw) (CHash.hashBytes raw) source+            Subst.clearStaleDestination dest+            pure (assertEqual "refusals (strict, streamed)" (Left expected, Left expected) (strict, either (Left . Subst.attemptFailureMessage) (const (Right ())) streamed)),+      -- The exclusive create reaches as far as base's own open on+      -- Windows, where a raw CreateFileW stops at MAX_PATH (260+      -- characters) unless the path is spelled in the file namespace.+      -- Every component here is short; only the whole path is long.+      runTestM "unpack writes a file whose path is past MAX_PATH" $ do+        tmpBase <- getTemporaryDirectory+        let dest = tmpBase </> "nova-nix-test-unpack-long"+            component = replicate 60 'd'+            depth = 5 :: Int+            nest inner = NAR.NarDirectory [(TE.encodeUtf8 (T.pack component), inner)]+            tree = foldr (const nest) (NAR.NarDirectory [("leaf", NAR.NarRegular False "deep")]) [1 .. depth]+            leafPath = foldl' (</>) dest (replicate depth component) </> "leaf"+            raw = NAR.serialise tree+            readLeaf = either (pure . Left) (const (Right <$> BS.readFile leafPath))+        Subst.clearStaleDestination dest+        strict <- unpackNarEntry tmpSensitivity dest tree >>= readLeaf+        Subst.clearStaleDestination dest+        source <- chunkReader [raw]+        streamed <-+          Subst.consumeNarStream tmpSensitivity dest (streamTestNarInfo raw) (CHash.hashBytes raw) source+            >>= readLeaf . either (Left . Subst.attemptFailureMessage) (const (Right ()))+        Subst.clearStaleDestination dest+        pure $+          if length leafPath <= 260+            then Fail "the fixture path is not past MAX_PATH"+            else assertEqual "leaf contents (strict, streamed)" (Right "deep", Right "deep") (strict, streamed),+      -- The pure case-hack naming is a function of the probed+      -- sensitivity, not of the platform: on a folding volume later+      -- case variants gain the reversible suffix with a per-name+      -- counter, on a sensitive one every name keeps its spelling.+      runTest "caseHackDiskNames renames later case variants on a folding volume" $+        assertEqual+          "hack naming"+          [("Foo", "Foo"), ("foo", "foo~nix~case~hack~1"), ("fOO", "fOO~nix~case~hack~2"), ("bar", "bar")]+          (caseHackDiskNames CaseInsensitive ["Foo", "foo", "fOO", "bar"]),+      runTest "caseHackDiskNames keeps every name on a sensitive volume" $+        assertEqual+          "identity naming"+          [("Foo", "Foo"), ("foo", "foo"), ("fOO", "fOO"), ("bar", "bar")]+          (caseHackDiskNames CaseSensitive ["Foo", "foo", "fOO", "bar"]),+      -- The key behind both: case variants share it exactly on a+      -- folding volume.+      runTest "onDiskNameKey folds case only on a folding volume" $+        if onDiskNameKey CaseSensitive "Makefile" /= onDiskNameKey CaseSensitive "makefile"+          && onDiskNameKey CaseInsensitive "Makefile" == onDiskNameKey CaseInsensitive "makefile"+          then Pass+          else Fail "the key does not follow the probed sensitivity",+      -- A name with no UTF-8 reading has no characters to fold, so it+      -- keys as its bytes even on a folding volume.+      runTest "onDiskNameKey keys a name with no UTF-8 reading as its bytes" $+        assertEqual+          "keys of a Latin-1 and a UTF-8 spelling"+          ("caf\xE9", "CAF\xC3\x89")+          (onDiskNameKey CaseInsensitive "caf\xE9", onDiskNameKey CaseInsensitive "caf\xC3\xA9"),+      -- The probe against the filesystem's own answer: two sibling+      -- names differing only by case are two entries on a sensitive+      -- volume and one on a folding one.+      runTestM "probeCaseSensitivity agrees with the filesystem" $ do+        tmpBase <- getTemporaryDirectory+        let dir = tmpBase </> "nova-nix-test-case-probe"+        Subst.clearStaleDestination dir+        createDirectoryIfMissing True dir+        BS.writeFile (dir </> "Probe") "upper"+        BS.writeFile (dir </> "probe") "lower"+        entries <- Dir.listDirectory dir+        probed <- probeCaseSensitivity dir+        Subst.clearStaleDestination dir+        let observed = if length entries == 2 then CaseSensitive else CaseInsensitive+        pure (assertEqual "probe against the filesystem" observed probed),+      -- Where the volume's serialiser strips the suffix (a folding+      -- volume), an incoming name carrying it must reject (it could+      -- not round-trip); on a volume that keeps names apart such a+      -- name is legitimate and materializes verbatim.+      runTestM "incoming case-hack suffix names reject where the serialiser strips" $ do+        tmpBase <- getTemporaryDirectory+        let dest = tmpBase </> "nova-nix-test-unpack-suffix"+            tree = NAR.NarDirectory [("x~nix~case~hack~1", NAR.NarRegular False "v")]+        Subst.clearStaleDestination dest+        result <- unpackNarEntry tmpSensitivity dest tree+        outcome <- case (tmpSensitivity, result) of+          (CaseInsensitive, Left _) -> pure Pass+          (CaseInsensitive, Right ()) -> pure (Fail "suffix-bearing name accepted where the serialiser strips")+          (CaseSensitive, Right ()) -> do+            kept <- BS.readFile (dest </> "x~nix~case~hack~1")+            pure (assertEqual "verbatim where names stay apart" "v" kept)+          (CaseSensitive, Left err) -> pure (Fail ("a volume keeping names apart rejected a legitimate name: " <> err))+        Subst.clearStaleDestination dest+        pure outcome,+      -- The capability probe itself: NTFS grants the per-directory flag+      -- (CI runners and the dev box run NTFS temp dirs); other+      -- platforms report unsupported.+      runTestM "trySetCaseSensitiveDir reflects platform support" $ do+        tmpBase <- getTemporaryDirectory+        let dir = tmpBase </> "nova-nix-test-csdir"+        Subst.clearStaleDestination dir+        createDirectoryIfMissing True dir+        flagged <- trySetCaseSensitiveDir dir+        Subst.clearStaleDestination dir+        pure (assertEqual "flag support" (SI.os == "mingw32") flagged),+      -- unpackAndVerify re-serialises the materialized tree and checks it+      -- against the declared hash before returning a registration: a+      -- faithful round-trip passes, and the registration carries the+      -- declared hash.+      runTestM "unpackAndVerify accepts a tree that reproduces its hash" $ do+        tmpBase <- getTemporaryDirectory+        let tmpStore = tmpBase </> "nova-nix-test-unpack-verify"+        forceRemoveIfExists tmpStore+        store <- openStore testLogger (StoreDir tmpStore)+        let sp = StorePath (T.replicate 32 "b") "roundtrip"+            tree =+              NAR.NarDirectory+                [ ("data.txt", NAR.NarRegular False "verified bytes"),+                  ("sub", NAR.NarDirectory [("inner", NAR.NarRegular False "nested")])+                ]+            rawNar = NAR.serialise tree+            narHash = CHash.formatNixHash (CHash.hashBytes rawNar)+            info =+              NarInfo.NarInfo+                { NarInfo.niStorePath = storePathToText defaultStoreDir sp,+                  NarInfo.niUrl = "nar/roundtrip.nar",+                  NarInfo.niCompression = "none",+                  NarInfo.niFileHash = Nothing,+                  NarInfo.niFileSize = Nothing,+                  NarInfo.niNarHash = narHash,+                  NarInfo.niNarSize = fromIntegral (BS.length rawNar),+                  NarInfo.niReferences = [],+                  NarInfo.niDeriver = Nothing,+                  NarInfo.niSigs = [],+                  NarInfo.niCA = Nothing+                }+        result <- Subst.unpackAndVerify store sp info rawNar+        onDisk <- BS.readFile (storePathToFilePath (stDir store) sp </> "data.txt")+        -- A success carries the path lock still held; release it before+        -- the store teardown (Windows cannot delete a file a handle+        -- holds open).+        case result of+          Subst.SubstSuccess _ lock -> releasePathLock lock+          _ -> pure ()+        closeStore store+        forceRemoveIfExists tmpStore+        pure $ case result of+          Subst.SubstSuccess reg _ ->+            if prNarHash reg == narHash && onDisk == "verified bytes"+              then Pass+              else Fail "registration or on-disk bytes diverge from the declared hash"+          other -> Fail ("unpackAndVerify failed: " <> T.pack (show other)),+      runTestM "a substituted tree takes upstream's modes and the store's time" $ do+        tmpBase <- getTemporaryDirectory+        let tmpStore = tmpBase </> "nova-nix-test-unpack-canonical"+        forceRemoveIfExists tmpStore+        store <- openStore testLogger (StoreDir tmpStore)+        let sp = StorePath (T.replicate 32 "t") "canonical"+            dest = storePathToFilePath (stDir store) sp+            rawNar =+              NAR.serialise+                ( NAR.NarDirectory+                    [ ("data", NAR.NarRegular False "data"),+                      ("run", NAR.NarRegular True "#!/bin/sh\n")+                    ]+                )+            info =+              NarInfo.NarInfo+                { NarInfo.niStorePath = storePathToText defaultStoreDir sp,+                  NarInfo.niUrl = "nar/canonical.nar",+                  NarInfo.niCompression = "none",+                  NarInfo.niFileHash = Nothing,+                  NarInfo.niFileSize = Nothing,+                  NarInfo.niNarHash = CHash.formatNixHash (CHash.hashBytes rawNar),+                  NarInfo.niNarSize = fromIntegral (BS.length rawNar),+                  NarInfo.niReferences = [],+                  NarInfo.niDeriver = Nothing,+                  NarInfo.niSigs = [],+                  NarInfo.niCA = Nothing+                }+        result <- Subst.unpackAndVerify store sp info rawNar+        outcome <- case result of+          Subst.SubstSuccess _ lock -> do+            releasePathLock lock+            foldr andThen Pass+              <$> traverse+                (uncurry canonicalAs)+                [(executablePermissions, dest), (readOnlyPermissions, dest </> "data"), (executablePermissions, dest </> "run")]+          other -> pure (Fail ("unpackAndVerify failed: " <> T.pack (show other)))+        closeStore store+        forceRemoveIfExists tmpStore+        pure outcome,+      -- The verify-fails branch of the strict pipeline: bytes that do+      -- not match the narinfo's NarHash or NarSize never reach+      -- the unpack sink, so nothing is written at the store path and+      -- the lock is free afterwards.+      runTestM "unpackAndVerify writes nothing for a NAR that fails verification" $ do+        tmpBase <- getTemporaryDirectory+        let tmpStore = tmpBase </> "nova-nix-test-unpack-unverified"+        forceRemoveIfExists tmpStore+        store <- openStore testLogger (StoreDir tmpStore)+        let sp = StorePath (T.replicate 32 "f") "unverified"+            rawNar = NAR.serialise (NAR.NarDirectory [("data.txt", NAR.NarRegular False "untrusted bytes")])+            consistent =+              NarInfo.NarInfo+                { NarInfo.niStorePath = storePathToText defaultStoreDir sp,+                  NarInfo.niUrl = "nar/unverified.nar",+                  NarInfo.niCompression = "none",+                  NarInfo.niFileHash = Nothing,+                  NarInfo.niFileSize = Nothing,+                  NarInfo.niNarHash = CHash.formatNixHash (CHash.hashBytes rawNar),+                  NarInfo.niNarSize = toInteger (BS.length rawNar),+                  NarInfo.niReferences = [],+                  NarInfo.niDeriver = Nothing,+                  NarInfo.niSigs = [],+                  NarInfo.niCA = Nothing+                }+            wrongHash = consistent {NarInfo.niNarHash = CHash.formatNixHash (CHash.hashBytes "not the nar")}+            wrongSize = consistent {NarInfo.niNarSize = toInteger (BS.length rawNar) + 1}+            destPath = storePathToFilePath (stDir store) sp+        hashResult <- Subst.unpackAndVerify store sp wrongHash rawNar+        sizeResult <- Subst.unpackAndVerify store sp wrongSize rawNar+        written <- Dir.doesPathExist destPath+        reLock <- tryAcquirePathLock (StoreDir tmpStore) sp+        mapM_ releasePathLock reLock+        closeStore store+        forceRemoveIfExists tmpStore+        pure $ case (hashResult, sizeResult, reLock) of+          (Subst.SubstError hashErr, Subst.SubstError sizeErr, Just _)+            | written -> Fail "an unverified NAR reached the store path"+            | not ("hash mismatch importing path" `T.isPrefixOf` hashErr) -> Fail ("wrong hash error: " <> hashErr)+            | not ("size mismatch importing path" `T.isPrefixOf` sizeErr) -> Fail ("wrong size error: " <> sizeErr)+            | otherwise -> Pass+          (_, _, Nothing) -> Fail "lock still held after a refused NAR"+          other -> Fail ("expected two SubstError results, got: " <> T.pack (show other)),+      -- Upstream refuses to register a path whose stated content address+      -- does not make it, in the strict pipeline as in the streaming one,+      -- and the tree it wrote goes.+      runTestM "unpackAndVerify refuses a content address that makes another path, warning at the error level, and leaves nothing" $ do+        tmpBase <- getTemporaryDirectory+        logged <- newIORef []+        let tmpStore = tmpBase </> "nova-nix-test-unpack-misaddressed"+            recording = plainLogger (\level message -> atomicModifyIORef' logged (\seen -> (seen ++ [(level, message)], ()))) (const (pure ()))+            sp = StorePath (T.replicate 32 "f") "misaddressed"+            spelled = storePathToText defaultStoreDir sp+            rawNar = NAR.serialise (NAR.NarDirectory [("data.txt", NAR.NarRegular False "claims too much")])+            narInfo = strictNarInfo sp rawNar (Just ("fixed:r:sha256:" <> Nix32.encode (fromMaybe BS.empty (rawHashWithAlgo "sha256" rawNar))))+        forceRemoveIfExists tmpStore+        store <- openStore recording (StoreDir tmpStore)+        result <- Subst.unpackAndVerify store sp narInfo rawNar+        written <- Dir.doesPathExist (storePathToFilePath (stDir store) sp)+        closeStore store+        forceRemoveIfExists tmpStore+        said <- readIORef logged+        pure $+          assertEqual+            "refused"+            ( Subst.SubstError ("cannot add path '" <> spelled <> "' to the Nix store because it claims to be content-addressed but isn't"),+              [(LevelError, "warning: path '" <> spelled <> "' claims to be content-addressed but isn't")],+              False+            )+            (result, said, written),+      runTestM "unpackAndVerify registers the content address that makes the path" $ do+        tmpBase <- getTemporaryDirectory+        let tmpStore = tmpBase </> "nova-nix-test-unpack-addressed"+            rawNar = NAR.serialise (NAR.NarDirectory [("data.txt", NAR.NarRegular False "claims what it is")])+            digest = fromMaybe BS.empty (rawHashWithAlgo "sha256" rawNar)+            address = "fixed:r:sha256:" <> Nix32.encode digest+        case makeSourcePath "addressed" digest Set.empty of+          Left err -> pure (Fail (T.pack (show err)))+          Right sp -> do+            forceRemoveIfExists tmpStore+            store <- openStore testLogger (StoreDir tmpStore)+            result <- Subst.unpackAndVerify store sp (strictNarInfo sp rawNar (Just address)) rawNar+            written <- Dir.doesPathExist (storePathToFilePath (stDir store) sp)+            judged <- case result of+              Subst.SubstSuccess reg lock -> do+                releasePathLock lock+                pure (assertEqual "registration" (either (const Nothing) Just (parseContentAddress address), True) (prContentAddress reg, written))+              other -> pure (Fail ("expected a verified path, got: " <> T.pack (show other)))+            closeStore store+            forceRemoveIfExists tmpStore+            pure judged+    ]+  where+    -- The narinfo of a NAR's path, uncompressed, stating a content+    -- address or none.+    strictNarInfo sp rawNar address =+      NarInfo.NarInfo+        { NarInfo.niStorePath = storePathToText defaultStoreDir sp,+          NarInfo.niUrl = "nar/strict.nar",+          NarInfo.niCompression = "none",+          NarInfo.niFileHash = Nothing,+          NarInfo.niFileSize = Nothing,+          NarInfo.niNarHash = CHash.formatNixHash (CHash.hashBytes rawNar),+          NarInfo.niNarSize = toInteger (BS.length rawNar),+          NarInfo.niReferences = [],+          NarInfo.niDeriver = Nothing,+          NarInfo.niSigs = [],+          NarInfo.niCA = address+        }+    -- A tree unpacked into a fresh destination through the strict and+    -- the streaming path, each read back from disk, or the unpack's+    -- refusal.  The read-back tree carries every name and link target+    -- as the bytes on disk, so equal trees serialise to the same NAR.+    unpackedBothWays sensitivity dest tree = do+      let raw = NAR.serialise tree+          streamed = do+            source <- chunkReader [raw]+            outcome <- Subst.consumeNarStream sensitivity dest (streamTestNarInfo raw) (CHash.hashBytes raw) source+            pure (either (Left . Subst.attemptFailureMessage) (const (Right ())) outcome)+          readBack unpack = do+            Subst.clearStaleDestination dest+            result <- unpack+            onDisk <- either (pure . Left) (const (Right <$> NAR.serialiseFromPath dest)) result+            Subst.clearStaleDestination dest+            pure onDisk+      strict <- readBack (unpackNarEntry sensitivity dest tree)+      viaStream <- readBack streamed+      pure (strict, viaStream)+    sampleNarBytes = "nova-nix nar sample bytes" :: BS.ByteString+    sampleNarHash = CHash.formatNixHash (CHash.hashBytes sampleNarBytes)+    wrongNarHash = CHash.formatNixHash (CHash.hashBytes ("different bytes" :: BS.ByteString))+    sampleHash = T.replicate 32 "a"+    sampleNarInfo narHash =+      NarInfo.NarInfo+        { NarInfo.niStorePath = "/nix/store/" <> sampleHash <> "-hello",+          NarInfo.niUrl = "nar/sample.nar",+          NarInfo.niCompression = "none",+          NarInfo.niFileHash = Just sampleNarHash,+          NarInfo.niFileSize = Just 0,+          NarInfo.niNarHash = narHash,+          NarInfo.niNarSize = fromIntegral (BS.length sampleNarBytes),+          NarInfo.niReferences = [],+          NarInfo.niDeriver = Nothing,+          NarInfo.niSigs = [],+          NarInfo.niCA = Nothing+        }+    -- A real xz stream: "nova-nix xz fixture payload\n" 64 times+    -- (1792 bytes) compressed with xz -9 to 112 bytes, embedded as+    -- base64 so the test source stays ASCII.+    xzFixturePayload = BS.concat (replicate 64 "nova-nix xz fixture payload\n")+    xzFixtureSize = toInteger (BS.length xzFixturePayload)+    xzFixtureB64 =+      "/Td6WFoAAATm1rRGAgAhARwAAAAQz1jM4Ab/AC1dADcbyzKSinKbUBue2bMHcUt1zJQMzAec5W6XwPbK3dKJtL3q9K3rfg1KQ/ZOAAAAAAAWUPRD8XwohgABSYAOAAAA2Eg7urHEZ/sCAAAAAARZWg==" :: Text+    -- cache.nixos.org narinfos recorded 2026-08-20 (nixos-25.05+    -- channel), verbatim: GNU hello (references including itself,+    -- deriver, production signature) and a doc output whose References+    -- line is empty.+    recordedHelloNarInfo =+      T.unlines+        [ "StorePath: /nix/store/jppkr0h8aap5z7m4xy4vg5yrwlly9h2v-hello-2.12.1",+          "URL: nar/1m1sbal63vqhlvbcxzdj8yr6fhhld7dsyhxbxwip54dgvg56rjnc.nar.xz",+          "Compression: xz",+          "FileHash: sha256:1m1sbal63vqhlvbcxzdj8yr6fhhld7dsyhxbxwip54dgvg56rjnc",+          "FileSize: 52056",+          "NarHash: sha256:0s8wi24d3bc4zxyxq3hffj102zi7cjp3wqnpj6nhqrwgjsgqff81",+          "NarSize: 249480",+          "References: dska0s3gxxd8azbsn85pwm6xcqhivldw-glibc-2.40-66 jppkr0h8aap5z7m4xy4vg5yrwlly9h2v-hello-2.12.1",+          "Deriver: a9y211d3lq3yf2mpfvb72f0qvsl0wi3s-hello-2.12.1.drv",+          "Sig: cache.nixos.org-1:xV9xUvtPGHTSo6eeFWYYhaNFiH8MYSXKZzmxe0cf+acdDkIYxFPLC/MNc1CjlbsVoaUwGhcigUdr9eW2+W1UAw=="+        ]+    recordedHelloDocNarInfo =+      T.unlines+        [ "StorePath: /nix/store/4xrqj3kcd89bsg5crbpnx1ppg7nxw9xp-hello-1.0.0.2-doc",+          "URL: nar/1r86zzj3g8jhzyvi17vchsj3frrqk5l329viq2i24iish53x922l.nar.xz",+          "Compression: xz",+          "FileHash: sha256:1r86zzj3g8jhzyvi17vchsj3frrqk5l329viq2i24iish53x922l",+          "FileSize: 892",+          "NarHash: sha256:0amizmj17fgj5sz1gvr743kncrzwvq747lml3zhd374f14hzgd7a",+          "NarSize: 2072",+          "References: ",+          "Deriver: 5knzybx32a3iq53jjw6xd6fn4awn2l3h-hello-1.0.0.2.drv",+          "Sig: cache.nixos.org-1:jUFHex7R7zPonZZqjVy/OOTguUZZE/sityC0zvu3sb35Az8zBTROeFhUC/J/UFx8Ui8UflA7uHyLJm5Z+Ca6Bw=="+        ]+    -- A NAR with the shapes streaming unpack must materialize:+    -- nesting, an executable, a symlink, a zero-byte file, an empty+    -- directory, and a sibling pair that collides on folding+    -- filesystems.  Entries in NAR name order.+    -- Both survive a round trip through disk on every platform.  The+    -- executable bit does on Windows because the store keeps it in an+    -- alternate data stream; the nested symlink target does because+    -- nova-cache 0.11.1.1 normalises a Windows reparse point's separators+    -- back to the POSIX spelling at the NAR boundary.+    streamTestLinkTarget = "bin/tool"+    streamTestNar =+      NAR.serialise+        ( NAR.NarDirectory+            [ ("Makefile", NAR.NarRegular False "all:\n"),+              ("bin", NAR.NarDirectory [("tool", NAR.NarRegular True "#!/bin/sh\n")]),+              ("empty", NAR.NarRegular False ""),+              ("emptydir", NAR.NarDirectory []),+              ("link", NAR.NarSymlink streamTestLinkTarget),+              ("makefile", NAR.NarRegular False "lower\n")+            ]+        )+    streamTestDigest = CHash.hashBytes streamTestNar+    streamTestNarInfo rawNar =+      NarInfo.NarInfo+        { NarInfo.niStorePath = "/nix/store/" <> sampleHash <> "-stream",+          NarInfo.niUrl = "nar/stream.nar",+          NarInfo.niCompression = "none",+          NarInfo.niFileHash = Nothing,+          NarInfo.niFileSize = Nothing,+          NarInfo.niNarHash = CHash.formatNixHash (CHash.hashBytes rawNar),+          NarInfo.niNarSize = fromIntegral (BS.length rawNar),+          NarInfo.niReferences = [],+          NarInfo.niDeriver = Nothing,+          NarInfo.niSigs = [],+          NarInfo.niCA = Nothing+        }+    streamChunks chunkLen bytes+      | BS.null bytes = []+      | otherwise = BS.take chunkLen bytes : streamChunks chunkLen (BS.drop chunkLen bytes)+    -- The xz fixture's payload, compressed by nova-cache:zstandard's+    -- own encoder - the exact pairing the push path ships.+    zstdFixtureCompressed = CZstd.compress CZstd.defaultCompressionLevel xzFixturePayload+    -- The same payload compressed by the bzip2 CLI (bzip2 -9),+    -- embedded base64 so the test source stays ASCII.  The reference+    -- encoder is deliberately the format's own tool and not the+    -- decoder's library: nova-cache:bzip2 decodes only, so a+    -- self-produced fixture could not catch the two disagreeing.+    bzip2FixtureB64 =+      "QlpoOTFBWSZTWTop7coAAf/RgAAQQAInJddwIACQKZMTIMjAqqBkDaJtTgCQKgZA5AyBAFwNwMAeAYAgCQLgXA+AoBUCQIAkCAJAUAgCgH4u5IpwoSB0U9uU" :: Text+    -- A NAR every platform materializes identically (no executable+    -- bit, no separator-bearing symlink target), and the bzip2 CLI's+    -- compression of exactly these bytes.+    bzip2NarFixture =+      NAR.serialise+        (NAR.NarDirectory [("greeting", NAR.NarRegular False "nova-nix bzip2 fixture\n")])+    bzip2NarFixtureB64 =+      "QlpoOTFBWSZTWa3VDM4AAFJ5gG7yAIBAYjAAP+ffcCAAlIaTJM1PUnqD1DJpoHo01BkkA9I0AAAAtARwcfWQAq1WLMjpmBpVKUAJM6EA8IDQEABOzcRgdDpvigJ6ZZa760fpxZtj+ts6GDiuqt/B6UuthWIrabWmZTkFlI46C8MmbMoVmMYwEYRUCYQW/F3JFOFCQrdUMzg=" :: Text++-- ---------------------------------------------------------------------------+-- Tests: Push (pure narinfo construction + closure computation)+-- ---------------------------------------------------------------------------++-- | A substituted tree is held to the content address its narinfo+-- states, as upstream's store holds a path it adds: hashed as the+-- address's method reads it, its NAR or the bytes of the one file a flat+-- or text address names, modulo the path's hash part, and refused in+-- upstream's words when that differs.+testStatedContentAddress :: IO [Bool]+testStatedContentAddress = do+  putStrLn "substituter/stated-content-address"+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-stated-ca"+      dir = StoreDir root+      hashPart = T.replicate 32 "c"+      sp = StorePath hashPart "addressed"+      dest = storePathToFilePath dir sp+      digestOf algo bytes = fromMaybe BS.empty (rawHashWithAlgo algo bytes)+      spelled prefix algo digest = prefix <> algo <> ":" <> Nix32.encode digest+      directory = NAR.NarDirectory [("f", NAR.NarRegular False "contents")]+      holdingHashPart = "before " <> TE.encodeUtf8 hashPart <> " after"+      -- Each tree checked against each address, the tree written fresh.+      checked tree address = do+        forceRemoveIfExists root+        createDirectoryIfMissing True root+        sensitivity <- probeCaseSensitivity root+        written <- unpackNarEntry sensitivity dest tree+        result <- either (pure . Left . ("unpack: " <>)) (const (Subst.checkStatedAddress (volumeCaseHack sensitivity) dir sp dest address)) written+        forceRemoveIfExists root+        pure result+      holds label tree address = runTestM label $ assertEqual label (Right (either (const Nothing) Just (parseContentAddress address))) <$> checked tree (Just address)+      mismatch label tree address = runTestM label $ do+        result <- checked tree (Just address)+        pure $ case result of+          Left err+            | ("ca hash mismatch importing path '" <> storePathToText dir sp <> "';\n  specified: ") `T.isPrefixOf` err -> Pass+          other -> Fail ("expected upstream's mismatch, got: " <> T.pack (show other))+      chunkings :: [Int] -> BS.ByteString -> [BS.ByteString]+      chunkings sizes bytes = case sizes of+        _ | BS.null bytes -> []+        size : rest -> BS.take size bytes : chunkings (rest <> [size]) (BS.drop size bytes)+        [] -> [bytes]+      moduloDigest modulus chunks = (\start -> moduloHashFinalize (foldl' moduloHashUpdate start chunks)) <$> moduloHashInit "sha256" modulus+  sequence+    [ runTestM "a narinfo with no content address holds the tree to its NarHash alone" $+        assertEqual "none" (Right Nothing) <$> checked directory Nothing,+      holds "a tree whose NAR has the recursive address stated is held" directory (spelled "fixed:r:" "sha256" (digestOf "sha256" (NAR.serialise directory))),+      holds "an address in another algorithm is read in that one" directory (spelled "fixed:r:" "sha1" (digestOf "sha1" (NAR.serialise directory))),+      mismatch "a tree whose NAR has another digest is refused in upstream's words" directory (spelled "fixed:r:" "sha256" (digestOf "sha256" "something else")),+      holds "a flat address is of the file's bytes" (NAR.NarRegular False "contents") (spelled "fixed:" "sha256" (digestOf "sha256" "contents")),+      holds "a text address is of the file's bytes" (NAR.NarRegular False "contents") (spelled "text:" "sha256" (digestOf "sha256" "contents")),+      runTestM "a flat address names a regular file, and a directory is refused" $ do+        result <- checked directory (Just (spelled "fixed:" "sha256" (digestOf "sha256" "contents")))+        pure (either (const Pass) (const (Fail "a directory was held to a flat address")) result),+      -- Each occurrence of the hash part is hashed as zeros, and its+      -- offset follows the bytes as |OFFSET.+      holds+        "the tree is hashed modulo the path's hash part"+        (NAR.NarRegular False holdingHashPart)+        (spelled "fixed:" "sha256" (digestOf "sha256" ("before " <> BS.replicate 32 0 <> " after" <> "|7"))),+      mismatch "the hash part is not hashed as itself" (NAR.NarRegular False holdingHashPart) (spelled "fixed:" "sha256" (digestOf "sha256" holdingHashPart)),+      runTest "a stream without the hash part hashes as it is" $+        assertEqual "plain" (Just (digestOf "sha256" "abc def")) (moduloDigest "xyz" ["abc ", "def"]),+      runTestM "a digest modulo a hash part is the same however the stream is split" $ do+        result <-+          QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} $+            QC.forAll ((,) <$> QC.listOf (QC.elements "abc") <*> QC.listOf1 (QC.choose (1, 5))) $ \(text, sizes) ->+              let bytes = TE.encodeUtf8 (T.pack text)+               in moduloDigest "abc" (chunkings sizes bytes) QC.=== moduloDigest "abc" [bytes]+        pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))+    ]++-- | The case sensitivity of the suite's temp directory, so a test+-- materializing a NAR there keys sibling names the way a store on that+-- volume would.+tempCaseSensitivity :: IO CaseSensitivity+tempCaseSensitivity = getTemporaryDirectory >>= probeCaseSensitivity++-- ---------------------------------------------------------------------------+-- Tests: NAR and hash known-answer vectors+-- ---------------------------------------------------------------------------++-- | An offer with the URL of the cache whose substitute it carries, the+-- part of a substitute a test can compare.+offerCache :: Realise.Offer Subst.Substitute -> Realise.Offer Text+offerCache offer = case offer of+  Realise.Offered substitute references -> Realise.Offered (Subst.ccUrl (Subst.substituteCache substitute)) references+  Realise.NotOffered -> Realise.NotOffered+  Realise.QueryFailed failure -> Realise.QueryFailed failure++-- | What substituting one path came to: what the store logged, how the+-- batch ended, whether the path is valid after, whether its tree is on+-- disk, and the content address the store records for it, if it+-- records the path.+data Substituted = Substituted+  { subLogged :: [(Level, Text)],+    subOutcome :: Realise.FetchOutcome,+    subValid :: Bool,+    subOnDisk :: Bool,+    subRecorded :: Maybe (Maybe ContentAddress)+  }+  deriving (Eq, Show)++-- | The substituter's narinfo and NAR requests under the transfer+-- layer's retry policy, against a loopback cache.  The policy's effects+-- are recorded rather than slept, so each case states the requests the+-- cache saw and the backoff the policy chose.+testSubstituterRetry :: IO [Bool]+testSubstituterRetry = do+  putStrLn "substituter/retry"+  case signedNarInfo of+    Left err -> (: []) <$> runTest "substituter retry setup" (Fail (T.pack err))+    Right (publicKey, narInfoText) ->+      let narInfoOk = Send (httpResponse "200 OK" (TE.encodeUtf8 narInfoText))+          narOk = Send (httpResponse "200 OK" nar)+          unavailable = Send (httpResponse "503 Service Unavailable" "")+          unsignedNarInfo = Send (httpResponse "200 OK" (TE.encodeUtf8 (NarInfo.renderNarInfo unsigned)))+          trustingCache base = Subst.CacheConfig base [publicKey] [] Subst.RequireSigs+          -- A cache whose settings take a narinfo unsigned.+          lenientCache base = (trustingCache base 40) {Subst.ccRequireSigs = Subst.AcceptUnsigned}+          forbidding = Map.singleton "allowSubstitutes" ""+          -- Realise a derivation whose one output is the fixture's path,+          -- from the caches given, under the adjusted config, in a store+          -- kept under the temporary directory rather than at /nix/store.+          -- Returns the result and whether the output is the substitute's+          -- tree or the builder's file.+          realiseFrom label = realiseWithEnv label Map.empty+          -- 'realiseFrom' for a derivation with more in its environment.+          realiseWithEnv label extraEnv caches adjust = do+            tmpBase <- getTemporaryDirectory+            let root = tmpBase </> ("nova-nix-test-subst-fallback-" ++ label)+                storeDir = StoreDir (root </> "store")+                drvSP = StorePath (T.replicate 32 "d") "retry.drv"+                (builder, builderArgs)+                  | SI.os == "mingw32" = ("cmd.exe", ["/c", "echo built>%out%"])+                  | otherwise = ("/bin/sh", ["-c", "echo built > $out"])+                drv =+                  Derivation+                    { drvOutputs = [DerivationOutput "out" sp "" ""],+                      drvInputDrvs = Map.empty,+                      drvInputSrcs = [],+                      drvPlatform = currentPlatform,+                      drvBuilder = builder,+                      drvArgs = builderArgs,+                      drvEnv = Map.insert "name" "retry" extraEnv+                    }+                config =+                  adjust+                    (defaultBuildConfig storeDir)+                      { bcCaches = caches,+                        bcFetchRetry = defaultFetchRetryPolicy {frpBaseDelayMs = 1}+                      }+                outPath = storePathToFilePath storeDir sp+            bracket_ (forceRemoveIfExists root) (forceRemoveIfExists root) $+              bracket (openStore testLogger storeDir) closeStore $ \store -> do+                writeDrv store drv drvSP+                result <- buildWithDeps config store drv drvSP+                substituted <- Dir.doesFileExist (outPath </> "data")+                built <- Dir.doesFileExist outPath+                pure (result, substituted, built)+          substitute label narInfoReply narReply =+            withHttpServer (route narInfoReply narReply) $ \base requests _ -> do+              tmpBase <- getTemporaryDirectory+              sleeps <- newIORef []+              warnings <- newIORef []+              let root = tmpBase </> ("nova-nix-test-subst-retry-" ++ label)+                  cache = Subst.CacheConfig base [publicKey] [] Subst.RequireSigs 40+                  effects =+                    RetryEffects+                      { reSleepMs = \ms -> atomicModifyIORef' sleeps (\seen -> (seen ++ [ms], ())),+                        reJitter = pure 0,+                        reWarn = \msg -> atomicModifyIORef' warnings (\seen -> (seen ++ [msg], ()))+                      }+              bracket_ (forceRemoveIfExists root) (forceRemoveIfExists root) $+                bracket (openStore testLogger (StoreDir root)) closeStore $ \store -> do+                  result <- offeredThenFetched defaultFetchRetryPolicy effects store [cache] sp+                  outcome <- case result of+                    Subst.SubstSuccess _ lock -> do+                      releasePathLock lock+                      Right <$> BS.readFile (storePathToFilePath (stDir store) sp </> "data")+                    other -> pure (Left other)+                  (,,,,) base outcome <$> requests <*> readIORef sleeps <*> readIORef warnings+       in sequence $+            [ -- The order two processes meet the locks in decides whether they+              -- can deadlock, and each path's NAR is requested under its lock,+              -- so the requests show the order without a race to observe.+              runTestM "a substitution takes its output locks in the order a build does" $ do+                let low = StorePath (T.replicate 32 "a") "lock-order-lib"+                    high = StorePath (T.replicate 32 "z") "lock-order-bin"+                case servedPaths [(high, []), (low, [])] of+                  Left err -> pure (Fail (T.pack err))+                  Right (key, serve) ->+                    withHttpServer (\target _ -> serve target) $ \base requests _ -> do+                      tmpBase <- getTemporaryDirectory+                      let root = tmpBase </> "nova-nix-test-substitute-lock-order"+                          caches = [Subst.CacheConfig base [key] [] Subst.RequireSigs 40]+                          config = (defaultBuildConfig (StoreDir root)) {bcCaches = caches}+                      bracket_ (forceRemoveIfExists root) (forceRemoveIfExists root) $+                        bracket (openStore testLogger (StoreDir root)) closeStore $ \store -> do+                          offers <- evalStateT (traverse (Subst.queryReferencesWith testLogger defaultFetchRetryPolicy quietRetry Realise.NoFallback caches) (high :| [low])) Subst.emptyCacheMemo+                          case traverse offeredSubstitute offers of+                            Nothing -> pure (Fail ("not offered: " <> T.pack (show (fmap offerCache offers))))+                            Just batch -> do+                              _ <- substitutePaths config store Realise.RegisterAll batch+                              assertEqual "NAR requests" (map narRequest [low, high]) . filter (`elem` map narRequest [low, high]) <$> requests,+              runTestM "a reference query believes a signed narinfo for the path" $+                withHttpServer (route (const narInfoOk) (const narOk)) $ \base _ _ ->+                  assertEqual "references" (Realise.Offered base [])+                    <$> queryOffer Realise.NoFallback [trustingCache base 40] sp,+              runTestM "an HTTP cache configured with trailing slashes is asked, and named, without them" $+                withHttpServer (route (const narInfoOk) (const narOk)) $ \base requests _ -> do+                  offer <- queryOffer Realise.NoFallback [trustingCache (base <> "//") 40] sp+                  seen <- requests+                  pure (assertEqual "offer and requests" (Realise.Offered base [], [narInfoPath]) (offer, seen)),+              runTestM "a reference query passes over a narinfo no trusted key signed, with upstream's warning" $+                withHttpServer (route (const unsignedNarInfo) (const narOk)) $ \base _ _ -> do+                  logged <- newIORef []+                  let recording = plainLogger (\level message -> atomicModifyIORef' logged (\seen -> (seen ++ [(level, message)], ()))) (const (pure ()))+                  offer <- evalStateT (Subst.queryReferencesWith recording defaultFetchRetryPolicy quietRetry Realise.NoFallback [trustingCache base 40] sp) Subst.emptyCacheMemo+                  said <- readIORef logged+                  pure $+                    assertEqual "references" Realise.NotOffered (offerCache offer)+                      `andThen` assertEqual+                        "warned"+                        [(LevelWarn, "warning: ignoring substitute for '" <> storePathToText defaultStoreDir sp <> "' from '" <> base <> "', as it's not signed by any of the keys in 'trusted-public-keys'")]+                        said,+              runTestM "under require-sigs off a reference query believes an unsigned narinfo" $+                withHttpServer (route (const unsignedNarInfo) (const narOk)) $ \base _ _ ->+                  assertEqual "references" (Realise.Offered base [])+                    <$> queryOffer Realise.NoFallback [(trustingCache base 40) {Subst.ccRequireSigs = Subst.AcceptUnsigned}] sp,+              runTestM "a reference query passes over a narinfo for another path" $+                withHttpServer (\_ _ -> narInfoOk) $ \base _ _ ->+                  assertEqual "references" Realise.NotOffered+                    <$> queryOffer Realise.NoFallback [trustingCache base 40] (StorePath (T.replicate 32 "c") "retry"),+              -- Upstream refuses to register a path whose stated content+              -- address does not make it, whether or not anything vouched+              -- for its narinfo.+              runTestM "under require-sigs off a narinfo whose content address makes another path is refused at registration, in upstream's words" $+                substitutedAs "misaddressed-unsigned" lenientCache sp (renderedNarInfo (statingAddress (narAddressIn "sha256"))) $ \base result ->+                  assertEqual+                    "refused, nothing registered"+                    (Substituted [(LevelError, claimWarning sp), (LevelInfo, "  [subst] retry: " <> base <> ": " <> claimRefusal sp)] (undelivered sp) False False Nothing)+                    result,+              runTestM "under require-sigs off a narinfo whose content address makes no path is refused at registration, in upstream's words" $+                substitutedAs "no-path-unsigned" lenientCache sp (renderedNarInfo (referencing (statingAddress (narAddressIn "sha1")))) $ \base result ->+                  assertEqual+                    "refused, nothing registered"+                    (Substituted [(LevelInfo, "  [subst] retry: " <> base <> ": " <> fixedRefusal)] (undelivered sp) False False Nothing)+                    result,+              runTestM "a signed narinfo whose content address makes another path is warned of at the query and again at registration, then refused" $+                case signedNarInfoFor (statingAddress (narAddressIn "sha256")) of+                  Left err -> pure (Fail (T.pack err))+                  Right (_, signedText) ->+                    substitutedAs "misaddressed-signed" (`trustingCache` 40) sp (TE.encodeUtf8 signedText) $ \base result ->+                      assertEqual+                        "refused, nothing registered"+                        (Substituted [(LevelError, claimWarning sp), (LevelError, claimWarning sp), (LevelInfo, "  [subst] retry: " <> base <> ": " <> claimRefusal sp)] (undelivered sp) False False Nothing)+                        result,+              runTestM "an unsigned narinfo whose content address makes its path is substituted and registered with that address, though signatures are required" $+                case addressedPath of+                  Left err -> pure (Fail (T.pack (show err)))+                  Right target ->+                    let addressed = (statingAddress (narAddressIn "sha256")) {NarInfo.niStorePath = storePathToText defaultStoreDir target}+                     in substitutedAs "addressed-unsigned" (`trustingCache` 40) target (renderedNarInfo addressed) $ \_ result ->+                          assertEqual+                            "registered"+                            (Substituted [] Realise.Fetched True True (Just (either (const Nothing) Just (parseContentAddress (narAddressIn "sha256")))))+                            result,+              -- Upstream decides trust outside the try that makes a failed+              -- narinfo query its cache's, so these end the query under+              -- every fallback, and the caches after are not asked.+              runTestM "a narinfo whose content address makes no path ends a reference query whatever the fallback" $+                withHttpServer (route (const (Send (httpResponse "200 OK" (renderedNarInfo (referencing (statingAddress (narAddressIn "sha1"))))))) (const narOk)) $ \failing _ _ ->+                  withHttpServer (route (const narInfoOk) (const narOk)) $ \working workingRequests _ -> do+                    offers <- traverse (\fallback -> queryOffer fallback [trustingCache failing 10, trustingCache working 40] sp) [Realise.NoFallback, Realise.BuildFromSource]+                    seen <- workingRequests+                    pure (assertEqual "stopped" (replicate 2 (Realise.QueryFailed (failing <> ": retry: " <> fixedRefusal)), []) (offers, seen)),+              runTestM "a secret key file that holds no key ends a reference query whatever the fallback" $ do+                tmpBase <- getTemporaryDirectory+                let root = tmpBase </> "nova-nix-test-subst-corrupt-key"+                    keyFile = root </> "corrupt-key"+                bracket_ (forceRemoveIfExists root >> createDirectoryIfMissing True root >> BS.writeFile keyFile "not a key\n") (forceRemoveIfExists root) $+                  argumentBytes keyFile >>= \case+                    Nothing -> pure (Fail "the key file's path has no spelling as bytes")+                    Just file ->+                      withHttpServer (route (const narInfoOk) (const narOk)) $ \failing _ _ ->+                        withHttpServer (route (const narInfoOk) (const narOk)) $ \working workingRequests _ -> do+                          offers <- traverse (\fallback -> queryOffer fallback [(trustingCache failing 10) {Subst.ccSecretKeyFiles = [file]}, trustingCache working 40] sp) [Realise.NoFallback, Realise.BuildFromSource]+                          seen <- workingRequests+                          pure (assertEqual "stopped" (replicate 2 (Realise.QueryFailed (failing <> ": retry: key is corrupt")), []) (offers, seen)),+              runTestM "a trusted public key that does not read ends a reference query whatever the fallback" $+                withHttpServer (route (const narInfoOk) (const narOk)) $ \failing _ _ ->+                  withHttpServer (route (const narInfoOk) (const narOk)) $ \working workingRequests _ -> do+                    offers <- traverse (\fallback -> queryOffer fallback [(trustingCache failing 10) {Subst.ccPublicKeys = ["not-a-key"]}, trustingCache working 40] sp) [Realise.NoFallback, Realise.BuildFromSource]+                    seen <- workingRequests+                    pure $ case offers of+                      [Realise.QueryFailed noFallback, Realise.QueryFailed fallback]+                        | all (T.isPrefixOf (failing <> ": retry: invalid public key")) [noFallback, fallback] && null seen -> Pass+                      _ -> Fail ("expected both queries to fail on the key, with no later cache asked, got: " <> T.pack (show (offers, seen))),+              runTestM "under fallback a narinfo whose content address makes no path stops the build instead of building" $+                withHttpServer (route (const (Send (httpResponse "200 OK" (renderedNarInfo (referencing (statingAddress (narAddressIn "sha1"))))))) (const narOk)) $ \base _ _ -> do+                  (result, substituted, built) <- realiseFrom "no-path-fallback" [trustingCache base 40] (\config -> config {bcFallback = Realise.BuildFromSource})+                  pure (assertEqual "stopped" (BuildFailure (base <> ": retry: " <> fixedRefusal) 1, False, False) (result, substituted, built)),+              -- Upstream rethrows a failed narinfo query unless fallback is+              -- set, so a later cache holding the path is never asked.+              runTestM "a reference query stops at a failing cache" $+                withHttpServer (route (const unavailable) (const narOk)) $ \failing _ _ ->+                  withHttpServer (route (const narInfoOk) (const narOk)) $ \working workingRequests _ -> do+                    offer <- queryOffer Realise.NoFallback [trustingCache failing 10, trustingCache working 40] sp+                    seen <- workingRequests+                    pure (assertEqual "stopped" (Realise.QueryFailed (failing <> ": retry: HTTP 503 fetching " <> failing <> "/" <> hash <> ".narinfo"), []) (offer, seen)),+              runTestM "a reference query stops at the first cache that offers the path" $+                withHttpServer (route (const narInfoOk) (const narOk)) $ \first _ _ ->+                  withHttpServer (route (const narInfoOk) (const narOk)) $ \later laterRequests _ -> do+                    offer <- queryOffer Realise.NoFallback [trustingCache first 10, trustingCache later 40] sp+                    seen <- laterRequests+                    pure (assertEqual "offered by the first" (Realise.Offered first [], []) (offer, seen)),+              runTestM "a reference query that no cache answers offers nothing, asking each cache once" $+                withHttpServer (\_ _ -> Send (httpResponse "404 Not Found" "")) $ \first firstRequests _ ->+                  withHttpServer (\_ _ -> Send (httpResponse "404 Not Found" "")) $ \later laterRequests _ -> do+                    offer <- queryOffer Realise.NoFallback [trustingCache first 10, trustingCache later 40] sp+                    seen <- (,) <$> firstRequests <*> laterRequests+                    pure (assertEqual "not offered" (Realise.NotOffered, ([narInfoPath], [narInfoPath])) (offer, seen)),+              runTestM "under fallback a reference query falls through a failing cache to the next" $+                withHttpServer (route (const unavailable) (const narOk)) $ \failing _ _ ->+                  withHttpServer (route (const narInfoOk) (const narOk)) $ \working _ _ ->+                    assertEqual "references" (Realise.Offered working [])+                      <$> queryOffer Realise.BuildFromSource [trustingCache failing 10, trustingCache working 40] sp,+              -- The whole realisation, against upstream's outcomes: a cache+              -- that fails stops the build unless fallback is on, and one+              -- that lacks the path or offers an untrusted narinfo does not.+              -- The .drv is named under the logical store directory, as+              -- upstream's printStorePath names it, though the store's files+              -- are kept elsewhere.+              runTestM "a NAR that fails after its retries stops the build and names --fallback" $+                withHttpServer (route (const narInfoOk) (const unavailable)) $ \base _ _ -> do+                  (result, substituted, built) <- realiseFrom "nar-down" [trustingCache base 40] id+                  pure+                    ( assertEqual+                        "stopped"+                        ( BuildFailure+                            ( "some substitutes for the outputs of derivation '/nix/store/"+                                <> T.replicate 32 "d"+                                <> "-retry.drv' failed (usually happens due to networking issues); try '--fallback' to build derivation from source"+                            )+                            1,+                          False,+                          False+                        )+                        (result, substituted, built)+                    ),+              runTestM "under fallback a NAR that fails builds from source instead" $+                withHttpServer (route (const narInfoOk) (const unavailable)) $ \base _ _ -> do+                  (result, substituted, built) <- realiseFrom "nar-down-fallback" [trustingCache base 40] (\config -> config {bcFallback = Realise.BuildFromSource})+                  pure (assertEqual "built" (BuildSuccess sp, False, True) (result, substituted, built)),+              -- 'bcSubstitutes' reaches the decision: the cache serves the+              -- output whole, and is asked for nothing.+              runTestM "a derivation that forbids substitutes builds beside a cache that serves its output" $+                withHttpServer (route (const narInfoOk) (const narOk)) $ \base requests _ -> do+                  (result, substituted, built) <- realiseWithEnv "forbidden" forbidding [trustingCache base 40] id+                  seen <- requests+                  pure (assertEqual "built" (BuildSuccess sp, False, True, []) (result, substituted, built, seen)),+              runTestM "under always-allow-substitutes the same derivation is substituted" $+                withHttpServer (route (const narInfoOk) (const narOk)) $ \base _ _ -> do+                  (result, substituted, built) <-+                    realiseWithEnv "forbidden-always" forbidding [trustingCache base 40] (\config -> config {bcSubstitutes = Realise.AlwaysAllowSubstitutes})+                  pure (assertEqual "substituted" (BuildSuccess sp, True, False) (result, substituted, built)),+              runTestM "a narinfo the cache lacks builds, with no flag" $+                withHttpServer (\_ _ -> Send (httpResponse "404 Not Found" "")) $ \base requests _ -> do+                  (result, substituted, built) <- realiseFrom "narinfo-404" [trustingCache base 40] id+                  seen <- requests+                  pure (assertEqual "built" (BuildSuccess sp, False, True, [narInfoPath]) (result, substituted, built, seen)),+              runTestM "a narinfo that fails after its retries stops the build with the failure" $+                withHttpServer (route (const unavailable) (const narOk)) $ \base requests _ -> do+                  (result, substituted, built) <- realiseFrom "narinfo-down" [trustingCache base 40] id+                  seen <- requests+                  pure+                    ( assertEqual+                        "stopped"+                        (BuildFailure (base <> ": retry: HTTP 503 fetching " <> base <> "/" <> hash <> ".narinfo") 1, False, False, replicate 5 narInfoPath)+                        (result, substituted, built, seen)+                    ),+              runTestM "under fallback a narinfo that fails builds from source instead" $+                withHttpServer (route (const unavailable) (const narOk)) $ \base _ _ -> do+                  (result, substituted, built) <- realiseFrom "narinfo-down-fallback" [trustingCache base 40] (\config -> config {bcFallback = Realise.BuildFromSource})+                  pure (assertEqual "built" (BuildSuccess sp, False, True) (result, substituted, built)),+              runTestM "an unsigned narinfo is passed over for the next cache" $+                withHttpServer (route (const unsignedNarInfo) (const narOk)) $ \untrusted untrustedRequests _ ->+                  withHttpServer (route (const narInfoOk) (const narOk)) $ \trusted _ _ -> do+                    (result, substituted, built) <- realiseFrom "unsigned-then-signed" [trustingCache untrusted 10, trustingCache trusted 40] id+                    seen <- untrustedRequests+                    pure (assertEqual "substituted" (BuildSuccess sp, True, False, False) (result, substituted, built, narPath `elem` seen)),+              runTestM "an unsigned narinfo alone builds, with no flag" $+                withHttpServer (route (const unsignedNarInfo) (const narOk)) $ \base requests _ -> do+                  (result, substituted, built) <- realiseFrom "unsigned" [trustingCache base 40] id+                  seen <- requests+                  pure (assertEqual "built" (BuildSuccess sp, False, True, False) (result, substituted, built, narPath `elem` seen)),+              runTestM "a narinfo that fails once with a 503 is fetched on the retry" $ do+                (base, outcome, seen, sleeps, warnings) <-+                  substitute "narinfo-503" (\earlier -> if earlier == 0 then unavailable else narInfoOk) (const narOk)+                pure+                  ( assertEqual+                      "substituted after one retry"+                      (Right payload, [narInfoPath, narInfoPath, narPath], [250], ["HTTP 503 fetching " <> base <> "/" <> hash <> ".narinfo; retrying in 250 ms"])+                      (outcome, seen, sleeps, warnings)+                  ),+              runTestM "a narinfo that keeps failing spends upstream's five attempts and doubling delay" $ do+                (_, outcome, seen, sleeps, _) <- substitute "narinfo-down" (const unavailable) (const narOk)+                pure $ case outcome of+                  Left (Subst.SubstError _) -> assertEqual "attempts" (replicate 5 narInfoPath, [250, 500, 1000, 2000]) (seen, sleeps)+                  other -> Fail ("expected a substitution error, got: " <> T.pack (show other)),+              runTestM "a NAR download answering 501 stops after one request and names the cache" $ do+                (base, outcome, seen, sleeps, _) <-+                  substitute "nar-501" (const narInfoOk) (const (Send (httpResponse "501 Not Implemented" "")))+                pure $ case outcome of+                  Left (Subst.SubstError err)+                    | (base <> ": ") `T.isPrefixOf` err && "HTTP 501" `T.isInfixOf` err -> assertEqual "one request" ([narInfoPath, narPath], []) (seen, sleeps)+                  other -> Fail ("expected an HTTP 501 substitution error, got: " <> T.pack (show other)),+              -- One attempt follows the client's redirect limit, then stops.+              runTestM "a NAR redirect loop stops after one attempt" $ do+                (_, outcome, seen, sleeps, _) <-+                  substitute "nar-redirect" (const narInfoOk) (const (Send "HTTP/1.1 302 Found\r\nLocation: /nar/retry.nar\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"))+                pure $ case outcome of+                  Left (Subst.SubstError err)+                    | "too many redirects" `T.isInfixOf` err ->+                        assertEqual "one attempt" (narInfoPath : replicate (HTTP.redirectCount HTTP.defaultRequest + 1) narPath, []) (seen, sleeps)+                  other -> Fail ("expected a redirect-loop substitution error, got: " <> T.pack (show other)),+              runTestM "a torn NAR transfer is retried from its first byte" $ do+                let torn = "HTTP/1.1 200 OK\r\nContent-Length: " <> TE.encodeUtf8 (T.pack (show (BS.length nar))) <> "\r\nConnection: close\r\n\r\n" <> BS.take 10 nar+                (base, outcome, seen, sleeps, warnings) <-+                  substitute "nar-torn" (const narInfoOk) (\earlier -> if earlier == 0 then Send torn else narOk)+                let warnedTorn = case warnings of+                      [warning] -> ("download error fetching " <> base <> "/nar/retry.nar: ResponseBodyTooShort") `T.isPrefixOf` warning+                      _ -> False+                pure $+                  if warnedTorn+                    then assertEqual "substituted after one retry" (Right payload, [narInfoPath, narPath, narPath], [250]) (outcome, seen, sleeps)+                    else Fail ("unexpected warnings: " <> T.pack (show warnings)),+              -- A cache that names a NAR by its NarHash, as cache.nixos.org+              -- names its zstd NARs, serves one file for every path with+              -- that NAR, and an upload that compresses the NAR again+              -- replaces it, so an earlier narinfo's FileSize and FileHash+              -- describe bytes the cache no longer serves.  The signed+              -- NarHash and NarSize still describe the NAR in the file.+              runTestM "a NAR longer than its narinfo's FileSize, under a FileHash of other bytes, is substituted" $+                case signedNarInfoFor staleFileFields of+                  Left err -> pure (Fail (T.pack err))+                  Right (_, staleText) -> do+                    (_, outcome, seen, sleeps, _) <-+                      substitute "stale-file-fields" (const (Send (httpResponse "200 OK" (TE.encodeUtf8 staleText)))) (const narOk)+                    pure (assertEqual "substituted" (Right payload, [narInfoPath, narPath], []) (outcome, seen, sleeps)),+              -- The signed NarSize bounds the body.  This body is the start+              -- of a NAR whose one file runs past the ceiling, so the parser+              -- is still reading when the cap stops the transfer, and a body+              -- past its signed ceiling is never asked for again.+              runTestM "a NAR body one byte past its signed ceiling fails after one request" $ do+                let ceilingBytes = Subst.compressedBodyCeiling (NarInfo.niNarSize unsigned)+                    pastCeiling = BS.take (fromInteger ceilingBytes + 1) (NAR.serialise (NAR.NarRegular False (BS.replicate (fromInteger ceilingBytes) 0x78)))+                (base, outcome, seen, sleeps, _) <-+                  substitute "past-ceiling" (const narInfoOk) (const (Send (httpResponse "200 OK" pastCeiling)))+                pure $+                  assertEqual "body" (fromInteger ceilingBytes + 1) (BS.length pastCeiling)+                    `andThen` assertEqual+                      "stopped"+                      (Left (Subst.SubstError (base <> ": NAR body exceeds its download ceiling (" <> T.pack (show ceilingBytes) <> " bytes)")), [narInfoPath, narPath], [])+                      (outcome, seen, sleeps)+            ]+              -- Upstream's NotFound and Forbidden: a binary cache store+              -- reads both as the file not being in that cache.+              ++ [ runTestM ("a narinfo answered " <> status <> " is a miss, not retried") $ do+                     (_, outcome, seen, sleeps, _) <-+                       substitute ("narinfo-" ++ statusCode status) (const (Send (httpResponse (TE.encodeUtf8 status) ""))) (const narOk)+                     pure (assertEqual "miss" (Left Subst.SubstNotFound, [narInfoPath], []) (outcome, seen, sleeps))+                 | status <- notInCache+                 ]+              -- A NAR the narinfo named and the cache no longer holds is+              -- upstream's SubstituteGone: one request, never retried, and+              -- a miss rather than a failed substitute.+              ++ [ runTestM ("a NAR answered " <> status <> " is a miss after one request") $ do+                     (_, outcome, seen, sleeps, _) <-+                       substitute ("nar-" ++ statusCode status) (const narInfoOk) (const (Send (httpResponse (TE.encodeUtf8 status) "")))+                     pure (assertEqual "gone" (Left Subst.SubstNotFound, [narInfoPath, narPath], []) (outcome, seen, sleeps))+                 | status <- notInCache+                 ]+  where+    notInCache :: [Text]+    notInCache = ["404 Not Found", "410 Gone", "401 Unauthorized", "403 Forbidden", "407 Proxy Authentication Required"]+    statusCode = T.unpack . T.take 3+    quietRetry = RetryEffects {reSleepMs = const (pure ()), reJitter = pure 0, reWarn = const (pure ())}+    queryOffer fallback caches path =+      offerCache <$> evalStateT (Subst.queryReferencesWith testLogger defaultFetchRetryPolicy quietRetry fallback caches path) Subst.emptyCacheMemo+    hash = T.replicate 32 "b"+    sp = StorePath hash "retry"+    narInfoPath = "/" <> TE.encodeUtf8 hash <> ".narinfo"+    narPath = "/nar/retry.nar"+    payload = "retried payload\n"+    nar = NAR.serialise (NAR.NarDirectory [("data", NAR.NarRegular False payload)])+    unsigned =+      NarInfo.NarInfo+        { NarInfo.niStorePath = "/nix/store/" <> hash <> "-retry",+          NarInfo.niUrl = "nar/retry.nar",+          NarInfo.niCompression = "none",+          NarInfo.niFileHash = Nothing,+          NarInfo.niFileSize = Nothing,+          NarInfo.niNarHash = CHash.formatNixHash (CHash.hashBytes nar),+          NarInfo.niNarSize = fromIntegral (BS.length nar),+          NarInfo.niReferences = [],+          NarInfo.niDeriver = Nothing,+          NarInfo.niSigs = [],+          NarInfo.niCA = Nothing+        }+    -- The file fields another compression of the NAR gives: a FileSize+    -- 139 bytes short of the body served, and a FileHash of other bytes.+    staleFileFields =+      unsigned+        { NarInfo.niFileSize = Just (NarInfo.niNarSize unsigned - 139),+          NarInfo.niFileHash = Just (CHash.formatNixHash (CHash.hashBytes "another compression of the NAR"))+        }+    signedNarInfo = signedNarInfoFor unsigned+    -- The fixture's digest in an algorithm, and the recursive content+    -- address that digest of its NAR spells.+    narDigestIn algo = fromMaybe BS.empty (rawHashWithAlgo algo nar)+    narAddressIn algo = "fixed:r:" <> algo <> ":" <> Nix32.encode (narDigestIn algo)+    -- The path that address makes, as upstream makes a path from a NAR's+    -- SHA-256: a source path of the fixture's name.+    addressedPath = makeSourcePath "retry" (narDigestIn "sha256") Set.empty+    -- The fixture's narinfo stating an address, and one that also names a+    -- reference, which no fixed address but a NAR's SHA-256 may.+    statingAddress address = unsigned {NarInfo.niCA = Just address}+    referencing narInfo = narInfo {NarInfo.niReferences = [T.replicate 32 "d" <> "-dep"]}+    renderedNarInfo = TE.encodeUtf8 . NarInfo.renderNarInfo+    -- Upstream's words for a path whose address says it is what it is not.+    claimWarning target = "warning: path '" <> storePathToText defaultStoreDir target <> "' claims to be content-addressed but isn't"+    claimRefusal target = "cannot add path '" <> storePathToText defaultStoreDir target <> "' to the Nix store because it claims to be content-addressed but isn't"+    -- Upstream's refusal of a fixed address stated with references.+    fixedRefusal = "fixed output derivation 'retry' is not allowed to refer to other store paths.\nYou may need to use the 'unsafeDiscardReferences' derivation attribute, see the manual for more details."+    -- What a failed batch of the fixture's path reports.+    undelivered target = Realise.NotFetched ((target, Realise.DeliveryFailed) :| [])+    -- Substitute a path as a build does, in a store of its own, from a+    -- cache serving the narinfo given for it and the fixture's NAR, and+    -- judge what came of it.+    substitutedAs label cache target narInfoBytes judge =+      withHttpServer (routeAt target (const (Send (httpResponse "200 OK" narInfoBytes))) (const (Send (httpResponse "200 OK" nar)))) $ \base _ _ -> do+        tmpBase <- getTemporaryDirectory+        logged <- newIORef []+        let root = tmpBase </> ("nova-nix-test-subst-registered-" ++ label)+            storeDir = StoreDir root+            recording = plainLogger (\level message -> atomicModifyIORef' logged (\seen -> (seen ++ [(level, message)], ()))) (const (pure ()))+            caches = [cache base]+            config = (defaultBuildConfig storeDir) {bcCaches = caches}+        bracket_ (forceRemoveIfExists root) (forceRemoveIfExists root) $+          bracket (openStore recording storeDir) closeStore $ \store -> do+            offer <- evalStateT (Subst.queryReferencesWith recording defaultFetchRetryPolicy quietRetry Realise.NoFallback caches target) Subst.emptyCacheMemo+            case offeredSubstitute offer of+              Nothing -> pure (Fail ("not offered: " <> T.pack (show (offerCache offer))))+              Just substitute -> do+                outcome <- substitutePaths config store Realise.RegisterAll (substitute :| [])+                valid <- isValid store target+                onDisk <- Dir.doesPathExist (storePathToFilePath storeDir target)+                recorded <- queryPathInfo (stDB store) target+                said <- readIORef logged+                pure (judge base (Substituted said outcome valid onDisk (piContentAddress <$> recorded)))+    -- A narinfo signed by 'sigTestKeyText' and rendered, with the public+    -- key that verifies it.+    signedNarInfoFor info = do+      secretKey <- Signing.parseSecretKey sigTestKeyText+      publicKey <- Signing.toPublicKey secretKey+      sig <- Signing.sign secretKey info+      pure (Signing.renderPublicKey publicKey, NarInfo.renderNarInfo info {NarInfo.niSigs = [sig]})+    route = routeAt sp+    -- What a cache answers for one path's narinfo and the fixture's NAR.+    routeAt target narInfoReply narReply path earlier+      | path == "/" <> TE.encodeUtf8 (spHash target) <> ".narinfo" = narInfoReply earlier+      | path == narPath = narReply earlier+      | otherwise = Send (httpResponse "500 Internal Server Error" "unexpected request")++-- ---------------------------------------------------------------------------+-- Tests: store-path name validation at write sinks+-- ---------------------------------------------------------------------------++-- | 'posixOnlyEntries' as one directory.+posixOnlyTree :: NAR.NarEntry+posixOnlyTree = NAR.NarDirectory posixOnlyEntries++-- ---------------------------------------------------------------------------+-- Tests: substituter signature verification (the --trusted-key trust gate)+-- ---------------------------------------------------------------------------++-- | Minimal narinfo for signing tests; the fingerprint covers StorePath,+-- NarHash, NarSize, and References.+sigTestNarInfo :: NarInfo.NarInfo+sigTestNarInfo =+  NarInfo.NarInfo+    { NarInfo.niStorePath = "/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-hello-1.0",+      NarInfo.niUrl = "nar/aaaa.nar",+      NarInfo.niCompression = "none",+      NarInfo.niFileHash = Just ("sha256:" <> T.replicate 52 "0"),+      NarInfo.niFileSize = Just 1,+      NarInfo.niNarHash = "sha256:" <> T.replicate 52 "0",+      NarInfo.niNarSize = 1,+      NarInfo.niReferences = [],+      NarInfo.niDeriver = Nothing,+      NarInfo.niSigs = [],+      NarInfo.niCA = Nothing+    }++-- | A substituter cache trusting the given public key text.+sigTestCache :: Text -> Subst.CacheConfig+sigTestCache publicKeyText =+  Subst.CacheConfig+    { Subst.ccUrl = "http://localhost/test-cache",+      Subst.ccPublicKeys = [publicKeyText],+      Subst.ccSecretKeyFiles = [],+      Subst.ccRequireSigs = Subst.RequireSigs,+      Subst.ccPriority = 40+    }++-- | The keys 'Subst.defaultCacheConfig' trusts.+defaultCacheKeys :: Either String [Signing.PublicKey]+defaultCacheKeys = traverse Signing.parsePublicKey (Subst.ccPublicKeys Subst.defaultCacheConfig)++-- | Whether one of the keys given signed a narinfo, or why not.+signedUnder :: Either String [Signing.PublicKey] -> NarInfo.NarInfo -> Either Text ()+signedUnder keys narInfo = case keys of+  Left err -> Left (T.pack err)+  Right parsed+    | Subst.verifySigs parsed narInfo -> Right ()+    | otherwise -> Left "no trusted key signed the narinfo"++-- | The keys a cache's settings have its narinfos judged under, read as+-- the substituter reads them, or why they do not read.+keysOf :: Subst.CacheConfig -> IO (Either Text [Signing.PublicKey])+keysOf cache =+  Subst.cacheRequirement cache <&> \case+    Left err -> Left err+    Right (RequireSignature keys) -> Right keys+    Right SignaturesNotRequired -> Left "no signature is required"++-- | Derive (trusted cache, signature by the trusted key, signature by an+-- impostor key with the same name).  Left on any setup failure.+sigTestSetup :: Either String (Subst.CacheConfig, Text, Text)+sigTestSetup = do+  secretKey <- Signing.parseSecretKey sigTestKeyText+  impostorKey <- Signing.parseSecretKey sigTestWrongKeyText+  publicKey <- Signing.toPublicKey secretKey+  let publicKeyText = Signing.renderPublicKey publicKey+  validSig <- Signing.sign secretKey sigTestNarInfo+  impostorSig <- Signing.sign impostorKey sigTestNarInfo+  pure (sigTestCache publicKeyText, validSig, impostorSig)++-- | The trust gate behind @--trusted-key@: unsigned narinfos,+-- wrong-key signatures, and malformed trusted keys must all be+-- rejected; a valid signature must be accepted.  The keys trusted are+-- read as the substituter reads them: @trusted-public-keys@, then the+-- public key of the secret key in each of @secret-key-files@, a file+-- that cannot be read passed over, and the first key of a name kept.+testVerifySigs :: IO [Bool]+testVerifySigs = do+  putStrLn "substituter/verify-sigs"+  tmpBase <- getTemporaryDirectory+  let root = tmpBase </> "nova-nix-test-verify-sigs"+      keyFile = root </> "secret-key"+      corruptFile = root </> "corrupt-key"+      shortFile = root </> "short-key"+      missingFile = root </> "missing-key"+      spelled path = argumentBytes path >>= maybe (ioError (userError ("'" <> path <> "' has no spelling as bytes"))) pure+  case (sigTestSetup, sigTestSecretKeyFile) of+    (Left err, _) -> (: []) <$> runTest "verifySigs test setup" (Fail (T.pack err))+    (_, Left err) -> (: []) <$> runTest "verifySigs test setup" (Fail (T.pack err))+    (Right (cache, validSig, impostorSig), Right secretKeyFile) -> do+      forceRemoveIfExists root+      createDirectoryIfMissing True root+      BS.writeFile keyFile secretKeyFile+      BS.writeFile corruptFile "not a key\n"+      BS.writeFile shortFile ("test-key-1:" <> TE.encodeUtf8 (B64.encode (BS.replicate 32 1)) <> "\n")+      trusted <- keysOf cache+      let signedWith sigs = sigTestNarInfo {NarInfo.niSigs = sigs}+          verifying expected sigs = either (Fail . ("the trusted keys: " <>)) (\keys -> assertEqual "verified" expected (Subst.verifySigs keys (signedWith sigs)))+          noKeys = cache {Subst.ccPublicKeys = []}+      results <-+        sequence+          [ runTest "valid signature accepted" (verifying True [validSig] trusted),+            runTest "unsigned narinfo rejected" (verifying False [] trusted),+            runTest "same-name signature from a different key rejected" (verifying False [impostorSig] trusted),+            runTest "valid signature among invalid ones accepted" (verifying True [impostorSig, validSig] trusted),+            runTest "signature under a different key name rejected" (verifying False ["other-key:" <> T.drop (T.length "test-key-1:") validSig] trusted),+            runTestM "malformed trusted public key rejected" $+              assertLeft "bad pubkey" <$> keysOf (sigTestCache "not-a-key"),+            -- The flat trusted-key set: a signature valid under ANY of+            -- several trusted keys is accepted, even when the matching key+            -- is not first.+            runTestM "a signature valid under any of several trusted keys is accepted" $+              verifying True [validSig] <$> keysOf cache {Subst.ccPublicKeys = Subst.ccPublicKeys Subst.defaultCacheConfig ++ Subst.ccPublicKeys cache},+            runTestM "a signature matching none of several trusted keys is rejected" $+              verifying False [validSig] <$> keysOf cache {Subst.ccPublicKeys = ["cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=", "other.cache-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY="]},+            -- A malformed key anywhere in the set is an error, not a+            -- silently skipped key: a typo must not quietly narrow the+            -- trusted set to the keys that happened to parse.+            runTestM "a malformed key among valid ones is an error, not skipped" $+              assertLeft "typo not skipped" <$> keysOf cache {Subst.ccPublicKeys = "not-a-key" : Subst.ccPublicKeys cache},+            runTestM "the public key of a secret key in secret-key-files is trusted, and a file that cannot be read is passed over" $ do+              files <- traverse spelled [missingFile, keyFile]+              verifying True [validSig] <$> keysOf noKeys {Subst.ccSecretKeyFiles = files},+            runTestM "a secret key file that holds no secret key refuses the keys in upstream's words" $ do+              corrupt <- spelled corruptFile >>= \file -> keysOf noKeys {Subst.ccSecretKeyFiles = [file]}+              short <- spelled shortFile >>= \file -> keysOf noKeys {Subst.ccSecretKeyFiles = [file]}+              pure (assertEqual "corrupt, short" (Left "key is corrupt", Left "secret key is not valid") (corrupt, short)),+            -- Upstream keeps one key a name, the first, so a secret key+            -- named as a trusted key is not trusted.+            runTestM "of keys that share a name, only the first is trusted" $ do+              file <- spelled keyFile+              verifying False [validSig] <$> keysOf noKeys {Subst.ccPublicKeys = [Signing.renderPublicKey (Signing.PublicKey "test-key-1" (BS.replicate 32 7))], Subst.ccSecretKeyFiles = [file]},+            runTestM "under require-sigs off no key is read, and a narinfo is taken unsigned" $ do+              required <- Subst.cacheRequirement cache {Subst.ccPublicKeys = ["not-a-key"], Subst.ccRequireSigs = Subst.AcceptUnsigned}+              pure $ case required of+                Right SignaturesNotRequired -> Pass+                Right (RequireSignature _) -> Fail "signatures are required"+                Left err -> Fail ("the keys were read: " <> err)+          ]+      forceRemoveIfExists root+      pure results++-- | Narinfo field validation gates the pipeline ahead of the signed+-- fingerprint: a malformed field must fail as a parse error before its+-- text can reach the fingerprint or anything downstream.+testNarInfoValidation :: IO [Bool]+testNarInfoValidation = do+  putStrLn "substituter/narinfo-field-validation"+  sequence+    [ runTest "well-formed narinfo passes" $+        assertEqual "valid" (Right ()) (Subst.validateNarInfoFields sigTestNarInfo),+      runTest "malformed StorePath rejected" $+        assertLeft "bad store path" (Subst.validateNarInfoFields sigTestNarInfo {NarInfo.niStorePath = "/nix/store/zzz"}),+      runTest "derivation StorePath rejected" $+        assertLeft "drv path" (Subst.validateNarInfoFields sigTestNarInfo {NarInfo.niStorePath = "/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-hello-1.0.drv"}),+      runTest "malformed reference rejected" $+        assertLeft "bad reference" (Subst.validateNarInfoFields sigTestNarInfo {NarInfo.niReferences = ["../escape"]}),+      runTest "malformed NarHash rejected" $+        assertLeft "bad narhash" (Subst.validateNarInfoFields sigTestNarInfo {NarInfo.niNarHash = "sha256:nope"}),+      runTest "negative NarSize rejected" $+        assertLeft "negative narsize" (Subst.validateNarInfoFields sigTestNarInfo {NarInfo.niNarSize = -1}),+      runTestM "field validation reports ahead of signature verification" $+        withJudge $ \judge _ validSig ->+          pure $ case judge sigTestPath sigTestNarInfo {NarInfo.niStorePath = "/nix/store/zzz", NarInfo.niSigs = [validSig]} of+            ([], Subst.NarInfoFailed err)+              | "invalid narinfo" `T.isInfixOf` err -> Pass+              | otherwise -> Fail ("expected the field-validation error, got: " <> err)+            other -> Fail ("expected a failed query, got: " <> T.pack (show other)),+      -- Upstream skips a substitute for another path and one no trusted+      -- key signed, and its trust check fails on a trusted key it cannot+      -- parse.+      runTestM "a narinfo for another path or unsigned is passed over, and a malformed key fails" $+        withJudge $ \judge _ validSig -> do+          malformed <- Subst.cacheRequirement (sigTestCache "not-a-key")+          let signed = sigTestNarInfo {NarInfo.niSigs = [validSig]}+              malformedKey = case Subst.judgeNarInfo malformed sigTestPath signed of+                ([], Subst.NarInfoTrustFailed err) | "invalid public key" `T.isPrefixOf` err -> Pass+                other -> Fail ("expected a failed query, got: " <> T.pack (show other))+          pure $+            assertEqual "usable" ([], Subst.NarInfoUsable signed) (judge sigTestPath signed)+              `andThen` assertEqual "unsigned" ([], Subst.NarInfoUnsigned) (judge sigTestPath sigTestNarInfo)+              `andThen` assertEqual+                "another path"+                ([], Subst.NarInfoPassedOver ("narinfo names " <> NarInfo.niStorePath sigTestNarInfo))+                (judge (StorePath (T.replicate 32 "c") "hello-1.0") signed)+              `andThen` malformedKey,+      -- Upstream counts a path whose content address makes it as signed,+      -- and warns at its error level of one whose address makes another+      -- path, which then needs a signature.+      runTestM "a narinfo whose content address makes its path is taken unsigned, and one whose address makes another path needs a signature" $+        withJudge $ \judge _ validSig -> pure $ case addressedNarInfo of+          Left err -> Fail err+          Right (addressedPath, addressed) ->+            let misaddressed = addressed {NarInfo.niStorePath = NarInfo.niStorePath sigTestNarInfo}+                warned = ["warning: path '" <> NarInfo.niStorePath sigTestNarInfo <> "' claims to be content-addressed but isn't"]+             in assertEqual "addressed" ([], Subst.NarInfoUsable addressed) (judge addressedPath addressed)+                  `andThen` assertEqual "misaddressed, unsigned" (warned, Subst.NarInfoUnsigned) (judge sigTestPath misaddressed)+                  `andThen` assertEqual "misaddressed, signed" (warned, Subst.NarInfoUsable misaddressed {NarInfo.niSigs = [validSig]}) (judge sigTestPath misaddressed {NarInfo.niSigs = [validSig]}),+      runTestM "a fixed content address stated with references fails the trust check in upstream's words" $+        withJudge $ \judge _ _ ->+          let flat = sigTestNarInfo {NarInfo.niReferences = [T.replicate 32 "d" <> "-dep"], NarInfo.niCA = Just ("fixed:sha256:" <> T.replicate 52 "0")}+           in pure+                ( assertEqual+                    "refused"+                    ([], Subst.NarInfoTrustFailed "fixed output derivation 'hello-1.0' is not allowed to refer to other store paths.\nYou may need to use the 'unsafeDiscardReferences' derivation attribute, see the manual for more details.")+                    (judge sigTestPath flat)+                ),+      runTest "under require-sigs off an unsigned narinfo is usable" $+        assertEqual "usable" ([], Subst.NarInfoUsable sigTestNarInfo) (Subst.judgeNarInfo (Right SignaturesNotRequired) sigTestPath sigTestNarInfo)+    ]+  where+    -- The judgement under 'sigTestSetup''s cache, the cache, and a+    -- signature its key makes.+    withJudge check = case sigTestSetup of+      Left err -> pure (Fail (T.pack err))+      Right (cache, validSig, _) -> do+        required <- Subst.cacheRequirement cache+        check (Subst.judgeNarInfo required) cache validSig+    -- 'sigTestNarInfo' named by the path a NAR's SHA-256 address makes,+    -- with that address.+    addressedNarInfo = do+      let digest = BS.replicate 32 5+      addressedPath <- either (Left . T.pack . show) Right (makeSourcePath "hello-1.0" digest Set.empty)+      address <- maybe (Left "no address") Right (contentAddressFromParts (FixedMethod NarIngestion) "sha256" digest)+      pure (addressedPath, sigTestNarInfo {NarInfo.niStorePath = storePathToText defaultStoreDir addressedPath, NarInfo.niCA = Just (renderContentAddress address)})+    sigTestPath = StorePath (T.replicate 32 "a") "hello-1.0"
+ test/Test/Trust.hs view
@@ -0,0 +1,935 @@+-- | Tests of trust: the classification of a closure and the scan of what+-- it fetches.+module Test.Trust+  ( testTrust,+    testTrustFetch,+    testTrustScanIO,+    testTrustWindowsGraphs,+  )+where++import qualified Codec.Archive.Tar as Tar+import qualified Codec.Archive.Tar.Entry as TarEntry+import qualified Codec.Compression.GZip as GZip+import qualified Codec.Compression.Zstd.Lazy as ZstdL+import Control.Exception (bracket_)+import Control.Monad (when)+import Control.Monad.State.Strict (State, modify', runState)+import Data.Bits (shiftR)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BS8+import qualified Data.ByteString.Lazy as BL+import Data.Char (isDigit)+import Data.List (sort)+import qualified Data.Map.Strict as Map+import Data.Maybe (catMaybes, fromMaybe)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Data.Word (Word16, Word32, Word8)+import Nix.Builtins (parseNixPath)+import qualified Nix.Cli.Args as Cli+import qualified Nix.DependencyGraph as DepGraph+import Nix.Derivation (Derivation (..), DerivationOutput (..), Platform (..))+import Nix.Eval (MonadEval (..), NixValue (..), evalParsed, typeName, unrestrictedPolicy)+import Nix.Eval.IO (evalBaseEnv, newEvalStateWith, runEvalIO)+import Nix.Hash (sha256Digest)+import qualified Nix.Hash as Hash+import Nix.Json (Json (..))+import Nix.Parser (parseNix)+import Nix.Realise (ClosureOutcome (..))+import Nix.Store.Path (StorePath, defaultStoreDir, parseStorePath, storePathHashLen, storePathToText)+import Nix.Store.Path.Internal (StorePath (..))+import qualified Nix.Trust as Trust+import qualified Nix.Trust.Fetch as Fetch+import Nix.Trust.Scan (scanFetched)+import System.Directory (createDirectoryIfMissing, getTemporaryDirectory)+import qualified System.Directory as Dir+import System.FilePath (takeDirectory, (</>))+import Test.Harness (TestResult (..), andThen, assertEqual, bytesText, evalNixIOStoreDir, forceRemoveIfExists, nixQuotedPath, runTest, runTestM, sessionClosure, symlinksAvailable, tarDir, tarFile, testLogger, testOrigin, testSessionStore, trustPe)+import qualified Test.QuickCheck as QC+import Text.Read (readMaybe)++-- ---------------------------------------------------------------------------+-- Tests: Push (pure narinfo construction + closure computation)+-- ---------------------------------------------------------------------------++-- | Zstd compression level for test archives (zstd's own default).+testZstdCompressionLevel :: Int+testZstdCompressionLevel = 3++-- | A zstd-compressed tar archive of these entries.+zstdArchive :: [TarEntry.Entry] -> BL.ByteString+zstdArchive = ZstdL.compress testZstdCompressionLevel . Tar.write++-- ---------------------------------------------------------------------------+-- Tests: trust+-- ---------------------------------------------------------------------------++-- | A store path whose hash repeats one nix-base32 letter.+trustPath :: Char -> Text -> StorePath+trustPath letter = StorePath (T.replicate storePathHashLen (T.singleton letter))++-- | A store path as a builder or an argument names it.+trustText :: StorePath -> BS.ByteString+trustText = TE.encodeUtf8 . storePathToText defaultStoreDir++-- | A hash a fixed-output test derivation states, one of its own for each+-- output name.+trustHashOf :: StorePath -> Text+trustHashOf output = Hash.bytesToHexText (sha256Digest (TE.encodeUtf8 (spName output)))++-- | A derivation with one output, fixed to a hash when one is given, built+-- by this builder from these derivations and sources.+trustDrv :: StorePath -> Maybe Text -> BS.ByteString -> [StorePath] -> [StorePath] -> Derivation+trustDrv output fixedHash builder inputs sources =+  Derivation+    { drvOutputs = [DerivationOutput "out" output (maybe "" (const "sha256") fixedHash) (fromMaybe "" fixedHash)],+      drvInputDrvs = Map.fromList [(input, ["out"]) | input <- inputs],+      drvInputSrcs = sources,+      drvPlatform = X86_64_Windows,+      drvBuilder = builder,+      drvArgs = [],+      drvEnv = Map.empty+    }++-- | A graph of these derivations, each under its @.drv@ path.+trustGraph :: [(StorePath, Derivation)] -> DepGraph.DepGraph+trustGraph nodes = DepGraph.DepGraph (Map.fromList [(path, DepGraph.DepNode path drv (Map.map Set.fromList (drvInputDrvs drv))) | (path, drv) <- nodes])++-- | A little-endian field of two bytes, and one of four.+trustLe16 :: Word16 -> BS.ByteString+trustLe16 value = BS.pack [fromIntegral value, fromIntegral (value `shiftR` 8)]++trustLe32 :: Word32 -> BS.ByteString+trustLe32 value = BS.pack [fromIntegral (value `shiftR` bits) | bits <- [0, 8, 16, 24]]++-- | An ELF header through its type, 64-bit, in the byte order its+-- encoding byte names (1 little-endian, 2 big-endian), with this type.+trustElf :: Word8 -> Word16 -> BS.ByteString+trustElf encoding elfType = BS.pack [0x7F, 0x45, 0x4C, 0x46, 2, encoding, 1] <> BS.replicate 9 0 <> ordered (trustLe16 elfType)+  where+    ordered = if encoding == 2 then BS.reverse else id++-- | A COFF object for a machine, laid out as a compiler lays one out: the+-- file header, naming one section and one symbol and no optional header,+-- the section header, and the symbol table right after it.+trustCoff :: Word16 -> BS.ByteString+trustCoff machine =+  trustLe16 machine+    <> trustLe16 1+    <> trustLe32 0+    <> trustLe32 60+    <> trustLe32 1+    <> trustLe16 0+    <> trustLe16 0+    <> ".text"+    <> BS.replicate 35 0+    <> BS.replicate 18 0++-- | A COFF object in the bigobj form for x86-64, as LLVM writes one for an+-- object of more sections than the plain form counts: the header with+-- its class identifier, one section header, and one 20-byte symbol.+trustBigObj :: BS.ByteString+trustBigObj =+  BS.pack [0, 0, 0xFF, 0xFF]+    <> trustLe16 2+    <> trustLe16 0x8664+    <> trustLe32 0+    <> BS.pack [0xC7, 0xA1, 0xBA, 0xD1, 0xEE, 0xBA, 0xA9, 0x4B, 0xAF, 0x20, 0xFA, 0xF6, 0x6A, 0xA4, 0xDC, 0xB8]+    <> BS.concat (replicate 4 (trustLe32 0))+    <> trustLe32 1+    <> trustLe32 96+    <> trustLe32 1+    <> ".text"+    <> BS.replicate 35 0+    <> BS.replicate 20 0++-- | An ar archive of one member, a COFF object, with the member header+-- the format gives every member.+trustAr :: BS.ByteString+trustAr = "!<arch>\n" <> field 16 "crt2.o/" <> field 12 "0" <> field 6 "0" <> field 6 "0" <> field 8 "644" <> field 10 (BS8.pack (show (BS.length object))) <> "`\n" <> object+  where+    object = trustCoff 0x8664+    field width text = text <> BS.replicate (width - BS.length text) 0x20++-- | 'trustPe' as @pkg/tool.exe@ in a ustar archive, compressed with xz, by+-- Python's lzma module: the suite has no xz compressor.+trustXzArchive :: BS.ByteString+trustXzArchive =+  fromMaybe BS.empty . Hash.hexToBytes $+    "fd377a585a000004e6d6b446020021011c00000010cf58cce007ff004b5d00381ac9159cbbcdf1065aadd096d83e844fa103a52c8bdef734e90ff4360d9ce437ad74279b938ad2a38e3ee7c2d25136f5b6f3ca8685a1de9669221704ebfe730166fada2b7057674ea6730000ac8e93cf09c3d66d0001678010000000320c5b37b1c467fb020000000004595a"++-- | The same archive compressed with bzip2, by Python's bz2 module.+trustBzip2Archive :: BS.ByteString+trustBzip2Archive =+  fromMaybe BS.empty . Hash.hexToBytes $+    "425a683931415926535944dfe55f000036df88cc804001f78042024410628cde400000880820005441400d3401a6807a9ed504a28c868032000043177caa0f6bd410b38ba723a5ae510505db5b18231443389085e9364876c2828444a5ba2b71e2a94e3e01833ccff17724538509044dfe55f0"++-- | What the header scanner makes of strict bytes.+headerOf :: BS.ByteString -> Maybe Trust.CodeKind+headerOf = Trust.prebuiltKind . BL.fromStrict++-- | Each fixed-output input of a report by output name, with its class.+trustClasses :: Trust.TrustReport -> [(Text, Trust.InputClass)]+trustClasses report = [(spName (Trust.inputOutput input), Trust.inputClass input) | input <- Trust.trInputs report]++-- | The fixed-output inputs a report says a build runs as builders.+trustRunAsBuilders :: Trust.TrustReport -> [StorePath]+trustRunAsBuilders report = [Trust.inputDrvPath input | input <- Trust.trInputs report, Trust.inputClass input == Trust.RunAsBuilder]++-- | What a scan found: this prebuilt code and nothing unread.+codeOnly :: [Trust.FoundCode] -> Trust.ContentFacts+codeOnly code = Trust.ContentFacts code []++-- | A member of a JSON object, or 'Nothing' for a missing member or a+-- value that is not an object.+jsonMember :: Text -> Json -> Maybe Json+jsonMember name value = case value of+  JsonObject members -> Map.lookup name members+  _ -> Nothing++-- | A @prebuiltCode@ entry of the JSON form, for a member of a fetched+-- archive: its kind's key, its member, its digest and the outputs it is+-- the bytes of.+codeJson :: Text -> Text -> Text -> [StorePath] -> Json+codeJson kind member digest copies =+  JsonObject+    ( Map.fromList+        [ ("kind", JsonString kind),+          ("file", JsonNull),+          ("member", JsonString member),+          ("sha256", JsonString digest),+          ("sameBytesAs", JsonArray (map (JsonString . storePathToText defaultStoreDir) copies))+        ]+    )++-- | How the JSON form names each class, which a reader of it keys on.+classJson :: Trust.InputClass -> Text+classJson inputClassValue = case inputClassValue of+  Trust.RunAsBuilder -> "runAsBuilder"+  Trust.HoldsPrebuiltCode -> "holdsPrebuiltCode"+  Trust.NotFullyRead -> "notFullyRead"+  Trust.HoldsNoPrebuiltCode -> "holdsNoPrebuiltCode"++-- | A file of prebuilt code of these bytes, at this place.+codeOf :: Trust.CodeKind -> Trust.CodePlace -> BS.ByteString -> Trust.FoundCode+codeOf kind place bytes = Trust.FoundCode kind place (Hash.sha256Hex bytes)++-- | A file of prebuilt code that a hand-built report's facts name, its+-- bytes its place's text, so that no two places and no fixed-output+-- hash share them.+codeAt :: Trust.CodeKind -> Trust.CodePlace -> Trust.FoundCode+codeAt kind place = codeOf kind place (TE.encodeUtf8 (T.pack (show place)))++-- | One file of prebuilt code of these bytes a scan found, and nothing+-- unread.+oneCodeOf :: Trust.CodeKind -> Trust.CodePlace -> BS.ByteString -> Trust.ContentFacts+oneCodeOf kind place bytes = codeOnly [codeOf kind place bytes]++-- | One file of prebuilt code a hand-built report's facts name, and+-- nothing unread.+oneCode :: Trust.CodeKind -> Trust.CodePlace -> Trust.ContentFacts+oneCode kind place = codeOnly [codeAt kind place]++-- | A scan that read everything and found no prebuilt code.+noCode :: Trust.ContentFacts+noCode = Trust.ContentFacts [] []++-- ---------------------------------------------------------------------------+-- Tests: making the inputs valid and reading them+-- ---------------------------------------------------------------------------++-- | What a store in a test was asked, in order.+data Asked+  = AskedFetch !StorePath+  | AskedSubstitute !StorePath+  | AskedHeld !StorePath+  | AskedScan !StorePath+  deriving (Eq, Show)++-- | A store over a state that records each call, whose fetches,+-- substitutions and held checks answer as the functions given say, and+-- whose scan of a path finds a fact that names it.+scriptedStore ::+  (StorePath -> Either Text ()) ->+  (StorePath -> Either Text ClosureOutcome) ->+  (StorePath -> Either Text Bool) ->+  Fetch.FixedOutputStore (State [Asked])+scriptedStore fetch substitute held =+  Fetch.FixedOutputStore+    { Fetch.fosFetch = \node -> asking (AskedFetch (DepGraph.dnDrvPath node)) (fetch (DepGraph.dnDrvPath node)),+      Fetch.fosSubstitute = \output -> asking (AskedSubstitute output) (substitute output),+      Fetch.fosHeld = \output -> asking (AskedHeld output) (held output),+      Fetch.fosScan = \output -> factsOf output <$ modify' (<> [AskedScan output])+    }+  where+    asking :: Asked -> a -> State [Asked] a+    asking call answer = answer <$ modify' (<> [call])++-- | The facts a scripted scan finds in a path.+factsOf :: StorePath -> Trust.ContentFacts+factsOf output = Trust.ContentFacts [] [Trust.UnreadFile (Just (spName output)) "scripted"]++-- | A fixed-output input, by the letters of its @.drv@ path and its+-- output's, and the builder that makes it.+fixedInput :: Char -> Char -> BS.ByteString -> (DepGraph.DepNode, StorePath)+fixedInput drvLetter outLetter builder =+  (DepGraph.DepNode drvPath (trustDrv output (Just (trustHashOf output)) builder [] []) Map.empty, output)+  where+    drvPath = trustPath drvLetter "input.drv"+    output = trustPath outLetter "input"++-- | An input a builtin fetches, and one that is only substituted.+fetchInput, substituteInput :: Char -> Char -> (DepGraph.DepNode, StorePath)+fetchInput drvLetter outLetter = fixedInput drvLetter outLetter "builtin:fetchurl"+substituteInput drvLetter outLetter = fixedInput drvLetter outLetter "/bin/sh"++-- | The derivation path of an input.+drvOf :: (DepGraph.DepNode, StorePath) -> StorePath+drvOf = DepGraph.dnDrvPath . fst++-- | Run 'Fetch.fetchAndScan' over a scripted store, and answer its result+-- and what the store was asked.+scripted :: Fetch.FixedOutputStore (State [Asked]) -> [(DepGraph.DepNode, StorePath)] -> (Either Text (Map.Map StorePath Trust.ContentFacts), [Asked])+scripted store inputs = runState (Fetch.fetchAndScan store inputs) []++-- | The order inputs are made valid and read in, and the words a failure+-- stops it with, over a store that records what it is asked.+testTrustFetch :: IO [Bool]+testTrustFetch = do+  putStrLn "trust/fetch"+  let substituteA = substituteInput 'a' 'b'+      fetchA = fetchInput 'c' 'd'+      substituteB = substituteInput 'e' 'f'+      fetchB = fetchInput 'g' 'h'+      substituteC = substituteInput 'i' 'j'+      mixed = [substituteA, fetchA, substituteB, fetchB]+      outputOf = snd+      always answer = const (Right answer)+      substituted = always ClosureComplete+      holds = always True+      substitutionFailed output = "a substitute for '" <> storePathToText defaultStoreDir output <> "' or a path it references failed"+  sequence+    [ runTest "fetchAndScan fetches every builtin fetch, then substitutes the other inputs, then reads each one the store holds, in order" $+        let heldExceptB output = Right (output /= outputOf substituteB)+            (result, asked) = scripted (scriptedStore (const (Right ())) substituted heldExceptB) mixed+         in assertEqual+              "asked"+              [ AskedFetch (drvOf fetchA),+                AskedFetch (drvOf fetchB),+                AskedSubstitute (outputOf substituteA),+                AskedSubstitute (outputOf substituteB),+                AskedHeld (outputOf substituteA),+                AskedScan (outputOf substituteA),+                AskedHeld (outputOf fetchA),+                AskedScan (outputOf fetchA),+                AskedHeld (outputOf substituteB),+                AskedHeld (outputOf fetchB),+                AskedScan (outputOf fetchB)+              ]+              asked+              `andThen` assertEqual "read" (Right (Map.fromList [(output, factsOf output) | output <- map outputOf [substituteA, fetchA, fetchB]])) result,+      runTest "a failed fetch, a failed substitute, a cache that cannot be asked, and a store that cannot be asked each stop it with their words, and nothing after is asked" $+        let failingFetch path = if path == drvOf fetchB then Left "the fetch failed" else Right ()+            substituteAs outcome output = Right (if output == outputOf substituteB then outcome else ClosureComplete)+            unaskable output = if output == outputOf substituteB then Left "the store cannot be asked" else Right ClosureComplete+            heldFails output = if output == outputOf fetchA then Left "the store cannot say" else Right True+            run fetch substitute held = scripted (scriptedStore fetch substitute held) mixed+            (fetchResult, fetchAsked) = run failingFetch substituted holds+            (failedResult, failedAsked) = run (const (Right ())) (substituteAs ClosureFailed) holds+            (queryResult, queryAsked) = run (const (Right ())) (substituteAs (ClosureQueryFailed "the cache cannot be asked")) holds+            (storeResult, storeAsked) = run (const (Right ())) unaskable holds+            (heldResult, heldAsked) = run (const (Right ())) substituted heldFails+            fetches = [AskedFetch (drvOf fetchA), AskedFetch (drvOf fetchB)]+            substitutes = [AskedSubstitute (outputOf substituteA), AskedSubstitute (outputOf substituteB)]+         in assertEqual "a fetch" (Left "the fetch failed", fetches) (fetchResult, fetchAsked)+              `andThen` assertEqual "a substitute" (Left (substitutionFailed (outputOf substituteB)), fetches <> substitutes) (failedResult, failedAsked)+              `andThen` assertEqual "a cache" (Left "the cache cannot be asked", fetches <> substitutes) (queryResult, queryAsked)+              `andThen` assertEqual "a store asked to substitute" (Left "the store cannot be asked", fetches <> substitutes) (storeResult, storeAsked)+              `andThen` assertEqual "a store asked what it holds" (Left "the store cannot say", fetches <> substitutes <> [AskedHeld (outputOf substituteA), AskedScan (outputOf substituteA), AskedHeld (outputOf fetchA)]) (heldResult, heldAsked),+      runTest "an input no cache offers, or whose references none offers, is left unread and the rest go on" $+        let inputs = [substituteA, substituteB, fetchA, substituteC]+            outcomes output+              | output == outputOf substituteA = Right ClosureUnavailable+              | output == outputOf substituteB = Right ClosureIncomplete+              | otherwise = Right ClosureComplete+            heldAfter output = Right (output `elem` map outputOf [fetchA, substituteC])+            (result, asked) = scripted (scriptedStore (const (Right ())) outcomes heldAfter) inputs+         in assertEqual "asked" [AskedFetch (drvOf fetchA), AskedSubstitute (outputOf substituteA), AskedSubstitute (outputOf substituteB), AskedSubstitute (outputOf substituteC)] (take 4 asked)+              `andThen` assertEqual "read" (Right (Map.fromList [(output, factsOf output) | output <- map outputOf [fetchA, substituteC]])) result+              `andThen` assertEqual "scans" [AskedScan (outputOf fetchA), AskedScan (outputOf substituteC)] [call | call@(AskedScan _) <- asked],+      runTestM "whatever the inputs and whichever the store holds, every fetch is asked before every substitution and each substitution before every read, and what is read is what is held" $ do+        let letters = zip ['a', 'c' .. 'y'] ['b', 'd' .. 'z']+            inputsOf kinds = [if builtin then fetchInput drvLetter outLetter else substituteInput drvLetter outLetter | ((drvLetter, outLetter), (builtin, _)) <- zip letters kinds]+            property kinds =+              let inputs = inputsOf kinds+                  heldOutputs = [output | ((_, output), (_, isHeld)) <- zip inputs kinds, isHeld]+                  (result, asked) = scripted (scriptedStore (const (Right ())) substituted (\output -> Right (output `elem` heldOutputs))) inputs+                  phase call = case call of+                    AskedFetch _ -> 0 :: Int+                    AskedSubstitute _ -> 1+                    AskedHeld _ -> 2+                    AskedScan _ -> 2+               in QC.conjoin+                    [ QC.counterexample "phases in order" (map phase asked QC.=== sort (map phase asked)),+                      QC.counterexample "read what is held" (fmap Map.keysSet result QC.=== Right (Set.fromList heldOutputs)),+                      QC.counterexample "one question for each input" (length [() | AskedHeld _ <- asked] QC.=== length inputs)+                    ]+        result <- QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} (QC.forAll (QC.resize 12 (QC.listOf QC.arbitrary)) property)+        pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))+    ]++-- | The header scanner over byte strings, the parser's trust command, and+-- the classification over hand built graphs.  As in @pkgs/windows@,+-- hex0's builder is the flat seed it fetches, hex0 is pinned to the+-- seed's hash, and stage0-pe32's source archive holds a copy of that+-- seed.  As in a stdenv made of binary packages, hello's builder is bash+-- in prebuilt packages builtin:unpack makes one tree of, and prebuilt+-- packages hold its toolchain.+testTrust :: IO [Bool]+testTrust = do+  putStrLn "trust"+  let seed = trustPath 'a' "hex0-seed.exe.drv"+      seedOut = trustPath 'b' "hex0-seed.exe"+      hex0 = trustPath 'c' "hex0.exe.drv"+      hex0Out = trustPath 'd' "hex0.exe"+      hex1 = trustPath 'f' "hex1.exe.drv"+      hex1Out = trustPath 'g' "hex1.exe"+      stage0Archive = trustPath 'h' "stage0-pe32-a81c837.tar.gz.drv"+      stage0ArchiveOut = trustPath 'i' "stage0-pe32-a81c837.tar.gz"+      stage0Tree = trustPath 'j' "stage0-pe32-a81c837.drv"+      stage0TreeOut = trustPath 'k' "stage0-pe32-a81c837"+      bash = trustPath 'l' "bash.tar.zst.drv"+      bashOut = trustPath 'm' "bash.tar.zst"+      runtime = trustPath 'n' "runtime.tar.zst.drv"+      runtimeOut = trustPath 'p' "runtime.tar.zst"+      tools = trustPath 'q' "tools.drv"+      toolsOut = trustPath 'r' "tools"+      gcc = trustPath 's' "gcc.tar.zst.drv"+      gccOut = trustPath 'v' "gcc.tar.zst"+      crt = trustPath 'w' "crt.tar.zst.drv"+      crtOut = trustPath 'x' "crt.tar.zst"+      toolchain = trustPath 'y' "toolchain.drv"+      toolchainOut = trustPath 'z' "toolchain"+      helloSrc = trustPath '0' "hello-2.12.3.tar.gz.drv"+      helloSrcOut = trustPath '1' "hello-2.12.3.tar.gz"+      hello = trustPath '2' "hello.drv"+      helloOut = trustPath '3' "hello"+      setup = trustPath '4' "setup.sh"+      greeting = trustPath '5' "greeting.drv"+      greetingOut = trustPath '6' "greeting"+      root = trustPath '7' "closure.drv"+      rootOut = trustPath '8' "closure"+      fetched output = trustDrv output (Just (trustHashOf output)) "builtin:fetchurl" [] []+      unpacked output inputs = trustDrv output Nothing "builtin:unpack" inputs []+      hex0Drv = trustDrv hex0Out (Just (trustHashOf seedOut)) (trustText seedOut) [seed, stage0Archive] []+      bashExe = trustText toolsOut <> "/bin/bash.exe"+      graph =+        trustGraph+          [ (seed, fetched seedOut),+            (hex0, hex0Drv),+            (hex1, trustDrv hex1Out Nothing (trustText hex0Out) [hex0, stage0Tree] []),+            (stage0Archive, fetched stage0ArchiveOut),+            (stage0Tree, unpacked stage0TreeOut [stage0Archive]),+            (bash, fetched bashOut),+            (runtime, fetched runtimeOut),+            (tools, unpacked toolsOut [bash, runtime]),+            (gcc, fetched gccOut),+            (crt, fetched crtOut),+            (toolchain, unpacked toolchainOut [gcc, crt]),+            (helloSrc, fetched helloSrcOut),+            (hello, trustDrv helloOut Nothing bashExe [tools, toolchain, helloSrc] [setup]),+            (greeting, trustDrv greetingOut Nothing "/bin/sh" [] []),+            (root, trustDrv rootOut Nothing "/bin/sh" [hello, hex1, greeting] [])+          ]+      facts =+        Map.fromList+          [ (seedOut, oneCode Trust.PeImage Trust.FetchedFile),+            (stage0ArchiveOut, oneCode Trust.PeImage (Trust.ArchiveMember "stage0-pe32-a81c8374592e8e897c0863d31c6480ea69669009/bootstrap-seeds/PE32/i386/hex0-seed.exe")),+            (bashOut, oneCode Trust.PeImage (Trust.ArchiveMember "bin/bash.exe")),+            (runtimeOut, oneCode Trust.PeImage (Trust.ArchiveMember "bin/runtime.dll")),+            (gccOut, Trust.ContentFacts [codeAt Trust.PeImage (Trust.ArchiveMember "bin/gcc.exe")] [Trust.UnreadFile Nothing "tar archive stops reading: truncated"]),+            (helloSrcOut, noCode)+          ]+      report = Trust.trustReport facts graph root+      builtOut = trustPath '9' "tool"+      built = trustPath 'a' "tool.drv"+      user = trustPath 'b' "user.drv"+      foreignBuilder = trustText (trustPath 'c' "foreign") <> "/bin/sh"+      nonUtf8Builder = trustText builtOut <> "/bin/\xFF"+      provenanceOf drvPath = [(Trust.inputProvenance input, Trust.inputSameHash input) | input <- Trust.trInputs report, Trust.inputDrvPath input == drvPath]+      shell = trustPath 'f' "shell.drv"+      script = trustPath 'g' "script.drv"+      small =+        trustGraph+          [ (seed, fetched seedOut),+            (hex0, hex0Drv),+            (hex1, trustDrv hex1Out Nothing (trustText hex0Out) [hex0] []),+            (stage0Archive, fetched stage0ArchiveOut),+            (helloSrc, fetched helloSrcOut),+            (bash, fetched bashOut),+            (tools, unpacked toolsOut [bash]),+            (shell, trustDrv greetingOut Nothing bashExe [tools] []),+            (script, trustDrv helloOut Nothing (trustText setup) [] [setup]),+            (root, trustDrv rootOut Nothing "/bin/sh" [hex1, helloSrc, shell, script] [setup])+          ]+      smallFacts =+        Map.fromList+          [ (seedOut, oneCode Trust.PeImage Trust.FetchedFile),+            (stage0ArchiveOut, codeOnly [seedCopy, codeAt Trust.ArArchive (Trust.ArchiveMember "stage0-pe32/lib/libc.a")]),+            (helloSrcOut, Trust.ContentFacts [] [Trust.UnreadFile Nothing "gzip stream error: truncated"]),+            (bashOut, oneCode Trust.PeImage (Trust.ArchiveMember "bin/bash.exe"))+          ]+      path = storePathToText defaultStoreDir+      -- stage0-pe32's archive holds a copy of the seed, by its bytes.+      seedCopy = Trust.FoundCode Trust.PeImage (Trust.ArchiveMember "stage0-pe32/bootstrap-seeds/PE32/i386/hex0-seed.exe") (trustHashOf seedOut)+      smallReport = Trust.trustReport smallFacts small root+      smallJson = Trust.trustReportJson smallReport+      -- A member of an input of the small report's JSON form.+      inputField name out = jsonMember "fixedOutputInputs" smallJson >>= jsonMember (path out) >>= jsonMember name+  sequence+    [ runTest "a Portable Executable is an MZ header whose e_lfanew points at a PE signature" $+        assertEqual "PE" (Just Trust.PeImage) (headerOf trustPe),+      runTest "an MZ header without a PE signature where e_lfanew points is not prebuilt code" $+        assertEqual "MZ alone" Nothing (headerOf ("MZ" <> BS.replicate 0x3A 0 <> BS.pack [0x40, 0, 0, 0] <> "NE\0\0"))+          `andThen` assertEqual "e_lfanew past the end" Nothing (headerOf ("MZ" <> BS.replicate 0x3A 0 <> BS.pack [0xFF, 0, 0, 0] <> "PE\0\0"))+          `andThen` assertEqual "no e_lfanew" Nothing (headerOf "MZ"),+      runTest "an ELF file is an object, an image or neither by its type, in either byte order" $+        assertEqual+          "kinds"+          (map Just [Trust.ElfObject, Trust.ElfImage, Trust.ElfImage, Trust.ElfObject, Trust.ElfImage, Trust.ElfOther, Trust.ElfOther])+          (map headerOf [trustElf 1 1, trustElf 1 2, trustElf 1 3, trustElf 2 1, trustElf 2 3, trustElf 1 4, BS.pack [0x7F, 0x45, 0x4C, 0x46, 2, 1, 1]]),+      runTest "Mach-O files of each width and order, and the universal form, are prebuilt code" $+        assertEqual+          "formats"+          (map Just [Trust.MachO, Trust.MachO, Trust.MachO, Trust.MachO, Trust.MachOUniversal, Trust.MachOUniversal])+          ( map+              (headerOf . BS.pack)+              [ [0xFE, 0xED, 0xFA, 0xCE],+                [0xCE, 0xFA, 0xED, 0xFE],+                [0xFE, 0xED, 0xFA, 0xCF],+                [0xCF, 0xFA, 0xED, 0xFE],+                [0xCA, 0xFE, 0xBA, 0xBE, 0, 0, 0, 2],+                [0xCA, 0xFE, 0xBA, 0xBF, 0, 0, 0, 1]+              ]+          ),+      runTest "a Java class file, which shares the universal magic, is not prebuilt code" $+        assertEqual "class" Nothing (headerOf (BS.pack [0xCA, 0xFE, 0xBA, 0xBE, 0, 0, 0, 0x34])),+      runTest "a COFF object is one for each machine, in the plain form and the bigobj one" $+        assertEqual "plain" (replicate 4 (Just Trust.CoffObject)) (map (headerOf . trustCoff) [0x014C, 0x8664, 0xAA64, 0x01C4])+          `andThen` assertEqual "bigobj" (Just Trust.CoffObject) (headerOf trustBigObj),+      runTest "a COFF header whose tables do not fit, or that has an optional header, is not an object" $+        assertEqual "symbol table cut" Nothing (headerOf (BS.take 70 (trustCoff 0x8664)))+          `andThen` assertEqual "too many sections" Nothing (headerOf (trustLe16 0x8664 <> trustLe16 0xFFFF <> BS.drop 4 (trustCoff 0x8664)))+          `andThen` assertEqual "optional header" Nothing (headerOf (BS.take 16 (trustCoff 0x8664) <> trustLe16 0xE0 <> BS.drop 18 (trustCoff 0x8664)))+          `andThen` assertEqual "unknown machine" Nothing (headerOf (trustLe16 0x0200 <> BS.drop 2 (trustCoff 0x8664)))+          `andThen` assertEqual "bigobj cut" Nothing (headerOf (BS.take 100 trustBigObj))+          `andThen` assertEqual "bigobj class" Nothing (headerOf (BS.take 12 trustBigObj <> BS.replicate 16 0 <> BS.drop 28 trustBigObj)),+      runTest "text that starts with i386's machine bytes is not a COFF object" $+        assertEqual "text" Nothing (headerOf "L\x01 is how an i386 object's header starts, but this is text\n"),+      runTest "an ar archive is prebuilt code by its magic, members unread" $+        assertEqual "ar" (Just Trust.ArArchive) (headerOf trustAr)+          `andThen` assertEqual "magic alone" (Just Trust.ArArchive) (headerOf "!<arch>\n")+          `andThen` assertEqual "no newline" Nothing (headerOf "!<arch> is how an ar archive starts"),+      runTest "a script is not prebuilt code, whatever its #! line runs" $+        assertEqual "script" Nothing (headerOf "#!/nix/store/hash-bash/bin/bash\necho hello\n")+          `andThen` assertEqual "empty" Nothing (headerOf ""),+      runTest "trust takes a target, -A, --json and its layout, and refuses the flags only build takes" $+        assertEqual "target" (Right (Cli.CmdTrust (Cli.TargetExpr "1") (Just "a.b") Cli.TrustLines Cli.IndentedOnTerminal)) (Cli.optCommand <$> Cli.parseArgs ["trust", "--expr", "1", "-A", "a.b"])+          `andThen` assertEqual "json" (Right (Cli.CmdTrust (Cli.TargetExpr "1") Nothing Cli.TrustJson Cli.IndentedOnTerminal)) (Cli.optCommand <$> Cli.parseArgs ["trust", "--json", "--expr", "1"])+          `andThen` assertEqual "pretty" (Right (Cli.CmdTrust (Cli.TargetExpr "1") Nothing Cli.TrustJson Cli.Indented)) (Cli.optCommand <$> Cli.parseArgs ["trust", "--no-pretty", "--expr", "1", "--json", "--pretty"])+          `andThen` assertEqual "no-pretty" (Right (Cli.CmdTrust (Cli.TargetExpr "1") Nothing Cli.TrustJson Cli.Compact)) (Cli.optCommand <$> Cli.parseArgs ["trust", "--pretty", "--json", "--no-pretty", "--expr", "1"])+          `andThen` assertEqual "check" (Left "unknown trust flag: --check") (Cli.optCommand <$> Cli.parseArgs ["trust", "--check", "--expr", "1"])+          `andThen` assertEqual "out-link" (Left "unknown trust flag: -o") (Cli.optCommand <$> Cli.parseArgs ["trust", "-o", "result", "--expr", "1"])+          `andThen` assertEqual "no-out-link" (Left "unknown trust flag: --no-out-link") (Cli.optCommand <$> Cli.parseArgs ["trust", "--no-out-link", "--expr", "1"])+          `andThen` assertEqual "exec-wrapper" (Left "unknown trust flag: --exec-wrapper") (Cli.optCommand <$> Cli.parseArgs ["trust", "--exec-wrapper", "x86_64-windows=wine", "--expr", "1"]),+      runTest "every fixed-output derivation of the closure is an input, one with inputs of its own included" $+        assertEqual+          "inputs"+          (sort [seed, hex0, stage0Archive, bash, runtime, gcc, crt, helloSrc])+          (sort (map (DepGraph.dnDrvPath . fst) (Trust.fixedOutputInputs graph root))),+      runTest "each fixed-output input lands in the class its facts give it" $+        assertEqual+          "classes"+          [ ("bash.tar.zst", Trust.RunAsBuilder),+            ("crt.tar.zst", Trust.NotFullyRead),+            ("gcc.tar.zst", Trust.HoldsPrebuiltCode),+            ("hello-2.12.3.tar.gz", Trust.HoldsNoPrebuiltCode),+            ("hex0-seed.exe", Trust.RunAsBuilder),+            ("hex0.exe", Trust.RunAsBuilder),+            ("runtime.tar.zst", Trust.RunAsBuilder),+            ("stage0-pe32-a81c837.tar.gz", Trust.HoldsPrebuiltCode)+          ]+          (trustClasses report),+      runTest "a flat seed that is a builder runs as one, and so does a fixed output built from it" $+        assertEqual+          "builders"+          [(seed, Map.singleton (trustText seedOut) 1, Map.empty), (hex0, Map.singleton (trustText hex0Out) 1, Map.empty)]+          [(Trust.inputDrvPath input, Trust.inputBuilders input, Trust.inputTreeBuilders input) | input <- Trust.trInputs report, Trust.inputDrvPath input `elem` [seed, hex0]],+      runTest "a fixed output the closure builds names its builder, and two pinned to one hash name each other" $+        assertEqual "seed" [(Trust.FetchedBy "builtin:fetchurl", [hex0Out])] (provenanceOf seed)+          `andThen` assertEqual "hex0" [(Trust.BuiltBy (trustText seedOut), [seedOut])] (provenanceOf hex0)+          `andThen` assertEqual "archive" [(Trust.FetchedBy "builtin:fetchurl", [])] (provenanceOf stage0Archive),+      runTest "packages builtin:unpack makes the builder's tree of run as builders, as part of the tree" $+        assertEqual+          "builders"+          [(Map.empty, Map.singleton bashExe 1), (Map.empty, Map.singleton bashExe 1)]+          [(Trust.inputBuilders input, Trust.inputTreeBuilders input) | input <- Trust.trInputs report, Trust.inputDrvPath input `elem` [bash, runtime]],+      runTest "a host program, the builtins and the input sources are counted" $+        assertEqual "outside" (Map.singleton "/bin/sh" 2) (Trust.trOutsideBuilders report)+          `andThen` assertEqual "builtins" (Map.fromList [("builtin:fetchurl", 7), ("builtin:unpack", 3)]) (Trust.trBuiltinBuilders report)+          `andThen` assertEqual "source builders" Map.empty (Trust.trSourceBuilders report)+          `andThen` assertEqual "sources" (Set.singleton setup) (Trust.trSources report),+      runTest "a builder a program in the closure made runs nothing as a fixed-output input" $+        let made =+              trustGraph+                [ (seed, fetched seedOut),+                  (built, trustDrv builtOut Nothing "/bin/sh" [seed] []),+                  (user, trustDrv rootOut Nothing (trustText builtOut <> "/bin/tool") [built] [])+                ]+         in assertEqual "run as builders" [] (trustRunAsBuilders (Trust.trustReport Map.empty made user))+              `andThen` assertEqual "outside" (Map.singleton "/bin/sh" 1) (Trust.trOutsideBuilders (Trust.trustReport Map.empty made user)),+      runTest "a builder whose path in its store path is not UTF-8 is still in that store path" $+        let made =+              trustGraph+                [ (built, trustDrv builtOut (Just (trustHashOf builtOut)) "builtin:fetchurl" [] []),+                  (user, trustDrv rootOut Nothing nonUtf8Builder [built] [])+                ]+         in assertEqual "run as builders" [built] (trustRunAsBuilders (Trust.trustReport Map.empty made user)),+      runTest "a builder in a store path the closure does not provide is outside it, and one in its sources is a source builder" $+        let foreignGraph = trustGraph [(user, trustDrv rootOut Nothing foreignBuilder [] [])]+            sourceReport = Trust.trustReport Map.empty (trustGraph [(user, trustDrv rootOut Nothing (trustText setup) [] [setup])]) user+         in assertEqual "foreign" (Map.singleton foreignBuilder 1) (Trust.trOutsideBuilders (Trust.trustReport Map.empty foreignGraph user))+              `andThen` assertEqual "source outside" Map.empty (Trust.trOutsideBuilders sourceReport)+              `andThen` assertEqual "source builder" (Map.singleton (trustText setup) 1) (Trust.trSourceBuilders sourceReport),+      runTest "only a fixed-output derivation a builtin fetches with no input is fetched by trust" $+        assertEqual+          "fetched"+          [True, False, False, False]+          (map Trust.fetchedByBuiltin [fetched seedOut, hex0Drv, unpacked stage0TreeOut [stage0Archive], trustDrv seedOut (Just (trustHashOf seedOut)) "builtin:fetchurl" [] [setup]]),+      runTest "the report lists the opaque inputs first, each with how it came to be, then the counts, then what it does not say" $+        assertEqual+          "lines"+          [ "Fixed-output inputs run as builders: 3",+            "  " <> path bashOut,+            "    fetched by builtin:fetchurl",+            "    in the tree of the builder of 1 derivation: " <> bytesText bashExe,+            "    PE image: bin/bash.exe",+            "  " <> path seedOut,+            "    fetched by builtin:fetchurl",+            "    same hash as " <> path hex0Out,+            "    builder of 1 derivation: " <> path seedOut,+            "    PE image: the fetched file",+            "  " <> path hex0Out,+            "    built in the closure by " <> path seedOut <> ", its bytes pinned by its hash",+            "    same hash as " <> path seedOut,+            "    builder of 1 derivation: " <> path hex0Out,+            "    not read: the store does not hold it",+            "Fixed-output inputs holding prebuilt code: 1",+            "  " <> path stage0ArchiveOut,+            "    fetched by builtin:fetchurl",+            "    PE image: stage0-pe32/bootstrap-seeds/PE32/i386/hex0-seed.exe, the bytes of " <> path seedOut <> " and " <> path hex0Out,+            "    ar archive: stage0-pe32/lib/libc.a",+            "Fixed-output inputs not fully read: 1",+            "  " <> path helloSrcOut,+            "    fetched by builtin:fetchurl",+            "    not read: gzip stream error: truncated",+            "Fixed-output inputs holding no prebuilt code: 0",+            "Builders outside the closure: 1",+            "  /bin/sh, for 1 derivation",+            "Builders in input sources: 1",+            "  " <> path setup <> ", for 1 derivation",+            "Builtin builders: 2",+            "  builtin:fetchurl, for 4 derivations",+            "  builtin:unpack, for 1 derivation",+            "Input sources: 1",+            "This reports what the closure relies on, not whether any of it is safe."+          ]+          (Trust.renderTrustReport smallReport),+      runTest "the JSON form gives each input's class, how it comes to be and what its scan found, the seed's copy as the seed, and the builders and sources" $+        assertEqual "version" (Just (JsonInt Trust.trustReportJsonVersion)) (jsonMember "version" smallJson)+          `andThen` assertEqual+            "seed"+            (Just (JsonString "runAsBuilder"), Just (JsonString "builtin:fetchurl"), Just (JsonArray [JsonString (path hex0Out)]), Just (JsonObject (Map.singleton (path seedOut) (JsonInt 1))))+            (inputField "class" seedOut, inputField "fetchedBy" seedOut, inputField "sameHash" seedOut, inputField "builderOf" seedOut)+          `andThen` assertEqual+            "hex0"+            (Just (JsonString (path seedOut)), Nothing, Just (JsonBool False), Just (JsonArray []))+            (inputField "builtBy" hex0Out, inputField "fetchedBy" hex0Out, inputField "inStore" hex0Out, inputField "prebuiltCode" hex0Out)+          `andThen` assertEqual+            "archive"+            ( Just (JsonString "holdsPrebuiltCode"),+              Just+                ( JsonArray+                    [ codeJson "peImage" "stage0-pe32/bootstrap-seeds/PE32/i386/hex0-seed.exe" (trustHashOf seedOut) [seedOut, hex0Out],+                      codeJson "arArchive" "stage0-pe32/lib/libc.a" (Trust.fcSha256 (codeAt Trust.ArArchive (Trust.ArchiveMember "stage0-pe32/lib/libc.a"))) []+                    ]+                )+            )+            (inputField "class" stage0ArchiveOut, inputField "prebuiltCode" stage0ArchiveOut)+          `andThen` assertEqual+            "unread"+            (Just (JsonArray [JsonObject (Map.fromList [("file", JsonNull), ("reason", JsonString "gzip stream error: truncated")])]))+            (inputField "notRead" helloSrcOut)+          `andThen` assertEqual+            "builders and sources"+            ( Just (JsonObject (Map.singleton "/bin/sh" (JsonInt 1))),+              Just (JsonObject (Map.singleton (path setup) (JsonInt 1))),+              Just (JsonObject (Map.fromList [("builtin:fetchurl", JsonInt 4), ("builtin:unpack", JsonInt 1)])),+              Just (JsonArray [JsonString (path setup)])+            )+            (jsonMember "buildersOutsideClosure" smallJson, jsonMember "buildersInInputSources" smallJson, jsonMember "builtinBuilders" smallJson, jsonMember "inputSources" smallJson),+      runTestM "the JSON form names every fixed-output input once, under its output, in the class the lines give it" $ do+        result <-+          QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} $+            QC.forAll genTrustCase $ \(nodes, _, rootPath, caseFacts) ->+              QC.within 2000000 $+                let caseReport = Trust.trustReport caseFacts (trustGraph nodes) rootPath+                    named = case jsonMember "fixedOutputInputs" (Trust.trustReportJson caseReport) of+                      Just (JsonObject inputs) -> Map.map (jsonMember "class") inputs+                      _ -> Map.empty+                 in named QC.=== Map.fromList [(path (Trust.inputOutput input), Just (JsonString (classJson (Trust.inputClass input)))) | input <- Trust.trInputs caseReport]+        pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result))),+      runTestM "every fixed-output derivation of a closure is in the report once, in one class, cycles and all" $ do+        result <-+          QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} $+            QC.forAll genTrustCase $ \(nodes, fixedHere, rootPath, caseFacts) ->+              QC.within 2000000 $+                let caseGraph = trustGraph nodes+                    caseReport = Trust.trustReport caseFacts caseGraph rootPath+                    expected = sort (Set.toList (Set.intersection fixedHere (trustReachable caseGraph rootPath)))+                    counts = [readMaybe (T.unpack (T.takeWhileEnd isDigit line)) | line <- Trust.renderTrustReport caseReport, "Fixed-output inputs" `T.isPrefixOf` line]+                 in sort (map Trust.inputDrvPath (Trust.trInputs caseReport)) QC.=== expected+                      QC..&&. sum (catMaybes counts) QC.=== length expected+        pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result))),+      runTestM "what runs as a builder is read from the graph alone, whatever the scans found" $ do+        result <-+          QC.quickCheckWithResult QC.stdArgs {QC.chatty = False} $+            QC.forAll genTrustCase $ \(nodes, _, rootPath, caseFacts) ->+              QC.within 2000000 $+                let caseGraph = trustGraph nodes+                 in trustRunAsBuilders (Trust.trustReport caseFacts caseGraph rootPath) QC.=== trustRunAsBuilders (Trust.trustReport Map.empty caseGraph rootPath)+        pure (if QC.isSuccess result then Pass else Fail (T.pack (QC.output result)))+    ]++-- | The derivations a root reaches in a graph, itself included.+trustReachable :: DepGraph.DepGraph -> StorePath -> Set.Set StorePath+trustReachable (DepGraph.DepGraph graph) root = go Set.empty [root]+  where+    go seen [] = seen+    go seen (path : rest)+      | Set.member path seen = go seen rest+      | otherwise = case Map.lookup path graph of+          Nothing -> go seen rest+          Just node -> go (Set.insert path seen) (Map.keys (DepGraph.dnDeps node) ++ rest)++-- | What kind of output a generated derivation has.+data TrustOutputKind = FixedKind | FloatingKind | ImpureKind | InputAddressedKind+  deriving (Show, Enum, Bounded)++-- | Up to a dozen derivations, each with a fixed, floating, impure or+-- input-addressed output, built by a host program, a builtin, something+-- inside another's output or an input source, each depending on any of+-- them, itself and cycles included; which of them are fixed-output, as+-- generated; a root among them; and facts for some of their outputs.+genTrustCase :: QC.Gen ([(StorePath, Derivation)], Set.Set StorePath, StorePath, Map.Map StorePath Trust.ContentFacts)+genTrustCase = do+  count <- QC.chooseInt (1, length letters)+  let ids = take count letters+      drvPathOf letter = trustPath letter "node.drv"+      outOf letter = trustPath letter "node"+      source = trustPath 'z' "source"+      outputFor letter kind = case kind of+        FixedKind -> DerivationOutput "out" (outOf letter) "sha256" (trustHashOf (outOf letter))+        FloatingKind -> DerivationOutput "out" (outOf letter) "r:sha256" ""+        ImpureKind -> DerivationOutput "out" (outOf letter) "r:sha256" "impure"+        InputAddressedKind -> DerivationOutput "out" (outOf letter) "" ""+      builderFor =+        QC.oneof+          [ pure "/bin/sh",+            pure "builtin:fetchurl",+            pure "builtin:unpack",+            pure (trustText source),+            (\letter sub -> trustText (outOf letter) <> sub) <$> QC.elements ids <*> QC.elements ["", "/bin/tool"]+          ]+      nodeFor letter = do+        kind <- QC.elements [minBound .. maxBound]+        builder <- builderFor+        inputs <- QC.sublistOf ids+        sources <- QC.elements [[], [source]]+        pure ((drvPathOf letter, (trustDrv (outOf letter) Nothing builder (map drvPathOf inputs) sources) {drvOutputs = [outputFor letter kind]}), kind)+      factFor = do+        code <- QC.sublistOf [codeAt Trust.PeImage Trust.FetchedFile, codeAt Trust.ElfImage (Trust.TreeFile "bin/tool")]+        unread <- QC.sublistOf [Trust.UnreadFile Nothing "unreadable"]+        pure (Trust.ContentFacts code unread)+  generated <- traverse nodeFor ids+  root <- QC.elements ids+  scanned <- QC.sublistOf ids+  facts <- traverse (\letter -> (,) (outOf letter) <$> factFor) scanned+  pure+    ( map fst generated,+      Set.fromList [path | ((path, _), FixedKind) <- generated],+      drvPathOf root,+      Map.fromList facts+    )+  where+    letters = "abcdfghijklm"++-- | 'Nix.Trust.Scan.scanFetched' over files and trees written here: a+-- fetched file, a tar archive in each compression it opens, a package of+-- object code, a tree, and the limits of the scan.  Names are chosen+-- against the format each file has, since the bytes decide.+testTrustScanIO :: IO [Bool]+testTrustScanIO = do+  putStrLn "trust/scan"+  tmpBase <- getTemporaryDirectory+  canLink <- symlinksAvailable+  let root = tmpBase </> "nova-nix-test-trust-scan"+      at = (root </>)+      member = Trust.ArchiveMember+      archive = Tar.write [tarDir "pkg", tarFile "pkg/bin/tool.exe" (BL.fromStrict trustPe), tarFile "pkg/bin/run.sh" "#!/bin/sh\necho hi\n", tarFile "pkg/README" "readme\n"]+      elf = trustElf 1 3+      machO = BS.pack [0xCF, 0xFA, 0xED, 0xFE, 7, 0, 0, 1]+      nested = GZip.compress (Tar.write [tarFile "inner/x.exe" (BL.fromStrict trustPe)])+      zstdTar = BL.toStrict (zstdArchive [tarFile "usr/bin/tool" (BL.fromStrict elf)])+      objectCode =+        zstdArchive+          [ tarFile "include/stdio.h" "int printf(const char *, ...);\n",+            tarFile "lib/crt2.o" (BL.fromStrict (trustCoff 0x8664)),+            tarFile "lib/libmingw32.a" (BL.fromStrict trustAr)+          ]+      skippable = BS.pack [0x50, 0x2A, 0x4D, 0x18, 4, 0, 0, 0] <> "pzst"+      write name bytes = createDirectoryIfMissing True (takeDirectory (at name)) >> BS.writeFile (at name) bytes+      crtOut = trustPath 'x' "crt.tar.zst"+      crtDrv = trustPath 'w' "crt.tar.zst.drv"+      crtGraph = trustGraph [(crtDrv, trustDrv crtOut (Just (trustHashOf crtOut)) "builtin:fetchurl" [] [])]+  bracket_+    ( do+        forceRemoveIfExists root+        write "seed.txt" trustPe+        write "script.exe" "#!/bin/sh\necho hi\n"+        write "source.exe" (BL.toStrict (GZip.compress archive))+        write "package.tar.gz" zstdTar+        write "skippable.tar.zst" (skippable <> zstdTar)+        write "package.tar.xz" trustXzArchive+        write "package.tar.bz2" trustBzip2Archive+        write "plain.tar" (BL.toStrict archive)+        write "crt.tar.zst" (BL.toStrict objectCode)+        write "library.txt" trustAr+        write "nested.tar.gz" (BL.toStrict (GZip.compress (Tar.write [tarFile "outer/inner.tar.gz" nested])))+        write "corrupt.tar.gz" (BS.pack [0x1F, 0x8B, 0x08] <> "not a deflate stream")+        write "notes.bz2" "BZh is how a bzip2 stream starts\n"+        write "tools.tar" "PK\x03\x04 a zip archive's local file header\n"+        write ("tree" </> "bin" </> "tool") machO+        write ("tree" </> "src" </> "main.c") "int main(void) { return 0; }\n"+        write ("tree" </> "tests" </> "broken.xz") (BS.take 12 trustXzArchive)+        write ("tree" </> "vendor" </> "blob") (BL.toStrict nested)+        write ("outside" </> "tool.exe") trustPe+        createDirectoryIfMissing True (at "linked")+        when canLink (Dir.createFileLink (at ("outside" </> "tool.exe")) (at ("linked" </> "tool.exe")))+    )+    (forceRemoveIfExists root)+    $ do+      results <- traverse (scanFetched . at) ["seed.txt", "script.exe", "source.exe", "package.tar.gz", "skippable.tar.zst", "package.tar.xz", "package.tar.bz2", "plain.tar", "crt.tar.zst", "library.txt", "nested.tar.gz", "corrupt.tar.gz", "notes.bz2", "tools.tar", "tree", "linked"]+      case results of+        [seedFacts, scriptFacts, sourceFacts, zstdFacts, skippableFacts, xzFacts, bzip2Facts, plainFacts, crtFacts, libraryFacts, nestedFacts, corruptFacts, notesFacts, zipFacts, treeFacts, linkedFacts] ->+          sequence+            [ runTest "a fetched file that is a Portable Executable is one, whatever its name" $+                assertEqual "seed" (oneCodeOf Trust.PeImage Trust.FetchedFile trustPe) seedFacts,+              runTest "a script holds no prebuilt code, whatever its name" $+                assertEqual "script" noCode scriptFacts,+              runTest "a gzip tar archive is opened, and only its prebuilt code is reported" $+                assertEqual "source" (oneCodeOf Trust.PeImage (member "pkg/bin/tool.exe") trustPe) sourceFacts,+              runTest "a zstd tar archive is opened, whatever its name, and so is one a skippable frame starts" $+                assertEqual "zstd" (oneCodeOf Trust.ElfImage (member "usr/bin/tool") elf) zstdFacts+                  `andThen` assertEqual "skippable" (oneCodeOf Trust.ElfImage (member "usr/bin/tool") elf) skippableFacts,+              runTest "xz and bzip2 tar archives are opened" $+                assertEqual "xz" (oneCodeOf Trust.PeImage (member "pkg/tool.exe") trustPe) xzFacts+                  `andThen` assertEqual "bzip2" (oneCodeOf Trust.PeImage (member "pkg/tool.exe") trustPe) bzip2Facts,+              runTest "an uncompressed tar archive is opened" $+                assertEqual "plain" (oneCodeOf Trust.PeImage (member "pkg/bin/tool.exe") trustPe) plainFacts,+              runTest "a package of an object and a static library holds prebuilt code, both named" $+                assertEqual "crt" (codeOnly [codeOf Trust.CoffObject (member "lib/crt2.o") (trustCoff 0x8664), codeOf Trust.ArArchive (member "lib/libmingw32.a") trustAr]) crtFacts+                  `andThen` assertEqual+                    "class"+                    [Trust.HoldsPrebuiltCode]+                    (map Trust.inputClass (Trust.trInputs (Trust.trustReport (Map.singleton crtOut crtFacts) crtGraph crtDrv))),+              runTest "a fetched ar archive is one file of prebuilt code, whatever its name" $+                assertEqual "library" (oneCodeOf Trust.ArArchive Trust.FetchedFile trustAr) libraryFacts,+              runTest "an archive inside an archive is not opened" $+                assertEqual "nested" noCode nestedFacts,+              runTest "a stream that does not decode is not read, with why" $+                case corruptFacts of+                  Trust.ContentFacts [] [Trust.UnreadFile Nothing reason] | "gzip stream error: " `T.isPrefixOf` reason -> Pass+                  other -> Fail (T.pack (show other)),+              runTest "text that starts as a bzip2 magic does, without its block size, is read as it is" $+                assertEqual "notes" noCode notesFacts,+              runTest "an archive in a format the scan does not open is not read, whatever its name" $+                assertEqual "zip" (Trust.ContentFacts [] [Trust.UnreadFile Nothing "a zip archive, which the scan does not open"]) zipFacts,+              runTest "each file of a tree is read in name order, an archive in it is opened, and one that does not decode is not read" $+                case treeFacts of+                  Trust.ContentFacts code [Trust.UnreadFile (Just "tests/broken.xz") reason]+                    | "xz stream error: " `T.isPrefixOf` reason ->+                        assertEqual "code" [codeOf Trust.MachO (Trust.TreeFile "bin/tool") machO, codeOf Trust.PeImage (Trust.TreeArchiveMember "vendor/blob" "inner/x.exe") trustPe] code+                  other -> Fail (T.pack (show other)),+              runTest "a symbolic link in a tree is not followed" $+                if canLink then assertEqual "linked" noCode linkedFacts else Pass+            ]+        _ -> sequence [runTest "trust scan results" (Fail "one result per fixture expected")]++-- | The closures of @pkgs/windows@'s stage0-pe32 kaem and GNU Hello as+-- evaluation records them, classified with no content facts: what runs as+-- a builder, and how each fixed output comes to be, is in the graph+-- alone.+testTrustWindowsGraphs :: IO [Bool]+testTrustWindowsGraphs = do+  putStrLn "trust/pkgs-windows"+  cwd <- Dir.getCurrentDirectory+  storeDir <- evalNixIOStoreDir+  searchPaths <- parseNixPath (TE.encodeUtf8 (T.pack (cwd </> "data")))+  st <- newEvalStateWith testLogger unrestrictedPolicy searchPaths (testSessionStore storeDir) storeDir cwd+  let windows = "(import " <> nixQuotedPath (cwd </> "pkgs" </> "windows") <> ")"+      source = "builtins.concatStringsSep \" \" [ " <> windows <> ".stage0-pe32.kaem-unwrapped.drvPath " <> windows <> ".hello.drvPath ]"+  outcome <- case parseNix cwd testOrigin (TE.encodeUtf8 source) of+    Left err -> pure (Left (T.pack (show err)))+    Right parsed -> runEvalIO st $ do+      value <- evalParsed (pure (evalBaseEnv st)) parsed+      case value of+        VStr bytes _ -> do+          let roots = T.words (bytesText bytes)+          closure <- sessionClosure roots+          pure (roots, closure)+        other -> throwEvalError ("expected the drvPaths as one string, got " <> typeName other)+  case outcome of+    Right ([kaemText, helloText], closure)+      | Just kaem <- parseStorePath defaultStoreDir kaemText,+        Just helloDrv <- parseStorePath defaultStoreDir helloText -> do+          let graph = DepGraph.DepGraph (Map.fromList [(sp, DepGraph.DepNode sp drv (Map.map Set.fromList (drvInputDrvs drv))) | (text, drv) <- Map.toList closure, Just sp <- [parseStorePath defaultStoreDir text]])+              kaemReport = Trust.trustReport Map.empty graph kaem+              helloReport = Trust.trustReport Map.empty graph helloDrv+              ranNames report = sort [spName (Trust.inputOutput input) | input <- Trust.trInputs report, Trust.inputClass input == Trust.RunAsBuilder]+              ranDirectly report = sort [spName (Trust.inputOutput input) | input <- Trust.trInputs report, not (Map.null (Trust.inputBuilders input))]+              treeBuilders report = Set.fromList (concatMap (Map.keys . Trust.inputTreeBuilders) (Trust.trInputs report))+              named name report = [input | input <- Trust.trInputs report, spName (Trust.inputOutput input) == name]+          sequence+            [ runTest "kaem's closure runs the seed as a builder, and hex0, which its hash fixes to the seed" $+                assertEqual "run as builders" ["hex0-seed.exe", "hex0.exe"] (ranNames kaemReport)+                  `andThen` assertEqual "directly" ["hex0-seed.exe", "hex0.exe"] (ranDirectly kaemReport)+                  `andThen` assertEqual "outside" Map.empty (Trust.trOutsideBuilders kaemReport)+                  `andThen` assertEqual "builtins" ["builtin:fetchurl", "builtin:unpack"] (Map.keys (Trust.trBuiltinBuilders kaemReport)),+              runTest "kaem's hex0 is built in the closure by the fetched seed, and has the seed's hash" $+                case (named "hex0-seed.exe" kaemReport, named "hex0.exe" kaemReport) of+                  ([seedInput], [hex0Input]) ->+                    assertEqual "seed" (Trust.FetchedBy "builtin:fetchurl", [Trust.inputOutput hex0Input]) (Trust.inputProvenance seedInput, Trust.inputSameHash seedInput)+                      `andThen` assertEqual "hex0" (Trust.BuiltBy (trustText (Trust.inputOutput seedInput)), [Trust.inputOutput seedInput]) (Trust.inputProvenance hex0Input, Trust.inputSameHash hex0Input)+                  other -> Fail ("inputs: " <> T.pack (show other)),+              runTest "hello's closure, through the stdenv, runs only the seed and hex0 as builders, as kaem's does" $+                assertEqual "run as builders" ["hex0-seed.exe", "hex0.exe"] (ranNames helloReport)+                  `andThen` assertEqual "directly" ["hex0-seed.exe", "hex0.exe"] (ranDirectly helloReport)+                  `andThen` assertEqual "tree builders" Set.empty (treeBuilders helloReport)+                  `andThen` assertEqual "outside" Map.empty (Trust.trOutsideBuilders helloReport)+            ]+    Right other -> sequence [runTest "trust over pkgs/windows evaluates" (Fail ("unexpected roots: " <> T.pack (show (fst other))))]+    Left err -> sequence [runTest "trust over pkgs/windows evaluates" (Fail err)]
+ test/Test/WindowsSandbox.hs view
@@ -0,0 +1,1519 @@+{-# LANGUAGE ScopedTypeVariables #-}++-- | The sandbox helper's Windows backend (@sandbox\/windows.c@), run as+-- the service that logs each build slot on runs it.+--+-- Most of its checks need that service's account: a virtual account+-- holding the privileges that start a process as another account.  CI's+-- Windows build runs the suite as an administrator+-- ('windowsSandboxInstall'), given the runner's user, whose files, hive+-- and processes a build must not reach.  That run makes two slot+-- accounts with the batch logon right, and a test service that runs as+-- its virtual account with those privileges; lays out a directory that+-- only the service, SYSTEM and administrators may use, and writes there+-- what the checks are given, the slots' passwords among it; starts the+-- service, waits for it to stop, and prints the checks' log.  It removes+-- the service and the accounts, each one's rights first, however the+-- checks end.  The service ('windowsSandboxService') runs the checks as a+-- process of its own ('windowsSandboxAccounts'), which logs each slot on+-- as the service that runs builds does and runs the helper over the plans+-- 'Sandbox.renderWindowsPlan' writes, with the suite itself as the+-- builder ('windowsSandboxBuilder').  The suite's own run, as a user+-- without those privileges, checks that the probe and a run report the+-- step that needs them ('testWindowsSandboxIO').+module Test.WindowsSandbox+  ( testWindowsSandboxIO,+    windowsSandboxInstallFlag,+    windowsSandboxInstall,+    windowsSandboxServiceFlag,+    windowsSandboxService,+    windowsSandboxAccountsFlag,+    windowsSandboxAccounts,+    windowsSandboxBuilderFlag,+    windowsSandboxBuilder,++    -- * Accounts the administrator's runs make+    SlotAccount (..),+    accountPrefix,+    withBuildersGroup,+    withAccount,+    makeAccount,+    removeAccount,+    withLogon,++    -- * Directories with a DACL of their own+    makeDirectory,+  )+where++import Control.Concurrent (threadDelay)+import Control.Concurrent.Async (poll, wait, withAsync)+import Control.Exception (IOException, bracket, finally, try)+import Control.Monad (unless, void, when, (<=<))+import Data.Bits ((.&.))+import qualified Data.ByteString as BS+import qualified Data.ByteString.Char8 as BS8+import Data.Foldable (traverse_)+import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef)+import Data.List (intercalate, isPrefixOf, sort)+import Data.Maybe (fromMaybe, isJust, isNothing, mapMaybe)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import qualified Data.Text.IO as TIO+import Data.Word (Word32, Word64)+import qualified DirDacl+import Foreign.C.Error (Errno (..), eINVAL)+import Foreign.C.String (CString, CWString, peekCString, peekCWString, withCWString)+import Foreign.C.Types (CInt (..), CULLong (..), CULong (..))+import Foreign.Marshal.Alloc (alloca)+import Foreign.Marshal.Array (allocaArray)+import Foreign.Ptr (Ptr, nullPtr, ptrToWordPtr)+import Foreign.Storable (peek)+import GHC.IO.Handle (hDuplicateTo)+import qualified Nix.Builder.Sandbox as Sandbox+import qualified Nix.Builder.Sandbox.Spawn as Spawn+import Nix.Logger (Logger, plainLogger)+import Nix.Store (canonicalizeMetadata)+import Nix.Store.Access (Sid, createStoreDirectory, sidFromText, sidText)+import Nix.Store.CaseSensitive (processCaseHack)+import qualified Nix.Store.ExecBit as ExecBit+import qualified NovaCache.Base64 as B64+import Numeric (showHex)+import qualified System.Directory as Dir+import System.Environment (getExecutablePath, lookupEnv)+import System.Exit (ExitCode (..), exitFailure, exitWith)+import System.FilePath (takeDirectory, takeDrive, takeFileName, (</>))+import System.IO (BufferMode (..), Handle, IOMode (..), hClose, hFlush, hSetBuffering, stderr, stdout, withBinaryFile)+import System.IO.Error (ioeGetFileName)+import qualified System.Info as SI+import qualified System.Process as Proc+import System.Timeout (timeout)+import Test.Builder (processWaitMicros, sandboxHelperVar, startWaitMicros, waitUntil, waitUntilWithin)+import Test.Harness (TestResult (..), andThen, assertEqual, runTest, runTestM)+import Text.Read (readMaybe)++-- ---------------------------------------------------------------------------+-- Windows' calls (test/cbits/nn_test_sandbox_windows.c)+-- ---------------------------------------------------------------------------++foreign import ccall unsafe "nova_test_account_make"+  c_account_make :: CWString -> Ptr CWString -> Ptr CString -> IO CULong++foreign import ccall unsafe "nova_test_group_make"+  c_group_make :: CWString -> IO CULong++foreign import ccall unsafe "nova_test_group_add"+  c_group_add :: CWString -> CWString -> IO CULong++foreign import ccall unsafe "nova_test_group_remove"+  c_group_remove :: CWString -> IO CULong++foreign import ccall unsafe "nova_test_account_sid"+  c_account_sid :: CWString -> Ptr CWString -> IO CULong++foreign import ccall unsafe "nova_test_mkdir"+  c_mkdir :: CWString -> IO CULong++foreign import ccall unsafe "nova_test_lock"+  c_lock :: CWString -> IO CULong++foreign import ccall unsafe "nova_test_account_remove"+  c_account_remove :: CWString -> Ptr CString -> IO CULong++foreign import ccall unsafe "nova_test_service_install"+  c_service_install :: CWString -> CWString -> Ptr CWString -> Ptr CString -> IO CULong++foreign import ccall unsafe "nova_test_service_start"+  c_service_start :: CWString -> IO CULong++foreign import ccall unsafe "nova_test_service_state"+  c_service_state :: CWString -> Ptr CULong -> Ptr CULong -> IO CULong++foreign import ccall unsafe "nova_test_service_remove"+  c_service_remove :: CWString -> Ptr CString -> IO CULong++-- Safe, as it returns only once the service has stopped.+foreign import ccall safe "nova_test_service_dispatch"+  c_service_dispatch :: CWString -> CWString -> IO CULong++foreign import ccall unsafe "nova_test_account_logon"+  c_account_logon :: CWString -> CWString -> Ptr CWString -> Ptr (Ptr ()) -> IO CULong++foreign import ccall unsafe "nova_test_close_handle"+  c_close_handle :: Ptr () -> IO CULong++foreign import ccall unsafe "nova_test_local_free"+  c_local_free :: CWString -> IO ()++foreign import ccall unsafe "nova_test_directory_with_sddl"+  c_directory_with_sddl :: CWString -> CWString -> IO CULong++foreign import ccall unsafe "nova_test_set_sddl"+  c_set_sddl :: CWString -> CWString -> IO CULong++foreign import ccall unsafe "nova_test_start_as"+  c_start_as :: Ptr () -> CWString -> Ptr CULong -> IO CULong++foreign import ccall unsafe "nova_test_process_running"+  c_process_running :: CULong -> IO CInt++foreign import ccall unsafe "nova_test_token_user"+  c_token_user :: Ptr CWString -> IO CULong++foreign import ccall unsafe "nova_test_user_object_name"+  c_user_object_name :: CInt -> CWString -> CULong -> IO CULong++foreign import ccall unsafe "nova_test_logon_id"+  c_logon_id :: Ptr CULong -> Ptr CULong -> IO CULong++foreign import ccall unsafe "nova_test_open_station"+  c_open_station :: CWString -> IO CULong++foreign import ccall unsafe "nova_test_station_dacl"+  c_station_dacl :: CWString -> Ptr CWString -> IO CULong++foreign import ccall unsafe "nova_test_account_processes"+  c_account_processes :: CWString -> CWString -> CULong -> Ptr CULong -> IO CULong++foreign import ccall unsafe "nova_test_stdout_value"+  c_stdout_value :: IO CULong++foreign import ccall unsafe "nova_test_hold_handle"+  c_hold_handle :: CULong -> CULong -> IO CULong++foreign import ccall unsafe "nova_test_in_job"+  c_in_job :: IO CInt++foreign import ccall unsafe "nova_test_console"+  c_console :: IO CULong++foreign import ccall unsafe "nova_test_commit"+  c_commit :: CULLong -> IO CULong++foreign import ccall unsafe "nova_test_start"+  c_start :: CWString -> CULong -> Ptr CULong -> Ptr (Ptr ()) -> IO CULong++-- Safe, as it blocks until the process it waits for ends.+foreign import ccall safe "nova_test_wait"+  c_wait :: Ptr () -> Ptr CULong -> IO CULong++foreign import ccall unsafe "nova_test_crash"+  c_crash :: IO ()++foreign import ccall unsafe "nova_test_open"+  c_open :: CWString -> CULong -> IO CULong++foreign import ccall unsafe "nova_test_create"+  c_create :: CWString -> IO CULong++foreign import ccall unsafe "nova_test_delete"+  c_delete :: CWString -> IO CULong++foreign import ccall unsafe "nova_test_list"+  c_list :: CWString -> IO CULong++foreign import ccall unsafe "nova_test_open_key"+  c_open_key :: CWString -> IO CULong++foreign import ccall unsafe "nova_test_open_process"+  c_open_process :: CULong -> IO CULong++-- | A wide string the Win32 API allocated, read and then released.+takeWide :: CWString -> IO Text+takeWide wide = (T.pack <$> peekCWString wide) `finally` c_local_free wide++-- | Throw unless a call answered 0, naming the call and its error.+succeeded :: String -> CULong -> IO ()+succeeded call code =+  unless (code == 0) (ioError (userError (call <> " failed with Win32 error " <> show code)))++-- | Throw unless a call that names what failed in it answered 0, naming+-- that, or the call where it names nothing.+succeededNaming :: String -> String -> (Ptr CString -> IO CULong) -> IO ()+succeededNaming call subject run =+  alloca $ \failedOut -> do+    code <- run failedOut+    unless (code == 0) $ do+      failed <- peek failedOut+      named <- if failed == nullPtr then pure call else peekCString failed+      succeeded (named <> " for " <> subject) code++-- | @GENERIC_READ@ (winnt.h).+genericRead :: CULong+genericRead = 0x80000000++-- | @CREATE_BREAKAWAY_FROM_JOB@ (winbase.h).+breakawayFromJob :: CULong+breakawayFromJob = 0x01000000++-- | @ERROR_ACCESS_DENIED@ (winerror.h).+accessDenied :: CULong+accessDenied = 5++-- | @ERROR_FILE_NOT_FOUND@ (winerror.h).+fileNotFound :: Int+fileNotFound = 2++-- | @ERROR_NOT_ALL_ASSIGNED@ (winerror.h): what enabling a privilege the+-- token does not hold answers.+notAllAssigned :: Int+notAllAssigned = 1300++-- | @SERVICE_STOPPED@ (winsvc.h).+serviceStopped :: CULong+serviceStopped = 1++-- | The code a builder's crash raises (@nova_test_crash@).+crashExceptionCode :: Word32+crashExceptionCode = 0xE04E4E01++-- | The exit code the helper ends a build's processes with, the process+-- library's.+endedBuildExitCode :: Int+endedBuildExitCode = 1++-- ---------------------------------------------------------------------------+-- The suite's own run+-- ---------------------------------------------------------------------------++-- | The helper as the suite's own user runs it, which holds neither+-- privilege that starts a process as another account: the probe and a run+-- each fail at enabling them, and a plan the helper refuses is reported+-- as the plan's.  Windows only, with the helper 'sandboxHelperVar' names.+testWindowsSandboxIO :: IO [Bool]+testWindowsSandboxIO = do+  putStrLn "builder/sandbox-windows"+  named <- lookupEnv sandboxHelperVar+  case (SI.os, named) of+    ("mingw32", Just helper) -> do+      present <- Dir.doesFileExist helper+      if present+        then unprivilegedChecks helper+        else (: []) <$> runTest (T.pack sandboxHelperVar <> " names a file") (Fail (T.pack helper))+    ("mingw32", Nothing) -> do+      putStrLn ("  SKIP  needs " ++ sandboxHelperVar)+      pure []+    _ -> do+      putStrLn "  SKIP  Windows only"+      pure []++unprivilegedChecks :: FilePath -> IO [Bool]+unprivilegedChecks helper = case sidFromText localSystemSid of+  Nothing -> (: []) <$> runTest "SYSTEM's SID reads as one" (Fail localSystemSid)+  Just system -> unprivilegedChecksAs helper system++-- | SYSTEM's SID, which a plan whose run never reaches its token names.+localSystemSid :: Text+localSystemSid = "S-1-5-18"++-- | A plan's token value for a run that never reaches its token.+unreachedToken :: Word32+unreachedToken = 4++unprivilegedChecksAs :: FilePath -> Sid -> IO [Bool]+unprivilegedChecksAs helper system = do+  scratch <- Dir.getTemporaryDirectory+  let plan = Sandbox.WindowsPlan (pathBytes scratch) unreachedToken system ordinaryMemoryCap []+      runPlan rendered = fst <$> capturingBuildLog (\logger -> Spawn.runHelper logger helper rendered scratch ["cmd.exe"])+  sequence+    [ runTestM "without the privileges that start a build as another account, the probe fails at enabling them, as a run does" $ do+        (code, out, _) <- Proc.readCreateProcessWithExitCode ((Proc.proc helper ["probe"]) {Proc.env = Just []}) ""+        run <- runPlan (Sandbox.renderWindowsPlan plan)+        pure $+          assertEqual "probe" (ExitFailure 1, Right (Just (Sandbox.StatusRecord Sandbox.ProbePrivileges notAllAssigned Nothing))) (code, Sandbox.parseStatus Sandbox.probeStageName (BS8.pack out))+            `andThen` assertEqual "run" (ExitFailure 1, Right (Just (Sandbox.StatusRecord Sandbox.WindowsStagePrivileges notAllAssigned Nothing))) (Spawn.hrExit run, windowsRecord (Spawn.hrStatus run)),+      runTestM "a plan the helper refuses is reported as the plan's" $ do+        run <- runPlan (Sandbox.renderWindowsPlan plan {Sandbox.windowsPlanMemoryCap = 0})+        pure (assertEqual "run" (ExitFailure 1, Right (Just (Sandbox.StatusRecord Sandbox.WindowsStagePlan einval Nothing))) (Spawn.hrExit run, windowsRecord (Spawn.hrStatus run)))+    ]++-- | What the helper wrote on its status channel, read with the Windows+-- stages' names.+windowsRecord :: BS.ByteString -> Either Text (Maybe (Sandbox.StatusRecord Sandbox.WindowsStage))+windowsRecord = Sandbox.parseStatus Sandbox.windowsStageName++-- | The errno a plan the helper refuses is reported with.+einval :: Int+einval = case eINVAL of Errno number -> fromIntegral number++-- ---------------------------------------------------------------------------+-- What the checks are given+-- ---------------------------------------------------------------------------++-- | The runner's user, whose own a build must not reach: its SID, its+-- profile, TEMP and APPDATA directories, one of its processes, a file+-- only it may read and a file in its profile.+data Victim = Victim+  { victimSid :: !Text,+    victimProfile :: !FilePath,+    victimTemp :: !FilePath,+    victimAppData :: !FilePath,+    victimPid :: !Word32,+    victimOnlyFile :: !FilePath,+    victimProfileFile :: !FilePath+  }+  deriving (Show, Read)++-- | A slot's account as the service holds it: its name and its password,+-- which the service logs it on with.+data SlotAccount = SlotAccount+  { saName :: !Text,+    saPassword :: !Text+  }+  deriving (Show, Read)++-- | What the checks the test service runs are given: the directory they+-- lay out, which holds their log; the helper; MSYS2's bash; the runner's+-- user; and the two slots' accounts.  The administrator's run writes it+-- in that directory, where the service, SYSTEM and administrators alone+-- may read it.+data ServiceChecks = ServiceChecks+  { scRoot :: !FilePath,+    scHelper :: !FilePath,+    scBash :: !FilePath,+    scVictim :: !Victim,+    scSlotOne :: !SlotAccount,+    scSlotTwo :: !SlotAccount+  }+  deriving (Show, Read)++-- | The file the checks are given in, in their directory.+checksConfig :: FilePath -> FilePath+checksConfig root = root </> "checks"++-- | The checks' log, in their directory.+checksLog :: FilePath -> FilePath+checksLog root = root </> "checks.log"++-- | The name every account the checks use starts with, which CI's step+-- that removes what a run left behind matches.+accountPrefix :: Text+accountPrefix = "nnslot"++-- | The name the test service starts with, which CI's step that removes+-- what a run left behind matches.+servicePrefix :: Text+servicePrefix = "nnsandbox"++-- ---------------------------------------------------------------------------+-- The administrator's run+-- ---------------------------------------------------------------------------++-- | The flag CI's step runs the suite with, as an administrator: the+-- directory the checks' directory is made in, the helper, MSYS2's bash,+-- and the runner's user ('Victim').+windowsSandboxInstallFlag :: String+windowsSandboxInstallFlag = "--windows-sandbox-install"++-- | Make the slot accounts and the test service, run the checks through+-- the service, print their log, and remove the service and the accounts+-- however the checks end; exit 0 only when every check passed.+windowsSandboxInstall :: [String] -> IO ()+windowsSandboxInstall args = case args of+  [parent, helper, bash, sid, profile, temp, appData, pidText, onlyFile, profileFile]+    | Just pid <- readMaybe pidText -> do+        hSetBuffering stdout LineBuffering+        tag <- T.pack . show <$> Proc.getCurrentPid+        suite <- getExecutablePath+        let root = parent </> ("nova-nix-sandbox-windows-" <> T.unpack tag)+            service = servicePrefix <> tag+            command = unwords [quoted suite, windowsSandboxServiceFlag, T.unpack service, quoted (checksConfig root)]+            victim = Victim (T.pack sid) profile temp appData pid onlyFile profileFile+        code <-+          withBuildersGroup $+            withAccount (accountPrefix <> tag <> "a") $ \one ->+              withAccount (accountPrefix <> tag <> "b") $ \two ->+                withService service command $ \serviceSid ->+                  withChecksRoot root serviceSid $ do+                    BS.writeFile (checksConfig root) (TE.encodeUtf8 (T.pack (show (ServiceChecks root helper bash victim one two))))+                    runChecks service (checksLog root)+        exitWith code+  _ -> do+    putStrLn ("usage: " <> windowsSandboxInstallFlag <> " PARENT HELPER BASH SID PROFILE TEMP APPDATA PID USER-ONLY-FILE PROFILE-FILE")+    exitFailure++-- | Run an action with a slot's account made for it, with the batch+-- logon right and a member of the build accounts' group, and removed+-- after it, its right first, however the action ends, a failure to make+-- it included.+withAccount :: Text -> (SlotAccount -> IO a) -> IO a+withAccount name use = (makeAccount name >>= joined >>= use) `finally` removeAccount name+  where+    joined account = do+      withCWString buildersGroupName $ \group ->+        withCWString (T.unpack name) (succeeded ("adding " <> T.unpack name <> " to the group " <> buildersGroupName) <=< c_group_add group)+      pure account++-- | The build accounts' local group, the one the store names+-- ("Nix.Store.Access"), which the checks make and every slot's account+-- is a member of.+buildersGroupName :: String+buildersGroupName = "nixbld"++-- | Run an action with the build accounts' group made for it and removed+-- after it however the action ends.  A group of that name already on the+-- machine fails the checks rather than being taken for theirs.+withBuildersGroup :: IO a -> IO a+withBuildersGroup action =+  withCWString buildersGroupName $ \wide -> do+    succeeded ("making the group " <> buildersGroupName) =<< c_group_make wide+    action `finally` (c_group_remove wide >>= reportRemoval)+  where+    reportRemoval code =+      unless (code == 0) (putStrLn ("  removing the group " <> buildersGroupName <> " failed with Win32 error " <> show code))++-- | The SID of the build accounts' group, which the administrator's run+-- made.+buildersGroupSid :: IO Sid+buildersGroupSid = do+  text <- withCWString buildersGroupName $ \wide -> wideResult (c_account_sid wide)+  maybe (ioError (userError ("the group " <> buildersGroupName <> " has no SID: " <> T.unpack text))) pure (sidFromText text)++makeAccount :: Text -> IO SlotAccount+makeAccount name =+  withCWString (T.unpack name) $ \wide -> alloca $ \passwordOut -> do+    succeededNaming "nova_test_account_make" (T.unpack name) (c_account_make wide passwordOut)+    SlotAccount name <$> (takeWide =<< peek passwordOut)++-- | Remove an account the checks used, saying why it could not be, where+-- it could not: CI's step after removes it by its name.+removeAccount :: Text -> IO ()+removeAccount name =+  withCWString (T.unpack name) $ \wide -> alloca $ \failedOut -> do+    code <- c_account_remove wide failedOut+    unless (code == 0) $ do+      failed <- peek failedOut+      call <- if failed == nullPtr then pure "nova_test_account_remove" else peekCString failed+      putStrLn ("  removing the account " <> T.unpack name <> ": " <> call <> " failed with Win32 error " <> show code)++-- | Run an action with the test service made for it, started by the+-- command line given and running as its virtual account, whose SID the+-- action is given, and removed after it, its account's rights first,+-- however the action ends, a failure to make it included.+withService :: Text -> String -> (Sid -> IO a) -> IO a+withService name command use = (installService name command >>= use) `finally` removeService name++installService :: Text -> String -> IO Sid+installService name command =+  withCWString (T.unpack name) $ \wideName -> withCWString command $ \wideCommand -> alloca $ \sidOut -> do+    succeededNaming "nova_test_service_install" (T.unpack name) (c_service_install wideName wideCommand sidOut)+    sidString <- takeWide =<< peek sidOut+    maybe (ioError (userError ("not a SID: " <> T.unpack sidString))) pure (sidFromText sidString)++-- | Remove the test service, saying why it could not be, where it could+-- not: CI's step after removes it by its name.+removeService :: Text -> IO ()+removeService name =+  withCWString (T.unpack name) $ \wide -> alloca $ \failedOut -> do+    code <- c_service_remove wide failedOut+    unless (code == 0) $ do+      failed <- peek failedOut+      call <- if failed == nullPtr then pure "nova_test_service_remove" else peekCString failed+      putStrLn ("  removing the service " <> T.unpack name <> ": " <> call <> " failed with Win32 error " <> show code)++-- | Run an action with the checks' directory made for it and removed+-- after it, saying why it could not be removed, where it could not.+withChecksRoot :: FilePath -> Sid -> IO a -> IO a+withChecksRoot root service action =+  (makeDirectory root (rootSddl service) *> action) `finally` removeRoot+  where+    removeRoot = do+      removed <- try (Dir.removePathForcibly root)+      case removed of+        Left (failure :: IOException) -> putStrLn ("  removing " <> root <> ": " <> show failure)+        Right () -> pure ()++-- | Start the test service, wait for it to stop, print the checks' log,+-- and answer whether every check passed: the service stopped within the+-- wait, with the checks' exit code 0, and the log ends with their count.+runChecks :: Text -> FilePath -> IO ExitCode+runChecks service logPath = do+  withCWString (T.unpack service) (succeeded "starting the test service" <=< c_service_start)+  stopped <- waitUntilWithin checksWaitMicros ((== serviceStopped) . fst <$> serviceState service)+  (_, code) <- serviceState service+  written <- try (BS.readFile logPath)+  let contents = either (\(_ :: IOException) -> "") id written+      counted = any isCount (BS8.lines contents)+  BS8.putStr contents+  unless stopped (putStrLn ("the test service had not stopped within " <> show checksWaitMinutes <> " minutes"))+  putStrLn ("the account checks ended with " <> show code)+  unless counted (putStrLn "the account checks did not finish: their log has no count")+  pure (if stopped && counted && code == 0 then ExitSuccess else ExitFailure 1)+  where+    isCount text = case BS8.words text of+      [flag, _, "passed"] -> flag == BS8.pack (windowsSandboxAccountsFlag <> ":")+      _ -> False++-- | How long the checks may take, in all.+checksWaitMinutes, checksWaitMicros :: Int+checksWaitMinutes = 20+checksWaitMicros = checksWaitMinutes * 60 * 1000000++-- | The test service's state and the code it stopped with.+serviceState :: Text -> IO (CULong, CULong)+serviceState service =+  withCWString (T.unpack service) $ \wide -> alloca $ \stateOut -> alloca $ \codeOut -> do+    succeeded "querying the test service" =<< c_service_state wide stateOut codeOut+    (,) <$> peek stateOut <*> peek codeOut++-- ---------------------------------------------------------------------------+-- The test service+-- ---------------------------------------------------------------------------++-- | The flag the test service is started with: its name, and the file+-- its checks are given in.+windowsSandboxServiceFlag :: String+windowsSandboxServiceFlag = "--windows-sandbox-service"++-- | Run as the test service until it stops, which runs the checks as a+-- process of its own and stops when they end.+windowsSandboxService :: [String] -> IO ()+windowsSandboxService args = case args of+  [name, config] -> do+    self <- getExecutablePath+    let checks = unwords [quoted self, windowsSandboxAccountsFlag, quoted config]+    code <- withCWString name $ \wideName -> withCWString checks (c_service_dispatch wideName)+    unless (code == 0) (exitWith (ExitFailure (fromIntegral code)))+  _ -> exitFailure++-- ---------------------------------------------------------------------------+-- The checks, as the test service+-- ---------------------------------------------------------------------------++-- | The flag the test service starts the checks with: the file they are+-- given in ('ServiceChecks').+windowsSandboxAccountsFlag :: String+windowsSandboxAccountsFlag = "--windows-sandbox-accounts"++-- | Run the checks as the test service, writing what the suite prints to+-- their log, and exit 0 only when every check passed.+windowsSandboxAccounts :: [String] -> IO ()+windowsSandboxAccounts args = case args of+  [config] -> do+    bytes <- BS.readFile config+    case either (const Nothing) (readMaybe . T.unpack) (TE.decodeUtf8' bytes) of+      Just checks ->+        withBinaryFile (checksLog (scRoot checks)) WriteMode $ \logHandle -> do+          redirectOutput logHandle+          results <- accountChecks checks+          let passed = length (filter id results)+          putStrLn (windowsSandboxAccountsFlag <> ": " <> show passed <> "/" <> show (length results) <> " passed")+          hFlush stdout+          when (passed /= length results) exitFailure+      Nothing -> exitFailure+  _ -> exitFailure++-- | Send this process's standard output and error to the log, line by+-- line, since no one reads the service's own.+redirectOutput :: Handle -> IO ()+redirectOutput logHandle = do+  hDuplicateTo logHandle stdout+  hDuplicateTo logHandle stderr+  hSetBuffering stdout LineBuffering++-- | A build slot: its account, the account's SID, its primary token,+-- which this process holds inheritable for the helpers it starts, and the+-- directory its builds start in.+data Slot = Slot+  { slotAccount :: !SlotAccount,+    slotSid :: !Sid,+    slotToken :: !(Ptr ()),+    slotBuildDir :: !FilePath+  }++-- | What every check runs with: the helper, the suite's copy every slot+-- may run as the builder, the directory the runs lay out, the service's+-- SID, Windows' directory, and how many runs have started, which names+-- the files some of them hold.+data Fixture = Fixture+  { fxHelper :: !FilePath,+    fxBuilder :: !FilePath,+    fxRoot :: !FilePath,+    fxService :: !Sid,+    fxSystemRoot :: !FilePath,+    fxRuns :: !(IORef Int)+  }++-- | The memory cap of a run whose builder needs room and no more.+ordinaryMemoryCap :: Word64+ordinaryMemoryCap = 1024 * mebibyte++-- | The memory check's cap, and a commit beneath it and past it, in+-- mebibytes.+cappedMemory :: Word64+cappedMemory = 256 * mebibyte++underCapMebibytes, overCapMebibytes :: Word64+underCapMebibytes = 64+overCapMebibytes = 1024++mebibyte :: Word64+mebibyte = 1024 * 1024++-- | The DACLs the checks' files are made with.  Each grants SYSTEM and+-- administrators full control, so the administrator's run can remove what+-- the checks leave.  The checks' directory grants the service full+-- control too, passing all three down, and Users read and execute on it+-- alone, so the slots reach their directories and the tools but not what+-- the checks are given; the tools grant the service full control and+-- Users read and execute, passing both down; and a slot's build directory+-- grants the service and that slot's account full control, passing both+-- down.+rootSddl, toolsSddl :: Sid -> Text+rootSddl service = "D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;" <> sidText service <> ")(A;;0x1200a9;;;BU)"+toolsSddl service = "D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;" <> sidText service <> ")(A;OICI;0x1200a9;;;BU)"++slotSddl :: Sid -> Sid -> Text+slotSddl service sid = "D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;" <> sidText service <> ")(A;OICI;FA;;;" <> sidText sid <> ")"++-- | The DACL of a builder's image that one account alone, beside SYSTEM+-- and administrators, may read and run.+readableBySddl :: Sid -> Text+readableBySddl sid = "D:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;" <> sidText sid <> ")"++accountChecks :: ServiceChecks -> IO [Bool]+accountChecks checks = do+  putStrLn "builder/sandbox-windows-accounts"+  systemRoot <- fromMaybe defaultSystemRoot <$> lookupEnv "SystemRoot"+  self <- getExecutablePath+  service <- ownSid+  runs <- newIORef 0+  let root = scRoot checks+      tools = root </> "tools"+      builder = tools </> takeFileName self+      fixture = Fixture (scHelper checks) builder root service systemRoot runs+  makeDirectory tools (toolsSddl service)+  Dir.copyFile self builder+  builders <- buildersGroupSid+  withSlot fixture (scSlotOne checks) $ \one ->+    withSlot fixture (scSlotTwo checks) $ \two ->+      (<>) <$> accountCheckList fixture checks one two <*> storeAccountChecks fixture builders one two++-- | Windows' directory where the environment does not say.+defaultSystemRoot :: FilePath+defaultSystemRoot = "C:\\Windows"++-- | The SID of the account this process runs as.+ownSid :: IO Sid+ownSid = do+  text <- wideResult c_token_user+  maybe (ioError (userError ("not a SID: " <> T.unpack text))) pure (sidFromText text)++-- | Make a directory with the DACL the SDDL describes.+makeDirectory :: FilePath -> Text -> IO ()+makeDirectory path sddl =+  withCWString path $ \wide -> withCWString (T.unpack sddl) (succeeded ("making " <> path) <=< c_directory_with_sddl wide)++-- | Give a file the DACL the SDDL describes, protected from its+-- directory's.+setSddl :: FilePath -> Text -> IO ()+setSddl path sddl =+  withCWString path $ \wide -> withCWString (T.unpack sddl) (succeeded ("setting the DACL of " <> path) <=< c_set_sddl wide)++-- | Run an action with a slot logged on, with a build directory of its+-- own; its token is closed after it.+withSlot :: Fixture -> SlotAccount -> (Slot -> IO a) -> IO a+withSlot fixture account use =+  withLogon account $ \(sid, token) -> do+    let buildDir = fxRoot fixture </> T.unpack (saName account)+    makeDirectory buildDir (slotSddl (fxService fixture) sid)+    use (Slot account sid token buildDir)++-- | Run an action with a slot's account logged on as the service logs it+-- on for a build, given its SID and its token, which is closed after it.+withLogon :: SlotAccount -> ((Sid, Ptr ()) -> IO a) -> IO a+withLogon account = bracket (logOn account) (void . c_close_handle . snd)++logOn :: SlotAccount -> IO (Sid, Ptr ())+logOn account =+  withCWString (T.unpack (saName account)) $ \wideName -> withCWString (T.unpack (saPassword account)) $ \widePassword ->+    alloca $ \sidOut -> alloca $ \tokenOut -> do+      succeeded ("logging " <> T.unpack (saName account) <> " on") =<< c_account_logon wideName widePassword sidOut tokenOut+      sidString <- takeWide =<< peek sidOut+      token <- peek tokenOut+      case sidFromText sidString of+        Just sid -> pure (sid, token)+        Nothing -> c_close_handle token *> ioError (userError ("not a SID: " <> T.unpack sidString))++-- | What a run of the helper came to: how it exited, what it wrote on its+-- status channel, and the build log.+data Run = Run+  { runExit :: !ExitCode,+    runStatus :: !BS.ByteString,+    runLog :: !BS.ByteString+  }++-- | A run's number, which names the files some runs hold.+nextRun :: Fixture -> IO Int+nextRun fixture = atomicModifyIORef' (fxRuns fixture) (\count -> (count + 1, count + 1))++-- | The plan of a run in a slot: the slot's build directory, token and+-- SID, and the environment a builder here needs, whose @PATH@ is+-- System32.+planFor :: Fixture -> Slot -> Sandbox.WindowsPlan+planFor fixture slot =+  Sandbox.WindowsPlan+    { Sandbox.windowsPlanBuildDir = pathBytes (slotBuildDir slot),+      Sandbox.windowsPlanToken = tokenValue (slotToken slot),+      Sandbox.windowsPlanSlot = slotSid slot,+      Sandbox.windowsPlanMemoryCap = ordinaryMemoryCap,+      Sandbox.windowsPlanEnvironment = environmentWith fixture slot [system32 fixture]+    }++-- | A token's handle as a plan names it.+tokenValue :: Ptr () -> Word32+tokenValue = fromIntegral . ptrToWordPtr++-- | A builder's environment: Windows' directory, a @PATH@ of the+-- directories given, and the slot's build directory as its temporary+-- directory.+environmentWith :: Fixture -> Slot -> [FilePath] -> [BS.ByteString]+environmentWith fixture slot path =+  map+    pathBytes+    [ "SystemRoot=" <> fxSystemRoot fixture,+      "PATH=" <> intercalate ";" path,+      "TEMP=" <> slotBuildDir slot,+      "TMP=" <> slotBuildDir slot+    ]++system32 :: Fixture -> FilePath+system32 fixture = fxSystemRoot fixture </> "System32"++-- | Windows PowerShell, which a builder starts a process through WMI+-- with.+powerShell :: FilePath -> FilePath+powerShell systemRoot = systemRoot </> "System32" </> "WindowsPowerShell" </> "v1.0" </> "powershell.exe"++-- | A path's or an entry's bytes, as a Windows plan holds them.+pathBytes :: String -> BS.ByteString+pathBytes = TE.encodeUtf8 . T.pack++-- | Run the helper over a command in a slot, the plan changed as given.+runCommand :: Fixture -> Slot -> (Sandbox.WindowsPlan -> Sandbox.WindowsPlan) -> [String] -> IO Run+runCommand fixture slot change command = do+  let plan = change (planFor fixture slot)+  (run, logBytes) <- capturingBuildLog (\logger -> Spawn.runHelper logger (fxHelper fixture) (Sandbox.renderWindowsPlan plan) (slotBuildDir slot) command)+  pure (Run (Spawn.hrExit run) (Spawn.hrStatus run) logBytes)++-- | Run an action with a logger that keeps each build line it is given,+-- and answer what the action answers with the build log those lines make,+-- each ended by its line feed again.  Messages go to this run's output.+capturingBuildLog :: (Logger -> IO a) -> IO (a, BS.ByteString)+capturingBuildLog action = do+  kept <- newIORef []+  let logger = plainLogger (const TIO.putStrLn) (\line -> atomicModifyIORef' kept (\earlier -> (line : earlier, ())))+  result <- action logger+  delivered <- readIORef kept+  pure (result, BS.concat [line <> "\n" | line <- reverse delivered])++-- | Run the helper over the suite's builder, with an operation and its+-- arguments.+runBuilder :: Fixture -> Slot -> (Sandbox.WindowsPlan -> Sandbox.WindowsPlan) -> [String] -> IO Run+runBuilder fixture slot change operation = runCommand fixture slot change (builderCommand (fxBuilder fixture) operation)++builderCommand :: FilePath -> [String] -> [String]+builderCommand builder operation = builder : windowsSandboxBuilderFlag : operation++-- | The value a line of a run's log gives a name: the line @NAME VALUE@.+logged :: BS.ByteString -> Run -> Maybe BS.ByteString+logged name run = case mapMaybe (BS.stripPrefix (name <> " ")) (BS8.lines (runLog run)) of+  [value] -> Just value+  _ -> Nothing++-- | The result line a builder's attempt to reach something writes.+attempt :: Run -> Maybe CULong+attempt run = logged "result" run >>= readMaybe . BS8.unpack++-- | That a run's builder ran and ended as expected, its status channel+-- empty, with its log shown should it not have.+ranAs :: ExitCode -> Run -> TestResult+ranAs expected run =+  assertEqual ("exit and status, log " <> TE.decodeUtf8Lenient (runLog run)) (expected, "") (runExit run, runStatus run)++-- | A run's record on its status channel, and how it exited.+reported :: Run -> (ExitCode, Either Text (Maybe (Sandbox.StatusRecord Sandbox.WindowsStage)))+reported run = (runExit run, windowsRecord (runStatus run))++-- | That a run's builder ran on the window station of its slot's logon,+-- which the logon's ID names, and its default desktop, as the slot's+-- account and with a console.+ranOnLogonStation :: Slot -> Run -> TestResult+ranOnLogonStation slot run =+  ranAs ExitSuccess run+    `andThen` assertEqual "user" (Just (TE.encodeUtf8 (sidText (slotSid slot)))) (logged "user" run)+    `andThen` assertEqual "the logon's station" (True, logged "logon-station" run) (isJust (logged "station" run), logged "station" run)+    `andThen` assertEqual "desktop" (Just "Default") (logged "desktop" run)+    `andThen` assertEqual "console" (Just "0") (logged "console" run)++accountCheckList :: Fixture -> ServiceChecks -> Slot -> Slot -> IO [Bool]+accountCheckList fixture checks one two =+  sequence+    [ runTestM "the probe finds the privileges that start a build as another account, which the service holds" $ do+        (code, out, err) <- Proc.readCreateProcessWithExitCode ((Proc.proc (fxHelper fixture) ["probe"]) {Proc.env = Just []}) ""+        pure (assertEqual "probe" (ExitSuccess, "", "") (code, out, err)),+      runTestM "a build runs as its slot's account, on the window station of its logon, with a console, and each logon's station is its own" $ do+        first <- runBuilder fixture one id ["identity"]+        other <- runBuilder fixture two id ["identity"]+        again <- withLogon (slotAccount one) $ \(_, token) -> runBuilder fixture one (\plan -> plan {Sandbox.windowsPlanToken = tokenValue token}) ["identity"]+        let stations = traverse (logged "station") [first, other, again]+        pure $+          ranOnLogonStation one first+            `andThen` ranOnLogonStation two other+            `andThen` ranOnLogonStation one again+            `andThen` assertEqual "three logons, three stations" (Just 3) (Set.size . Set.fromList <$> stations),+      runTestM "a running build's window station opens by name for the build, and for no other slot's build" $ do+        number <- nextRun fixture+        let held = slotBuildDir one </> ("station-" <> show number)+            release = held <> ".release"+        withAsync (runBuilder fixture one id ["station-hold", held, release]) $ \build -> do+          started <- waitUntil (Dir.doesFileExist held)+          fields <- readFields held+          let field name = fields >>= lookup name+              dacl = maybe "unread" TE.decodeLatin1 (field "dacl")+          other <- traverse (\name -> runBuilder fixture two id ["open-station", BS8.unpack name]) (field "name")+          BS.writeFile release ""+          finished <- timeout startWaitMicros (wait build)+          pure $ case other of+            Just opened ->+              assertEqual ("opened by its own build, the station's DACL " <> dacl) (Just "0") (field "open")+                `andThen` ranAs ExitSuccess opened+                `andThen` assertEqual ("opened by another slot's build, which answered " <> T.pack (show (attempt opened)) <> ", the station's DACL " <> dacl) True (maybe False (/= 0) (attempt opened))+                `andThen` assertEqual "the build that held it" (Just (ExitSuccess, "")) (fmap (\run -> (runExit run, runStatus run)) finished)+            Nothing -> Fail ("the build wrote no station, started " <> T.pack (show started)),+      runTestM "a build's standard output and error are its log, and the helper exits as its builder does" $ do+        run <- runBuilder fixture one id ["echo", "7"]+        pure (ranAs (ExitFailure 7) run `andThen` assertEqual "log" "out\nerr\n" (runLog run)),+      runTestM "each process of a build may commit memory up to the plan's cap and no more, and the helper says so in the log" $ do+        let capped plan = plan {Sandbox.windowsPlanMemoryCap = cappedMemory}+        under <- runBuilder fixture one capped ["commit", show underCapMebibytes]+        over <- runBuilder fixture one capped ["commit", show overCapMebibytes]+        let limitLine = "reached its memory limit of " <> BS8.pack (show cappedMemory) <> " bytes"+        pure $+          ranAs ExitSuccess under+            `andThen` assertEqual "under the cap" (Just 0) (attempt under)+            `andThen` ranAs ExitSuccess over+            `andThen` assertEqual "past the cap, refused" True (maybe False (/= 0) (attempt over))+            `andThen` assertEqual "the helper's line" True (limitLine `BS.isInfixOf` runLog over),+      runTestM "a process a build starts shares its console, and none breaks away from the build's job" $ do+        shared <- runBuilder fixture one id ["spawn", "0"]+        breaking <- runBuilder fixture one id ["spawn", show breakawayFromJob]+        pure $+          ranAs ExitSuccess shared+            `andThen` assertEqual "sharing the console" (Just "0 0") (logged "spawn" shared)+            `andThen` ranAs ExitSuccess breaking+            `andThen` assertEqual "breaking away" (Just (BS8.pack (show accessDenied))) (BS8.takeWhile (/= ' ') <$> logged "spawn" breaking),+      runTestM "a crash ends its build at once with the crash's code" $ do+        run <- runBuilder fixture one id ["crash"]+        pure $ case runExit run of+          ExitFailure code -> assertEqual "code and status" (crashExceptionCode, "") (fromIntegral code, runStatus run)+          ExitSuccess -> Fail "the build ended with 0",+      runTestM "the helper waits for every process of its build, not its builder alone" $ do+        let release = slotBuildDir one </> "release"+            out = slotBuildDir one </> "lingered"+            pids = slotBuildDir one </> "pids"+        withAsync (runBuilder fixture one id ["leave", release, out, pids]) $ \build -> do+          started <- waitUntil (Dir.doesFileExist pids)+          written <- readPids pids+          case written of+            Just (builderPid, lingering) -> do+              builderGone <- waitUntil ((== 0) <$> c_process_running (fromIntegral builderPid))+              lingeringRuns <- (== 1) <$> c_process_running (fromIntegral lingering)+              stillWaiting <- isNothing <$> poll build+              BS.writeFile release ""+              finished <- timeout startWaitMicros (wait build)+              left <- BS.readFile out+              pure $+                assertEqual "the builder ended, and what it left runs while the helper waits" (True, True, True) (builderGone, lingeringRuns, stillWaiting)+                  `andThen` assertEqual "the helper's run" (Just (ExitSuccess, "")) (fmap (\run -> (runExit run, runStatus run)) finished)+                  `andThen` assertEqual "what the process it left wrote" "lingered\n" left+            Nothing -> pure (Fail ("the builder wrote no process IDs, started " <> T.pack (show started))),+      runTestM "the lifeline's end, or the helper's, ends every process of the build" $ do+        lifeline <- heldBuild fixture one (\planIn _ -> hClose planIn)+        terminated <- heldBuild fixture one (\_ process -> Proc.terminateProcess process)+        pure $+          assertEqual "the lifeline: started, helper ended, processes gone, exit" (True, True, True, Just (ExitFailure endedBuildExitCode)) lifeline+            `andThen` assertEqual "the helper terminated: started, helper ended, processes gone" (True, True, True) (dropExit terminated),+      runTestM "a step that fails is the one record on the status channel" $ do+        missing <- runCommand fixture one id [slotBuildDir one </> "absent.exe"]+        otherToken <- runBuilder fixture one (\plan -> plan {Sandbox.windowsPlanToken = tokenValue (slotToken two)}) ["echo", "0"]+        refused <- runBuilder fixture one (\plan -> plan {Sandbox.windowsPlanMemoryCap = 0}) ["echo", "0"]+        pure $+          assertEqual "a program that does not exist" (ExitFailure 1, Right (Just (Sandbox.StatusRecord Sandbox.WindowsStageExec fileNotFound Nothing))) (reported missing)+            `andThen` assertEqual "another slot's token" (ExitFailure 1, Right (Just (Sandbox.StatusRecord Sandbox.WindowsStageTokenUser 0 Nothing))) (reported otherToken)+            `andThen` assertEqual "a plan the helper refuses" (ExitFailure 1, Right (Just (Sandbox.StatusRecord Sandbox.WindowsStagePlan einval Nothing))) (reported refused),+      runTestM "the builder's image is opened as its slot: one the slot may not read is refused, and one only the slot may read runs" $ do+        let tools = takeDirectory (fxBuilder fixture)+            serviceOnly = tools </> "service-only.exe"+            slotOnly = tools </> "slot-only.exe"+        Dir.copyFile (fxBuilder fixture) serviceOnly+        setSddl serviceOnly (readableBySddl (fxService fixture))+        Dir.copyFile (fxBuilder fixture) slotOnly+        setSddl slotOnly (readableBySddl (slotSid one))+        refused <- runCommand fixture one id (builderCommand serviceOnly ["echo", "0"])+        ran <- runCommand fixture one id (builderCommand slotOnly ["echo", "0"])+        pure $+          assertEqual "an image the service alone may read" (ExitFailure 1, Right (Just (Sandbox.StatusRecord Sandbox.WindowsStageExec (fromIntegral accessDenied) Nothing))) (reported refused)+            `andThen` ranAs ExitSuccess ran+            `andThen` assertEqual "the log of the image the slot alone may read" "out\nerr\n" (runLog ran),+      runTestM "a process a build starts through WMI runs outside its job, the service may end every process of the slot's, and the build ends with them, its log with it" $ do+        number <- nextRun fixture+        let marker = slotBuildDir one </> ("escaped-" <> show number)+            release = marker <> ".release"+            withPowerShell plan = plan {Sandbox.windowsPlanEnvironment = powerShellEnvironment fixture one}+        withAsync (runBuilder fixture one withPowerShell ["escape", marker, release]) $ \build -> do+          appeared <- waitUntilWithin startWaitMicros (Dir.doesFileExist marker)+          reach <- accountProcesses (slotSid one)+          BS.writeFile release ""+          finished <- timeout startWaitMicros (wait build)+          written <- readEscaped marker+          case (finished, written) of+            (Just run, Just (pid, inJob, held)) -> do+              running <- c_process_running (fromIntegral pid)+              pure $+                ranAs ExitSuccess run+                  `andThen` assertEqual "WMI's start" (Just "0") (logged "wmi" run)+                  `andThen` assertEqual "outside the job, holding the build log" (0, 0) (inJob, held)+                  `andThen` assertEqual ("the slot's processes, each its program, ending it, waiting on it: " <> reach) True (all endable (T.splitOn ";" reach))+                  `andThen` assertEqual "running once the build ended" 0 running+            (Nothing, _) -> pure (Fail ("the build, or its log, had not ended within the wait; the slot's processes " <> reach))+            (Just run, Nothing) -> pure (Fail ("the process started through WMI wrote nothing, appeared " <> T.pack (show appeared) <> "; log " <> TE.decodeUtf8Lenient (runLog run))),+      runTestM "a process left running as a slot's account ends when the slot's next build starts" $ do+        pid <- startAs (slotToken two) (unwords (map quoted (builderCommand (fxBuilder fixture) ["wait"])))+        before <- c_process_running pid+        run <- runBuilder fixture two id ["echo", "0"]+        after <- c_process_running pid+        pure (assertEqual "running before the build" 1 before `andThen` ranAs ExitSuccess run `andThen` assertEqual "running after it" 0 after),+      runTestM "a build cannot reach the user's own: its TEMP, profile and APPDATA, a file only it may read, a profile file, its hive or its process" $ do+        let victim = scVictim checks+            attempts =+              [ ("create in TEMP", ["create", victimTemp victim </> buildMade]),+                ("list the profile", ["list", victimProfile victim </> "*"]),+                ("create in the profile", ["create", victimProfile victim </> buildMade]),+                ("create in APPDATA", ["create", victimAppData victim </> buildMade]),+                ("read a file only the user may", ["open", victimOnlyFile victim]),+                ("read a profile file", ["open", victimProfileFile victim]),+                ("delete a profile file", ["delete", victimProfileFile victim]),+                ("read the hive", ["key", T.unpack (victimSid victim) <> "\\Software"]),+                ("open the process", ["process", show (victimPid victim)])+              ]+        outcomes <- traverse (\(label, operation) -> (,) label <$> runBuilder fixture one id operation) attempts+        pure (foldr (andThen . refusedAttempt) Pass outcomes),+      runTestM "a build cannot reach another slot's build directory" $ do+        let made = slotBuildDir one </> "made"+        own <- runBuilder fixture one id ["create", made]+        outcomes <-+          traverse+            (\(label, operation) -> (,) label <$> runBuilder fixture two id operation)+            [ ("read the other slot's file", ["open", made]),+              ("create in the other slot's directory", ["create", slotBuildDir one </> "other"]),+              ("delete the other slot's file", ["delete", made])+            ]+        pure (ranAs ExitSuccess own `andThen` assertEqual "its own" (Just 0) (attempt own) `andThen` foldr (andThen . refusedAttempt) Pass outcomes),+      runTestM "MSYS2's bash runs a command under the pseudoconsole, and starts an MSYS2 program" $ do+        let bash = scBash checks+            withBash plan = plan {Sandbox.windowsPlanEnvironment = environmentWith fixture one [takeDirectory bash, system32 fixture]}+        run <- runCommand fixture one withBash [bash, "-c", "/usr/bin/true && echo ok"]+        pure (assertEqual "exit and status" (ExitSuccess, "") (runExit run, runStatus run) `andThen` assertEqual "ok in the log" True ("ok\n" `BS.isInfixOf` runLog run))+    ]+  where+    dropExit (started, ended, gone, _) = (started, ended, gone)+    -- The name of a file a build tries to make where it may not.+    buildMade = "nova-nix-sandbox-build"++-- | A builder's environment for Windows PowerShell: the ordinary one,+-- PowerShell's directory on its @PATH@ too, and the slot's build+-- directory as its profile and application data.+powerShellEnvironment :: Fixture -> Slot -> [BS.ByteString]+powerShellEnvironment fixture slot =+  environmentWith fixture slot [system32 fixture, takeDirectory (powerShell (fxSystemRoot fixture))]+    <> map+      pathBytes+      [ "USERPROFILE=" <> slotBuildDir slot,+        "APPDATA=" <> slotBuildDir slot,+        "LOCALAPPDATA=" <> slotBuildDir slot+      ]++-- ---------------------------------------------------------------------------+-- The store, as build accounts meet it+-- ---------------------------------------------------------------------------++-- | The store's layout as build accounts meet it, this process being the+-- service: a store directory made where the machine has the build+-- accounts' group, an output a slot makes in it, which this process+-- registers, and what each slot may do to it before and after.  The+-- store is made at the system drive's root, since the store's open+-- checks every directory on the way to it, and the runner's own are not+-- the store's to vouch for.+storeAccountChecks :: Fixture -> Sid -> Slot -> Slot -> IO [Bool]+storeAccountChecks fixture builders one two = do+  putStrLn "store/build-accounts"+  tag <- Proc.getCurrentPid+  let base = takeDrive (fxSystemRoot fixture) </> ("nova-nix-store-accounts-" <> show tag)+      store = base </> "store"+      output = store </> "output"+      file = output </> "file"+      locked = store </> "locked"+      lockedFile = locked </> "file"+      service = sidText (fxService fixture)+      sidOf slot = sidText (slotSid slot)+      -- Each entry of a DACL as DirDacl reads it, the SIDs given as text.+      allowing flags rights sid = DirDacl.DaclEntry 0 flags rights (Just sid)+      itself = 0x0+      -- OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE.+      passedDown = 0x3+      -- INHERITED_ACE.+      inheritedFlag = 0x10+      carries label protected expected path = do+        dacl <- try (DirDacl.directoryDacl path)+        pure $ case dacl of+          Left (failure :: IOException) -> Fail (label <> ": " <> T.pack (show failure))+          Right found -> assertEqual label (Just (DirDacl.Dacl protected (sort expected))) (fmap (\reading -> reading {DirDacl.daclEntries = sort (DirDacl.daclEntries reading)}) found)+      ownerOf path = do+        owner <- try (DirDacl.entryOwner path)+        pure (either (\(failure :: IOException) -> Left (T.pack (show failure))) Right owner)+      -- The rights a build might use to change a node.+      changes =+        [ ("write its data", fileWriteData),+          ("append to it", fileAppendData),+          ("write its attributes", fileWriteAttributes),+          ("delete it", deleteRight),+          ("change its DACL", writeDac),+          ("change its owner", writeOwner)+        ]+      refusedOpens slot path = traverse (\(label, access) -> (,) (label <> " as " <> sidOf slot) <$> runBuilder fixture slot id ["open-for", show access, path])+      refusedChanges slot path = refusedOpens slot path changes+      -- What the group's grant leaves out on the store's directory: the+      -- two rights it holds, FILE_ADD_FILE and FILE_ADD_SUBDIRECTORY, are+      -- the first two the list names on a file.+      storeChanges = drop 2 changes+      allRefused = foldr (andThen . refusedAttempt) Pass+  results <-+    sequence+      [ runTestM "where the machine has the build accounts' group, a store's directory grants its entries to itself alone, and the group the right to create entries alone" $ do+          createStoreDirectory store+          carries+            "the store's DACL"+            True+            [ allowing itself fileAllAccess service,+              allowing itself fileAllAccess localSystemSid,+              allowing itself fileAllAccess administratorsSid,+              allowing itself readAndExecute usersSid,+              allowing itself createOnly (sidText builders)+            ]+            store,+        -- The group's entry is the only one that lets a slot create in the+        -- store's directory, so a slot making its output there is the group+        -- entry standing for the account's.+        runTestM "a build account makes its output in the store's directory through the group's entry, and what it makes takes its token's own DACL" $ do+          made <- runBuilder fixture one id ["mkdir", output]+          filled <- runBuilder fixture one id ["create", file]+          aside <- refusedOpens one store storeChanges+          owner <- ownerOf output+          dacl <- try (DirDacl.directoryDacl output)+          let entries = either (\(_ :: IOException) -> []) (maybe [] DirDacl.daclEntries) dacl+          pure $+            ranAs ExitSuccess made+              `andThen` assertEqual "the output made" (Just 0) (attempt made)+              `andThen` assertEqual "a file made in it" (Just 0) (attempt filled)+              `andThen` assertEqual "its owner" (Right (Just (sidOf one))) owner+              `andThen` assertEqual "an entry it took from the store's directory" [] (filter ((/= 0) . (.&. inheritedFlag) . DirDacl.deFlags) entries)+              `andThen` assertEqual "an entry for the group" [] (filter ((== Just (sidText builders)) . DirDacl.deSid) entries)+              `andThen` allRefused aside,+        runTestM "another build account cannot reach an output while it is built" $ do+          outcomes <-+            traverse+              (\(label, operation) -> (,) label <$> runBuilder fixture two id operation)+              [ ("read the other slot's output", ["open", file]),+                ("create in the other slot's output", ["create", output </> "added"]),+                ("delete the other slot's file", ["delete", file])+              ]+          pure (allRefused outcomes),+        runTestM "registering an output makes each node this process's, as the service's, with a valid path's DACL, and keeps its NAR hash" $ do+          before <- ExecBit.narHashOfPath processCaseHack output+          canonicalizeMetadata output+          after <- ExecBit.narHashOfPath processCaseHack output+          owners <- traverse ownerOf [output, file]+          -- A directory's entries are passed down; a file's carry no+          -- inheritance flags.+          let valid flags =+                [ allowing flags fileAllAccess service,+                  allowing flags fileAllAccess localSystemSid,+                  allowing flags fileAllAccess administratorsSid,+                  allowing flags readAndExecute usersSid,+                  allowing flags readAndExecute (sidText builders),+                  allowing flags readControl ownerRightsSid+                ]+          outputDacl <- carries "the output's DACL" True (valid passedDown) output+          fileDacl <- carries "its file's DACL" True (valid itself) file+          pure $+            assertEqual "the NAR hash" before after+              `andThen` assertEqual "the owners" [Right (Just service), Right (Just service)] owners+              `andThen` outputDacl+              `andThen` fileDacl,+        runTestM "a registered output is kept from every build, the one that made it included, and each may read it" $ do+          changed <- concat <$> traverse (\slot -> (<>) <$> refusedChanges slot file <*> refusedChanges slot output) [one, two]+          others <-+            traverse+              (\(label, slot, operation) -> (,) label <$> runBuilder fixture slot id operation)+              [ ("create in it as the slot that made it", one, ["create", output </> "added"]),+                ("create in it as another slot", two, ["create", output </> "added"]),+                ("delete its file as the slot that made it", one, ["delete", file])+              ]+          readings <- traverse (\slot -> runBuilder fixture slot id ["open", file]) [one, two]+          pure (allRefused (changed <> others) `andThen` assertEqual "reading it" [Just 0, Just 0] (map attempt readings)),+        -- Whether the service can take such an output, holding the+        -- privileges it is given and no others, is what this measures, so+        -- the log says which it did: made the output its own, or failed,+        -- naming the node it could not reach.+        runTestM "registering an output whose DACL a build set to grant it alone makes it this process's, or fails naming a node of it" $ do+          steps <- traverse (runBuilder fixture one id) [["mkdir", locked], ["create", lockedFile], ["lock", lockedFile], ["lock", locked]]+          registered <- try (canonicalizeMetadata locked)+          outcome <- case registered of+            Right () -> do+              putStrLn "  NOTE  registering an output that grants this process nothing made it this process's"+              owner <- ownerOf locked+              pure (assertEqual "its owner" (Right (Just service)) owner)+            Left err -> do+              putStrLn ("  NOTE  registering an output that grants this process nothing failed: " <> show (err :: IOException))+              pure (assertEqual "the failure names a node of the output" True (maybe False (locked `isPrefixOf`) (ioeGetFileName err)))+          pure (assertEqual "the build's steps" (replicate 4 (Just 0)) (map attempt steps) `andThen` outcome)+      ]+  -- What the slot locked is the slot's to remove, where registering it did+  -- not make it this process's.+  _ <- runBuilder fixture one id ["remove-tree", locked]+  removed <- try (Dir.removePathForcibly base)+  either (\err -> putStrLn ("  removing " <> base <> ": " <> show (err :: IOException))) pure removed+  pure results++-- | The rights a node's DACL grants (winnt.h): @FILE_ALL_ACCESS@,+-- @FILE_GENERIC_READ | FILE_GENERIC_EXECUTE@, the build accounts' group's+-- create-only grant on the store's directory, and @READ_CONTROL@.+fileAllAccess, readAndExecute, createOnly, readControl :: Word32+fileAllAccess = 0x1F01FF+readAndExecute = 0x1200A9+createOnly = 0x1000A6+readControl = 0x20000++-- | The rights a build could change a node through (winnt.h):+-- @FILE_WRITE_DATA@, @FILE_APPEND_DATA@, @FILE_WRITE_ATTRIBUTES@,+-- @DELETE@, @WRITE_DAC@ and @WRITE_OWNER@.+fileWriteData, fileAppendData, fileWriteAttributes, deleteRight, writeDac, writeOwner :: CULong+fileWriteData = 0x2+fileAppendData = 0x4+fileWriteAttributes = 0x100+deleteRight = 0x10000+writeDac = 0x40000+writeOwner = 0x80000++-- | The well-known SIDs a store's DACLs name beside SYSTEM's:+-- Administrators, Users and OWNER RIGHTS.+administratorsSid, usersSid, ownerRightsSid :: Text+administratorsSid = "S-1-5-32-544"+usersSid = "S-1-5-32-545"+ownerRightsSid = "S-1-3-4"++-- | That a builder's attempt was refused access, labelled.+refusedAttempt :: (Text, Run) -> TestResult+refusedAttempt (label, run) =+  ranAs ExitSuccess run `andThen` assertEqual label (Just accessDenied) (attempt run)++-- | Start a command line as the account whose token is given, outside+-- any job, as a process a build left running is: its process ID.+startAs :: Ptr () -> String -> IO CULong+startAs token command =+  withCWString command $ \wide -> alloca $ \pidOut -> do+    succeeded "starting a process as a slot's account" =<< c_start_as token wide pidOut+    peek pidOut++-- | The words a file holds, once it appears whole.+readWords :: FilePath -> IO (Maybe [BS.ByteString])+readWords path = do+  contents <- try (BS.readFile path)+  pure $ case contents of+    Left (_ :: IOException) -> Nothing+    Right bytes -> Just (BS8.words bytes)++-- | The process IDs a builder wrote: its own and the one it started.+readPids :: FilePath -> IO (Maybe (Word32, Word32))+readPids path = do+  written <- readWords path+  pure $ case traverse (readMaybe . BS8.unpack) =<< written of+    Just [builderPid, started] -> Just (builderPid, started)+    _ -> Nothing++-- | The lines of a file a builder wrote whole, each a name and a value.+readFields :: FilePath -> IO (Maybe [(BS.ByteString, BS.ByteString)])+readFields path = do+  contents <- try (BS.readFile path)+  pure $ case contents of+    Left (_ :: IOException) -> Nothing+    Right bytes -> traverse field (BS8.lines bytes)+  where+    field text = case BS8.words text of+      [name, value] -> Just (name, value)+      _ -> Nothing++-- | What the test service may do to each process running as an account,+-- as @nova_test_account_processes@ lists it.+accountProcesses :: Sid -> IO Text+accountProcesses sid =+  withCWString (T.unpack (sidText sid)) $ \wide -> allocaArray processListChars $ \text -> alloca $ \countOut -> do+    succeeded "listing an account's processes" =<< c_account_processes wide text (fromIntegral processListChars) countOut+    T.pack <$> peekCWString text++-- | The room a listing of an account's processes is given.+processListChars :: Int+processListChars = 4096++-- | Whether an entry of 'accountProcesses' says the process may be ended;+-- the empty text after the last entry's semicolon is no entry.+endable :: Text -> Bool+endable entry = case T.splitOn ":" entry of+  [_, terminate, _] -> terminate == "0"+  [""] -> True+  _ -> False++-- | What a process a build started through WMI wrote: its ID, whether it+-- is in a job, and what copying the build log answered.+readEscaped :: FilePath -> IO (Maybe (Word32, CInt, CULong))+readEscaped path = do+  written <- readWords path+  pure $ case written of+    Just [pidText, inJobText, heldText] -> (,,) <$> readMaybe (BS8.unpack pidText) <*> readMaybe (BS8.unpack inJobText) <*> readMaybe (BS8.unpack heldText)+    _ -> Nothing++-- | Start the helper over a builder that starts a process and holds the+-- lifeline, end the build as told once both run, and answer whether they+-- started, the helper ended within the wait, both processes are gone,+-- and how the helper exited.+heldBuild :: Fixture -> Slot -> (Handle -> Proc.ProcessHandle -> IO ()) -> IO (Bool, Bool, Bool, Maybe ExitCode)+heldBuild fixture slot stop = do+  number <- nextRun fixture+  let pids = slotBuildDir slot </> ("held-" <> show number)+      logPath = fxRoot fixture </> ("run-" <> show number <> ".log")+      plan = planFor fixture slot+      spec =+        (Proc.proc (fxHelper fixture) ("run" : builderCommand (fxBuilder fixture) ["hold", pids]))+          { Proc.cwd = Just (slotBuildDir slot),+            Proc.env = Just [],+            Proc.std_in = Proc.CreatePipe,+            Proc.std_out = Proc.CreatePipe+          }+  withBinaryFile logPath WriteMode $ \logHandle -> do+    spawned <- Proc.createProcess spec {Proc.std_err = Proc.UseHandle logHandle}+    case spawned of+      (Just planIn, Just statusOut, _, process) -> do+        BS.hPut planIn (Sandbox.renderWindowsPlan plan) *> hFlush planIn+        started <- waitUntil (Dir.doesFileExist pids)+        written <- readPids pids+        let running = maybe [] (\(builderPid, held) -> [builderPid, held]) written+        stop planIn process+        ended <- timeout processWaitMicros (Proc.waitForProcess process)+        when (isNothing ended) (Proc.terminateProcess process *> void (Proc.waitForProcess process))+        gone <- waitUntil (all (== 0) <$> traverse (c_process_running . fromIntegral) running)+        -- A pipe whose reader or writer is gone can fail its close.+        traverse_ (\handle -> void (try (hClose handle) :: IO (Either IOException ()))) [planIn, statusOut]+        pure (started && isJust written, isJust ended, gone && not (null running), ended)+      _ -> pure (False, False, False, Nothing)++-- ---------------------------------------------------------------------------+-- The builder+-- ---------------------------------------------------------------------------++-- | The flag that makes the suite a builder the helper runs as a slot's+-- account, given an operation and its arguments.+windowsSandboxBuilderFlag :: String+windowsSandboxBuilderFlag = "--windows-sandbox-builder"++-- | How long a process a build starts through WMI holds what it copied+-- from the build: past the check's wait for the build to end, so that the+-- build ends within it only when the process is ended.+escapedHoldMicros :: Int+escapedHoldMicros = 2 * startWaitMicros++-- | Carry out one operation as a builder, writing what it finds to+-- standard output, the build log, as lines of a name and a value.+-- Output is written as bytes, which no newline translation touches.+windowsSandboxBuilder :: [String] -> IO ()+windowsSandboxBuilder operation = case operation of+  ["echo", codeText] | Just code <- readMaybe codeText -> do+    BS8.hPutStr stdout "out\n" *> hFlush stdout+    BS8.hPutStr stderr "err\n"+    exitWith (if code == 0 then ExitSuccess else ExitFailure code)+  ["identity"] -> do+    user <- wideResult c_token_user+    station <- userObjectName 0+    desktop <- userObjectName 1+    console <- c_console+    logonStation <- logonStationName+    traverse_ logLine [("user", user), ("station", station), ("desktop", desktop), ("console", T.pack (show console)), ("logon-station", logonStation)]+  ["station-hold", held, release] -> do+    station <- userObjectName 0+    own <- withCWString (T.unpack station) c_open_station+    dacl <- withCWString (T.unpack station) (wideResult . c_station_dacl)+    writeWhole held (BS8.unlines [field "name" station, field "open" (T.pack (show own)), field "dacl" dacl])+    released <- waitUntilWithin startWaitMicros (Dir.doesFileExist release)+    unless released exitFailure+  ["open-station", name] -> attemptOn name c_open_station+  ["commit", mebibytesText] | Just mebibytes <- readMaybe mebibytesText -> do+    code <- c_commit (fromIntegral (mebibytes * mebibyte))+    logLine ("result", T.pack (show code))+  ["spawn", flagsText] | Just flags <- readMaybe flagsText -> do+    self <- getExecutablePath+    (code, process) <- start (quoted self <> " " <> windowsSandboxBuilderFlag <> " console") flags+    exitCode <- if code == 0 then waitFor process else pure 0+    logLine ("spawn", T.pack (show code <> " " <> show exitCode))+  ["console"] -> do+    code <- c_console+    exitWith (if code == 0 then ExitSuccess else ExitFailure (fromIntegral code))+  ["crash"] -> c_crash+  ["open", path] -> attemptOn path (`c_open` genericRead)+  ["open-for", accessText, path] | Just access <- readMaybe accessText -> attemptOn path (`c_open` access)+  ["create", path] -> attemptOn path c_create+  ["mkdir", path] -> attemptOn path c_mkdir+  ["lock", path] -> attemptOn path c_lock+  ["remove-tree", path] -> do+    removed <- try (Dir.removePathForcibly path)+    logLine ("result", either (\(failure :: IOException) -> T.pack (show failure)) (const "0") removed)+  ["delete", path] -> attemptOn path c_delete+  ["list", wildcard] -> attemptOn wildcard c_list+  ["key", path] -> attemptOn path c_open_key+  ["process", pidText] | Just pid <- readMaybe pidText -> c_open_process pid >>= \code -> logLine ("result", T.pack (show code))+  ["escape", marker, release] -> escapeThroughWmi marker release+  ["escaped", marker, builderText, valueText]+    | Just builderPid <- readMaybe builderText,+      Just value <- readMaybe valueText -> do+        held <- c_hold_handle builderPid value+        inJob <- c_in_job+        own <- Proc.getCurrentPid+        writeWhole marker (BS8.pack (unwords [show own, show inJob, show held]))+        threadDelay escapedHoldMicros+  ["hold", pids] -> do+    held <- startSelf ["wait"]+    writePids pids held+    threadDelay startWaitMicros+  ["leave", release, out, pids] -> do+    held <- startSelf ["linger", release, out]+    writePids pids held+  ["linger", release, out] -> do+    released <- waitUntilWithin startWaitMicros (Dir.doesFileExist release)+    when released (BS.writeFile out "lingered\n")+  ["wait"] -> threadDelay startWaitMicros+  _ -> do+    BS8.hPutStr stderr ("unknown builder operation: " <> BS8.pack (show operation) <> "\n")+    exitFailure+  where+    attemptOn path call = withCWString path call >>= \code -> logLine ("result", T.pack (show code))+    -- A line of a name and a value, the value's spaces made dashes so+    -- that it stays one word.+    field name value = name <> " " <> TE.encodeUtf8 (T.replace " " "-" value)++-- | Write a line of a name and a value to the build log.+logLine :: (BS.ByteString, Text) -> IO ()+logLine (name, value) = BS8.hPutStr stdout (name <> " " <> TE.encodeUtf8 value <> "\n")++-- | The name of this process's window station, for 0, or of its thread's+-- desktop, or the error that kept it from being read.+userObjectName :: CInt -> IO Text+userObjectName which =+  allocaArray objectNameChars $ \name -> do+    code <- c_user_object_name which name (fromIntegral objectNameChars)+    if code == 0 then T.pack <$> peekCWString name else pure ("error " <> T.pack (show code))++-- | The name of the window station Windows makes for this process's+-- logon: @Service-0x@, the logon's ID's high and low parts in hex, and a+-- dollar sign.+logonStationName :: IO Text+logonStationName =+  alloca $ \highOut -> alloca $ \lowOut -> do+    code <- c_logon_id highOut lowOut+    high <- peek highOut+    low <- peek lowOut+    pure $+      if code == 0+        then T.pack ("Service-0x" <> showHex high "" <> "-" <> showHex low "" <> "$")+        else "error " <> T.pack (show code)++-- | Have WMI start this program for the build, as a process that copies+-- the build log from this one and says in MARKER whether it is in a job,+-- then wait for that, write what WMI's start answered, and wait for+-- RELEASE before ending.+escapeThroughWmi :: FilePath -> FilePath -> IO ()+escapeThroughWmi marker release = do+  self <- getExecutablePath+  builderPid <- Proc.getCurrentPid+  value <- c_stdout_value+  systemRoot <- fromMaybe defaultSystemRoot <$> lookupEnv "SystemRoot"+  let escaped = unwords [quoted self, windowsSandboxBuilderFlag, "escaped", quoted marker, show builderPid, show value]+      script = "$r = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine='" <> T.pack escaped <> "'}; exit [int]$r.ReturnValue"+      encoded = T.unpack (B64.encode (TE.encodeUtf16LE script))+  (code, _, err) <- Proc.readCreateProcessWithExitCode (Proc.proc (powerShell systemRoot) ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded]) ""+  logLine ("wmi", T.pack (exitNumber code))+  unless (code == ExitSuccess) (putStr err)+  written <- waitUntilWithin startWaitMicros (Dir.doesFileExist marker)+  released <- waitUntilWithin startWaitMicros (Dir.doesFileExist release)+  unless (written && released) exitFailure+  where+    exitNumber code = case code of+      ExitSuccess -> "0"+      ExitFailure number -> show number++-- | A word of a command line, quoted whole.+quoted :: String -> String+quoted word = "\"" <> word <> "\""++-- | The room a window station's or desktop's name is given.+objectNameChars :: Int+objectNameChars = 256++-- | A wide string a call writes for LocalFree, or the call's error.+wideResult :: (Ptr CWString -> IO CULong) -> IO Text+wideResult call =+  alloca $ \out -> do+    code <- call out+    if code == 0 then takeWide =<< peek out else pure ("error " <> T.pack (show code))++-- | Start a command line with CreateProcessW's flags, inheriting no+-- handle: the call's error, and the process, for 'waitFor'.+start :: String -> CULong -> IO (CULong, (CULong, Ptr ()))+start command flags =+  withCWString command $ \wide -> alloca $ \pidOut -> alloca $ \processOut -> do+    code <- c_start wide flags pidOut processOut+    pid <- peek pidOut+    process <- peek processOut+    pure (code, (pid, process))++-- | Wait for a process 'start' started, answering its exit code.+waitFor :: (CULong, Ptr ()) -> IO CULong+waitFor (_, process) =+  alloca $ \codeOut -> do+    succeeded "waiting for a process" =<< c_wait process codeOut+    peek codeOut++-- | Start this program as a builder with an operation, not waiting for it,+-- answering its process ID.  Each word is quoted whole, which holds for+-- the program's path, the flag and the paths an operation takes, none+-- holding a quote or ending in a backslash.+startSelf :: [String] -> IO CULong+startSelf operation = do+  self <- getExecutablePath+  (code, (pid, process)) <- start (unwords (map quoted (builderCommand self operation))) 0+  succeeded "starting a process" code+  succeeded "closing a process's handle" =<< c_close_handle process+  pure pid++-- | Write this process's ID and another's to a file, whole.+writePids :: FilePath -> CULong -> IO ()+writePids path other = do+  own <- Proc.getCurrentPid+  writeWhole path (BS8.pack (show own <> " " <> show other))++-- | Write a file whole: it appears by a rename once it holds every byte.+writeWhole :: FilePath -> BS.ByteString -> IO ()+writeWhole path bytes = do+  let partial = path <> ".partial"+  BS.writeFile partial bytes+  Dir.renameFile partial path
+ test/UserResources.hs view
@@ -0,0 +1,124 @@+{-# LANGUAGE CPP #-}++-- | Resources of the invoking user's that the macOS sandbox tests reach+-- for from a build: a session of its own, which takes a process out of+-- the builder's group; a pseudo-terminal, as a terminal the user types+-- in; a Unix socket listening where the user's live ones are;+-- @SIGHUP@ ignored, as a program started under @nohup@ has it; and+-- @SIGCONT@, which continues a stopped process.  And what the tests of a+-- builder's start read: a process's session, and a soft limit on core+-- dumps a builder would inherit.  Windows has no sessions,+-- pseudo-terminals, signals or such limits, so those answer that there is+-- none there, or run the action as it is.+module UserResources+  ( newSession,+    processSession,+    withCoreDumpsAllowed,+    withPseudoTerminal,+    withUnixListener,+    withHangupIgnored,+    continueProcess,+  )+where++import Control.Concurrent.Async (withAsync)+import Control.Exception (bracket, bracketOnError)+import Control.Monad (forever)+import Data.IORef (atomicModifyIORef', newIORef, readIORef)+import qualified Network.Socket as Socket+import qualified System.Process as Proc++#if !defined(mingw32_HOST_OS)+import qualified Control.Exception as Exception+import Data.Foldable (traverse_)+import System.Posix.IO (closeFd)+import System.Posix.Process (createSession, getProcessID)+import System.Posix.Resource (Resource (ResourceCoreFileSize), ResourceLimit (..), ResourceLimits (..), getResourceLimit, setResourceLimit)+import System.Posix.Signals (Handler (Ignore), installHandler, sigCONT, sigHUP, signalProcess)+import System.Posix.Terminal (getSlaveTerminalName, openPseudoTerminal)+import System.Posix.Types (CPid (..))+#endif++-- | Start a session of the calling process's own, which takes it out of+-- its process group, answering whether it did.+newSession :: IO Bool+#if defined(mingw32_HOST_OS)+newSession = pure False+#else+newSession = True <$ createSession+#endif++-- | This process's id and its session's, where there are sessions.+processSession :: IO (Maybe (Integer, Integer))+#if defined(mingw32_HOST_OS)+processSession = pure Nothing+#else+processSession = do+  pid <- getProcessID+  session <- c_getsid 0+  pure (Just (fromIntegral pid, fromIntegral session))++foreign import ccall unsafe "unistd.h getsid"+  c_getsid :: CPid -> IO CPid+#endif++-- | Run an action with this process's soft limit on core dumps raised to+-- its hard limit, which a process it starts would inherit, and put the+-- limit back afterwards, answering what the action did; or run nothing+-- and answer 'Nothing' where the hard limit is not unlimited.+withCoreDumpsAllowed :: IO a -> IO (Maybe a)+#if defined(mingw32_HOST_OS)+withCoreDumpsAllowed _ = pure Nothing+#else+withCoreDumpsAllowed action = do+  limits <- getResourceLimit ResourceCoreFileSize+  case hardLimit limits of+    ResourceLimitInfinity -> Just <$> Exception.bracket_ (setResourceLimit ResourceCoreFileSize limits {softLimit = ResourceLimitInfinity}) (setResourceLimit ResourceCoreFileSize limits) action+    _ -> pure Nothing+#endif++-- | Run an action given the name of a pseudo-terminal's device, which is+-- open while it runs, or answer 'Nothing' where there is none.+withPseudoTerminal :: (FilePath -> IO a) -> IO (Maybe a)+#if defined(mingw32_HOST_OS)+withPseudoTerminal _ = pure Nothing+#else+withPseudoTerminal action =+  bracket openPseudoTerminal (\(controller, terminal) -> closeFd controller *> closeFd terminal) $ \(controller, _) ->+    getSlaveTerminalName controller >>= fmap Just . action+#endif++-- | Run an action while a Unix socket listens at the given path, given how+-- many connections it has accepted so far; each is closed once accepted.+withUnixListener :: FilePath -> (IO Int -> IO a) -> IO a+withUnixListener path action =+  bracket open Socket.close $ \listener -> do+    accepted <- newIORef (0 :: Int)+    let serve = forever $ do+          (connection, _) <- Socket.accept listener+          Socket.close connection+          atomicModifyIORef' accepted (\count -> (count + 1, ()))+    withAsync serve $ \_ -> action (readIORef accepted)+  where+    open =+      bracketOnError (Socket.socket Socket.AF_UNIX Socket.Stream Socket.defaultProtocol) Socket.close $ \listener ->+        listener <$ (Socket.bind listener (Socket.SockAddrUnix path) *> Socket.listen listener Socket.maxListenQueue)++-- | Run an action with this process ignoring @SIGHUP@, which a process it+-- starts then inherits, and restore what it did before afterwards.+withHangupIgnored :: IO a -> IO a+#if defined(mingw32_HOST_OS)+withHangupIgnored = id+#else+withHangupIgnored action =+  bracket (installHandler sigHUP Ignore Nothing) (\previous -> installHandler sigHUP previous Nothing) (const action)+#endif++-- | Send @SIGCONT@ to a process this one started, which continues it if it+-- is stopped.+continueProcess :: Proc.ProcessHandle -> IO ()+#if defined(mingw32_HOST_OS)+continueProcess _ = pure ()+#else+continueProcess handle = Proc.getPid handle >>= traverse_ (signalProcess sigCONT)+#endif
+ test/cbits/keyring.c view
@@ -0,0 +1,47 @@+/*+ * A key for the Linux sandbox tests to look for: planted in a session+ * keyring of the calling thread's own, which a process it then starts+ * inherits, and viewable only by a process that possesses it, so a+ * builder sees it in /proc/keys exactly when it still possesses that+ * keyring.+ */++#define _GNU_SOURCE++#include <errno.h>++#if defined(__linux__)+#include <linux/keyctl.h>+#include <sys/syscall.h>+#include <unistd.h>++/* Every permission for the key's possessor, and none for anyone else+ * (KEY_POS_ALL in the kernel's include/linux/key.h). */+#define POSSESSOR_ALL 0x3f000000UL++/* The payload the key holds, which no test reads. */+static const char payload[] = "nova-nix test";+#endif++/* Join a fresh session keyring and add a user key named DESCRIPTION to it.+ * Answers the key's serial, or -1 with errno set, ENOSYS off Linux.  Only+ * the calling OS thread joins: a keyring is part of a thread's+ * credentials. */+long nova_test_plant_possessed_key(const char *description)+{+#if defined(__linux__)+    long serial;+    if (syscall(SYS_keyctl, KEYCTL_JOIN_SESSION_KEYRING, (char *)NULL) < 0)+        return -1;+    serial = syscall(SYS_add_key, "user", description, payload, sizeof payload - 1, KEY_SPEC_SESSION_KEYRING);+    if (serial < 0)+        return -1;+    if (syscall(SYS_keyctl, KEYCTL_SETPERM, serial, POSSESSOR_ALL) < 0)+        return -1;+    return serial;+#else+    (void)description;+    errno = ENOSYS;+    return -1;+#endif+}
+ test/cbits/nn_test_dacl.c view
@@ -0,0 +1,114 @@+/* A directory's DACL read back through the Win32 API, for the store+ * access tests (test/DirDacl.hs): whether it is protected and each of its+ * entries.  The test suite builds it on Windows alone, the one platform+ * whose directories carry a DACL. */++#include <windows.h>+#include <aclapi.h>+#include <sddl.h>++/* The security descriptor of the entry at path, holding its DACL, written+ * to *descriptor for the caller to release with LocalFree.  Returns 0 or+ * the Win32 error code. */+unsigned long nn_test_dacl_read(const wchar_t *path, void **descriptor) {+  PACL dacl = NULL;+  PSECURITY_DESCRIPTOR read = NULL;+  DWORD error;++  error = GetNamedSecurityInfoW(path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,+                                NULL, NULL, &dacl, NULL, &read);+  *descriptor = read;+  return error;+}++/* 1 when the descriptor's DACL is protected, taking no entry from the+ * parent, 0 when it is not, and -1 when its control bits cannot be+ * read. */+int nn_test_dacl_protected(void *descriptor) {+  SECURITY_DESCRIPTOR_CONTROL control;+  DWORD revision;++  if (!GetSecurityDescriptorControl(descriptor, &control, &revision)) {+    return -1;+  }+  return (control & SE_DACL_PROTECTED) != 0 ? 1 : 0;+}++/* How many entries the descriptor's DACL holds, or -1 when it has none+ * to count: no DACL, or a NULL one, which grants every account every+ * right. */+long nn_test_dacl_count(void *descriptor) {+  BOOL present;+  BOOL defaulted;+  PACL dacl = NULL;+  ACL_SIZE_INFORMATION size;++  if (!GetSecurityDescriptorDacl(descriptor, &present, &dacl, &defaulted) ||+      !present || dacl == NULL) {+    return -1;+  }+  if (!GetAclInformation(dacl, &size, sizeof size, AclSizeInformation)) {+    return -1;+  }+  return (long)size.AceCount;+}++/* The entry at index of the descriptor's DACL: fields gets its type, its+ * flags and its access mask, and *sid its SID's string form, which the+ * caller releases with LocalFree.  An allow and a deny entry share one+ * layout; an entry of any other type gets a mask of 0 and no SID (NULL).+ * Returns 0 or the Win32 error code. */+unsigned long nn_test_dacl_entry(void *descriptor, unsigned long index,+                                 unsigned long fields[3], wchar_t **sid) {+  BOOL present;+  BOOL defaulted;+  PACL dacl = NULL;+  LPVOID entry;+  ACE_HEADER *header;+  ACCESS_ALLOWED_ACE *allowed;++  *sid = NULL;+  if (!GetSecurityDescriptorDacl(descriptor, &present, &dacl, &defaulted) ||+      !GetAce(dacl, index, &entry)) {+    return GetLastError();+  }+  header = (ACE_HEADER *)entry;+  fields[0] = header->AceType;+  fields[1] = header->AceFlags;+  fields[2] = 0;+  if (header->AceType != ACCESS_ALLOWED_ACE_TYPE &&+      header->AceType != ACCESS_DENIED_ACE_TYPE) {+    return ERROR_SUCCESS;+  }+  allowed = (ACCESS_ALLOWED_ACE *)header;+  fields[2] = allowed->Mask;+  if (!ConvertSidToStringSidW((PSID)&allowed->SidStart, sid)) {+    *sid = NULL;+    return GetLastError();+  }+  return ERROR_SUCCESS;+}++/* The owner of the entry at path, in the string form+ * ConvertSidToStringSidW writes, to *sid for the caller to release with+ * LocalFree.  Returns 0 or the Win32 error code. */+unsigned long nn_test_owner_read(const wchar_t *path, wchar_t **sid) {+  PSID owner = NULL;+  PSECURITY_DESCRIPTOR read = NULL;+  DWORD error;++  *sid = NULL;+  error = GetNamedSecurityInfoW(path, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION,+                                &owner, NULL, NULL, NULL, &read);+  if (error != ERROR_SUCCESS) {+    return error;+  }+  if (owner == NULL) {+    error = ERROR_INVALID_SECURITY_DESCR;+  } else if (!ConvertSidToStringSidW(owner, sid)) {+    error = GetLastError();+    *sid = NULL;+  }+  LocalFree(read);+  return error;+}
+ test/cbits/nn_test_pipe_owner.c view
@@ -0,0 +1,342 @@+/* The tokens and pipes the tests of the daemon's pipe make+ * (test/Test/DaemonPipe.hs): whether this process's token holds+ * Administrators enabled, a copy of it that holds the group for deny only+ * as a filtered administrator's token does, a copy of a token at an+ * integrity level, a pipe made as a token with the owner its descriptor+ * names, a pipe opened as a token, and whether a connection ends.  The+ * test suite builds it on Windows alone, the one platform with these+ * tokens and pipes.  Each call returns 0 or the Win32 error code of the+ * call that failed. */++#include <stdlib.h>+#include <windows.h>+#include <sddl.h>++/* What each direction of the pipes the tests make holds. */+enum { NN_TEST_PIPE_BUFFER_BYTES = 4096 };++/* Whether this process's token holds Administrators enabled, as+ * CheckTokenMembership reads a token, which a group held for deny only is+ * not: *held gets 1 or 0. */+unsigned long nn_test_administrators_enabled(int *held) {+  BYTE administrators[SECURITY_MAX_SID_SIZE];+  DWORD size = sizeof administrators;+  BOOL member = FALSE;++  *held = 0;+  if (!CreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, administrators,+                          &size)) {+    return GetLastError();+  }+  if (!CheckTokenMembership(NULL, administrators, &member)) {+    return GetLastError();+  }+  *held = member ? 1 : 0;+  return ERROR_SUCCESS;+}++/* A copy of this process's token, as a primary token for the caller to+ * release with CloseHandle, that holds Administrators for deny only and no+ * privilege, as a filtered administrator's token does. */+unsigned long nn_test_filtered_token(void **token) {+  BYTE administrators[SECURITY_MAX_SID_SIZE];+  DWORD size = sizeof administrators;+  SID_AND_ATTRIBUTES deny;+  HANDLE own = NULL;+  HANDLE filtered = NULL;+  DWORD error = ERROR_SUCCESS;++  *token = NULL;+  if (!CreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, administrators,+                          &size)) {+    return GetLastError();+  }+  deny.Sid = administrators;+  deny.Attributes = 0;+  if (!OpenProcessToken(GetCurrentProcess(),+                        TOKEN_DUPLICATE | TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY,+                        &own)) {+    return GetLastError();+  }+  if (!CreateRestrictedToken(own, DISABLE_MAX_PRIVILEGE, 1, &deny, 0, NULL, 0,+                             NULL, &filtered)) {+    error = GetLastError();+  } else {+    *token = filtered;+  }+  CloseHandle(own);+  return error;+}++/* A copy of a token, a primary one for the caller to release with+ * CloseHandle, at the integrity level the RID names (SECURITY_MANDATORY_*_RID).+ * The base token is a primary token such as nn_test_filtered_token gives, or+ * NULL for this process's. */+unsigned long nn_test_integrity_token(void *base, unsigned long rid,+                                      void **token) {+  SID_IDENTIFIER_AUTHORITY authority = SECURITY_MANDATORY_LABEL_AUTHORITY;+  TOKEN_MANDATORY_LABEL label;+  PSID level = NULL;+  HANDLE own = NULL;+  HANDLE copy = NULL;+  DWORD error = ERROR_SUCCESS;++  *token = NULL;+  if (base == NULL) {+    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE | TOKEN_QUERY,+                          &own)) {+      return GetLastError();+    }+    base = own;+  }+  if (!DuplicateTokenEx(base, TOKEN_ALL_ACCESS, NULL, SecurityImpersonation,+                        TokenPrimary, &copy)) {+    error = GetLastError();+  } else if (!AllocateAndInitializeSid(&authority, 1, rid, 0, 0, 0, 0, 0, 0, 0,+                                       &level)) {+    error = GetLastError();+  } else {+    label.Label.Sid = level;+    label.Label.Attributes = SE_GROUP_INTEGRITY;+    if (!SetTokenInformation(copy, TokenIntegrityLevel, &label,+                             sizeof label + GetLengthSid(level))) {+      error = GetLastError();+    }+  }+  if (error == ERROR_SUCCESS) {+    *token = copy;+  } else if (copy != NULL) {+    CloseHandle(copy);+  }+  if (level != NULL) {+    FreeSid(level);+  }+  if (own != NULL) {+    CloseHandle(own);+  }+  return error;+}++/* A copy of this process's token, a primary one for the caller to release+ * with CloseHandle, that holds the group the SID text names for deny only,+ * as a token shaped to hide a group holds it. */+unsigned long nn_test_deny_group_token(const wchar_t *group, void **token) {+  SID_AND_ATTRIBUTES deny;+  PSID sid = NULL;+  HANDLE own = NULL;+  HANDLE shaped = NULL;+  DWORD error = ERROR_SUCCESS;++  *token = NULL;+  if (!ConvertStringSidToSidW(group, &sid)) {+    return GetLastError();+  }+  deny.Sid = sid;+  deny.Attributes = 0;+  if (!OpenProcessToken(GetCurrentProcess(),+                        TOKEN_DUPLICATE | TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY,+                        &own)) {+    error = GetLastError();+  } else if (!CreateRestrictedToken(own, 0, 1, &deny, 0, NULL, 0, NULL,+                                    &shaped)) {+    error = GetLastError();+  } else {+    *token = shaped;+  }+  if (own != NULL) {+    CloseHandle(own);+  }+  LocalFree(sid);+  return error;+}++/* Enable the restore privilege on the token, which lets its holder give+ * what it makes any owner.  ERROR_NOT_ALL_ASSIGNED where the token does+ * not hold it. */+static DWORD enable_restore(HANDLE token) {+  TOKEN_PRIVILEGES privileges;++  privileges.PrivilegeCount = 1;+  privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;+  if (!LookupPrivilegeValueW(NULL, L"SeRestorePrivilege",+                             &privileges.Privileges[0].Luid)) {+    return GetLastError();+  }+  if (!AdjustTokenPrivileges(token, FALSE, &privileges, 0, NULL, NULL)) {+    return GetLastError();+  }+  return GetLastError();+}++/* A copy of the token as an impersonation token, which becomes this+ * thread's until restore_self.  Windows' guidance for a thread that cannot+ * stop impersonating is to end the process. */+static DWORD impersonate(HANDLE token, HANDLE *copy) {+  if (!DuplicateTokenEx(token, TOKEN_ALL_ACCESS, NULL, SecurityImpersonation,+                        TokenImpersonation, copy)) {+    return GetLastError();+  }+  if (!SetThreadToken(NULL, *copy)) {+    DWORD error = GetLastError();+    CloseHandle(*copy);+    *copy = NULL;+    return error;+  }+  return ERROR_SUCCESS;+}++static void restore_self(HANDLE copy) {+  if (!RevertToSelf()) {+    abort();+  }+  CloseHandle(copy);+}++/* Make the pipe at name, with the security descriptor the SDDL string+ * describes, on this thread running as a copy of the token, which is a+ * primary token such as nn_test_filtered_token gives or NULL for this+ * process's; with restore nonzero the copy has the restore privilege+ * enabled.  A NULL SDDL makes the pipe with no descriptor of its own, as+ * a further instance of a pipe is made, which Windows checks against the+ * first instance's descriptor.  *pipe gets the instance for the caller to+ * release with CloseHandle. */+unsigned long nn_test_make_pipe(void *token, int restore, const wchar_t *name,+                                const wchar_t *sddl, void **pipe) {+  HANDLE own = NULL;+  HANDLE copy = NULL;+  PSECURITY_DESCRIPTOR descriptor = NULL;+  SECURITY_ATTRIBUTES attributes;+  HANDLE made;+  DWORD error = ERROR_SUCCESS;++  *pipe = NULL;+  if (token == NULL) {+    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE | TOKEN_QUERY,+                          &own)) {+      return GetLastError();+    }+    token = own;+  }+  if (sddl != NULL &&+      !ConvertStringSecurityDescriptorToSecurityDescriptorW(+          sddl, SDDL_REVISION_1, &descriptor, NULL)) {+    error = GetLastError();+  }+  if (error == ERROR_SUCCESS) {+    error = impersonate(token, &copy);+  }+  if (error == ERROR_SUCCESS && restore) {+    error = enable_restore(copy);+  }+  if (error == ERROR_SUCCESS) {+    attributes.nLength = sizeof attributes;+    attributes.lpSecurityDescriptor = descriptor;+    attributes.bInheritHandle = FALSE;+    made = CreateNamedPipeW(+        name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,+        PIPE_TYPE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,+        PIPE_UNLIMITED_INSTANCES, NN_TEST_PIPE_BUFFER_BYTES,+        NN_TEST_PIPE_BUFFER_BYTES, 0, descriptor == NULL ? NULL : &attributes);+    if (made == INVALID_HANDLE_VALUE) {+      error = GetLastError();+    } else {+      *pipe = made;+    }+  }+  if (copy != NULL) {+    restore_self(copy);+  }+  if (descriptor != NULL) {+    LocalFree(descriptor);+  }+  if (own != NULL) {+    CloseHandle(own);+  }+  return error;+}++/* Open the pipe at name for the access, on this thread running as a copy+ * of the token (a primary token, or NULL for this process's), as the+ * library's client opens it: letting the server identify the caller but+ * not act as it, and with effective_only nonzero seeing only the groups+ * the token has enabled.  *pipe gets the connection for the caller to+ * release with CloseHandle, and is NULL where the open failed. */+unsigned long nn_test_open_as(void *token, const wchar_t *name,+                              unsigned long access, int effective_only,+                              void **pipe) {+  HANDLE own = NULL;+  HANDLE copy = NULL;+  HANDLE opened;+  DWORD flags = SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION;+  DWORD error = ERROR_SUCCESS;++  *pipe = NULL;+  if (effective_only) {+    flags |= SECURITY_EFFECTIVE_ONLY;+  }+  if (token == NULL) {+    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE | TOKEN_QUERY,+                          &own)) {+      return GetLastError();+    }+    token = own;+  }+  error = impersonate(token, &copy);+  if (error == ERROR_SUCCESS) {+    opened = CreateFileW(name, access, 0, NULL, OPEN_EXISTING,+                         FILE_FLAG_OVERLAPPED | flags, NULL);+    if (opened == INVALID_HANDLE_VALUE) {+      error = GetLastError();+    } else {+      *pipe = opened;+    }+    restore_self(copy);+  }+  if (own != NULL) {+    CloseHandle(own);+  }+  return error;+}++/* Whether the server of the connection ends it, which a read of a pipe the+ * server has closed does, within the milliseconds: *closed gets 1 where it+ * does and 0 where the read is still waiting then, or got data.  The pipe+ * is one opened with FILE_FLAG_OVERLAPPED, as nn_test_open_as opens it. */+unsigned long nn_test_wait_closed(void *pipe, unsigned long milliseconds,+                                  int *closed) {+  OVERLAPPED read;+  BYTE byte;+  DWORD transferred = 0;+  DWORD error = ERROR_SUCCESS;++  *closed = 0;+  ZeroMemory(&read, sizeof read);+  read.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);+  if (read.hEvent == NULL) {+    return GetLastError();+  }+  if (ReadFile(pipe, &byte, 1, NULL, &read)) {+    CloseHandle(read.hEvent);+    return ERROR_SUCCESS;+  }+  error = GetLastError();+  if (error == ERROR_IO_PENDING) {+    if (WaitForSingleObject(read.hEvent, milliseconds) == WAIT_TIMEOUT) {+      CancelIoEx(pipe, &read);+    }+    /* The read ends, completed or cancelled, before the OVERLAPPED goes. */+    if (GetOverlappedResult(pipe, &read, &transferred, TRUE)) {+      error = ERROR_SUCCESS;+    } else {+      error = GetLastError();+    }+  }+  if (error == ERROR_BROKEN_PIPE) {+    *closed = 1;+    error = ERROR_SUCCESS;+  } else if (error == ERROR_OPERATION_ABORTED) {+    error = ERROR_SUCCESS;+  }+  CloseHandle(read.hEvent);+  return error;+}
+ test/cbits/nn_test_sandbox_windows.c view
@@ -0,0 +1,1416 @@+/*+ * The Windows calls the sandbox helper's Windows tests make+ * (test/Test/WindowsSandbox.hs).  As an administrator: the build accounts+ * and the test service the tests make and remove.  As the test service,+ * which stands in for the service that logs each build slot on: the+ * service's own dispatch, the slots' logons, the directories and files+ * the tests lay out, and a process started as a slot.  In a builder, run+ * as a slot's account: what the builder is, and what it may reach.  Each+ * answers 0 or the Win32 error code of the call that failed.  An+ * unsandboxed builder's test (test/Test/Builder.hs) reads the limits of+ * the job it runs in here too.  The suite compiles this file on every OS;+ * off Windows each call answers NOT_ON_WINDOWS, and the tests never make+ * one there.+ */++#include <stddef.h>+#include <stdlib.h>+#include <string.h>+#include <wchar.h>++/* The error each call answers off Windows (ERROR_CALL_NOT_IMPLEMENTED's+ * value). */+#define NOT_ON_WINDOWS 120UL++#if defined(_WIN32)++#include <windows.h>+#include <aclapi.h>+#include <bcrypt.h>+#include <tlhelp32.h>+#include <lmaccess.h>+#include <lmerr.h>+#include <ntsecapi.h>+#include <sddl.h>++/* The right a build account's batch logon needs, and the privileges the+ * service that starts builds as another account needs, which ntsecapi.h+ * and winnt.h spell narrow without UNICODE. */+#define BATCH_LOGON_RIGHT L"SeBatchLogonRight"+static const WCHAR *const service_privileges[] = {L"SeAssignPrimaryTokenPrivilege", L"SeIncreaseQuotaPrivilege"};+#define SERVICE_PRIVILEGE_COUNT (sizeof service_privileges / sizeof service_privileges[0])++/* The account a service runs as when it runs as its virtual account:+ * this prefix, then the service's name. */+#define VIRTUAL_ACCOUNT_PREFIX L"NT SERVICE\\"++/* A password: an upper-case letter, a lower-case letter, a digit and a+ * symbol, which the password complexity policy asks one to hold, then+ * random letters and digits. */+#define PASSWORD_PREFIX L"Aa1!"+#define PASSWORD_RANDOM_CHARS 24++/* The room a domain name and a window station's or desktop's name are+ * given. */+#define NAME_CHARS 256++/* A code a builder's crash raises: a customer code (bit 29), with the+ * severity of an error, which no runtime the test suite links handles. */+#define CRASH_EXCEPTION_CODE 0xE04E4E01UL++/* The exit code a process the test service's stop ends is given. */+#define STOPPED_EXIT_CODE ERROR_PROCESS_ABORTED++/* A token's user: a TOKEN_USER and the SID it points at, which follows it+ * in the buffer and is at most SECURITY_MAX_SID_SIZE bytes, so one call+ * fills it.  The union aligns the buffer for the structure. */+union token_user {+    TOKEN_USER user;+    BYTE bytes[sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE];+};++/* Fill PASSWORD, PASSWORD_PREFIX and PASSWORD_RANDOM_CHARS random+ * letters and digits and a NUL. */+static unsigned long make_password(WCHAR *password)+{+    static const WCHAR alphabet[] = L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";+    size_t prefix = wcslen(PASSWORD_PREFIX);+    unsigned char bytes[PASSWORD_RANDOM_CHARS];+    size_t i;+    if (BCryptGenRandom(NULL, bytes, sizeof bytes, BCRYPT_USE_SYSTEM_PREFERRED_RNG) != 0)+        return ERROR_GEN_FAILURE;+    memcpy(password, PASSWORD_PREFIX, prefix * sizeof *password);+    for (i = 0; i < PASSWORD_RANDOM_CHARS; i++)+        password[prefix + i] = alphabet[bytes[i] % (sizeof alphabet / sizeof alphabet[0] - 1)];+    password[prefix + PASSWORD_RANDOM_CHARS] = L'\0';+    return 0;+}++/* The local security policy, opened to look accounts up and grant them+ * rights. */+static unsigned long open_policy(LSA_HANDLE *policy)+{+    LSA_OBJECT_ATTRIBUTES attributes;+    memset(&attributes, 0, sizeof attributes);+    return LsaNtStatusToWinError(LsaOpenPolicy(NULL, &attributes, POLICY_CREATE_ACCOUNT | POLICY_LOOKUP_NAMES, policy));+}++/* NAME's SID, in SID, SECURITY_MAX_SID_SIZE bytes. */+static unsigned long account_sid(const wchar_t *name, PSID sid)+{+    DWORD sid_size = SECURITY_MAX_SID_SIZE;+    WCHAR domain[NAME_CHARS];+    DWORD domain_size = NAME_CHARS;+    SID_NAME_USE use;+    return LookupAccountNameW(NULL, name, sid, &sid_size, domain, &domain_size, &use) ? 0 : GetLastError();+}++/* An LSA string for TEXT, which it points into. */+static LSA_UNICODE_STRING lsa_string(const WCHAR *text)+{+    LSA_UNICODE_STRING string;+    string.Buffer = (PWSTR)text;+    string.Length = (USHORT)(wcslen(text) * sizeof(WCHAR));+    string.MaximumLength = (USHORT)(string.Length + sizeof(WCHAR));+    return string;+}++/* Make the local account NAME, a member of Users alone, with a password+ * generated for it, and grant it the batch logon right, as the service's+ * install makes each slot's account.  *PASSWORD gets the password, for+ * LocalFree, which the test service logs the account on with.  A failure+ * names its call in *FAILED; what was made by then,+ * nova_test_account_remove removes. */+unsigned long nova_test_account_make(const wchar_t *name, wchar_t **password, const char **failed)+{+    WCHAR generated[sizeof PASSWORD_PREFIX / sizeof(WCHAR) + PASSWORD_RANDOM_CHARS];+    BYTE sid_bytes[SECURITY_MAX_SID_SIZE];+    USER_INFO_1 user;+    LSA_UNICODE_STRING right = lsa_string(BATCH_LOGON_RIGHT);+    LSA_HANDLE policy = NULL;+    DWORD bad_field = 0;+    unsigned long error;++    *password = NULL;+    *failed = NULL;+    if ((error = make_password(generated)) != 0) {+        *failed = "BCryptGenRandom";+        return error;+    }+    memset(&user, 0, sizeof user);+    user.usri1_name = (LPWSTR)name;+    user.usri1_password = generated;+    user.usri1_priv = USER_PRIV_USER;+    user.usri1_flags = UF_SCRIPT | UF_DONT_EXPIRE_PASSWD;+    if ((error = NetUserAdd(NULL, 1, (LPBYTE)&user, &bad_field)) != NERR_Success) {+        *failed = "NetUserAdd";+        goto done;+    }+    if ((error = account_sid(name, sid_bytes)) != 0) {+        *failed = "LookupAccountNameW";+        goto done;+    }+    if ((error = open_policy(&policy)) != 0) {+        *failed = "LsaOpenPolicy";+        policy = NULL;+        goto done;+    }+    if ((error = LsaNtStatusToWinError(LsaAddAccountRights(policy, sid_bytes, &right, 1))) != 0) {+        *failed = "LsaAddAccountRights";+        goto done;+    }+    *password = LocalAlloc(LMEM_FIXED, sizeof generated);+    if (*password == NULL) {+        error = GetLastError();+        *failed = "LocalAlloc";+        goto done;+    }+    memcpy(*password, generated, sizeof generated);+done:+    SecureZeroMemory(generated, sizeof generated);+    if (policy != NULL)+        LsaClose(policy);+    return error;+}++/* Remove the local account NAME, its rights first, while its name still+ * finds its SID; an account or a right already gone is no failure.  A+ * failure names its call in *FAILED. */+unsigned long nova_test_account_remove(const wchar_t *name, const char **failed)+{+    BYTE sid_bytes[SECURITY_MAX_SID_SIZE];+    LSA_HANDLE policy = NULL;+    unsigned long error;+    *failed = NULL;+    error = account_sid(name, sid_bytes);+    if (error == ERROR_NONE_MAPPED)+        return 0;+    if (error != 0) {+        *failed = "LookupAccountNameW";+        return error;+    }+    if ((error = open_policy(&policy)) != 0) {+        *failed = "LsaOpenPolicy";+        return error;+    }+    /* An account holding no right has none to remove. */+    error = LsaNtStatusToWinError(LsaRemoveAccountRights(policy, sid_bytes, TRUE, NULL, 0));+    LsaClose(policy);+    if (error != 0 && error != ERROR_FILE_NOT_FOUND) {+        *failed = "LsaRemoveAccountRights";+        return error;+    }+    error = NetUserDel(NULL, name);+    if (error != NERR_Success && error != NERR_UserNotFound) {+        *failed = "NetUserDel";+        return error;+    }+    return 0;+}++/* The virtual account the service NAME runs as, NT SERVICE\NAME, for+ * free. */+static WCHAR *virtual_account(const wchar_t *name)+{+    size_t prefix = wcslen(VIRTUAL_ACCOUNT_PREFIX);+    size_t length = wcslen(name) + 1;+    WCHAR *account = malloc((prefix + length) * sizeof *account);+    if (account == NULL)+        return NULL;+    memcpy(account, VIRTUAL_ACCOUNT_PREFIX, prefix * sizeof *account);+    memcpy(account + prefix, name, length * sizeof *account);+    return account;+}++/* Make the service NAME, which COMMAND starts and which runs as its+ * virtual account, and grant that account the privileges that start a+ * process as another account, as the service's install does.  *SID gets+ * the account's SID's string, for LocalFree.  A failure names its call in+ * *FAILED; what was made by then, nova_test_service_remove removes. */+unsigned long nova_test_service_install(const wchar_t *name, const wchar_t *command, wchar_t **sid,+                                        const char **failed)+{+    WCHAR *account = virtual_account(name);+    SC_HANDLE manager = NULL;+    SC_HANDLE service = NULL;+    BYTE sid_bytes[SECURITY_MAX_SID_SIZE];+    LSA_HANDLE policy = NULL;+    LSA_UNICODE_STRING rights[SERVICE_PRIVILEGE_COUNT];+    unsigned long error = 0;+    size_t i;++    *sid = NULL;+    *failed = NULL;+    if (account == NULL) {+        *failed = "malloc";+        return ERROR_NOT_ENOUGH_MEMORY;+    }+    manager = OpenSCManagerW(NULL, NULL, SC_MANAGER_CREATE_SERVICE);+    if (manager == NULL) {+        error = GetLastError();+        *failed = "OpenSCManagerW";+        goto done;+    }+    service = CreateServiceW(manager, name, name, SERVICE_QUERY_STATUS, SERVICE_WIN32_OWN_PROCESS, SERVICE_DEMAND_START,+                             SERVICE_ERROR_NORMAL, command, NULL, NULL, NULL, account, NULL);+    if (service == NULL) {+        error = GetLastError();+        *failed = "CreateServiceW";+        goto done;+    }+    /* The virtual account's name finds its SID once the service exists. */+    if ((error = account_sid(account, sid_bytes)) != 0) {+        *failed = "LookupAccountNameW";+        goto done;+    }+    if ((error = open_policy(&policy)) != 0) {+        *failed = "LsaOpenPolicy";+        policy = NULL;+        goto done;+    }+    for (i = 0; i < SERVICE_PRIVILEGE_COUNT; i++)+        rights[i] = lsa_string(service_privileges[i]);+    if ((error = LsaNtStatusToWinError(LsaAddAccountRights(policy, sid_bytes, rights, SERVICE_PRIVILEGE_COUNT))) != 0) {+        *failed = "LsaAddAccountRights";+        goto done;+    }+    if (!ConvertSidToStringSidW(sid_bytes, sid)) {+        error = GetLastError();+        *failed = "ConvertSidToStringSidW";+        *sid = NULL;+    }+done:+    if (policy != NULL)+        LsaClose(policy);+    if (service != NULL)+        CloseServiceHandle(service);+    if (manager != NULL)+        CloseServiceHandle(manager);+    free(account);+    return error;+}++/* The service NAME, opened with ACCESS, in *SERVICE, and the service+ * manager it was opened through, in *MANAGER, for CloseServiceHandle. */+static unsigned long open_service(const wchar_t *name, DWORD access, SC_HANDLE *manager, SC_HANDLE *service)+{+    *service = NULL;+    *manager = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);+    if (*manager == NULL)+        return GetLastError();+    *service = OpenServiceW(*manager, name, access);+    return *service != NULL ? 0 : GetLastError();+}++static void close_service(SC_HANDLE manager, SC_HANDLE service)+{+    if (service != NULL)+        CloseServiceHandle(service);+    if (manager != NULL)+        CloseServiceHandle(manager);+}++unsigned long nova_test_service_start(const wchar_t *name)+{+    SC_HANDLE manager = NULL;+    SC_HANDLE service = NULL;+    unsigned long error = open_service(name, SERVICE_START, &manager, &service);+    if (error == 0 && !StartServiceW(service, 0, NULL))+        error = GetLastError();+    close_service(manager, service);+    return error;+}++/* The state of the service NAME, a SERVICE_* state, in *STATE, and the+ * code it reported when it stopped, in *CODE: its own, where it reported+ * one, or else the Win32 error it stopped with. */+unsigned long nova_test_service_state(const wchar_t *name, unsigned long *state, unsigned long *code)+{+    SC_HANDLE manager = NULL;+    SC_HANDLE service = NULL;+    SERVICE_STATUS status;+    unsigned long error = open_service(name, SERVICE_QUERY_STATUS, &manager, &service);+    *state = 0;+    *code = 0;+    if (error == 0 && !QueryServiceStatus(service, &status))+        error = GetLastError();+    if (error == 0) {+        *state = status.dwCurrentState;+        *code = status.dwWin32ExitCode == ERROR_SERVICE_SPECIFIC_ERROR ? status.dwServiceSpecificExitCode+                                                                        : status.dwWin32ExitCode;+    }+    close_service(manager, service);+    return error;+}++/* Remove the account rights of the service NAME's virtual account, while+ * the service exists and so its name finds its SID.  A failure names its+ * call in *FAILED. */+static unsigned long remove_service_rights(const wchar_t *name, const char **failed)+{+    WCHAR *account = virtual_account(name);+    BYTE sid_bytes[SECURITY_MAX_SID_SIZE];+    LSA_HANDLE policy = NULL;+    unsigned long error;+    if (account == NULL) {+        *failed = "malloc";+        return ERROR_NOT_ENOUGH_MEMORY;+    }+    error = account_sid(account, sid_bytes);+    free(account);+    if (error != 0) {+        *failed = "LookupAccountNameW";+        return error;+    }+    if ((error = open_policy(&policy)) != 0) {+        *failed = "LsaOpenPolicy";+        return error;+    }+    /* An account holding no right has none to remove. */+    error = LsaNtStatusToWinError(LsaRemoveAccountRights(policy, sid_bytes, TRUE, NULL, 0));+    LsaClose(policy);+    if (error != 0 && error != ERROR_FILE_NOT_FOUND) {+        *failed = "LsaRemoveAccountRights";+        return error;+    }+    return 0;+}++/* Remove the service NAME: its account's rights first, then the service,+ * asked to stop if it runs, which goes once it has stopped.  Each step is+ * tried whatever the one before came to, and a service already gone is no+ * failure.  The first failure names its call in *FAILED. */+unsigned long nova_test_service_remove(const wchar_t *name, const char **failed)+{+    SC_HANDLE manager = NULL;+    SC_HANDLE service = NULL;+    SERVICE_STATUS status;+    unsigned long error;++    *failed = NULL;+    error = open_service(name, SERVICE_STOP | DELETE, &manager, &service);+    if (error != 0) {+        close_service(manager, service);+        if (error == ERROR_SERVICE_DOES_NOT_EXIST)+            return 0;+        *failed = "OpenServiceW";+        return error;+    }+    error = remove_service_rights(name, failed);+    if (!ControlService(service, SERVICE_CONTROL_STOP, &status) && GetLastError() != ERROR_SERVICE_NOT_ACTIVE+        && error == 0) {+        error = GetLastError();+        *failed = "ControlService";+    }+    if (!DeleteService(service) && GetLastError() != ERROR_SERVICE_MARKED_FOR_DELETE && error == 0) {+        error = GetLastError();+        *failed = "DeleteService";+    }+    close_service(manager, service);+    return error;+}++/* The test service as it runs: its name, the command line of the checks+ * it starts, the event its control handler sets when it is asked to+ * stop, and the handle it reports its state through. */+static const WCHAR *service_name;+static WCHAR *service_checks;+static HANDLE service_stop;+static SERVICE_STATUS_HANDLE service_status;++/* Report the test service's STATE, and, once it has stopped, CODE: 0, or+ * the checks' exit code, or the error that kept them from starting. */+static void report_service(DWORD state, DWORD code)+{+    SERVICE_STATUS status;+    memset(&status, 0, sizeof status);+    status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;+    status.dwCurrentState = state;+    status.dwControlsAccepted = state == SERVICE_RUNNING ? SERVICE_ACCEPT_STOP : 0;+    status.dwWin32ExitCode = code == 0 ? NO_ERROR : ERROR_SERVICE_SPECIFIC_ERROR;+    status.dwServiceSpecificExitCode = code;+    SetServiceStatus(service_status, &status);+}++static DWORD WINAPI service_control(DWORD control, DWORD type, LPVOID data, LPVOID context)+{+    (void)type;+    (void)data;+    (void)context;+    switch (control) {+    case SERVICE_CONTROL_STOP:+        SetEvent(service_stop);+        return NO_ERROR;+    case SERVICE_CONTROL_INTERROGATE:+        return NO_ERROR;+    default:+        return ERROR_CALL_NOT_IMPLEMENTED;+    }+}++/* Run the checks as a process of the service's own, which runs as its+ * account with its token, wait until they end or the service is asked to+ * stop, which ends them, and stop with their exit code. */+static VOID WINAPI service_main(DWORD argc, LPWSTR *argv)+{+    STARTUPINFOW startup;+    PROCESS_INFORMATION checks;+    HANDLE waits[2];+    DWORD code = 0;+    (void)argc;+    (void)argv;+    service_status = RegisterServiceCtrlHandlerExW(service_name, service_control, NULL);+    if (service_status == NULL)+        return;+    report_service(SERVICE_RUNNING, 0);+    memset(&startup, 0, sizeof startup);+    startup.cb = sizeof startup;+    if (!CreateProcessW(NULL, service_checks, NULL, NULL, FALSE, 0, NULL, NULL, &startup, &checks)) {+        report_service(SERVICE_STOPPED, GetLastError());+        return;+    }+    CloseHandle(checks.hThread);+    waits[0] = checks.hProcess;+    waits[1] = service_stop;+    if (WaitForMultipleObjects(2, waits, FALSE, INFINITE) != WAIT_OBJECT_0) {+        TerminateProcess(checks.hProcess, STOPPED_EXIT_CODE);+        WaitForSingleObject(checks.hProcess, INFINITE);+    }+    if (!GetExitCodeProcess(checks.hProcess, &code))+        code = GetLastError();+    CloseHandle(checks.hProcess);+    report_service(SERVICE_STOPPED, code);+}++/* Run as the service NAME, which the service manager started, until it+ * stops: it runs the command line CHECKS and stops when that ends.+ * Answers once the service has stopped. */+unsigned long nova_test_service_dispatch(const wchar_t *name, const wchar_t *checks)+{+    SERVICE_TABLE_ENTRYW table[2];+    size_t length = wcslen(checks) + 1;+    unsigned long error = 0;+    service_checks = malloc(length * sizeof *service_checks);+    if (service_checks == NULL)+        return ERROR_NOT_ENOUGH_MEMORY;+    memcpy(service_checks, checks, length * sizeof *service_checks);+    service_name = name;+    service_stop = CreateEventW(NULL, TRUE, FALSE, NULL);+    if (service_stop == NULL) {+        error = GetLastError();+        free(service_checks);+        return error;+    }+    table[0].lpServiceName = (LPWSTR)name;+    table[0].lpServiceProc = service_main;+    table[1].lpServiceName = NULL;+    table[1].lpServiceProc = NULL;+    if (!StartServiceCtrlDispatcherW(table))+        error = GetLastError();+    CloseHandle(service_stop);+    free(service_checks);+    return error;+}++/* An ACL granting all access to each of the COUNT SIDS, in a buffer of+ * its own. */+static PACL grant_all(PSID *sids, size_t count)+{+    DWORD size = (DWORD)sizeof(ACL);+    PACL acl;+    size_t i;+    for (i = 0; i < count; i++)+        size += (DWORD)(sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD)) + GetLengthSid(sids[i]);+    acl = malloc(size);+    if (acl == NULL)+        return NULL;+    if (!InitializeAcl(acl, size, ACL_REVISION)) {+        free(acl);+        return NULL;+    }+    for (i = 0; i < count; i++)+        if (!AddAccessAllowedAce(acl, ACL_REVISION, GENERIC_ALL, sids[i])) {+            free(acl);+            return NULL;+        }+    return acl;+}++/* Log the account NAME on with PASSWORD as a batch job, as the service+ * logs a slot on for its builds, and give the token the default DACL the+ * service gives it, which every process it starts takes: all access for+ * SYSTEM, for this process's user, the service, and for the account.  *SID+ * gets the account's SID's string, for LocalFree, and *TOKEN the primary+ * token, inheritable, so a helper this process starts holds it. */+unsigned long nova_test_account_logon(const wchar_t *name, const wchar_t *password, wchar_t **sid, void **token)+{+    union token_user own;+    union token_user slot;+    BYTE system_bytes[SECURITY_MAX_SID_SIZE];+    DWORD system_size = sizeof system_bytes;+    PSID grantees[3];+    TOKEN_DEFAULT_DACL dacl;+    HANDLE logged = NULL;+    HANDLE self = NULL;+    DWORD size = 0;+    unsigned long error = 0;++    *sid = NULL;+    *token = NULL;+    dacl.DefaultDacl = NULL;+    if (!LogonUserW(name, L".", password, LOGON32_LOGON_BATCH, LOGON32_PROVIDER_DEFAULT, &logged))+        return GetLastError();+    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &self)+        || !GetTokenInformation(self, TokenUser, &own, sizeof own, &size)+        || !GetTokenInformation(logged, TokenUser, &slot, sizeof slot, &size)+        || !CreateWellKnownSid(WinLocalSystemSid, NULL, system_bytes, &system_size)) {+        error = GetLastError();+        goto done;+    }+    grantees[0] = system_bytes;+    grantees[1] = own.user.User.Sid;+    grantees[2] = slot.user.User.Sid;+    dacl.DefaultDacl = grant_all(grantees, sizeof grantees / sizeof grantees[0]);+    if (dacl.DefaultDacl == NULL) {+        error = ERROR_NOT_ENOUGH_MEMORY;+        goto done;+    }+    if (!SetTokenInformation(logged, TokenDefaultDacl, &dacl, sizeof dacl)+        || !SetHandleInformation(logged, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)+        || !ConvertSidToStringSidW(slot.user.User.Sid, sid)) {+        error = GetLastError();+        *sid = NULL;+        goto done;+    }+    *token = logged;+    logged = NULL;+done:+    free(dacl.DefaultDacl);+    if (self != NULL)+        CloseHandle(self);+    if (logged != NULL)+        CloseHandle(logged);+    return error;+}++/* Give the file or directory PATH the DACL of the security descriptor+ * SDDL describes, protected from what its directory passes down. */+unsigned long nova_test_set_sddl(const wchar_t *path, const wchar_t *sddl)+{+    PSECURITY_DESCRIPTOR descriptor = NULL;+    PACL dacl = NULL;+    BOOL present = FALSE;+    BOOL defaulted = FALSE;+    unsigned long error;+    if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl, SDDL_REVISION_1, &descriptor, NULL))+        return GetLastError();+    if (!GetSecurityDescriptorDacl(descriptor, &present, &dacl, &defaulted))+        error = GetLastError();+    else+        error = SetNamedSecurityInfoW((LPWSTR)path, SE_FILE_OBJECT,+                                      DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, NULL, NULL, dacl,+                                      NULL);+    LocalFree(descriptor);+    return error;+}++/* Start COMMAND as the account whose primary TOKEN this is, with no+ * console, as a process a build left running is, outside the build's+ * job; *PID gets its ID.  The privileges that takes are enabled in this+ * process's token first. */+unsigned long nova_test_start_as(void *token, const wchar_t *command, unsigned long *pid)+{+    static WCHAR logon_desktop[] = L"";+    HANDLE self = NULL;+    STARTUPINFOW startup;+    PROCESS_INFORMATION started;+    size_t length = wcslen(command) + 1;+    WCHAR *line;+    unsigned long error = 0;+    size_t i;++    *pid = 0;+    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &self))+        return GetLastError();+    for (i = 0; i < SERVICE_PRIVILEGE_COUNT && error == 0; i++) {+        TOKEN_PRIVILEGES wanted;+        wanted.PrivilegeCount = 1;+        wanted.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;+        if (!LookupPrivilegeValueW(NULL, service_privileges[i], &wanted.Privileges[0].Luid)+            || !AdjustTokenPrivileges(self, FALSE, &wanted, 0, NULL, NULL))+            error = GetLastError();+        /* The call succeeds for a privilege the token does not hold, and+         * says so in the thread's last error alone. */+        else if (GetLastError() != ERROR_SUCCESS)+            error = GetLastError();+    }+    CloseHandle(self);+    if (error != 0)+        return error;+    line = malloc(length * sizeof *line);+    if (line == NULL)+        return ERROR_NOT_ENOUGH_MEMORY;+    memcpy(line, command, length * sizeof *line);+    memset(&startup, 0, sizeof startup);+    startup.cb = sizeof startup;+    startup.lpDesktop = logon_desktop;+    if (CreateProcessAsUserW(token, NULL, line, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &startup, &started)) {+        CloseHandle(started.hThread);+        CloseHandle(started.hProcess);+        *pid = started.dwProcessId;+    } else {+        error = GetLastError();+    }+    free(line);+    return error;+}++/* What this process may do to each process running as the account whose+ * SID's string SID_TEXT is: entries of its program's name and what opening+ * it to end it and to wait on it answer, NAME:TERMINATE:SYNCHRONIZE, each+ * ended by a semicolon, in TEXT, CAPACITY characters; one that does not+ * fit is left out, and *COUNT gets how many processes there are. */+unsigned long nova_test_account_processes(const wchar_t *sid_text, wchar_t *text, unsigned long capacity,+                                          unsigned long *count)+{+    PSID sid = NULL;+    HANDLE snapshot;+    PROCESSENTRY32W entry;+    size_t used = 0;+    BOOL listed;+    unsigned long error = 0;+    *count = 0;+    if (capacity == 0)+        return ERROR_INSUFFICIENT_BUFFER;+    text[0] = L'\0';+    if (!ConvertStringSidToSidW(sid_text, &sid))+        return GetLastError();+    snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);+    if (snapshot == INVALID_HANDLE_VALUE) {+        error = GetLastError();+        LocalFree(sid);+        return error;+    }+    entry.dwSize = sizeof entry;+    for (listed = Process32FirstW(snapshot, &entry); listed; listed = Process32NextW(snapshot, &entry)) {+        HANDLE process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, entry.th32ProcessID);+        HANDLE token = NULL;+        union token_user user;+        DWORD size = 0;+        if (process == NULL)+            continue;+        if (OpenProcessToken(process, TOKEN_QUERY, &token)+            && GetTokenInformation(token, TokenUser, &user, sizeof user, &size) && EqualSid(user.user.User.Sid, sid)) {+            HANDLE ending = OpenProcess(PROCESS_TERMINATE, FALSE, entry.th32ProcessID);+            unsigned long terminate = ending != NULL ? 0 : GetLastError();+            HANDLE waitable = OpenProcess(SYNCHRONIZE, FALSE, entry.th32ProcessID);+            unsigned long synchronize = waitable != NULL ? 0 : GetLastError();+            WCHAR line[MAX_PATH + 32];+            int length = swprintf(line, sizeof line / sizeof line[0], L"%ls:%lu:%lu;", entry.szExeFile, terminate,+                                  synchronize);+            if (length > 0 && used + (size_t)length < capacity) {+                memcpy(text + used, line, ((size_t)length + 1) * sizeof *text);+                used += (size_t)length;+            }+            (*count)++;+            if (ending != NULL)+                CloseHandle(ending);+            if (waitable != NULL)+                CloseHandle(waitable);+        }+        if (token != NULL)+            CloseHandle(token);+        CloseHandle(process);+    }+    CloseHandle(snapshot);+    LocalFree(sid);+    return 0;+}++unsigned long nova_test_close_handle(void *handle)+{+    return CloseHandle(handle) ? 0 : GetLastError();+}++/* Release what a call here allocated for LocalFree: a SID's string or a+ * password. */+void nova_test_local_free(wchar_t *text)+{+    LocalFree(text);+}++/* Make the directory PATH with the security descriptor SDDL describes. */+unsigned long nova_test_directory_with_sddl(const wchar_t *path, const wchar_t *sddl)+{+    PSECURITY_DESCRIPTOR descriptor = NULL;+    SECURITY_ATTRIBUTES attributes;+    unsigned long error = 0;+    if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl, SDDL_REVISION_1, &descriptor, NULL))+        return GetLastError();+    attributes.nLength = sizeof attributes;+    attributes.lpSecurityDescriptor = descriptor;+    attributes.bInheritHandle = FALSE;+    if (!CreateDirectoryW(path, &attributes))+        error = GetLastError();+    LocalFree(descriptor);+    return error;+}++/* Whether the process PID is running: 1 when it is, 0 when it has ended+ * or no process has the ID, and -1 when it cannot be told. */+int nova_test_process_running(unsigned long pid)+{+    HANDLE process = OpenProcess(SYNCHRONIZE, FALSE, pid);+    DWORD waited;+    if (process == NULL)+        return GetLastError() == ERROR_INVALID_PARAMETER ? 0 : -1;+    waited = WaitForSingleObject(process, 0);+    CloseHandle(process);+    if (waited == WAIT_TIMEOUT)+        return 1;+    return waited == WAIT_OBJECT_0 ? 0 : -1;+}++/* The SID of the user this process runs as, its token's user, for+ * LocalFree. */+unsigned long nova_test_token_user(wchar_t **sid)+{+    union token_user buffer;+    HANDLE token = NULL;+    DWORD size = 0;+    unsigned long error = 0;+    *sid = NULL;+    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token))+        return GetLastError();+    if (!GetTokenInformation(token, TokenUser, &buffer, sizeof buffer, &size)+        || !ConvertSidToStringSidW(buffer.user.User.Sid, sid))+        error = GetLastError();+    CloseHandle(token);+    return error;+}++/* The user object WHICH names, this process's window station for 0 and+ * its thread's desktop for anything else.  Neither handle is closed. */+static HANDLE user_object(int which)+{+    return which == 0 ? (HANDLE)GetProcessWindowStation() : (HANDLE)GetThreadDesktop(GetCurrentThreadId());+}++/* The name of this process's window station or desktop, as WHICH says,+ * in NAME, CAPACITY characters. */+unsigned long nova_test_user_object_name(int which, wchar_t *name, unsigned long capacity)+{+    DWORD needed = 0;+    return GetUserObjectInformationW(user_object(which), UOI_NAME, name, capacity * sizeof *name, &needed)+               ? 0+               : GetLastError();+}++/* The ID of the logon session this process's token belongs to, its high+ * and low parts, which name the window station Windows makes for it. */+unsigned long nova_test_logon_id(unsigned long *high, unsigned long *low)+{+    TOKEN_STATISTICS statistics;+    HANDLE token = NULL;+    DWORD size = 0;+    unsigned long error = 0;+    *high = 0;+    *low = 0;+    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token))+        return GetLastError();+    if (GetTokenInformation(token, TokenStatistics, &statistics, sizeof statistics, &size)) {+        *high = (unsigned long)statistics.AuthenticationId.HighPart;+        *low = statistics.AuthenticationId.LowPart;+    } else {+        error = GetLastError();+    }+    CloseHandle(token);+    return error;+}++/* Open the window station NAME with whatever access its DACL grants this+ * process, and close it: a refusal says it grants none. */+unsigned long nova_test_open_station(const wchar_t *name)+{+    HWINSTA station = OpenWindowStationW(name, FALSE, MAXIMUM_ALLOWED);+    if (station == NULL)+        return GetLastError();+    CloseWindowStation(station);+    return 0;+}++/* The DACL of STATION, a window station, in SDDL, for LocalFree. */+static unsigned long station_sddl(HWINSTA station, wchar_t **sddl)+{+    SECURITY_INFORMATION wanted = DACL_SECURITY_INFORMATION;+    PSECURITY_DESCRIPTOR descriptor;+    DWORD needed = 0;+    unsigned long error = 0;+    GetUserObjectSecurity(station, &wanted, NULL, 0, &needed);+    if (needed == 0)+        return GetLastError();+    descriptor = LocalAlloc(LMEM_FIXED, needed);+    if (descriptor == NULL)+        return GetLastError();+    if (!GetUserObjectSecurity(station, &wanted, descriptor, needed, &needed)+        || !ConvertSecurityDescriptorToStringSecurityDescriptorW(descriptor, SDDL_REVISION_1, DACL_SECURITY_INFORMATION,+                                                                 sddl, NULL))+        error = GetLastError();+    LocalFree(descriptor);+    return error;+}++/* The DACL of this process's window station, NAME, in SDDL, for+ * LocalFree: read through the handle the process was given to it, or,+ * where that may not read it, through one opened by name to read it. */+unsigned long nova_test_station_dacl(const wchar_t *name, wchar_t **sddl)+{+    HWINSTA opened;+    unsigned long error;+    *sddl = NULL;+    if (station_sddl(GetProcessWindowStation(), sddl) == 0)+        return 0;+    *sddl = NULL;+    opened = OpenWindowStationW(name, FALSE, READ_CONTROL);+    if (opened == NULL)+        return GetLastError();+    error = station_sddl(opened, sddl);+    CloseWindowStation(opened);+    return error;+}++/* The value of this process's standard output handle, as another process+ * names it to copy it. */+unsigned long nova_test_stdout_value(void)+{+    return (unsigned long)(ULONG_PTR)GetStdHandle(STD_OUTPUT_HANDLE);+}++/* Copy the handle VALUE of the process PID into this one, which keeps the+ * copy until it ends, as a process holding what it copied from a build+ * does. */+unsigned long nova_test_hold_handle(unsigned long pid, unsigned long value)+{+    HANDLE source = OpenProcess(PROCESS_DUP_HANDLE, FALSE, pid);+    HANDLE copy = NULL;+    unsigned long error = 0;+    if (source == NULL)+        return GetLastError();+    if (!DuplicateHandle(source, (HANDLE)(ULONG_PTR)value, GetCurrentProcess(), &copy, 0, FALSE, DUPLICATE_SAME_ACCESS))+        error = GetLastError();+    CloseHandle(source);+    return error;+}++/* Whether this process is in a job: 1 when it is, 0 when it is not, and+ * -1 when it cannot be told. */+int nova_test_in_job(void)+{+    BOOL in_job = FALSE;+    if (!IsProcessInJob(GetCurrentProcess(), NULL, &in_job))+        return -1;+    return in_job ? 1 : 0;+}++/* The limit flags of the job this process is in, the innermost when jobs+ * nest, in *flags. */+unsigned long nova_test_job_limits(unsigned long *flags)+{+    JOBOBJECT_BASIC_LIMIT_INFORMATION limits;+    if (!QueryInformationJobObject(NULL, JobObjectBasicLimitInformation, &limits, sizeof limits, NULL))+        return GetLastError();+    *flags = limits.LimitFlags;+    return 0;+}++/* Whether this process has a console to write: CONOUT$ opens, which+ * libiberty asks of gcc's console before it lets gcc's subprograms share+ * it. */+unsigned long nova_test_console(void)+{+    HANDLE console = CreateFileW(L"CONOUT$", GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);+    if (console == INVALID_HANDLE_VALUE)+        return GetLastError();+    CloseHandle(console);+    return 0;+}++/* Commit BYTES of memory and release them. */+unsigned long nova_test_commit(unsigned long long bytes)+{+    void *block = VirtualAlloc(NULL, (SIZE_T)bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);+    if (block == NULL)+        return GetLastError();+    VirtualFree(block, 0, MEM_RELEASE);+    return 0;+}++/* Start COMMAND with CreateProcessW's FLAGS, inheriting no handle, so it+ * shares this process's console; *PID gets its ID and *PROCESS its handle,+ * for nova_test_wait. */+unsigned long nova_test_start(const wchar_t *command, unsigned long flags, unsigned long *pid, void **process)+{+    STARTUPINFOW startup;+    PROCESS_INFORMATION started;+    size_t length = wcslen(command) + 1;+    WCHAR *line = malloc(length * sizeof *line);+    unsigned long error = 0;+    *pid = 0;+    *process = NULL;+    if (line == NULL)+        return ERROR_NOT_ENOUGH_MEMORY;+    memcpy(line, command, length * sizeof *line);+    memset(&startup, 0, sizeof startup);+    startup.cb = sizeof startup;+    if (CreateProcessW(NULL, line, NULL, NULL, FALSE, flags, NULL, NULL, &startup, &started)) {+        CloseHandle(started.hThread);+        *pid = started.dwProcessId;+        *process = started.hProcess;+    } else {+        error = GetLastError();+    }+    free(line);+    return error;+}++/* Wait for PROCESS, from nova_test_start, to end, put its exit code in+ * *CODE and close it. */+unsigned long nova_test_wait(void *process, unsigned long *code)+{+    DWORD exit_code = 0;+    unsigned long error = 0;+    if (WaitForSingleObject(process, INFINITE) != WAIT_OBJECT_0 || !GetExitCodeProcess(process, &exit_code))+        error = GetLastError();+    *code = exit_code;+    CloseHandle(process);+    return error;+}++/* Raise CRASH_EXCEPTION_CODE with no handler left to take it: the test+ * suite's runtime installs a filter for unhandled exceptions, which this+ * takes out first, so the crash ends the process as a crash ends one with+ * none. */+void nova_test_crash(void)+{+    SetUnhandledExceptionFilter(NULL);+    RaiseException(CRASH_EXCEPTION_CODE, EXCEPTION_NONCONTINUABLE, 0, NULL);+}++/* Open PATH with ACCESS, a file or a directory, and close it. */+unsigned long nova_test_open(const wchar_t *path, unsigned long access)+{+    HANDLE file = CreateFileW(path, access, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,+                              OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);+    if (file == INVALID_HANDLE_VALUE)+        return GetLastError();+    CloseHandle(file);+    return 0;+}++/* Create the file PATH, which must not exist. */+unsigned long nova_test_create(const wchar_t *path)+{+    HANDLE file = CreateFileW(path, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);+    if (file == INVALID_HANDLE_VALUE)+        return GetLastError();+    CloseHandle(file);+    return 0;+}++unsigned long nova_test_delete(const wchar_t *path)+{+    return DeleteFileW(path) ? 0 : GetLastError();+}++/* List the first entry PATTERN, such as DIRECTORY\*, finds. */+unsigned long nova_test_list(const wchar_t *pattern)+{+    WIN32_FIND_DATAW found;+    HANDLE search = FindFirstFileW(pattern, &found);+    if (search == INVALID_HANDLE_VALUE)+        return GetLastError();+    FindClose(search);+    return 0;+}++/* Open the key PATH beneath HKEY_USERS to read it. */+unsigned long nova_test_open_key(const wchar_t *path)+{+    HKEY key;+    LSTATUS status = RegOpenKeyExW(HKEY_USERS, path, 0, KEY_READ, &key);+    if (status != ERROR_SUCCESS)+        return (unsigned long)status;+    RegCloseKey(key);+    return 0;+}++/* Open the process PID to read its memory. */+unsigned long nova_test_open_process(unsigned long pid)+{+    HANDLE process = OpenProcess(PROCESS_VM_READ, FALSE, pid);+    if (process == NULL)+        return GetLastError();+    CloseHandle(process);+    return 0;+}++/* Make the local group NAME, which the build accounts are made members+ * of; one already there is a failure, ERROR_ALIAS_EXISTS, so a machine's+ * own group is never taken for the tests'. */+unsigned long nova_test_group_make(const wchar_t *name)+{+    LOCALGROUP_INFO_0 group;+    DWORD bad_field = 0;+    group.lgrpi0_name = (LPWSTR)name;+    return NetLocalGroupAdd(NULL, 0, (LPBYTE)&group, &bad_field);+}++/* Make the local account MEMBER a member of the local group GROUP, before+ * it is logged on, so its token holds the group. */+unsigned long nova_test_group_add(const wchar_t *group, const wchar_t *member)+{+    LOCALGROUP_MEMBERS_INFO_3 entry;+    entry.lgrmi3_domainandname = (LPWSTR)member;+    return NetLocalGroupAddMembers(NULL, group, 3, (LPBYTE)&entry, 1);+}++/* Remove the local group NAME; one already gone is no failure. */+unsigned long nova_test_group_remove(const wchar_t *name)+{+    NET_API_STATUS status = NetLocalGroupDel(NULL, name);+    return status == NERR_Success || status == NERR_GroupNotFound || status == ERROR_NO_SUCH_ALIAS ? 0 : status;+}++/* The SID of the account NAME, in the string form ConvertSidToStringSidW+ * writes, to *SID for LocalFree. */+unsigned long nova_test_account_sid(const wchar_t *name, wchar_t **sid)+{+    BYTE sid_bytes[SECURITY_MAX_SID_SIZE];+    unsigned long error = account_sid(name, sid_bytes);+    *sid = NULL;+    if (error != 0)+        return error;+    if (!ConvertSidToStringSidW(sid_bytes, sid)) {+        *sid = NULL;+        return GetLastError();+    }+    return 0;+}++/* Make the directory PATH with no security descriptor of its own, as a+ * builder makes one: it takes what its parent passes down, or the+ * token's default DACL where the parent passes nothing down. */+unsigned long nova_test_mkdir(const wchar_t *path)+{+    return CreateDirectoryW(path, NULL) ? 0 : GetLastError();+}++/* Give PATH a protected DACL granting this process's user alone full+ * control, passed down, as a build would to keep its output from the+ * service. */+unsigned long nova_test_lock(const wchar_t *path)+{+    union {+        TOKEN_USER user;+        BYTE bytes[sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE];+    } buffer;+    union {+        ACL acl;+        BYTE bytes[sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + SECURITY_MAX_SID_SIZE];+    } list;+    HANDLE token;+    DWORD size;+    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token))+        return GetLastError();+    if (!GetTokenInformation(token, TokenUser, &buffer, sizeof buffer, &size)) {+        DWORD error = GetLastError();+        CloseHandle(token);+        return error;+    }+    CloseHandle(token);+    if (!InitializeAcl(&list.acl, sizeof list, ACL_REVISION))+        return GetLastError();+    if (!AddAccessAllowedAceEx(&list.acl, ACL_REVISION, OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE, FILE_ALL_ACCESS,+                               buffer.user.User.Sid))+        return GetLastError();+    return SetNamedSecurityInfoW((LPWSTR)path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,+                                 NULL, NULL, &list.acl, NULL);+}++#else++unsigned long nova_test_group_make(const wchar_t *name)+{+    (void)name;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_group_add(const wchar_t *group, const wchar_t *member)+{+    (void)group;+    (void)member;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_group_remove(const wchar_t *name)+{+    (void)name;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_account_sid(const wchar_t *name, wchar_t **sid)+{+    (void)name;+    *sid = NULL;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_mkdir(const wchar_t *path)+{+    (void)path;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_lock(const wchar_t *path)+{+    (void)path;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_account_make(const wchar_t *name, wchar_t **password, const char **failed)+{+    (void)name;+    *password = NULL;+    *failed = "nova_test_account_make";+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_account_remove(const wchar_t *name, const char **failed)+{+    (void)name;+    *failed = "nova_test_account_remove";+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_close_handle(void *handle)+{+    (void)handle;+    return NOT_ON_WINDOWS;+}++void nova_test_local_free(wchar_t *text)+{+    (void)text;+}++unsigned long nova_test_service_install(const wchar_t *name, const wchar_t *command, wchar_t **sid,+                                        const char **failed)+{+    (void)name;+    (void)command;+    *sid = NULL;+    *failed = "nova_test_service_install";+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_service_start(const wchar_t *name)+{+    (void)name;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_service_state(const wchar_t *name, unsigned long *state, unsigned long *code)+{+    (void)name;+    *state = 0;+    *code = 0;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_service_remove(const wchar_t *name, const char **failed)+{+    (void)name;+    *failed = "nova_test_service_remove";+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_service_dispatch(const wchar_t *name, const wchar_t *checks)+{+    (void)name;+    (void)checks;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_account_logon(const wchar_t *name, const wchar_t *password, wchar_t **sid, void **token)+{+    (void)name;+    (void)password;+    *sid = NULL;+    *token = NULL;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_set_sddl(const wchar_t *path, const wchar_t *sddl)+{+    (void)path;+    (void)sddl;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_start_as(void *token, const wchar_t *command, unsigned long *pid)+{+    (void)token;+    (void)command;+    *pid = 0;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_directory_with_sddl(const wchar_t *path, const wchar_t *sddl)+{+    (void)path;+    (void)sddl;+    return NOT_ON_WINDOWS;+}++int nova_test_process_running(unsigned long pid)+{+    (void)pid;+    return -1;+}++unsigned long nova_test_token_user(wchar_t **sid)+{+    *sid = NULL;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_user_object_name(int which, wchar_t *name, unsigned long capacity)+{+    (void)which;+    (void)name;+    (void)capacity;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_logon_id(unsigned long *high, unsigned long *low)+{+    *high = 0;+    *low = 0;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_open_station(const wchar_t *name)+{+    (void)name;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_station_dacl(const wchar_t *name, wchar_t **sddl)+{+    (void)name;+    *sddl = NULL;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_account_processes(const wchar_t *sid_text, wchar_t *text, unsigned long capacity,+                                          unsigned long *count)+{+    (void)sid_text;+    if (capacity > 0)+        text[0] = L'\0';+    *count = 0;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_stdout_value(void)+{+    return 0;+}++unsigned long nova_test_hold_handle(unsigned long pid, unsigned long value)+{+    (void)pid;+    (void)value;+    return NOT_ON_WINDOWS;+}++int nova_test_in_job(void)+{+    return -1;+}++unsigned long nova_test_job_limits(unsigned long *flags)+{+    *flags = 0;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_console(void)+{+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_commit(unsigned long long bytes)+{+    (void)bytes;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_start(const wchar_t *command, unsigned long flags, unsigned long *pid, void **process)+{+    (void)command;+    (void)flags;+    *pid = 0;+    *process = NULL;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_wait(void *process, unsigned long *code)+{+    (void)process;+    *code = 0;+    return NOT_ON_WINDOWS;+}++void nova_test_crash(void)+{+}++unsigned long nova_test_open(const wchar_t *path, unsigned long access)+{+    (void)path;+    (void)access;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_create(const wchar_t *path)+{+    (void)path;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_delete(const wchar_t *path)+{+    (void)path;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_list(const wchar_t *pattern)+{+    (void)pattern;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_open_key(const wchar_t *path)+{+    (void)path;+    return NOT_ON_WINDOWS;+}++unsigned long nova_test_open_process(unsigned long pid)+{+    (void)pid;+    return NOT_ON_WINDOWS;+}++#endif
+ test/cbits/process_wait.c view
@@ -0,0 +1,86 @@+/*+ * The end of a process the test is not the parent of: a process a build+ * left behind, which a build user's kill or a stopped build's kill is to+ * end, is waited for through what refers to it, a pidfd on Linux and a+ * kqueue process filter on macOS, rather than looked at once or polled.+ */++#if defined(__APPLE__)+#define _DARWIN_C_SOURCE+#else+#define _GNU_SOURCE+#endif++#include <errno.h>++#if defined(__linux__)+#include <poll.h>+#include <sys/syscall.h>+#include <unistd.h>+#elif defined(__APPLE__)+#include <stdint.h>+#include <sys/event.h>+#include <sys/time.h>+#include <sys/types.h>+#include <time.h>+#include <unistd.h>+#endif++/* Wait up to TIMEOUT_MS milliseconds for the process PID to end.  Answers+ * 0 once it has ended or when there is no such process, 1 when it is+ * still running at the timeout, or -1 with errno set, ENOSYS where the+ * system has no way to watch a process. */+int nova_test_await_exit(int pid, int timeout_ms)+{+#if defined(__linux__) && defined(SYS_pidfd_open)+    struct pollfd watched;+    int ready;+    int fd = (int)syscall(SYS_pidfd_open, pid, 0);+    if (fd < 0)+        return errno == ESRCH ? 0 : -1;+    watched.fd = fd;+    watched.events = POLLIN;+    watched.revents = 0;+    do {+        ready = poll(&watched, 1, timeout_ms);+    } while (ready < 0 && errno == EINTR);+    close(fd);+    if (ready < 0)+        return -1;+    return ready == 0 ? 1 : 0;+#elif defined(__APPLE__)+    struct kevent change;+    struct kevent event;+    struct timespec limit;+    int queue;+    int ready;+    int saved;+    queue = kqueue();+    if (queue < 0)+        return -1;+    EV_SET(&change, (uintptr_t)pid, EVFILT_PROC, EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, NULL);+    limit.tv_sec = timeout_ms / 1000;+    limit.tv_nsec = (long)(timeout_ms % 1000) * 1000000L;+    /* A process already gone cannot be watched, and has ended. */+    if (kevent(queue, &change, 1, NULL, 0, NULL) < 0) {+        saved = errno;+        close(queue);+        errno = saved;+        return saved == ESRCH ? 0 : -1;+    }+    do {+        ready = kevent(queue, NULL, 0, &event, 1, &limit);+    } while (ready < 0 && errno == EINTR);+    saved = errno;+    close(queue);+    errno = saved;+    if (ready < 0)+        return -1;+    return ready == 0 ? 1 : 0;+#else+    (void)pid;+    (void)timeout_ms;+    errno = ENOSYS;+    return -1;+#endif+}
+ test/cbits/sandbox_check.c view
@@ -0,0 +1,216 @@+/*+ * The sandbox helper's parsers as the test suite calls them: a plan parsed+ * by plan.c and written back in the plan's own token form, and the mount+ * points mountinfo.c finds, so the suite can hold each to what+ * Nix.Builder.Sandbox renders and Nix.Builder.Sandbox.Spawn reads.+ */++#include "mountinfo.h"+#include "plan.h"++#include <errno.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++/* The longest decimal length a token is given, a 64-bit size's. */+#define LENGTH_DIGITS_MAX 20++struct buffer {+    char *bytes;+    size_t used;+    size_t capacity;+};++static int append(struct buffer *buffer, const char *bytes, size_t length)+{+    if (buffer->capacity - buffer->used < length) {+        size_t capacity = buffer->capacity == 0 ? 256 : buffer->capacity;+        char *larger;+        while (capacity - buffer->used < length)+            capacity *= 2;+        larger = realloc(buffer->bytes, capacity);+        if (larger == NULL)+            return 0;+        buffer->bytes = larger;+        buffer->capacity = capacity;+    }+    memcpy(buffer->bytes + buffer->used, bytes, length);+    buffer->used += length;+    return 1;+}++/* Append LENGTH bytes as a length-prefixed item: the length in decimal, a+ * colon and the bytes, then a NUL when TERMINATED, as a plan's tokens+ * end. */+static int append_item(struct buffer *buffer, const char *bytes, size_t length, int terminated)+{+    char prefix[LENGTH_DIGITS_MAX + 2];+    int written = snprintf(prefix, sizeof prefix, "%lu:", (unsigned long)length);+    return written > 0 && append(buffer, prefix, (size_t)written) && append(buffer, bytes, length)+        && (!terminated || append(buffer, "", 1));+}++static int append_token(struct buffer *buffer, const char *token)+{+    return append_item(buffer, token, strlen(token), 1);+}++static int append_number(struct buffer *buffer, unsigned long number)+{+    char text[LENGTH_DIGITS_MAX + 1];+    snprintf(text, sizeof text, "%lu", number);+    return append_token(buffer, text);+}++static int append_bind(struct buffer *buffer, const struct bind *bind)+{+    char flags[4];+    size_t count = 0;+    if (bind->read_only)+        flags[count++] = 'r';+    if (bind->optional)+        flags[count++] = 'o';+    if (bind->canonical)+        flags[count++] = 'c';+    if (count == 0)+        flags[count++] = '-';+    flags[count] = '\0';+    return append_token(buffer, "bind") && append_token(buffer, bind->target) && append_token(buffer, bind->source)+        && append_token(buffer, flags);+}++static int render_linux(struct buffer *buffer, const struct plan *plan)+{+    size_t i;+    if (!(append_token(buffer, "backend") && append_token(buffer, "linux") && append_token(buffer, "root")+          && append_token(buffer, plan->root) && append_token(buffer, "build-dir")+          && append_token(buffer, plan->build_dir) && append_token(buffer, "dev-shm-size")+          && append_token(buffer, plan->dev_shm_size) && append_token(buffer, "sandbox-uid")+          && append_number(buffer, plan->sandbox_uid) && append_token(buffer, "sandbox-gid")+          && append_number(buffer, plan->sandbox_gid) && append_token(buffer, "host-uid")+          && append_number(buffer, plan->host_uid) && append_token(buffer, "host-gid")+          && append_number(buffer, plan->host_gid) && append_token(buffer, "network")+          && append_token(buffer, plan->private_network ? "private" : "host") && append_token(buffer, "drop-groups")+          && append_token(buffer, plan->require_drop_groups ? "require" : "tolerate")))+        return 0;+    for (i = 0; i < plan->bind_count; i++)+        if (!append_bind(buffer, &plan->binds[i]))+            return 0;+    return 1;+}++static int render_darwin(struct buffer *buffer, const struct plan *plan)+{+    size_t i;+    if (!(append_token(buffer, "backend") && append_token(buffer, "darwin") && append_token(buffer, "build-dir")+          && append_token(buffer, plan->build_dir) && append_token(buffer, "profile")+          && append_token(buffer, plan->profile)))+        return 0;+    if (plan->as_build_user) {+        if (!(append_token(buffer, "build-uid") && append_number(buffer, plan->build_uid)+              && append_token(buffer, "build-gid") && append_number(buffer, plan->build_gid)))+            return 0;+    } else if (!(append_token(buffer, "build-uid") && append_token(buffer, "-") && append_token(buffer, "build-gid")+                 && append_token(buffer, "-"))) {+        return 0;+    }+    for (i = 0; i < plan->parameter_count; i++)+        if (!(append_token(buffer, "param") && append_token(buffer, plan->parameters[2 * i])+              && append_token(buffer, plan->parameters[2 * i + 1])))+            return 0;+    return plan->parameters[2 * plan->parameter_count] == NULL;+}++static int render_windows(struct buffer *buffer, const struct plan *plan)+{+    char cap[LENGTH_DIGITS_MAX + 1];+    snprintf(cap, sizeof cap, "%llu", plan->memory_cap);+    return append_token(buffer, "backend") && append_token(buffer, "windows") && append_token(buffer, "build-dir")+        && append_token(buffer, plan->build_dir) && append_token(buffer, "token")+        && append_number(buffer, plan->token_handle) && append_token(buffer, "slot-sid")+        && append_token(buffer, plan->slot_sid) && append_token(buffer, "memory-cap") && append_token(buffer, cap);+}++static int render_backend(struct buffer *buffer, const struct plan *plan)+{+    switch (plan->backend) {+    case PLAN_LINUX:+        return render_linux(buffer, plan);+    case PLAN_DARWIN:+        return render_darwin(buffer, plan);+    case PLAN_WINDOWS:+        return render_windows(buffer, plan);+    }+    return 0;+}++static int render(struct buffer *buffer, const struct plan *plan)+{+    size_t i;+    if (!render_backend(buffer, plan))+        return 0;+    for (i = 0; i < plan->environment_count; i++)+        if (!append_token(buffer, "env") || !append_token(buffer, plan->environment[i]))+            return 0;+    return plan->environment[plan->environment_count] == NULL;+}++/* Parse the LENGTH bytes of a plan's tokens at BYTES and write the plan+ * parsed back as tokens, in a buffer for the caller to free.  Answers 0,+ * or plan_parse's errno value. */+int nova_test_plan_echo(const char *bytes, size_t length, char **out, size_t *out_length)+{+    struct plan plan;+    struct buffer rendered = {NULL, 0, 0};+    char *copy = malloc(length > 0 ? length : 1);+    int error;+    if (copy == NULL)+        return ENOMEM;+    memcpy(copy, bytes, length);+    error = plan_parse(copy, length, &plan);+    if (error == 0) {+        if (!render(&rendered, &plan))+            error = ENOMEM;+        plan_release(&plan);+    }+    free(copy);+    if (error != 0) {+        free(rendered.bytes);+        return error;+    }+    *out = rendered.bytes;+    *out_length = rendered.used;+    return 0;+}++/* The mount points at or beneath DIR in a mountinfo text, each written+ * length-prefixed, with no terminator, in a buffer for the caller to free.+ * Answers 0, or ENOMEM. */+int nova_test_mountinfo_within(const char *text, size_t length, const char *dir, size_t dir_length, char **out,+                               size_t *out_length)+{+    struct mountinfo_cursor cursor;+    struct buffer found = {NULL, 0, 0};+    size_t capacity = length + 1;+    char *point = malloc(capacity);+    size_t point_length = 0;+    int error = 0;+    if (point == NULL)+        return ENOMEM;+    cursor.next = text;+    cursor.end = text + length;+    while (mountinfo_next_within(&cursor, dir, dir_length, point, capacity, &point_length) == MOUNTINFO_FOUND)+        if (!append_item(&found, point, point_length, 0)) {+            error = ENOMEM;+            break;+        }+    free(point);+    if (error != 0) {+        free(found.bytes);+        return error;+    }+    *out = found.bytes;+    *out_length = found.used;+    return 0;+}