about summary refs log tree commit diff
path: root/pkgs/build-support
diff options
context:
space:
mode:
authorJohn Ericson <John.Ericson@Obsidian.Systems>2019-11-24 17:25:07 +0000
committerJohn Ericson <John.Ericson@Obsidian.Systems>2019-11-24 17:25:07 +0000
commitd0d5136cce5e0cbe2305c53090bd4bd886114746 (patch)
tree70092947536a3c65e215df9df20e571e34652f7a /pkgs/build-support
parent9b090ccbca3f7dd26d91db06e96e8bf8282c37ca (diff)
parent195c263a812dec532656dcfd5d0360458cdc93fd (diff)
downloadnixlib-d0d5136cce5e0cbe2305c53090bd4bd886114746.tar
nixlib-d0d5136cce5e0cbe2305c53090bd4bd886114746.tar.gz
nixlib-d0d5136cce5e0cbe2305c53090bd4bd886114746.tar.bz2
nixlib-d0d5136cce5e0cbe2305c53090bd4bd886114746.tar.lz
nixlib-d0d5136cce5e0cbe2305c53090bd4bd886114746.tar.xz
nixlib-d0d5136cce5e0cbe2305c53090bd4bd886114746.tar.zst
nixlib-d0d5136cce5e0cbe2305c53090bd4bd886114746.zip
Merge remote-tracking branch 'upstream/master' into wrapper-pname-support
Diffstat (limited to 'pkgs/build-support')
-rw-r--r--pkgs/build-support/appimage/default.nix2
-rw-r--r--pkgs/build-support/bintools-wrapper/default.nix13
-rw-r--r--pkgs/build-support/bintools-wrapper/setup-hook.sh11
-rw-r--r--pkgs/build-support/build-bazel-package/default.nix1
-rw-r--r--pkgs/build-support/build-dotnet-package/default.nix8
-rwxr-xr-xpkgs/build-support/buildenv/builder.pl16
-rw-r--r--pkgs/build-support/cc-wrapper/cc-wrapper.sh11
-rw-r--r--pkgs/build-support/cc-wrapper/default.nix4
-rw-r--r--pkgs/build-support/cc-wrapper/setup-hook.sh3
-rw-r--r--pkgs/build-support/docker/default.nix7
-rw-r--r--pkgs/build-support/emacs/setup-hook.sh6
-rw-r--r--pkgs/build-support/emacs/wrapper.nix209
-rw-r--r--pkgs/build-support/fetchgit/private.nix26
-rw-r--r--pkgs/build-support/kernel/make-initrd.nix19
-rw-r--r--pkgs/build-support/nix-prefetch-github/default.nix29
-rw-r--r--pkgs/build-support/nuke-references/default.nix5
-rw-r--r--pkgs/build-support/ocaml/default.nix2
-rw-r--r--pkgs/build-support/rust/build-rust-crate/build-crate.nix4
-rw-r--r--pkgs/build-support/rust/build-rust-crate/configure-crate.nix6
-rw-r--r--pkgs/build-support/rust/build-rust-crate/default.nix24
-rw-r--r--pkgs/build-support/rust/build-rust-crate/test/default.nix26
-rw-r--r--pkgs/build-support/rust/cargo-vendor/cargo-vendor.nix693
-rw-r--r--pkgs/build-support/rust/cargo-vendor/default.nix10
-rw-r--r--pkgs/build-support/rust/default-crate-overrides.nix5
-rw-r--r--pkgs/build-support/rust/default.nix35
-rw-r--r--pkgs/build-support/rust/fetchcargo.nix22
-rw-r--r--pkgs/build-support/setup-hooks/audit-tmpdir.sh2
-rw-r--r--pkgs/build-support/setup-hooks/auto-patchelf.sh2
-rw-r--r--pkgs/build-support/setup-hooks/compress-man-pages.sh2
-rw-r--r--pkgs/build-support/setup-hooks/find-xml-catalogs.sh4
-rw-r--r--pkgs/build-support/setup-hooks/make-wrapper.sh9
-rw-r--r--pkgs/build-support/setup-hooks/move-lib64.sh2
-rw-r--r--pkgs/build-support/setup-hooks/move-sbin.sh2
-rw-r--r--pkgs/build-support/setup-hooks/multiple-outputs.sh6
-rw-r--r--pkgs/build-support/setup-hooks/patch-shebangs.sh2
-rw-r--r--pkgs/build-support/setup-hooks/prune-libtool-files.sh2
-rw-r--r--pkgs/build-support/setup-hooks/strip.sh4
-rw-r--r--pkgs/build-support/setup-hooks/update-autotools-gnu-config-scripts.sh2
-rw-r--r--pkgs/build-support/setup-hooks/wrap-gapps-hook.sh28
-rw-r--r--pkgs/build-support/skaware/build-skaware-package.nix6
-rw-r--r--pkgs/build-support/vm/default.nix4
-rw-r--r--pkgs/build-support/writers/default.nix4
-rw-r--r--pkgs/build-support/writers/test.nix30
43 files changed, 320 insertions, 988 deletions
diff --git a/pkgs/build-support/appimage/default.nix b/pkgs/build-support/appimage/default.nix
index 1f84403c10fc..c871df787b7e 100644
--- a/pkgs/build-support/appimage/default.nix
+++ b/pkgs/build-support/appimage/default.nix
@@ -185,10 +185,12 @@ rec {
       keyutils.lib
       libjack2
       fribidi
+      p11-kit
 
       # libraries not on the upstream include list, but nevertheless expected
       # by at least one appimage
       libtool.lib # for Synfigstudio
+      at-spi2-core
     ];
   };
 }
