diff --git a/doc/stdenv.xml b/doc/stdenv.xml
index 68441ea9393ab..34566dc9988d1 100644
--- a/doc/stdenv.xml
+++ b/doc/stdenv.xml
@@ -1008,6 +1008,15 @@ installcheck.
in the derivation to enable install checks.
+
+ noErrorBuildTop
+ Allow outputs to capture references to the build
+ directory. Normally, all outputs are scanned for references to
+ the build directory and the build aborted if any are found. Such
+ references are most likely accidental and may make the build
+ non-reproducible.
+
+
preInstallCheck
Hook executed at the start of the installCheck
diff --git a/pkgs/stdenv/generic/setup.sh b/pkgs/stdenv/generic/setup.sh
index 154fdefd789c7..0bf75c8614f3b 100644
--- a/pkgs/stdenv/generic/setup.sh
+++ b/pkgs/stdenv/generic/setup.sh
@@ -794,6 +794,16 @@ installCheckPhase() {
$makeFlags "${makeFlagsArray[@]}" \
$installCheckFlags "${installCheckFlagsArray[@]}" ${installCheckTarget:-installcheck}
+ if [ -z "$noErrorBuildTop" -a "$NIX_ENFORCE_PURITY" = "1" -a -n "$NIX_BUILD_TOP" ]; then
+ for output in $outputs; do
+ if grep -qr $NIX_BUILD_TOP ${!output} ; then
+ echo "ERROR: found reference to build path $NIX_BUILD_TOP in the following files"
+ grep -lr $NIX_BUILD_TOP ${!output}
+ exit 1
+ fi
+ done
+ done
+
runHook postInstallCheck
}