diff --git a/pkgs/build-support/bintools-wrapper/default.nix b/pkgs/build-support/bintools-wrapper/default.nix
index 2a039513d2f6..3fcbe105c008 100644
--- a/pkgs/build-support/bintools-wrapper/default.nix
+++ b/pkgs/build-support/bintools-wrapper/default.nix
@@ -111,17 +111,13 @@ stdenv.mkDerivation {
 
   installPhase =
     ''
-      set -u
-
       mkdir -p $out/bin $out/nix-support
 
       wrap() {
         local dst="$1"
         local wrapper="$2"
         export prog="$3"
-        set +u
         substituteAll "$wrapper" "$out/bin/$dst"
-        set -u
         chmod +x "$out/bin/$dst"
       }
     ''
@@ -163,8 +159,6 @@ stdenv.mkDerivation {
         [[ -e "$underlying" ]] || continue
         wrap ${targetPrefix}$variant ${./ld-wrapper.sh} $underlying
       done
-
-      set +u
     '';
 
   emulation = let
@@ -205,11 +199,7 @@ stdenv.mkDerivation {
   ];
 
   postFixup =
-    ''
-      set -u
-    ''
-
-    + optionalString (libc != null) (''
+    optionalString (libc != null) (''
       ##
       ## General libc support
       ##
@@ -307,7 +297,6 @@ stdenv.mkDerivation {
     ''
 
     + ''
-      set +u
       substituteAll ${./add-flags.sh} $out/nix-support/add-flags.sh
       substituteAll ${./add-hardening.sh} $out/nix-support/add-hardening.sh
       substituteAll ${../wrapper-common/utils.bash} $out/nix-support/utils.bash
diff --git a/pkgs/build-support/bintools-wrapper/setup-hook.sh b/pkgs/build-support/bintools-wrapper/setup-hook.sh
index f65b792485a0..a714bd151c90 100644
--- a/pkgs/build-support/bintools-wrapper/setup-hook.sh
+++ b/pkgs/build-support/bintools-wrapper/setup-hook.sh
@@ -2,8 +2,6 @@
 #
 # See comments in cc-wrapper's setup hook. This works exactly the same way.
 
-set -u
-
 # Skip setup hook if we're neither a build-time dep, nor, temporarily, doing a
 # native compile.
 #
@@ -24,7 +22,8 @@ bintoolsWrapper_addLDVars () {
         # Python and Haskell packages often only have directories like $out/lib/ghc-8.4.3/ or
         # $out/lib/python3.6/, so having them in LDFLAGS just makes the linker search unnecessary
         # directories and bloats the size of the environment variable space.
-        if [[ -n "$(echo $1/lib/lib*)" ]]; then
+        local -a glob=( $1/lib/lib* )
+        if [ "${#glob[*]}" -gt 0 ]; then
             export NIX_${role_pre}LDFLAGS+=" -L$1/lib"
         fi
     fi
@@ -61,9 +60,8 @@ do
     if
         PATH=$_PATH type -p "@targetPrefix@${cmd}" > /dev/null
     then
-        upper_case="$(echo "$cmd" | tr "[:lower:]" "[:upper:]")"
-        export "${role_pre}${upper_case}=@targetPrefix@${cmd}";
-        export "${upper_case}${role_post}=@targetPrefix@${cmd}";
+        export "${role_pre}${cmd^^}=@targetPrefix@${cmd}";
+        export "${cmd^^}${role_post}=@targetPrefix@${cmd}";
     fi
 done
 
@@ -73,4 +71,3 @@ export NIX_HARDENING_ENABLE
 
 # No local scope in sourced file
 unset -v role_pre role_post cmd upper_case
-set +u
diff --git a/pkgs/build-support/build-bazel-package/default.nix b/pkgs/build-support/build-bazel-package/default.nix
index d4318b715ba3..a1a38484386d 100644
--- a/pkgs/build-support/build-bazel-package/default.nix
+++ b/pkgs/build-support/build-bazel-package/default.nix
@@ -60,6 +60,7 @@ in stdenv.mkDerivation (fBuildAttrs // {
 
       # Remove all built in external workspaces, Bazel will recreate them when building
       rm -rf $bazelOut/external/{bazel_tools,\@bazel_tools.marker}
+      rm -rf $bazelOut/external/{rules_cc,\@rules_cc.marker}
       rm -rf $bazelOut/external/{embedded_jdk,\@embedded_jdk.marker}
       rm -rf $bazelOut/external/{local_*,\@local_*.marker}
 
diff --git a/pkgs/build-support/build-dotnet-package/default.nix b/pkgs/build-support/build-dotnet-package/default.nix
index f36c69e43392..dae9ed888c75 100644
--- a/pkgs/build-support/build-dotnet-package/default.nix
+++ b/pkgs/build-support/build-dotnet-package/default.nix
@@ -29,9 +29,9 @@ attrsOrig @
       configurePhase = ''
         runHook preConfigure
 
-        [ -z "$dontPlacateNuget" ] && placate-nuget.sh
-        [ -z "$dontPlacatePaket" ] && placate-paket.sh
-        [ -z "$dontPatchFSharpTargets" ] && patch-fsharp-targets.sh
+        [ -z "''${dontPlacateNuget-}" ] && placate-nuget.sh
+        [ -z "''${dontPlacatePaket-}" ] && placate-paket.sh
+        [ -z "''${dontPatchFSharpTargets-}" ] && patch-fsharp-targets.sh
 
         runHook postConfigure
       '';
@@ -69,7 +69,7 @@ attrsOrig @
 
         cp -rv ${arrayToShell outputFiles} "''${outputFilesArray[@]}" "$target"
 
-        if [ -z "$dontRemoveDuplicatedDlls" ]
+        if [ -z "''${dontRemoveDuplicatedDlls-}" ]
         then
           pushd "$out"
           remove-duplicated-dlls.sh
diff --git a/pkgs/build-support/buildenv/builder.pl b/pkgs/build-support/buildenv/builder.pl
index b699d762d29c..fc6ffce735cc 100755
--- a/pkgs/build-support/buildenv/builder.pl
+++ b/pkgs/build-support/buildenv/builder.pl
@@ -26,6 +26,19 @@ sub isInPathsToLink {
     return 0;
 }
 
+# Returns whether a path in one of the linked packages may contain
+# files in one of the elements of pathsToLink.
+sub hasPathsToLink {
+    my $path = shift;
+    foreach my $elem (@pathsToLink) {
+        return 1 if
+            $path eq "" ||
+            (substr($elem, 0, length($path)) eq $path
+             && (($path eq $elem) || (substr($elem, length($path), 1) eq "/")));
+    }
+    return 0;
+}
+
 # Similar to `lib.isStorePath`
 sub isStorePath {
     my $path = shift;
@@ -103,7 +116,8 @@ sub findFiles {
         $relName =~ /info\/dir/ ||
         ( $relName =~ /^\/share\/mime\// && !( $relName =~ /^\/share\/mime\/packages/ ) ) ||
         $baseName eq "perllocal.pod" ||
-        $baseName eq "log";
+        $baseName eq "log" ||
+        ! (hasPathsToLink($relName) || isInPathsToLink($relName));
 
     my ($oldTarget, $oldPriority) = @{$symlinks{$relName} // [undef, undef]};
 
diff --git a/pkgs/build-support/cc-wrapper/cc-wrapper.sh b/pkgs/build-support/cc-wrapper/cc-wrapper.sh
index bb7890100087..ba3dfc96f5c4 100644
--- a/pkgs/build-support/cc-wrapper/cc-wrapper.sh
+++ b/pkgs/build-support/cc-wrapper/cc-wrapper.sh
@@ -33,6 +33,7 @@ fi
 # GCC prints annoying warnings when they are not needed.
 dontLink=0
 nonFlagArgs=0
+cc1=0
 # shellcheck disable=SC2193
 [[ "@prog@" = *++ ]] && isCpp=1 || isCpp=0
 cppInclude=1
@@ -68,6 +69,8 @@ while (( "$n" < "$nParams" )); do
     elif [[ "$p" != -?* ]]; then
         # A dash alone signifies standard input; it is not a flag
         nonFlagArgs=1
+    elif [ "$p" = -cc1 ]; then
+        cc1=1
     fi
     n+=1
 done
@@ -167,6 +170,14 @@ if [ "$*" = -v ]; then
     extraBefore=()
 fi
 
+# clang's -cc1 mode is not compatible with most options
+# that we would pass. Rather than trying to pass only
+# options that would work, let's just remove all of them.
+if [ "$cc1" = 1 ]; then
+  extraAfter=()
+  extraBefore=()
+fi
+
 # Optionally print debug info.
 if (( "${NIX_DEBUG:-0}" >= 1 )); then
     # Old bash workaround, see ld-wrapper for explanation.
diff --git a/pkgs/build-support/cc-wrapper/default.nix b/pkgs/build-support/cc-wrapper/default.nix
index 9851602179cb..d02f47fde8cd 100644
--- a/pkgs/build-support/cc-wrapper/default.nix
+++ b/pkgs/build-support/cc-wrapper/default.nix
@@ -134,8 +134,6 @@ stdenv.mkDerivation {
 
   installPhase =
     ''
-      set -u
-
       mkdir -p $out/bin $out/nix-support
 
       wrap() {
@@ -224,8 +222,6 @@ stdenv.mkDerivation {
 
   postFixup =
     ''
-      set -u
-
       # Backwards compatability for packages expecting this file, e.g. with
       # `$NIX_CC/nix-support/dynamic-linker`.
       #
diff --git a/pkgs/build-support/cc-wrapper/setup-hook.sh b/pkgs/build-support/cc-wrapper/setup-hook.sh
index 211b50632914..5b13f2683097 100644
--- a/pkgs/build-support/cc-wrapper/setup-hook.sh
+++ b/pkgs/build-support/cc-wrapper/setup-hook.sh
@@ -54,8 +54,6 @@
 # For more details, read the individual files where the mechanisms used to
 # accomplish this will be individually documented.
 
-set -u
-
 # Skip setup hook if we're neither a build-time dep, nor, temporarily, doing a
 # native compile.
 #
@@ -120,4 +118,3 @@ export NIX_HARDENING_ENABLE
 
 # No local scope in sourced file
 unset -v role_pre role_post
-set +u
diff --git a/pkgs/build-support/docker/default.nix b/pkgs/build-support/docker/default.nix
index 83e21c8945dc..37b25232b961 100644
--- a/pkgs/build-support/docker/default.nix
+++ b/pkgs/build-support/docker/default.nix
@@ -1,4 +1,5 @@
 {
+  buildPackages,
   cacert,
   callPackage,
   closureInfo,
@@ -47,7 +48,7 @@ rec {
     , imageDigest
     , sha256
     , os ? "linux"
-    , arch ? "amd64"
+    , arch ? buildPackages.go.GOARCH
 
       # This is used to set name to the pulled image
     , finalImageName ? imageName
@@ -540,7 +541,7 @@ rec {
       configJson = let
           pure = writeText "${baseName}-config.json" (builtins.toJSON {
             inherit created config;
-            architecture = "amd64";
+            architecture = buildPackages.go.GOARCH;
             os = "linux";
           });
           impure = runCommand "${baseName}-standard-dynamic-date.json"
@@ -658,7 +659,7 @@ rec {
       baseJson = let
           pure = writeText "${baseName}-config.json" (builtins.toJSON {
             inherit created config;
-            architecture = "amd64";
+            architecture = buildPackages.go.GOARCH;
             os = "linux";
           });
           impure = runCommand "${baseName}-config.json"
diff --git a/pkgs/build-support/emacs/setup-hook.sh b/pkgs/build-support/emacs/setup-hook.sh
index e1db3e828fd7..b210511d670d 100644
--- a/pkgs/build-support/emacs/setup-hook.sh
+++ b/pkgs/build-support/emacs/setup-hook.sh
@@ -1,11 +1,13 @@
 addEmacsVars () {
   if test -d $1/share/emacs/site-lisp; then
-      export EMACSLOADPATH="$1/share/emacs/site-lisp:$EMACSLOADPATH"
+      # it turns out, that the trailing : is actually required
+      # see https://www.gnu.org/software/emacs/manual/html_node/elisp/Library-Search.html
+      export EMACSLOADPATH="$1/share/emacs/site-lisp:${EMACSLOADPATH-}"
   fi
 }
 
 # If this is for a wrapper derivation, emacs and the dependencies are all
 # run-time dependencies. If this is for precompiling packages into bytecode,
 # emacs is a compile-time dependency of the package.
-addEnvHooks "$targetOffset" addEmacsVars
+addEnvHooks "$hostOffset" addEmacsVars
 addEnvHooks "$targetOffset" addEmacsVars
diff --git a/pkgs/build-support/emacs/wrapper.nix b/pkgs/build-support/emacs/wrapper.nix
index b242672df10b..25f068cd3fa0 100644
--- a/pkgs/build-support/emacs/wrapper.nix
+++ b/pkgs/build-support/emacs/wrapper.nix
@@ -32,7 +32,7 @@ in customEmacsPackages.emacsWithPackages (epkgs: [ epkgs.evil epkgs.magit ])
 
 */
 
-{ lib, lndir, makeWrapper, runCommand, stdenv }: self:
+{ lib, lndir, makeWrapper, runCommand }: self:
 
 with lib; let inherit (self) emacs; in
 
@@ -45,105 +45,110 @@ let
     else packagesFun;
 in
 
-stdenv.mkDerivation {
-  name = (appendToName "with-packages" emacs).name;
-  nativeBuildInputs = [ emacs lndir makeWrapper ];
-  inherit emacs explicitRequires;
-
-  # Store all paths we want to add to emacs here, so that we only need to add
-  # one path to the load lists
-  deps = runCommand "emacs-packages-deps"
-   { inherit explicitRequires lndir emacs; }
-   ''
-     findInputsOld() {
-         local pkg="$1"; shift
-         local var="$1"; shift
-         local propagatedBuildInputsFiles=("$@")
-
-         # TODO(@Ericson2314): Restore using associative array once Darwin
-         # nix-shell doesn't use impure bash. This should replace the O(n)
-         # case with an O(1) hash map lookup, assuming bash is implemented
-         # well :D.
-         local varSlice="$var[*]"
-         # ''${..-} to hack around old bash empty array problem
-         case "''${!varSlice-}" in
-             *" $pkg "*) return 0 ;;
-         esac
-         unset -v varSlice
-
-         eval "$var"'+=("$pkg")'
-
-         if ! [ -e "$pkg" ]; then
-             echo "build input $pkg does not exist" >&2
-             exit 1
-         fi
-
-         local file
-         for file in "''${propagatedBuildInputsFiles[@]}"; do
-             file="$pkg/nix-support/$file"
-             [[ -f "$file" ]] || continue
-
-             local pkgNext
-             for pkgNext in $(< "$file"); do
-                 findInputsOld "$pkgNext" "$var" "''${propagatedBuildInputsFiles[@]}"
-             done
-         done
-     }
-     mkdir -p $out/bin
-     mkdir -p $out/share/emacs/site-lisp
-
-     local requires
-     for pkg in $explicitRequires; do
-       findInputsOld $pkg requires propagated-user-env-packages
-     done
-     # requires now holds all requested packages and their transitive dependencies
-
-     linkPath() {
-       local pkg=$1
-       local origin_path=$2
-       local dest_path=$3
-
-       # Add the path to the search path list, but only if it exists
-       if [[ -d "$pkg/$origin_path" ]]; then
-         $lndir/bin/lndir -silent "$pkg/$origin_path" "$out/$dest_path"
-       fi
-     }
-
-     linkEmacsPackage() {
-       linkPath "$1" "bin" "bin"
-       linkPath "$1" "share/emacs/site-lisp" "share/emacs/site-lisp"
-     }
-
-     # Iterate over the array of inputs (avoiding nix's own interpolation)
-     for pkg in "''${requires[@]}"; do
-       linkEmacsPackage $pkg
-     done
-
-     siteStart="$out/share/emacs/site-lisp/site-start.el"
-     siteStartByteCompiled="$siteStart"c
-     subdirs="$out/share/emacs/site-lisp/subdirs.el"
-     subdirsByteCompiled="$subdirs"c
-
-     # A dependency may have brought the original siteStart or subdirs, delete
-     # it and create our own
-     # Begin the new site-start.el by loading the original, which sets some
-     # NixOS-specific paths. Paths are searched in the reverse of the order
-     # they are specified in, so user and system profile paths are searched last.
-     rm -f $siteStart $siteStartByteCompiled $subdirs $subdirsByteCompiled
-     cat >"$siteStart" <<EOF
-(load-file "$emacs/share/emacs/site-lisp/site-start.el")
-(add-to-list 'load-path "$out/share/emacs/site-lisp")
-(add-to-list 'exec-path "$out/bin")
-EOF
-      # Link subdirs.el from the emacs distribution
-      ln -s $emacs/share/emacs/site-lisp/subdirs.el -T $subdirs
-
-     # Byte-compiling improves start-up time only slightly, but costs nothing.
-     $emacs/bin/emacs --batch -f batch-byte-compile "$siteStart" "$subdirs"
-  '';
-
-  phases = [ "installPhase" ];
-  installPhase = ''
+runCommand
+  (appendToName "with-packages" emacs).name
+  {
+    nativeBuildInputs = [ emacs lndir makeWrapper ];
+    inherit emacs explicitRequires;
+
+    preferLocalBuild = true;
+    allowSubstitutes = false;
+
+    # Store all paths we want to add to emacs here, so that we only need to add
+    # one path to the load lists
+    deps = runCommand "emacs-packages-deps"
+      { inherit explicitRequires lndir emacs; }
+      ''
+        findInputsOld() {
+          local pkg="$1"; shift
+          local var="$1"; shift
+          local propagatedBuildInputsFiles=("$@")
+
+          # TODO(@Ericson2314): Restore using associative array once Darwin
+          # nix-shell doesn't use impure bash. This should replace the O(n)
+          # case with an O(1) hash map lookup, assuming bash is implemented
+          # well :D.
+          local varSlice="$var[*]"
+          # ''${..-} to hack around old bash empty array problem
+          case "''${!varSlice-}" in
+              *" $pkg "*) return 0 ;;
+          esac
+          unset -v varSlice
+
+          eval "$var"'+=("$pkg")'
+
+          if ! [ -e "$pkg" ]; then
+              echo "build input $pkg does not exist" >&2
+              exit 1
+          fi
+
+          local file
+          for file in "''${propagatedBuildInputsFiles[@]}"; do
+              file="$pkg/nix-support/$file"
+              [[ -f "$file" ]] || continue
+
+              local pkgNext
+              for pkgNext in $(< "$file"); do
+                  findInputsOld "$pkgNext" "$var" "''${propagatedBuildInputsFiles[@]}"
+              done
+          done
+        }
+        mkdir -p $out/bin
+        mkdir -p $out/share/emacs/site-lisp
+
+        local requires
+        for pkg in $explicitRequires; do
+          findInputsOld $pkg requires propagated-user-env-packages
+        done
+        # requires now holds all requested packages and their transitive dependencies
+
+        linkPath() {
+          local pkg=$1
+          local origin_path=$2
+          local dest_path=$3
+
+          # Add the path to the search path list, but only if it exists
+          if [[ -d "$pkg/$origin_path" ]]; then
+            $lndir/bin/lndir -silent "$pkg/$origin_path" "$out/$dest_path"
+          fi
+        }
+
+        linkEmacsPackage() {
+          linkPath "$1" "bin" "bin"
+          linkPath "$1" "share/emacs/site-lisp" "share/emacs/site-lisp"
+        }
+
+        # Iterate over the array of inputs (avoiding nix's own interpolation)
+        for pkg in "''${requires[@]}"; do
+          linkEmacsPackage $pkg
+        done
+
+        siteStart="$out/share/emacs/site-lisp/site-start.el"
+        siteStartByteCompiled="$siteStart"c
+        subdirs="$out/share/emacs/site-lisp/subdirs.el"
+        subdirsByteCompiled="$subdirs"c
+
+        # A dependency may have brought the original siteStart or subdirs, delete
+        # it and create our own
+        # Begin the new site-start.el by loading the original, which sets some
+        # NixOS-specific paths. Paths are searched in the reverse of the order
+        # they are specified in, so user and system profile paths are searched last.
+        rm -f $siteStart $siteStartByteCompiled $subdirs $subdirsByteCompiled
+        cat >"$siteStart" <<EOF
+        (load-file "$emacs/share/emacs/site-lisp/site-start.el")
+        (add-to-list 'load-path "$out/share/emacs/site-lisp")
+        (add-to-list 'exec-path "$out/bin")
+        EOF
+        # Link subdirs.el from the emacs distribution
+        ln -s $emacs/share/emacs/site-lisp/subdirs.el -T $subdirs
+
+        # Byte-compiling improves start-up time only slightly, but costs nothing.
+        $emacs/bin/emacs --batch -f batch-byte-compile "$siteStart" "$subdirs"
+      '';
+
+    inherit (emacs) meta;
+  }
+  ''
     mkdir -p "$out/bin"
 
     # Wrap emacs and friends so they find our site-start.el before the original.
@@ -172,6 +177,4 @@ EOF
     for dir in applications icons info man; do
       ln -s $emacs/share/$dir $out/share/$dir
     done
-  '';
-  inherit (emacs) meta;
-}
+  ''
diff --git a/pkgs/build-support/fetchgit/private.nix b/pkgs/build-support/fetchgit/private.nix
deleted file mode 100644
index 6731cf87fbd1..000000000000
--- a/pkgs/build-support/fetchgit/private.nix
+++ /dev/null
@@ -1,26 +0,0 @@
-{ fetchgit, runCommand, makeWrapper, openssh }: args: derivation ((fetchgit args).drvAttrs // {
-  SSH_AUTH_SOCK = if (builtins.tryEval <ssh-auth-sock>).success
-    then builtins.toString <ssh-auth-sock>
-    else null;
-
-  GIT_SSH = let
-    config = let
-        sshConfigFile = if (builtins.tryEval <ssh-config-file>).success
-          then <ssh-config-file>
-          else builtins.trace ''
-            Please set your nix-path such that ssh-config-file points to a file that will allow ssh to access private repositories. The builder will not be able to see any running ssh agent sessions unless ssh-auth-sock is also set in the nix-path.
-
-            Note that the config file and any keys it points to must be readable by the build user, which depending on your nix configuration means making it readable by the build-users-group, the user of the running nix-daemon, or the user calling the nix command which started the build. Similarly, if using an ssh agent ssh-auth-sock must point to a socket the build user can access.
-
-            You may need StrictHostKeyChecking=no in the config file. Since ssh will refuse to use a group-readable private key, if using build-users you will likely want to use something like IdentityFile /some/directory/%u/key and have a directory for each build user accessible to that user.
-          '' "/var/lib/empty/config";
-      in builtins.toString sshConfigFile;
-
-    ssh-wrapped = runCommand "fetchgit-ssh" {
-      nativeBuildInputs = [ makeWrapper ];
-    } ''
-      mkdir -p $out/bin
-      makeWrapper ${openssh}/bin/ssh $out/bin/ssh --prefix PATH : "$out/bin" --add-flags "-F ${config}" "$@"
-    '';
-  in "${ssh-wrapped}/bin/ssh";
-})
diff --git a/pkgs/build-support/kernel/make-initrd.nix b/pkgs/build-support/kernel/make-initrd.nix
index 7a5642e565de..ed5dbdaee171 100644
--- a/pkgs/build-support/kernel/make-initrd.nix
+++ b/pkgs/build-support/kernel/make-initrd.nix
@@ -12,26 +12,26 @@
 # `contents = {object = ...; symlink = /init;}' is a typical
 # argument.
 
-{ stdenv, perl, cpio, contents, ubootTools
+{ stdenvNoCC, perl, cpio, contents, ubootTools
 , name ? "initrd"
 , compressor ? "gzip -9n"
 , prepend ? []
 , lib
 }:
-let 
+let
   # !!! Move this into a public lib function, it is probably useful for others
-  toValidStoreName = x: with builtins; 
+  toValidStoreName = x: with builtins;
     lib.concatStringsSep "-" (filter (x: !(isList x)) (split "[^a-zA-Z0-9_=.?-]+" x));
 
-in stdenv.mkDerivation rec {
+in stdenvNoCC.mkDerivation rec {
   inherit name;
 
   builder = ./make-initrd.sh;
 
-  makeUInitrd = stdenv.hostPlatform.platform.kernelTarget == "uImage";
+  makeUInitrd = stdenvNoCC.hostPlatform.platform.kernelTarget == "uImage";
 
   nativeBuildInputs = [ perl cpio ]
-    ++ stdenv.lib.optional makeUInitrd ubootTools;
+    ++ stdenvNoCC.lib.optional makeUInitrd ubootTools;
 
   # !!! should use XML.
   objects = map (x: x.object) contents;
@@ -42,12 +42,11 @@ in stdenv.mkDerivation rec {
   # Note: we don't use closureInfo yet, as that won't build with nix-1.x.
   # See #36268.
   exportReferencesGraph =
-    lib.zipListsWith 
-      (x: i: [("closure-${toValidStoreName (baseNameOf x.symlink)}-${toString i}") x.object]) 
-      contents 
+    lib.zipListsWith
+      (x: i: [("closure-${toValidStoreName (baseNameOf x.symlink)}-${toString i}") x.object])
+      contents
       (lib.range 0 (lib.length contents - 1));
   pathsFromGraph = ./paths-from-graph.pl;
 
   inherit compressor prepend;
 }
-
diff --git a/pkgs/build-support/nix-prefetch-github/default.nix b/pkgs/build-support/nix-prefetch-github/default.nix
deleted file mode 100644
index 10a6daaf53f7..000000000000
--- a/pkgs/build-support/nix-prefetch-github/default.nix
+++ /dev/null
@@ -1,29 +0,0 @@
-{ python3
-, fetchFromGitHub
-, stdenv
-}:
-
-python3.pkgs.buildPythonApplication rec {
-  pname = "nix-prefetch-github";
-  version = "2.3.1";
-
-  src = fetchFromGitHub {
-    owner = "seppeljordan";
-    repo = "nix-prefetch-github";
-    rev = "v${version}";
-    sha256 = "13wvq13iiva97a16kahfpxar5ppb015nnbn7d4v9s9jyxdickc2c";
-  };
-
-  propagatedBuildInputs = with python3.pkgs; [
-    attrs
-    click
-    effect
-    jinja2
-  ];
-  meta = with stdenv.lib; {
-    description = "Prefetch sources from github";
-    homepage = https://github.com/seppeljordan/nix-prefetch-github;
-    license = licenses.gpl3;
-    maintainers = [ maintainers.seppeljordan ];
-  };
-}
diff --git a/pkgs/build-support/nuke-references/default.nix b/pkgs/build-support/nuke-references/default.nix
index 8f976ad462cc..d894b56d366a 100644
--- a/pkgs/build-support/nuke-references/default.nix
+++ b/pkgs/build-support/nuke-references/default.nix
@@ -3,10 +3,11 @@
 # path (/nix/store/eeee...).  This is useful for getting rid of
 # dependencies that you know are not actually needed at runtime.
 
-{ stdenv, perl }:
+{ stdenvNoCC, perl }:
 
-stdenv.mkDerivation {
+stdenvNoCC.mkDerivation {
   name = "nuke-references";
   builder = ./builder.sh;
+  # FIXME: get rid of perl dependency.
   inherit perl;
 }
diff --git a/pkgs/build-support/ocaml/default.nix b/pkgs/build-support/ocaml/default.nix
index cc2001c66e2e..3957b955a2c6 100644
--- a/pkgs/build-support/ocaml/default.nix
+++ b/pkgs/build-support/ocaml/default.nix
@@ -23,7 +23,7 @@ stdenv.mkDerivation (args // {
 
   setupHook = if setupHook == null && hasSharedObjects
   then writeText "setupHook.sh" ''
-    export CAML_LD_LIBRARY_PATH="''${CAML_LD_LIBRARY_PATH}''${CAML_LD_LIBRARY_PATH:+:}''$1/lib/ocaml/${ocaml.version}/site-lib/${name}/"
+    export CAML_LD_LIBRARY_PATH="''${CAML_LD_LIBRARY_PATH-}''${CAML_LD_LIBRARY_PATH:+:}''$1/lib/ocaml/${ocaml.version}/site-lib/${name}/"
     ''
   else setupHook;
 
diff --git a/pkgs/build-support/rust/build-rust-crate/build-crate.nix b/pkgs/build-support/rust/build-rust-crate/build-crate.nix
index 2999c3d4c1d9..e0a52e62561b 100644
--- a/pkgs/build-support/rust/build-rust-crate/build-crate.nix
+++ b/pkgs/build-support/rust/build-rust-crate/build-crate.nix
@@ -1,13 +1,13 @@
 { lib, stdenv, echo_build_heading, noisily, makeDeps }:
 { crateName,
   dependencies,
-  crateFeatures, libName, release, libPath,
+  crateFeatures, crateRenames, libName, release, libPath,
   crateType, metadata, crateBin, hasCrateBin,
   extraRustcOpts, verbose, colors }:
 
   let
 
-    deps = makeDeps dependencies;
+    deps = makeDeps dependencies crateRenames;
     rustcOpts =
       lib.lists.foldl' (opts: opt: opts + " " + opt)
         (if release then "-C opt-level=3" else "-C debuginfo=2")
diff --git a/pkgs/build-support/rust/build-rust-crate/configure-crate.nix b/pkgs/build-support/rust/build-rust-crate/configure-crate.nix
index 169adcf2d43a..2c7226b09622 100644
--- a/pkgs/build-support/rust/build-rust-crate/configure-crate.nix
+++ b/pkgs/build-support/rust/build-rust-crate/configure-crate.nix
@@ -9,6 +9,7 @@
 , crateHomepage
 , crateFeatures
 , crateName
+, crateRenames
 , crateVersion
 , extraLinkFlags
 , extraRustcOpts
@@ -20,11 +21,11 @@
 , workspace_member }:
 let version_ = lib.splitString "-" crateVersion;
     versionPre = if lib.tail version_ == [] then "" else builtins.elemAt version_ 1;
-    version = lib.splitString "." (lib.head version_);
+    version = lib.splitVersion (lib.head version_);
     rustcOpts = lib.lists.foldl' (opts: opt: opts + " " + opt)
         (if release then "-C opt-level=3" else "-C debuginfo=2")
         (["-C codegen-units=$NIX_BUILD_CORES"] ++ extraRustcOpts);
-    buildDeps = makeDeps buildDependencies;
+    buildDeps = makeDeps buildDependencies crateRenames;
     authors = lib.concatStringsSep ":" crateAuthors;
     optLevel = if release then 3 else 0;
     completeDepsDir = lib.concatStringsSep " " completeDeps;
@@ -149,4 +150,3 @@ in ''
   fi
   runHook postConfigure
 ''
-
diff --git a/pkgs/build-support/rust/build-rust-crate/default.nix b/pkgs/build-support/rust/build-rust-crate/default.nix
index acb2ee63cce4..6534e21c0f0c 100644
--- a/pkgs/build-support/rust/build-rust-crate/default.nix
+++ b/pkgs/build-support/rust/build-rust-crate/default.nix
@@ -13,13 +13,18 @@ let
       then "macos"
       else stdenv.hostPlatform.parsed.kernel.name;
 
-    makeDeps = dependencies:
+    makeDeps = dependencies: crateRenames:
       (lib.concatMapStringsSep " " (dep:
-        let extern = lib.strings.replaceStrings ["-"] ["_"] dep.libName; in
-        (if lib.lists.any (x: x == "lib") dep.crateType then
-           " --extern ${extern}=${dep.out}/lib/lib${extern}-${dep.metadata}.rlib"
+        let
+          extern = lib.strings.replaceStrings ["-"] ["_"] dep.libName;
+          name = if builtins.hasAttr dep.crateName crateRenames then
+            lib.strings.replaceStrings ["-"] ["_"] crateRenames.${dep.crateName}
+          else
+            extern;
+        in (if lib.lists.any (x: x == "lib") dep.crateType then
+           " --extern ${name}=${dep.out}/lib/lib${extern}-${dep.metadata}.rlib"
          else
-           " --extern ${extern}=${dep.out}/lib/lib${extern}-${dep.metadata}${stdenv.hostPlatform.extensions.sharedLibrary}")
+           " --extern ${name}=${dep.out}/lib/lib${extern}-${dep.metadata}${stdenv.hostPlatform.extensions.sharedLibrary}")
       ) dependencies);
 
     echo_build_heading = colors: ''
@@ -60,7 +65,7 @@ let
     in
 
 crate_: lib.makeOverridable ({ rust, release, verbose, features, buildInputs, crateOverrides,
-  dependencies, buildDependencies,
+  dependencies, buildDependencies, crateRenames,
   extraRustcOpts,
   preUnpack, postUnpack, prePatch, patches, postPatch,
   preConfigure, postConfigure, preBuild, postBuild, preInstall, postInstall }:
@@ -70,7 +75,7 @@ let crate = crate_ // (lib.attrByPath [ crate_.crateName ] (attr: {}) crateOverr
     buildDependencies_ = buildDependencies;
     processedAttrs = [
       "src" "buildInputs" "crateBin" "crateLib" "libName" "libPath"
-      "buildDependencies" "dependencies" "features"
+      "buildDependencies" "dependencies" "features" "crateRenames"
       "crateName" "version" "build" "authors" "colors" "edition"
     ];
     extraDerivationAttrs = lib.filterAttrs (n: v: ! lib.elem n processedAttrs) crate;
@@ -143,13 +148,13 @@ stdenv.mkDerivation (rec {
 
     configurePhase = configureCrate {
       inherit crateName buildDependencies completeDeps completeBuildDeps crateDescription
-              crateFeatures libName build workspace_member release libPath crateVersion
+              crateFeatures crateRenames libName build workspace_member release libPath crateVersion
               extraLinkFlags extraRustcOpts
               crateAuthors crateHomepage verbose colors target_os;
     };
     buildPhase = buildCrate {
       inherit crateName dependencies
-              crateFeatures libName release libPath crateType
+              crateFeatures crateRenames libName release libPath crateType
               metadata crateBin hasCrateBin verbose colors
               extraRustcOpts;
     };
@@ -177,4 +182,5 @@ stdenv.mkDerivation (rec {
   postInstall = crate_.postInstall or "";
   dependencies = crate_.dependencies or [];
   buildDependencies = crate_.buildDependencies or [];
+  crateRenames = crate_.crateRenames or {};
 }
diff --git a/pkgs/build-support/rust/build-rust-crate/test/default.nix b/pkgs/build-support/rust/build-rust-crate/test/default.nix
index f3f9ef377c8c..4a90cf442a4d 100644
--- a/pkgs/build-support/rust/build-rust-crate/test/default.nix
+++ b/pkgs/build-support/rust/build-rust-crate/test/default.nix
@@ -22,6 +22,13 @@ let
     }
   '';
 
+  mkBinExtern = name: extern: mkFile name ''
+    extern crate ${extern};
+    fn main() {
+      assert_eq!(${extern}::test(), 23);
+    }
+  '';
+
   mkLib = name: mkFile name "pub fn test() -> i32 { return 23; }";
 
   mkTest = crateArgs: let
@@ -34,12 +41,7 @@ let
     libTestBinary = if !isLib then null else mkCrate {
       crateName = "run-test-${crateName}";
       dependencies = [ crate ];
-      src = mkFile "src/main.rs" ''
-        extern crate ${libName};
-        fn main() {
-          assert_eq!(${libName}::test(), 23);
-        }
-      '';
+      src = mkBinExtern "src/main.rs" libName;
     };
 
     in runCommand "run-buildRustCrate-${crateName}-test" {
@@ -71,6 +73,18 @@ let
       };
       crateBinNoPath3 =  { crateBin = [{ name = "my-binary5"; }]; src = mkBin "src/bin/main.rs"; };
       crateBinNoPath4 =  { crateBin = [{ name = "my-binary6"; }]; src = mkBin "src/main.rs";};
+      crateBinRename1 = {
+        crateBin = [{ name = "my-binary-rename1"; }];
+        src = mkBinExtern "src/main.rs" "foo_renamed";
+        dependencies = [ (mkCrate { crateName = "foo"; src = mkLib "src/lib.rs"; }) ];
+        crateRenames = { "foo" = "foo_renamed"; };
+      };
+      crateBinRename2 = {
+        crateBin = [{ name = "my-binary-rename2"; }];
+        src = mkBinExtern "src/main.rs" "foo_renamed";
+        dependencies = [ (mkCrate { crateName = "foo"; libName = "foolib"; src = mkLib "src/lib.rs"; }) ];
+        crateRenames = { "foo" = "foo_renamed"; };
+      };
     };
     brotliCrates = (callPackage ./brotli-crates.nix {});
   in lib.mapAttrs (key: value: mkTest (value // lib.optionalAttrs (!value?crateName) { crateName = key; })) cases // {
diff --git a/pkgs/build-support/rust/cargo-vendor/cargo-vendor.nix b/pkgs/build-support/rust/cargo-vendor/cargo-vendor.nix
deleted file mode 100644
index 9af5cbe652c3..000000000000
--- a/pkgs/build-support/rust/cargo-vendor/cargo-vendor.nix
+++ /dev/null
@@ -1,693 +0,0 @@
-# Generated by carnix 0.10.0: carnix generate-nix --src .
-{ lib, buildPlatform, buildRustCrate, buildRustCrateHelpers, cratesIO, fetchgit }:
-with buildRustCrateHelpers;
-let inherit (lib.lists) fold;
-    inherit (lib.attrsets) recursiveUpdate;
-in
-rec {
-  crates = cratesIO // rec {
-# cargo-vendor-0.1.23
-
-    crates.cargo_vendor."0.1.23" = deps: { features?(features_.cargo_vendor."0.1.23" deps {}) }: buildRustCrate {
-      crateName = "cargo-vendor";
-      version = "0.1.23";
-      description = "A Cargo subcommand to vendor all crates.io dependencies onto the local\nfilesystem.\n";
-      authors = [ "Alex Crichton <alex@alexcrichton.com>" ];
-      edition = "2018";
-      src = exclude [ ".git" "target" ] ./.;
-      dependencies = mapFeatures features ([
-        (cratesIO.crates."cargo"."${deps."cargo_vendor"."0.1.23"."cargo"}" deps)
-        (cratesIO.crates."docopt"."${deps."cargo_vendor"."0.1.23"."docopt"}" deps)
-        (cratesIO.crates."env_logger"."${deps."cargo_vendor"."0.1.23"."env_logger"}" deps)
-        (cratesIO.crates."failure"."${deps."cargo_vendor"."0.1.23"."failure"}" deps)
-        (cratesIO.crates."serde"."${deps."cargo_vendor"."0.1.23"."serde"}" deps)
-        (cratesIO.crates."serde_json"."${deps."cargo_vendor"."0.1.23"."serde_json"}" deps)
-        (cratesIO.crates."toml"."${deps."cargo_vendor"."0.1.23"."toml"}" deps)
-      ]
-        ++ (if features.cargo_vendor."0.1.23".openssl or false then [ (cratesIO.crates.openssl."${deps."cargo_vendor"."0.1.23".openssl}" deps) ] else []));
-      features = mkFeatures (features."cargo_vendor"."0.1.23" or {});
-    };
-    features_.cargo_vendor."0.1.23" = deps: f: updateFeatures f (rec {
-      cargo."${deps.cargo_vendor."0.1.23".cargo}".default = true;
-      cargo_vendor."0.1.23".default = (f.cargo_vendor."0.1.23".default or true);
-      docopt."${deps.cargo_vendor."0.1.23".docopt}".default = true;
-      env_logger."${deps.cargo_vendor."0.1.23".env_logger}".default = true;
-      failure."${deps.cargo_vendor."0.1.23".failure}".default = true;
-      openssl = fold recursiveUpdate {} [
-        { "${deps.cargo_vendor."0.1.23".openssl}"."vendored" =
-          (f.openssl."${deps.cargo_vendor."0.1.23".openssl}"."vendored" or false) ||
-          (cargo_vendor."0.1.23"."vendored-openssl" or false) ||
-          (f."cargo_vendor"."0.1.23"."vendored-openssl" or false); }
-        { "${deps.cargo_vendor."0.1.23".openssl}".default = true; }
-      ];
-      serde = fold recursiveUpdate {} [
-        { "${deps.cargo_vendor."0.1.23".serde}"."derive" = true; }
-        { "${deps.cargo_vendor."0.1.23".serde}".default = true; }
-      ];
-      serde_json."${deps.cargo_vendor."0.1.23".serde_json}".default = true;
-      toml."${deps.cargo_vendor."0.1.23".toml}".default = true;
-    }) [
-      (cratesIO.features_.cargo."${deps."cargo_vendor"."0.1.23"."cargo"}" deps)
-      (cratesIO.features_.docopt."${deps."cargo_vendor"."0.1.23"."docopt"}" deps)
-      (cratesIO.features_.env_logger."${deps."cargo_vendor"."0.1.23"."env_logger"}" deps)
-      (cratesIO.features_.failure."${deps."cargo_vendor"."0.1.23"."failure"}" deps)
-      (cratesIO.features_.openssl."${deps."cargo_vendor"."0.1.23"."openssl"}" deps)
-      (cratesIO.features_.serde."${deps."cargo_vendor"."0.1.23"."serde"}" deps)
-      (cratesIO.features_.serde_json."${deps."cargo_vendor"."0.1.23"."serde_json"}" deps)
-      (cratesIO.features_.toml."${deps."cargo_vendor"."0.1.23"."toml"}" deps)
-    ];
-
-
-# end
-
-  };
-
-  cargo_vendor = crates.crates.cargo_vendor."0.1.23" deps;
-  __all = [ (cargo_vendor {}) ];
-  deps.adler32."1.0.3" = {};
-  deps.aho_corasick."0.7.3" = {
-    memchr = "2.2.0";
-  };
-  deps.ansi_term."0.11.0" = {
-    winapi = "0.3.7";
-  };
-  deps.atty."0.2.11" = {
-    termion = "1.5.1";
-    libc = "0.2.51";
-    winapi = "0.3.7";
-  };
-  deps.autocfg."0.1.2" = {};
-  deps.backtrace."0.3.15" = {
-    cfg_if = "0.1.7";
-    rustc_demangle = "0.1.14";
-    autocfg = "0.1.2";
-    backtrace_sys = "0.1.28";
-    libc = "0.2.51";
-    winapi = "0.3.7";
-  };
-  deps.backtrace_sys."0.1.28" = {
-    libc = "0.2.51";
-    cc = "1.0.35";
-  };
-  deps.bitflags."1.0.4" = {};
-  deps.bstr."0.1.2" = {
-    memchr = "2.2.0";
-  };
-  deps.build_const."0.2.1" = {};
-  deps.byteorder."1.3.1" = {};
-  deps.bytes."0.4.12" = {
-    byteorder = "1.3.1";
-    iovec = "0.1.2";
-  };
-  deps.bytesize."1.0.0" = {};
-  deps.cargo."0.35.0" = {
-    atty = "0.2.11";
-    byteorder = "1.3.1";
-    bytesize = "1.0.0";
-    clap = "2.33.0";
-    crates_io = "0.23.0";
-    crossbeam_utils = "0.6.5";
-    crypto_hash = "0.3.3";
-    curl = "0.4.21";
-    curl_sys = "0.4.18";
-    env_logger = "0.6.1";
-    failure = "0.1.5";
-    filetime = "0.2.4";
-    flate2 = "1.0.7";
-    fs2 = "0.4.3";
-    git2 = "0.8.0";
-    git2_curl = "0.9.0";
-    glob = "0.2.11";
-    hex = "0.3.2";
-    home = "0.3.4";
-    ignore = "0.4.7";
-    im_rc = "12.3.4";
-    jobserver = "0.1.13";
-    lazy_static = "1.3.0";
-    lazycell = "1.2.1";
-    libc = "0.2.51";
-    libgit2_sys = "0.7.11";
-    log = "0.4.6";
-    num_cpus = "1.10.0";
-    opener = "0.3.2";
-    rustc_workspace_hack = "1.0.0";
-    rustfix = "0.4.5";
-    same_file = "1.0.4";
-    semver = "0.9.0";
-    serde = "1.0.90";
-    serde_ignored = "0.0.4";
-    serde_json = "1.0.39";
-    shell_escape = "0.1.4";
-    tar = "0.4.22";
-    tempfile = "3.0.7";
-    termcolor = "1.0.4";
-    toml = "0.4.10";
-    unicode_width = "0.1.5";
-    url = "1.7.2";
-    url_serde = "0.2.0";
-    core_foundation = "0.6.4";
-    fwdansi = "1.0.1";
-    miow = "0.3.3";
-    winapi = "0.3.7";
-  };
-  deps.cargo_vendor."0.1.23" = {
-    cargo = "0.35.0";
-    docopt = "1.1.0";
-    env_logger = "0.6.1";
-    failure = "0.1.5";
-    openssl = "0.10.20";
-    serde = "1.0.90";
-    serde_json = "1.0.39";
-    toml = "0.5.0";
-  };
-  deps.cc."1.0.35" = {};
-  deps.cfg_if."0.1.7" = {};
-  deps.clap."2.33.0" = {
-    atty = "0.2.11";
-    bitflags = "1.0.4";
-    strsim = "0.8.0";
-    textwrap = "0.11.0";
-    unicode_width = "0.1.5";
-    vec_map = "0.8.1";
-    ansi_term = "0.11.0";
-  };
-  deps.cloudabi."0.0.3" = {
-    bitflags = "1.0.4";
-  };
-  deps.commoncrypto."0.2.0" = {
-    commoncrypto_sys = "0.2.0";
-  };
-  deps.commoncrypto_sys."0.2.0" = {
-    libc = "0.2.51";
-  };
-  deps.core_foundation."0.6.4" = {
-    core_foundation_sys = "0.6.2";
-    libc = "0.2.51";
-  };
-  deps.core_foundation_sys."0.6.2" = {};
-  deps.crates_io."0.23.0" = {
-    curl = "0.4.21";
-    failure = "0.1.5";
-    http = "0.1.17";
-    serde = "1.0.90";
-    serde_derive = "1.0.90";
-    serde_json = "1.0.39";
-    url = "1.7.2";
-  };
-  deps.crc."1.8.1" = {
-    build_const = "0.2.1";
-  };
-  deps.crc32fast."1.2.0" = {
-    cfg_if = "0.1.7";
-  };
-  deps.crossbeam_channel."0.3.8" = {
-    crossbeam_utils = "0.6.5";
-    smallvec = "0.6.9";
-  };
-  deps.crossbeam_utils."0.6.5" = {
-    cfg_if = "0.1.7";
-    lazy_static = "1.3.0";
-  };
-  deps.crypto_hash."0.3.3" = {
-    hex = "0.3.2";
-    commoncrypto = "0.2.0";
-    openssl = "0.10.20";
-    winapi = "0.3.7";
-  };
-  deps.curl."0.4.21" = {
-    curl_sys = "0.4.18";
-    libc = "0.2.51";
-    socket2 = "0.3.8";
-    openssl_probe = "0.1.2";
-    openssl_sys = "0.9.43";
-    kernel32_sys = "0.2.2";
-    schannel = "0.1.15";
-    winapi = "0.2.8";
-  };
-  deps.curl_sys."0.4.18" = {
-    libc = "0.2.51";
-    libnghttp2_sys = "0.1.1";
-    libz_sys = "1.0.25";
-    cc = "1.0.35";
-    pkg_config = "0.3.14";
-    openssl_sys = "0.9.43";
-    winapi = "0.3.7";
-  };
-  deps.docopt."1.1.0" = {
-    lazy_static = "1.3.0";
-    regex = "1.1.6";
-    serde = "1.0.90";
-    strsim = "0.9.1";
-  };
-  deps.either."1.5.2" = {};
-  deps.env_logger."0.6.1" = {
-    atty = "0.2.11";
-    humantime = "1.2.0";
-    log = "0.4.6";
-    regex = "1.1.6";
-    termcolor = "1.0.4";
-  };
-  deps.failure."0.1.5" = {
-    backtrace = "0.3.15";
-    failure_derive = "0.1.5";
-  };
-  deps.failure_derive."0.1.5" = {
-    proc_macro2 = "0.4.27";
-    quote = "0.6.12";
-    syn = "0.15.32";
-    synstructure = "0.10.1";
-  };
-  deps.filetime."0.2.4" = {
-    cfg_if = "0.1.7";
-    redox_syscall = "0.1.54";
-    libc = "0.2.51";
-  };
-  deps.flate2."1.0.7" = {
-    crc32fast = "1.2.0";
-    libc = "0.2.51";
-    libz_sys = "1.0.25";
-    miniz_sys = "0.1.11";
-    miniz_oxide_c_api = "0.2.1";
-  };
-  deps.fnv."1.0.6" = {};
-  deps.foreign_types."0.3.2" = {
-    foreign_types_shared = "0.1.1";
-  };
-  deps.foreign_types_shared."0.1.1" = {};
-  deps.fs2."0.4.3" = {
-    libc = "0.2.51";
-    winapi = "0.3.7";
-  };
-  deps.fuchsia_cprng."0.1.1" = {};
-  deps.fwdansi."1.0.1" = {
-    memchr = "2.2.0";
-    termcolor = "1.0.4";
-  };
-  deps.git2."0.8.0" = {
-    bitflags = "1.0.4";
-    libc = "0.2.51";
-    libgit2_sys = "0.7.11";
-    log = "0.4.6";
-    url = "1.7.2";
-    openssl_probe = "0.1.2";
-    openssl_sys = "0.9.43";
-  };
-  deps.git2_curl."0.9.0" = {
-    curl = "0.4.21";
-    git2 = "0.8.0";
-    log = "0.4.6";
-    url = "1.7.2";
-  };
-  deps.glob."0.2.11" = {};
-  deps.globset."0.4.3" = {
-    aho_corasick = "0.7.3";
-    bstr = "0.1.2";
-    fnv = "1.0.6";
-    log = "0.4.6";
-    regex = "1.1.6";
-  };
-  deps.hashbrown."0.1.8" = {
-    byteorder = "1.3.1";
-    scopeguard = "0.3.3";
-  };
-  deps.hex."0.3.2" = {};
-  deps.home."0.3.4" = {
-    scopeguard = "0.3.3";
-    winapi = "0.3.7";
-  };
-  deps.http."0.1.17" = {
-    bytes = "0.4.12";
-    fnv = "1.0.6";
-    itoa = "0.4.3";
-  };
-  deps.humantime."1.2.0" = {
-    quick_error = "1.2.2";
-  };
-  deps.idna."0.1.5" = {
-    matches = "0.1.8";
-    unicode_bidi = "0.3.4";
-    unicode_normalization = "0.1.8";
-  };
-  deps.ignore."0.4.7" = {
-    crossbeam_channel = "0.3.8";
-    globset = "0.4.3";
-    lazy_static = "1.3.0";
-    log = "0.4.6";
-    memchr = "2.2.0";
-    regex = "1.1.6";
-    same_file = "1.0.4";
-    thread_local = "0.3.6";
-    walkdir = "2.2.7";
-    winapi_util = "0.1.2";
-  };
-  deps.im_rc."12.3.4" = {
-    sized_chunks = "0.1.3";
-    typenum = "1.10.0";
-    rustc_version = "0.2.3";
-  };
-  deps.iovec."0.1.2" = {
-    libc = "0.2.51";
-    winapi = "0.2.8";
-  };
-  deps.itertools."0.7.11" = {
-    either = "1.5.2";
-  };
-  deps.itoa."0.4.3" = {};
-  deps.jobserver."0.1.13" = {
-    log = "0.4.6";
-    libc = "0.2.51";
-    rand = "0.6.5";
-  };
-  deps.kernel32_sys."0.2.2" = {
-    winapi = "0.2.8";
-    winapi_build = "0.1.1";
-  };
-  deps.lazy_static."1.3.0" = {};
-  deps.lazycell."1.2.1" = {};
-  deps.libc."0.2.51" = {};
-  deps.libgit2_sys."0.7.11" = {
-    curl_sys = "0.4.18";
-    libc = "0.2.51";
-    libssh2_sys = "0.2.11";
-    libz_sys = "1.0.25";
-    cc = "1.0.35";
-    pkg_config = "0.3.14";
-    openssl_sys = "0.9.43";
-  };
-  deps.libnghttp2_sys."0.1.1" = {
-    libc = "0.2.51";
-    cc = "1.0.35";
-  };
-  deps.libssh2_sys."0.2.11" = {
-    libc = "0.2.51";
-    libz_sys = "1.0.25";
-    cc = "1.0.35";
-    pkg_config = "0.3.14";
-    openssl_sys = "0.9.43";
-  };
-  deps.libz_sys."1.0.25" = {
-    libc = "0.2.51";
-    cc = "1.0.35";
-    pkg_config = "0.3.14";
-  };
-  deps.lock_api."0.1.5" = {
-    scopeguard = "0.3.3";
-  };
-  deps.log."0.4.6" = {
-    cfg_if = "0.1.7";
-  };
-  deps.matches."0.1.8" = {};
-  deps.matrixmultiply."0.1.15" = {
-    rawpointer = "0.1.0";
-  };
-  deps.memchr."2.2.0" = {};
-  deps.miniz_sys."0.1.11" = {
-    libc = "0.2.51";
-    cc = "1.0.35";
-  };
-  deps.miniz_oxide."0.2.1" = {
-    adler32 = "1.0.3";
-  };
-  deps.miniz_oxide_c_api."0.2.1" = {
-    crc = "1.8.1";
-    libc = "0.2.51";
-    miniz_oxide = "0.2.1";
-    cc = "1.0.35";
-  };
-  deps.miow."0.3.3" = {
-    socket2 = "0.3.8";
-    winapi = "0.3.7";
-  };
-  deps.ndarray."0.12.1" = {
-    itertools = "0.7.11";
-    matrixmultiply = "0.1.15";
-    num_complex = "0.2.1";
-    num_traits = "0.2.6";
-  };
-  deps.num_complex."0.2.1" = {
-    num_traits = "0.2.6";
-  };
-  deps.num_traits."0.2.6" = {};
-  deps.num_cpus."1.10.0" = {
-    libc = "0.2.51";
-  };
-  deps.once_cell."0.1.8" = {
-    parking_lot = "0.7.1";
-  };
-  deps.opener."0.3.2" = {
-    failure = "0.1.5";
-    failure_derive = "0.1.5";
-    winapi = "0.3.7";
-  };
-  deps.openssl."0.10.20" = {
-    bitflags = "1.0.4";
-    cfg_if = "0.1.7";
-    foreign_types = "0.3.2";
-    lazy_static = "1.3.0";
-    libc = "0.2.51";
-    openssl_sys = "0.9.43";
-  };
-  deps.openssl_probe."0.1.2" = {};
-  deps.openssl_src."111.2.1+1.1.1b" = {
-    cc = "1.0.35";
-  };
-  deps.openssl_sys."0.9.43" = {
-    libc = "0.2.51";
-    cc = "1.0.35";
-    openssl_src = "111.2.1+1.1.1b";
-    pkg_config = "0.3.14";
-    rustc_version = "0.2.3";
-  };
-  deps.parking_lot."0.7.1" = {
-    lock_api = "0.1.5";
-    parking_lot_core = "0.4.0";
-  };
-  deps.parking_lot_core."0.4.0" = {
-    rand = "0.6.5";
-    smallvec = "0.6.9";
-    rustc_version = "0.2.3";
-    libc = "0.2.51";
-    winapi = "0.3.7";
-  };
-  deps.percent_encoding."1.0.1" = {};
-  deps.pkg_config."0.3.14" = {};
-  deps.proc_macro2."0.4.27" = {
-    unicode_xid = "0.1.0";
-  };
-  deps.quick_error."1.2.2" = {};
-  deps.quote."0.6.12" = {
-    proc_macro2 = "0.4.27";
-  };
-  deps.rand."0.6.5" = {
-    rand_chacha = "0.1.1";
-    rand_core = "0.4.0";
-    rand_hc = "0.1.0";
-    rand_isaac = "0.1.1";
-    rand_jitter = "0.1.3";
-    rand_os = "0.1.3";
-    rand_pcg = "0.1.2";
-    rand_xorshift = "0.1.1";
-    autocfg = "0.1.2";
-    libc = "0.2.51";
-    winapi = "0.3.7";
-  };
-  deps.rand_chacha."0.1.1" = {
-    rand_core = "0.3.1";
-    autocfg = "0.1.2";
-  };
-  deps.rand_core."0.3.1" = {
-    rand_core = "0.4.0";
-  };
-  deps.rand_core."0.4.0" = {};
-  deps.rand_hc."0.1.0" = {
-    rand_core = "0.3.1";
-  };
-  deps.rand_isaac."0.1.1" = {
-    rand_core = "0.3.1";
-  };
-  deps.rand_jitter."0.1.3" = {
-    rand_core = "0.4.0";
-    libc = "0.2.51";
-    winapi = "0.3.7";
-  };
-  deps.rand_os."0.1.3" = {
-    rand_core = "0.4.0";
-    rdrand = "0.4.0";
-    cloudabi = "0.0.3";
-    fuchsia_cprng = "0.1.1";
-    libc = "0.2.51";
-    winapi = "0.3.7";
-  };
-  deps.rand_pcg."0.1.2" = {
-    rand_core = "0.4.0";
-    autocfg = "0.1.2";
-  };
-  deps.rand_xorshift."0.1.1" = {
-    rand_core = "0.3.1";
-  };
-  deps.rawpointer."0.1.0" = {};
-  deps.rdrand."0.4.0" = {
-    rand_core = "0.3.1";
-  };
-  deps.redox_syscall."0.1.54" = {};
-  deps.redox_termios."0.1.1" = {
-    redox_syscall = "0.1.54";
-  };
-  deps.regex."1.1.6" = {
-    aho_corasick = "0.7.3";
-    memchr = "2.2.0";
-    regex_syntax = "0.6.6";
-    thread_local = "0.3.6";
-    utf8_ranges = "1.0.2";
-  };
-  deps.regex_syntax."0.6.6" = {
-    ucd_util = "0.1.3";
-  };
-  deps.remove_dir_all."0.5.1" = {
-    winapi = "0.3.7";
-  };
-  deps.rustc_demangle."0.1.14" = {};
-  deps.rustc_workspace_hack."1.0.0" = {};
-  deps.rustc_version."0.2.3" = {
-    semver = "0.9.0";
-  };
-  deps.rustfix."0.4.5" = {
-    failure = "0.1.5";
-    log = "0.4.6";
-    serde = "1.0.90";
-    serde_derive = "1.0.90";
-    serde_json = "1.0.39";
-  };
-  deps.ryu."0.2.7" = {};
-  deps.same_file."1.0.4" = {
-    winapi_util = "0.1.2";
-  };
-  deps.schannel."0.1.15" = {
-    lazy_static = "1.3.0";
-    winapi = "0.3.7";
-  };
-  deps.scopeguard."0.3.3" = {};
-  deps.semver."0.9.0" = {
-    semver_parser = "0.7.0";
-    serde = "1.0.90";
-  };
-  deps.semver_parser."0.7.0" = {};
-  deps.serde."1.0.90" = {
-    serde_derive = "1.0.90";
-  };
-  deps.serde_derive."1.0.90" = {
-    proc_macro2 = "0.4.27";
-    quote = "0.6.12";
-    syn = "0.15.32";
-  };
-  deps.serde_ignored."0.0.4" = {
-    serde = "1.0.90";
-  };
-  deps.serde_json."1.0.39" = {
-    itoa = "0.4.3";
-    ryu = "0.2.7";
-    serde = "1.0.90";
-  };
-  deps.shell_escape."0.1.4" = {};
-  deps.sized_chunks."0.1.3" = {
-    typenum = "1.10.0";
-  };
-  deps.smallvec."0.6.9" = {};
-  deps.socket2."0.3.8" = {
-    cfg_if = "0.1.7";
-    libc = "0.2.51";
-    redox_syscall = "0.1.54";
-    winapi = "0.3.7";
-  };
-  deps.strsim."0.8.0" = {};
-  deps.strsim."0.9.1" = {
-    hashbrown = "0.1.8";
-    ndarray = "0.12.1";
-  };
-  deps.syn."0.15.32" = {
-    proc_macro2 = "0.4.27";
-    quote = "0.6.12";
-    unicode_xid = "0.1.0";
-  };
-  deps.synstructure."0.10.1" = {
-    proc_macro2 = "0.4.27";
-    quote = "0.6.12";
-    syn = "0.15.32";
-    unicode_xid = "0.1.0";
-  };
-  deps.tar."0.4.22" = {
-    filetime = "0.2.4";
-    redox_syscall = "0.1.54";
-    libc = "0.2.51";
-  };
-  deps.tempfile."3.0.7" = {
-    cfg_if = "0.1.7";
-    rand = "0.6.5";
-    remove_dir_all = "0.5.1";
-    redox_syscall = "0.1.54";
-    libc = "0.2.51";
-    winapi = "0.3.7";
-  };
-  deps.termcolor."1.0.4" = {
-    wincolor = "1.0.1";
-  };
-  deps.termion."1.5.1" = {
-    libc = "0.2.51";
-    redox_syscall = "0.1.54";
-    redox_termios = "0.1.1";
-  };
-  deps.textwrap."0.11.0" = {
-    unicode_width = "0.1.5";
-  };
-  deps.thread_local."0.3.6" = {
-    lazy_static = "1.3.0";
-  };
-  deps.toml."0.4.10" = {
-    serde = "1.0.90";
-  };
-  deps.toml."0.5.0" = {
-    serde = "1.0.90";
-  };
-  deps.typenum."1.10.0" = {};
-  deps.ucd_util."0.1.3" = {};
-  deps.unicode_bidi."0.3.4" = {
-    matches = "0.1.8";
-  };
-  deps.unicode_normalization."0.1.8" = {
-    smallvec = "0.6.9";
-  };
-  deps.unicode_width."0.1.5" = {};
-  deps.unicode_xid."0.1.0" = {};
-  deps.url."1.7.2" = {
-    idna = "0.1.5";
-    matches = "0.1.8";
-    percent_encoding = "1.0.1";
-  };
-  deps.url_serde."0.2.0" = {
-    serde = "1.0.90";
-    url = "1.7.2";
-  };
-  deps.utf8_ranges."1.0.2" = {};
-  deps.vcpkg."0.2.6" = {};
-  deps.vec_map."0.8.1" = {};
-  deps.walkdir."2.2.7" = {
-    same_file = "1.0.4";
-    winapi = "0.3.7";
-    winapi_util = "0.1.2";
-  };
-  deps.winapi."0.2.8" = {};
-  deps.winapi."0.3.7" = {
-    winapi_i686_pc_windows_gnu = "0.4.0";
-    winapi_x86_64_pc_windows_gnu = "0.4.0";
-  };
-  deps.winapi_build."0.1.1" = {};
-  deps.winapi_i686_pc_windows_gnu."0.4.0" = {};
-  deps.winapi_util."0.1.2" = {
-    winapi = "0.3.7";
-  };
-  deps.winapi_x86_64_pc_windows_gnu."0.4.0" = {};
-  deps.wincolor."1.0.1" = {
-    winapi = "0.3.7";
-    winapi_util = "0.1.2";
-  };
-}
diff --git a/pkgs/build-support/rust/cargo-vendor/default.nix b/pkgs/build-support/rust/cargo-vendor/default.nix
deleted file mode 100644
index f252c6a6cb1f..000000000000
--- a/pkgs/build-support/rust/cargo-vendor/default.nix
+++ /dev/null
@@ -1,10 +0,0 @@
-{ callPackage, fetchFromGitHub }:
-
-((callPackage ./cargo-vendor.nix {}).cargo_vendor {}).overrideAttrs (attrs: {
-  src = fetchFromGitHub {
-    owner = "alexcrichton";
-    repo = "cargo-vendor";
-    rev = "9355661303ce2870d68a69d99953fce22581e31e";
-    sha256 = "0d4j3r09am3ynwhczimzv39264f5xz37jxa9js123y46w5by3wd2";
-  };
-})
diff --git a/pkgs/build-support/rust/default-crate-overrides.nix b/pkgs/build-support/rust/default-crate-overrides.nix
index b3ab9f5ba780..1c4fe9daeada 100644
--- a/pkgs/build-support/rust/default-crate-overrides.nix
+++ b/pkgs/build-support/rust/default-crate-overrides.nix
@@ -15,11 +15,6 @@ in
       ++ stdenv.lib.optionals stdenv.isDarwin [ CoreFoundation Security libiconv ];
   };
 
-  cargo-vendor = attrs: {
-    buildInputs = [ openssl zlib curl ]
-      ++ stdenv.lib.optionals stdenv.isDarwin [ Security ];
-  };
-
   libz-sys = attrs: {
     buildInputs = [ pkgconfig zlib ];
     extraLinkFlags = ["-L${zlib.out}/lib"];
diff --git a/pkgs/build-support/rust/default.nix b/pkgs/build-support/rust/default.nix
index ce1bf8002767..f0f949b22056 100644
--- a/pkgs/build-support/rust/default.nix
+++ b/pkgs/build-support/rust/default.nix
@@ -13,8 +13,12 @@
 , cargoUpdateHook ? ""
 , cargoDepsHook ? ""
 , cargoBuildFlags ? []
+, # Set to true to verify if the cargo dependencies are up to date.
+  # This will change the value of cargoSha256.
+  verifyCargoDeps ? false
 , buildType ? "release"
 , meta ? {}
+, target ? null
 
 , cargoVendorDir ? null
 , ... } @ args:
@@ -26,6 +30,7 @@ let
   cargoDeps = if cargoVendorDir == null
     then fetchcargo {
         inherit name src srcs sourceRoot cargoUpdateHook;
+        copyLockfile = verifyCargoDeps;
         patches = cargoPatches;
         sha256 = cargoSha256;
       }
@@ -46,12 +51,13 @@ let
   rustHostConfig = {
     x86_64-pc-mingw32 = "x86_64-pc-windows-gnu";
   }.${hostConfig} or hostConfig;
+  rustTarget = if target == null then rustHostConfig else target;
 
   ccForBuild="${buildPackages.stdenv.cc}/bin/${buildPackages.stdenv.cc.targetPrefix}cc";
   cxxForBuild="${buildPackages.stdenv.cc}/bin/${buildPackages.stdenv.cc.targetPrefix}c++";
   ccForHost="${stdenv.cc}/bin/${stdenv.cc.targetPrefix}cc";
   cxxForHost="${stdenv.cc}/bin/${stdenv.cc.targetPrefix}c++";
-  releaseDir = "target/${rustHostConfig}/${buildType}";
+  releaseDir = "target/${rustTarget}/${buildType}";
 in
 
 stdenv.mkDerivation (args // {
@@ -84,13 +90,32 @@ stdenv.mkDerivation (args // {
     [target."${stdenv.buildPlatform.config}"]
     "linker" = "${ccForBuild}"
     ${stdenv.lib.optionalString (stdenv.buildPlatform.config != stdenv.hostPlatform.config) ''
-    [target."${rustHostConfig}"]
+    [target."${rustTarget}"]
     "linker" = "${ccForHost}"
+    ${# https://github.com/rust-lang/rust/issues/46651#issuecomment-433611633
+      stdenv.lib.optionalString (stdenv.hostPlatform.isMusl && stdenv.hostPlatform.isAarch64) ''
+    "rustflags" = [ "-C", "target-feature=+crt-static", "-C", "link-arg=-lgcc" ]
+    ''}
     ''}
     EOF
 
     unset cargoDepsCopy
     export RUST_LOG=${logLevel}
+  '' + stdenv.lib.optionalString verifyCargoDeps ''
+    if ! diff source/Cargo.lock $cargoDeps/Cargo.lock ; then
+      echo
+      echo "ERROR: cargoSha256 is out of date."
+      echo
+      echo "Cargo.lock is not the same in $cargoDeps."
+      echo
+      echo "To fix the issue:"
+      echo '1. Use "1111111111111111111111111111111111111111111111111111" as the cargoSha256 value'
+      echo "2. Build the derivation and wait it to fail with a hash mismatch"
+      echo "3. Copy the 'got: sha256:' value back into the cargoSha256 field"
+      echo
+
+      exit 1
+    fi
   '' + (args.postUnpack or "");
 
   configurePhase = args.configurePhase or ''
@@ -110,7 +135,7 @@ stdenv.mkDerivation (args // {
       "CXX_${stdenv.hostPlatform.config}"="${cxxForHost}" \
       cargo build \
         ${stdenv.lib.optionalString (buildType == "release") "--release"} \
-        --target ${rustHostConfig} \
+        --target ${rustTarget} \
         --frozen ${concatStringsSep " " cargoBuildFlags}
     )
 
@@ -126,8 +151,8 @@ stdenv.mkDerivation (args // {
 
   checkPhase = args.checkPhase or ''
     runHook preCheck
-    echo "Running cargo test"
-    cargo test
+    echo "Running cargo cargo test -- ''${checkFlags} ''${checkFlagsArray+''${checkFlagsArray[@]}}"
+    cargo test -- ''${checkFlags} ''${checkFlagsArray+"''${checkFlagsArray[@]}"}
     runHook postCheck
   '';
 
diff --git a/pkgs/build-support/rust/fetchcargo.nix b/pkgs/build-support/rust/fetchcargo.nix
index 4e6058383d48..a515ce9c6eb5 100644
--- a/pkgs/build-support/rust/fetchcargo.nix
+++ b/pkgs/build-support/rust/fetchcargo.nix
@@ -1,4 +1,4 @@
-{ stdenv, cacert, git, cargo, cargo-vendor, python3 }:
+{ stdenv, cacert, git, cargo, python3 }:
 let cargo-vendor-normalise = stdenv.mkDerivation {
   name = "cargo-vendor-normalise";
   src = ./cargo-vendor-normalise.py;
@@ -17,10 +17,19 @@ let cargo-vendor-normalise = stdenv.mkDerivation {
   preferLocalBuild = true;
 };
 in
-{ name ? "cargo-deps", src, srcs, patches, sourceRoot, sha256, cargoUpdateHook ? "" }:
+{ name ? "cargo-deps"
+, src
+, srcs
+, patches
+, sourceRoot
+, sha256
+, cargoUpdateHook ? ""
+, # whenever to also include the Cargo.lock in the output
+  copyLockfile ? false
+}:
 stdenv.mkDerivation {
   name = "${name}-vendor";
-  nativeBuildInputs = [ cacert cargo-vendor git cargo-vendor-normalise cargo ];
+  nativeBuildInputs = [ cacert git cargo-vendor-normalise cargo ];
   inherit src srcs patches sourceRoot;
 
   phases = "unpackPhase patchPhase installPhase";
@@ -37,6 +46,9 @@ stdenv.mkDerivation {
         exit 1
     fi
 
+    # Keep the original around for copyLockfile
+    cp Cargo.lock Cargo.lock.orig
+
     export CARGO_HOME=$(mktemp -d cargo-home.XXX)
     CARGO_CONFIG=$(mktemp cargo-config.XXXX)
 
@@ -52,6 +64,10 @@ stdenv.mkDerivation {
     if ! cmp $CARGO_CONFIG ${./fetchcargo-default-config.toml} > /dev/null; then
       install -D $CARGO_CONFIG $out/.cargo/config;
     fi;
+
+  '' + stdenv.lib.optionalString copyLockfile ''
+    # add the Cargo.lock to allow hash invalidation
+    cp Cargo.lock.orig $out/Cargo.lock
   '';
 
   outputHashAlgo = "sha256";
diff --git a/pkgs/build-support/setup-hooks/audit-tmpdir.sh b/pkgs/build-support/setup-hooks/audit-tmpdir.sh
index 5264ce398511..c9dd32d1dd22 100644
--- a/pkgs/build-support/setup-hooks/audit-tmpdir.sh
+++ b/pkgs/build-support/setup-hooks/audit-tmpdir.sh
@@ -7,7 +7,7 @@
 # the moment that would produce too many spurious errors (e.g. debug
 # info or assertion messages that refer to $TMPDIR).
 
-fixupOutputHooks+=('if [ -z "$noAuditTmpdir" -a -e "$prefix" ]; then auditTmpdir "$prefix"; fi')
+fixupOutputHooks+=('if [[ -z "${noAuditTmpdir-}" && -e "$prefix" ]]; then auditTmpdir "$prefix"; fi')
 
 auditTmpdir() {
     local dir="$1"
diff --git a/pkgs/build-support/setup-hooks/auto-patchelf.sh b/pkgs/build-support/setup-hooks/auto-patchelf.sh
index 6af8eb1aed99..52c50091d08c 100644
--- a/pkgs/build-support/setup-hooks/auto-patchelf.sh
+++ b/pkgs/build-support/setup-hooks/auto-patchelf.sh
@@ -228,7 +228,7 @@ autoPatchelf() {
 # behaviour as fixupOutputHooks because the setup hook for patchelf is run in
 # fixupOutput and the postFixup hook runs later.
 postFixupHooks+=('
-    if [ -z "$dontAutoPatchelf" ]; then
+    if [ -z "${dontAutoPatchelf-}" ]; then
         autoPatchelf -- $(for output in $outputs; do
             [ -e "${!output}" ] || continue
             echo "${!output}"
diff --git a/pkgs/build-support/setup-hooks/compress-man-pages.sh b/pkgs/build-support/setup-hooks/compress-man-pages.sh
index d10a898d6e46..82e48cd8aa77 100644
--- a/pkgs/build-support/setup-hooks/compress-man-pages.sh
+++ b/pkgs/build-support/setup-hooks/compress-man-pages.sh
@@ -1,4 +1,4 @@
-fixupOutputHooks+=('if [ -z "$dontGzipMan" ]; then compressManPages "$prefix"; fi')
+fixupOutputHooks+=('if [ -z "${dontGzipMan-}" ]; then compressManPages "$prefix"; fi')
 
 compressManPages() {
     local dir="$1"
diff --git a/pkgs/build-support/setup-hooks/find-xml-catalogs.sh b/pkgs/build-support/setup-hooks/find-xml-catalogs.sh
index 85364a61f612..f446a6f27fd9 100644
--- a/pkgs/build-support/setup-hooks/find-xml-catalogs.sh
+++ b/pkgs/build-support/setup-hooks/find-xml-catalogs.sh
@@ -11,12 +11,12 @@ addXMLCatalogs () {
     done
 }
 
-if [ -z "$libxmlHookDone" ]; then
+if [ -z "${libxmlHookDone-}" ]; then
     libxmlHookDone=1
 
     # Set up XML_CATALOG_FILES.  An empty initial value prevents
     # xmllint and xsltproc from looking in /etc/xml/catalog.
-    export XML_CATALOG_FILES
+    export XML_CATALOG_FILES=''
     if [ -z "$XML_CATALOG_FILES" ]; then XML_CATALOG_FILES=" "; fi
     addEnvHooks "$hostOffset" addXMLCatalogs
 fi
diff --git a/pkgs/build-support/setup-hooks/make-wrapper.sh b/pkgs/build-support/setup-hooks/make-wrapper.sh
index 06891893e8c1..8b7012677cd5 100644
--- a/pkgs/build-support/setup-hooks/make-wrapper.sh
+++ b/pkgs/build-support/setup-hooks/make-wrapper.sh
@@ -19,9 +19,6 @@ assertExecutable() {
 #                         the environment
 # --unset       VAR     : remove VAR from the environment
 # --run         COMMAND : run command before the executable
-#                         The command can push extra flags to a magic list
-#                         variable extraFlagsArray, which are then added to
-#                         the invocation of the executable
 # --add-flags   FLAGS   : add FLAGS to invocation of executable
 
 # --prefix          ENV SEP VAL   : suffix/prefix ENV with VAL, separated by SEP
@@ -109,12 +106,8 @@ makeWrapper() {
         fi
     done
 
-    # Note: extraFlagsArray is an array containing additional flags
-    # that may be set by --run actions.
-    # Silence warning about unexpanded extraFlagsArray:
-    # shellcheck disable=SC2016
     echo exec ${argv0:+-a \"$argv0\"} \""$original"\" \
-         "$flagsBefore" '"${extraFlagsArray[@]}"' '"$@"' >> "$wrapper"
+         "$flagsBefore" '"$@"' >> "$wrapper"
 
     chmod +x "$wrapper"
 }
diff --git a/pkgs/build-support/setup-hooks/move-lib64.sh b/pkgs/build-support/setup-hooks/move-lib64.sh
index 7724be369c9c..9517af797323 100644
--- a/pkgs/build-support/setup-hooks/move-lib64.sh
+++ b/pkgs/build-support/setup-hooks/move-lib64.sh
@@ -8,7 +8,7 @@
 fixupOutputHooks+=(_moveLib64)
 
 _moveLib64() {
-    if [ "$dontMoveLib64" = 1 ]; then return; fi
+    if [ "${dontMoveLib64-}" = 1 ]; then return; fi
     if [ ! -e "$prefix/lib64" -o -L "$prefix/lib64" ]; then return; fi
     echo "moving $prefix/lib64/* to $prefix/lib"
     mkdir -p $prefix/lib
diff --git a/pkgs/build-support/setup-hooks/move-sbin.sh b/pkgs/build-support/setup-hooks/move-sbin.sh
index cc51c27cafdf..1c0c4dc9f2d9 100644
--- a/pkgs/build-support/setup-hooks/move-sbin.sh
+++ b/pkgs/build-support/setup-hooks/move-sbin.sh
@@ -5,7 +5,7 @@
 fixupOutputHooks+=(_moveSbin)
 
 _moveSbin() {
-    if [ "$dontMoveSbin" = 1 ]; then return; fi
+    if [ "${dontMoveSbin-}" = 1 ]; then return; fi
     if [ ! -e "$prefix/sbin" -o -L "$prefix/sbin" ]; then return; fi
     echo "moving $prefix/sbin/* to $prefix/bin"
     mkdir -p $prefix/bin
diff --git a/pkgs/build-support/setup-hooks/multiple-outputs.sh b/pkgs/build-support/setup-hooks/multiple-outputs.sh
index d43b18776742..2e95495c96fd 100644
--- a/pkgs/build-support/setup-hooks/multiple-outputs.sh
+++ b/pkgs/build-support/setup-hooks/multiple-outputs.sh
@@ -9,8 +9,8 @@ _assignFirst() {
     local varName="$1"
     local REMOVE=REMOVE # slightly hacky - we allow REMOVE (i.e. not a variable name)
     shift
-    while [ $# -ge 1 ]; do
-        if [ -n "${!1}" ]; then eval "${varName}"="$1"; return; fi
+    while (( $# )); do
+        if [ -n "${!1-}" ]; then eval "${varName}"="$1"; return; fi
         shift
     done
     echo "Error: _assignFirst found no valid variant!"
@@ -19,7 +19,7 @@ _assignFirst() {
 
 # Same as _assignFirst, but only if "$1" = ""
 _overrideFirst() {
-    if [ -z "${!1}" ]; then
+    if [ -z "${!1-}" ]; then
         _assignFirst "$@"
     fi
 }
diff --git a/pkgs/build-support/setup-hooks/patch-shebangs.sh b/pkgs/build-support/setup-hooks/patch-shebangs.sh
index 3e900d0704cf..29fed7ad7940 100644
--- a/pkgs/build-support/setup-hooks/patch-shebangs.sh
+++ b/pkgs/build-support/setup-hooks/patch-shebangs.sh
@@ -105,7 +105,7 @@ patchShebangs() {
 }
 
 patchShebangsAuto () {
-    if [ -z "$dontPatchShebangs" -a -e "$prefix" ]; then
+    if [ -z "${dontPatchShebangs-}" -a -e "$prefix" ]; then
 
         # Dev output will end up being run on the build platform. An
         # example case of this is sdl2-config. Otherwise, we can just
diff --git a/pkgs/build-support/setup-hooks/prune-libtool-files.sh b/pkgs/build-support/setup-hooks/prune-libtool-files.sh
index 5d7432e8f09a..0ec56549645c 100644
--- a/pkgs/build-support/setup-hooks/prune-libtool-files.sh
+++ b/pkgs/build-support/setup-hooks/prune-libtool-files.sh
@@ -8,7 +8,7 @@
 fixupOutputHooks+=(_pruneLibtoolFiles)
 
 _pruneLibtoolFiles() {
-    if [ "$dontPruneLibtoolFiles" ] || [ ! -e "$prefix" ]; then
+    if [ "${dontPruneLibtoolFiles-}" ] || [ ! -e "$prefix" ]; then
        return
     fi
 
diff --git a/pkgs/build-support/setup-hooks/strip.sh b/pkgs/build-support/setup-hooks/strip.sh
index fc4c7bfbaf95..f5fa9378fd7e 100644
--- a/pkgs/build-support/setup-hooks/strip.sh
+++ b/pkgs/build-support/setup-hooks/strip.sh
@@ -10,7 +10,7 @@ _doStrip() {
     local -ra stripCmds=(STRIP TARGET_STRIP)
 
     # Optimization
-    if [[ "$STRIP" == "$TARGET_STRIP" ]]; then
+    if [[ "${STRIP-}" == "${TARGET_STRIP-}" ]]; then
         dontStripTarget+=1
     fi
 
@@ -20,7 +20,7 @@ _doStrip() {
         local -n stripCmd="${stripCmds[$i]}"
 
         # `dontStrip` disables them all
-        if [[ "$dontStrip" || "$flag" ]] || ! type -f "$stripCmd" 2>/dev/null
+        if [[ "${dontStrip-}" || "${flag-}" ]] || ! type -f "${stripCmd-}" 2>/dev/null
         then continue; fi
 
         stripDebugList=${stripDebugList:-lib lib32 lib64 libexec bin sbin}
diff --git a/pkgs/build-support/setup-hooks/update-autotools-gnu-config-scripts.sh b/pkgs/build-support/setup-hooks/update-autotools-gnu-config-scripts.sh
index 66f4e91c7bb6..ebd3afa05d94 100644
--- a/pkgs/build-support/setup-hooks/update-autotools-gnu-config-scripts.sh
+++ b/pkgs/build-support/setup-hooks/update-autotools-gnu-config-scripts.sh
@@ -1,7 +1,7 @@
 preConfigurePhases+=" updateAutotoolsGnuConfigScriptsPhase"
 
 updateAutotoolsGnuConfigScriptsPhase() {
-    if [ -n "$dontUpdateAutotoolsGnuConfigScripts" ]; then return; fi
+    if [ -n "${dontUpdateAutotoolsGnuConfigScripts-}" ]; then return; fi
 
     for script in config.sub config.guess; do
         for f in $(find . -type f -name "$script"); do
diff --git a/pkgs/build-support/setup-hooks/wrap-gapps-hook.sh b/pkgs/build-support/setup-hooks/wrap-gapps-hook.sh
index 906b1db9d10e..a05d4f689db9 100644
--- a/pkgs/build-support/setup-hooks/wrap-gapps-hook.sh
+++ b/pkgs/build-support/setup-hooks/wrap-gapps-hook.sh
@@ -1,14 +1,21 @@
+# shellcheck shell=bash
 gappsWrapperArgs=()
 
 find_gio_modules() {
-    if [ -d "$1"/lib/gio/modules ] && [ -n "$(ls -A $1/lib/gio/modules)" ] ; then
+    if [ -d "$1/lib/gio/modules" ] && [ -n "$(ls -A "$1/lib/gio/modules")" ] ; then
         gappsWrapperArgs+=(--prefix GIO_EXTRA_MODULES : "$1/lib/gio/modules")
     fi
 }
 
-addEnvHooks "$targetOffset" find_gio_modules
+addEnvHooks "${targetOffset:?}" find_gio_modules
 
-# Note: $gappsWrapperArgs still gets defined even if $dontWrapGApps is set.
+wrapGApp() {
+    local program="$1"
+    shift 1
+    wrapProgram "$program" "${gappsWrapperArgs[@]}" "$@"
+}
+
+# Note: $gappsWrapperArgs still gets defined even if ${dontWrapGApps-} is set.
 wrapGAppsHook() {
   # guard against running multiple times (e.g. due to propagation)
   [ -z "$wrapGAppsHookHasRun" ] || return 0
@@ -26,20 +33,19 @@ wrapGAppsHook() {
     gappsWrapperArgs+=(--prefix XDG_DATA_DIRS : "$GSETTINGS_SCHEMAS_PATH")
   fi
 
-  if [ -d "$prefix/share" ]; then
+  if [ -d "${prefix:?}/share" ]; then
     gappsWrapperArgs+=(--prefix XDG_DATA_DIRS : "$prefix/share")
   fi
 
-  if [ -d "$prefix/lib/gio/modules" ] && [ -n "$(ls -A $prefix/lib/gio/modules)" ] ; then
+  if [ -d "$prefix/lib/gio/modules" ] && [ -n "$(ls -A "$prefix/lib/gio/modules")" ] ; then
     gappsWrapperArgs+=(--prefix GIO_EXTRA_MODULES : "$prefix/lib/gio/modules")
   fi
 
-  for v in $wrapPrefixVariables GST_PLUGIN_SYSTEM_PATH_1_0 GI_TYPELIB_PATH GRL_PLUGIN_PATH; do
-    eval local dummy="\$$v"
-    gappsWrapperArgs+=(--prefix $v : "$dummy")
+  for v in ${wrapPrefixVariables:-} GST_PLUGIN_SYSTEM_PATH_1_0 GI_TYPELIB_PATH GRL_PLUGIN_PATH; do
+    gappsWrapperArgs+=(--prefix "$v" : "${!v}")
   done
 
-  if [[ -z "$dontWrapGApps" ]]; then
+  if [[ -z "${dontWrapGApps:-}" ]]; then
     targetDirsThatExist=()
     targetDirsRealPath=()
 
@@ -52,7 +58,7 @@ wrapGAppsHook() {
         find "${targetDir}" -type f -executable -print0 \
           | while IFS= read -r -d '' file; do
           echo "Wrapping program '${file}'"
-          wrapProgram "${file}" "${gappsWrapperArgs[@]}"
+          wrapGApp "${file}"
         done
       fi
     done
@@ -71,7 +77,7 @@ wrapGAppsHook() {
           fi
         done
         echo "Wrapping link: '$linkPath'"
-        wrapProgram "${linkPath}" "${gappsWrapperArgs[@]}"
+        wrapGApp "${linkPath}"
       done
     fi
   fi
diff --git a/pkgs/build-support/skaware/build-skaware-package.nix b/pkgs/build-support/skaware/build-skaware-package.nix
index ce32279710e2..9b159a994c80 100644
--- a/pkgs/build-support/skaware/build-skaware-package.nix
+++ b/pkgs/build-support/skaware/build-skaware-package.nix
@@ -19,10 +19,6 @@ in {
   # mostly for moving and deleting files from the build directory
   # : lines
 , postInstall
-  # packages with setup hooks that should be run
-  # (see definition of `makeSetupHook`)
-  # : list drv
-, setupHooks ? []
   # : list Maintainer
 , maintainers ? []
 
@@ -67,8 +63,6 @@ in stdenv.mkDerivation {
   dontDisableStatic = true;
   enableParallelBuilding = true;
 
-  nativeBuildInputs = setupHooks;
-
   configureFlags = configureFlags ++ [
     "--enable-absolute-paths"
     (if stdenv.isDarwin
diff --git a/pkgs/build-support/vm/default.nix b/pkgs/build-support/vm/default.nix
index 371ab13c5281..335cab7c45e1 100644
--- a/pkgs/build-support/vm/default.nix
+++ b/pkgs/build-support/vm/default.nix
@@ -719,7 +719,7 @@ rec {
     { name, fullName, size ? 4096, urlPrefix
     , packagesList ? "", packagesLists ? [packagesList]
     , packages, extraPackages ? [], postInstall ? ""
-    , extraDebs ? []
+    , extraDebs ? [], createRootFS ? defaultCreateRootFS
     , QEMU_OPTS ? "", memSize ? 512 }:
 
     let
@@ -729,7 +729,7 @@ rec {
       };
     in
       (fillDiskWithDebs {
-        inherit name fullName size postInstall QEMU_OPTS memSize;
+        inherit name fullName size postInstall createRootFS QEMU_OPTS memSize;
         debs = import expr {inherit fetchurl;} ++ extraDebs;
       }) // {inherit expr;};
 
diff --git a/pkgs/build-support/writers/default.nix b/pkgs/build-support/writers/default.nix
index 8dbe0dbdbd03..2cd4f1af022b 100644
--- a/pkgs/build-support/writers/default.nix
+++ b/pkgs/build-support/writers/default.nix
@@ -92,13 +92,15 @@ rec {
         PATH=${makeBinPath [
           pkgs.binutils-unwrapped
           pkgs.coreutils
+          pkgs.findutils
           pkgs.gcc
           pkgs.pkgconfig
         ]}
+        export PKG_CONFIG_PATH=${concatMapStringsSep ":" (pkg: "${pkg}/lib/pkgconfig") libraries}
         gcc \
             ${optionalString (libraries != [])
               "$(pkg-config --cflags --libs ${
-                concatMapStringsSep " " (pkg: "$(find ${escapeShellArg pkg}/lib/pkgsconfig -name \*.pc -exec basename {} \;)") libraries
+                concatMapStringsSep " " (pkg: "$(find ${escapeShellArg pkg}/lib/pkgconfig -name \\*.pc)") libraries
               })"
             } \
             -O \
diff --git a/pkgs/build-support/writers/test.nix b/pkgs/build-support/writers/test.nix
index d7c347a559ef..3cd0a080ae8f 100644
--- a/pkgs/build-support/writers/test.nix
+++ b/pkgs/build-support/writers/test.nix
@@ -1,4 +1,16 @@
-{ stdenv, lib, runCommand, haskellPackages, nodePackages, perlPackages, python2Packages, python3Packages, writers, writeText }:
+{
+  glib,
+  haskellPackages,
+  lib,
+  nodePackages,
+  perlPackages,
+  python2Packages,
+  python3Packages,
+  runCommand,
+  stdenv,
+  writers,
+  writeText
+}:
 with writers;
 let
 
@@ -49,9 +61,11 @@ let
     python2 = writePython2Bin "test_writers" { libraries = [ python2Packages.enum ]; } ''
       from enum import Enum
 
+
       class Test(Enum):
           a = "success"
 
+
       print Test.a
     '';
 
@@ -70,9 +84,19 @@ let
      if [[ "test" == "test" ]]; then echo "success"; fi
     '';
 
-    c = writeC "test_c" { libraries = [ ]; } ''
+    c = writeC "test_c" { libraries = [ glib.dev ]; } ''
+      #include <gio/gio.h>
       #include <stdio.h>
       int main() {
+        GApplication *application = g_application_new ("hello.world", G_APPLICATION_FLAGS_NONE);
+        g_application_register (application, NULL, NULL);
+        GNotification *notification = g_notification_new ("Hello world!");
+        g_notification_set_body (notification, "This is an example notification.");
+        GIcon *icon = g_themed_icon_new ("dialog-information");
+        g_notification_set_icon (notification, icon);
+        g_object_unref (icon);
+        g_object_unref (notification);
+        g_object_unref (application);
         printf("success\n");
         return 0;
       }
@@ -112,9 +136,11 @@ let
     python2 = writePython2 "test_python2" { libraries = [ python2Packages.enum ]; } ''
       from enum import Enum
 
+
       class Test(Enum):
           a = "success"
 
+
       print Test.a
     '';