summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--pkgs/applications/altcoins/bitcoin.nix3
-rw-r--r--pkgs/applications/misc/jekyll/default.nix2
-rw-r--r--pkgs/applications/networking/cluster/panamax/api/default.nix8
-rw-r--r--pkgs/applications/networking/cluster/panamax/ui/default.nix7
-rw-r--r--pkgs/applications/version-management/git-and-tools/git/default.nix3
-rw-r--r--pkgs/build-support/cc-wrapper/cc-wrapper.sh8
-rw-r--r--pkgs/build-support/setup-hooks/set-source-date-epoch-to-latest.sh31
-rw-r--r--pkgs/development/compilers/gcc/4.9/default.nix3
-rw-r--r--pkgs/development/compilers/gcc/5/default.nix3
-rw-r--r--pkgs/development/compilers/gcc/use-source-date-epoch.patch52
-rw-r--r--pkgs/development/compilers/llvm/3.7/clang/default.nix2
-rw-r--r--pkgs/development/compilers/llvm/3.7/default.nix6
-rw-r--r--pkgs/development/compilers/llvm/3.7/libc++/default.nix2
-rw-r--r--pkgs/development/compilers/llvm/3.7/libc++abi.nix4
-rw-r--r--pkgs/development/compilers/llvm/3.7/lldb.nix2
-rw-r--r--pkgs/development/compilers/llvm/3.7/llvm.nix7
-rw-r--r--pkgs/development/compilers/llvm/3.7/r242372-fix-LLVMBuildLandingPad.patch60
-rw-r--r--pkgs/development/compilers/rustc/head.nix20
-rw-r--r--pkgs/development/compilers/sbcl/bootstrap.nix5
-rw-r--r--pkgs/development/interpreters/perl/5.20/default.nix8
-rw-r--r--pkgs/development/interpreters/ruby/build-ruby-gem/default.nix208
-rw-r--r--pkgs/development/interpreters/ruby/build-ruby-gem/gem-post-build.rb77
-rw-r--r--pkgs/development/interpreters/ruby/build-ruby-gem/nix-bundle-install.rb153
-rw-r--r--pkgs/development/interpreters/ruby/bundix/Gemfile4
-rw-r--r--pkgs/development/interpreters/ruby/bundix/Gemfile.lock18
-rw-r--r--pkgs/development/interpreters/ruby/bundix/default.nix25
-rw-r--r--pkgs/development/interpreters/ruby/bundix/gemset.nix22
-rw-r--r--pkgs/development/interpreters/ruby/bundler-env/default.nix361
-rw-r--r--pkgs/development/interpreters/ruby/bundler-env/gen-bin-stubs.rb46
-rw-r--r--pkgs/development/interpreters/ruby/bundler-env/monkey_patches.rb246
-rw-r--r--pkgs/development/interpreters/ruby/bundler-env/package-1.8.rb29
-rw-r--r--pkgs/development/interpreters/ruby/bundler.nix17
-rw-r--r--pkgs/development/interpreters/ruby/gem.nix136
-rw-r--r--pkgs/development/interpreters/ruby/gemconfig/default.nix (renamed from pkgs/development/interpreters/ruby/bundler-env/default-gem-config.nix)28
-rw-r--r--pkgs/development/interpreters/ruby/gemconfig/mkrf_conf_xapian.rb (renamed from pkgs/development/interpreters/ruby/bundler-env/mkrf_conf_xapian.rb)0
-rw-r--r--pkgs/development/interpreters/ruby/gemconfig/xapian-Rakefile (renamed from pkgs/development/interpreters/ruby/bundler-env/xapian-Rakefile)0
-rw-r--r--pkgs/development/interpreters/ruby/load-ruby-env.nix69
-rw-r--r--pkgs/development/interpreters/ruby/rubygems.nix34
-rw-r--r--pkgs/development/libraries/apr-util/default.nix25
-rw-r--r--pkgs/development/libraries/apr-util/include-static-dependencies.patch12
-rw-r--r--pkgs/development/libraries/at-spi2-atk/default.nix4
-rw-r--r--pkgs/development/libraries/at-spi2-core/default.nix4
-rw-r--r--pkgs/development/libraries/avahi/default.nix9
-rw-r--r--pkgs/development/libraries/boost/generic.nix2
-rw-r--r--pkgs/development/libraries/cyrus-sasl/default.nix13
-rw-r--r--pkgs/development/libraries/cyrus-sasl/missing-size_t.patch4
-rw-r--r--pkgs/development/libraries/db/clang-4.8.patch22
-rw-r--r--pkgs/development/libraries/db/clang-5.3.patch (renamed from pkgs/development/libraries/db/osx.patch)0
-rw-r--r--pkgs/development/libraries/db/db-4.8.nix1
-rw-r--r--pkgs/development/libraries/db/db-5.3.nix2
-rw-r--r--pkgs/development/libraries/db/generic.nix1
-rw-r--r--pkgs/development/libraries/exiv2/default.nix20
-rw-r--r--pkgs/development/libraries/expat/default.nix2
-rw-r--r--pkgs/development/libraries/ffmpeg-full/default.nix4
-rw-r--r--pkgs/development/libraries/ffmpeg/2.8.nix4
-rw-r--r--pkgs/development/libraries/gdk-pixbuf/default.nix4
-rw-r--r--pkgs/development/libraries/gecode/3.nix21
-rw-r--r--pkgs/development/libraries/glib/default.nix6
-rw-r--r--pkgs/development/libraries/gnutls/generic.nix2
-rw-r--r--pkgs/development/libraries/gtk+/2.x.nix4
-rw-r--r--pkgs/development/libraries/harfbuzz/default.nix4
-rw-r--r--pkgs/development/libraries/icu/default.nix2
-rw-r--r--pkgs/development/libraries/kerberos/heimdal.nix10
-rw-r--r--pkgs/development/libraries/kerberos/krb5.nix16
-rw-r--r--pkgs/development/libraries/libdrm/default.nix4
-rw-r--r--pkgs/development/libraries/libedit/default.nix14
-rw-r--r--pkgs/development/libraries/libedit/freebsd-wchar.patch13
-rw-r--r--pkgs/development/libraries/libelf-freebsd/default.nix37
-rw-r--r--pkgs/development/libraries/libiconv/default.nix14
-rw-r--r--pkgs/development/libraries/libossp-uuid/default.nix2
-rw-r--r--pkgs/development/libraries/libxml2/default.nix8
-rw-r--r--pkgs/development/libraries/openldap/default.nix14
-rw-r--r--pkgs/development/libraries/pango/default.nix4
-rw-r--r--pkgs/development/libraries/qt-4.x/4.8/default.nix11
-rw-r--r--pkgs/development/libraries/serf/default.nix2
-rw-r--r--pkgs/development/libraries/zlib/default.nix3
-rw-r--r--pkgs/development/tools/build-managers/cargo/head.nix39
-rw-r--r--pkgs/development/tools/guile/g-wrap/default.nix2
-rw-r--r--pkgs/development/tools/misc/gnum4/default.nix3
-rw-r--r--pkgs/development/tools/misc/tet/default.nix29
-rw-r--r--pkgs/development/tools/vagrant/default.nix3
-rw-r--r--pkgs/os-specific/darwin/apple-source-releases/Csu/default.nix4
-rw-r--r--pkgs/os-specific/darwin/apple-source-releases/IOKit/default.nix194
-rw-r--r--pkgs/os-specific/darwin/apple-source-releases/Libsystem/default.nix2
-rw-r--r--pkgs/os-specific/darwin/apple-source-releases/default.nix285
-rw-r--r--pkgs/os-specific/darwin/apple-source-releases/xnu/default.nix2
-rw-r--r--pkgs/os-specific/darwin/cctools/port.nix15
-rw-r--r--pkgs/servers/shishi/default.nix2
-rw-r--r--pkgs/servers/shishi/freebsd-unistd.patch12
-rw-r--r--pkgs/servers/x11/xorg/default.nix50
-rw-r--r--pkgs/servers/x11/xorg/old.list2
-rw-r--r--pkgs/servers/x11/xorg/tarballs-7.7.list22
-rw-r--r--pkgs/stdenv/default.nix3
-rw-r--r--pkgs/stdenv/freebsd/default.nix65
-rw-r--r--pkgs/stdenv/freebsd/trivial-bootstrap.sh204
-rw-r--r--pkgs/stdenv/generic/default.nix1
-rw-r--r--pkgs/stdenv/generic/setup.sh41
-rw-r--r--pkgs/tools/archivers/sharutils/default.nix2
-rw-r--r--pkgs/tools/audio/mpdcron/default.nix2
-rw-r--r--pkgs/tools/compression/bzip2/default.nix5
-rw-r--r--pkgs/tools/compression/lz4/default.nix2
-rw-r--r--pkgs/tools/compression/lz4/install-on-freebsd.patch54
-rw-r--r--pkgs/tools/misc/fluentd/default.nix2
-rw-r--r--pkgs/tools/networking/miniupnpc/default.nix6
-rw-r--r--pkgs/tools/networking/miniupnpc/freebsd.patch11
-rw-r--r--pkgs/tools/text/gawk/default.nix1
-rw-r--r--pkgs/tools/text/gnugrep/default.nix5
-rw-r--r--pkgs/top-level/all-packages.nix45
-rw-r--r--pkgs/top-level/perl-packages.nix10
109 files changed, 1833 insertions, 1325 deletions
diff --git a/pkgs/applications/altcoins/bitcoin.nix b/pkgs/applications/altcoins/bitcoin.nix
index bdd0335fe3b5..91432f2f5a8a 100644
--- a/pkgs/applications/altcoins/bitcoin.nix
+++ b/pkgs/applications/altcoins/bitcoin.nix
@@ -17,7 +17,8 @@ stdenv.mkDerivation rec{
   };
 
   buildInputs = [ pkgconfig autoreconfHook openssl db48 boost zlib
-                  miniupnpc utillinux protobuf ]
+                  miniupnpc protobuf ]
+                  ++ optionals stdenv.isLinux [ utillinux ]
                   ++ optionals withGui [ qt4 qrencode ];
 
   configureFlags = [ "--with-boost-libdir=${boost.lib}/lib" ]
diff --git a/pkgs/applications/misc/jekyll/default.nix b/pkgs/applications/misc/jekyll/default.nix
index bca43398f6ff..e9536055ca3b 100644
--- a/pkgs/applications/misc/jekyll/default.nix
+++ b/pkgs/applications/misc/jekyll/default.nix
@@ -9,8 +9,6 @@ bundlerEnv rec {
   lockfile = ./Gemfile.lock;
   gemset = ./gemset.nix;
 
-  buildInputs = [ curl ];
-
   meta = with lib; {
     description = "Simple, blog aware, static site generator";
     homepage    =  http://jekyllrb.com/;
diff --git a/pkgs/applications/networking/cluster/panamax/api/default.nix b/pkgs/applications/networking/cluster/panamax/api/default.nix
index dcfef83f1bec..6e20f7c23038 100644
--- a/pkgs/applications/networking/cluster/panamax/api/default.nix
+++ b/pkgs/applications/networking/cluster/panamax/api/default.nix
@@ -1,6 +1,6 @@
-{ stdenv, buildEnv, fetchgit, fetchurl, makeWrapper, bundlerEnv, bundler_HEAD
+{ stdenv, buildEnv, fetchgit, fetchurl, makeWrapper, bundlerEnv, bundler
 , ruby, libxslt, libxml2, sqlite, openssl, docker
-, dataDir ? "/var/lib/panamax-api" }:
+, dataDir ? "/var/lib/panamax-api" }@args:
 
 with stdenv.lib;
 
@@ -14,9 +14,9 @@ stdenv.mkDerivation rec {
     gemset = ./gemset.nix;
     gemfile = ./Gemfile;
     lockfile = ./Gemfile.lock;
-    buildInputs = [ openssl ];
   };
-  bundler = bundler_HEAD.override { inherit ruby; };
+
+  bundler = args.bundler.override { inherit ruby; };
 
   database_yml = builtins.toFile "database.yml" ''
     production:
diff --git a/pkgs/applications/networking/cluster/panamax/ui/default.nix b/pkgs/applications/networking/cluster/panamax/ui/default.nix
index 3dac10613625..88e0efc18a64 100644
--- a/pkgs/applications/networking/cluster/panamax/ui/default.nix
+++ b/pkgs/applications/networking/cluster/panamax/ui/default.nix
@@ -1,5 +1,5 @@
-{ stdenv, fetchgit, fetchurl, makeWrapper, bundlerEnv, bundler_HEAD
-, ruby, rubygemsFun, openssl, sqlite, dataDir ? "/var/lib/panamax-ui"}:
+{ stdenv, fetchgit, fetchurl, makeWrapper, bundlerEnv, bundler
+, ruby, openssl, sqlite, dataDir ? "/var/lib/panamax-ui"}@args:
 
 with stdenv.lib;
 
@@ -13,10 +13,9 @@ stdenv.mkDerivation rec {
     gemset = ./gemset.nix;
     gemfile = ./Gemfile;
     lockfile = ./Gemfile.lock;
-    buildInputs = [ openssl ];
   };
 
-  bundler = bundler_HEAD.override { inherit ruby; };
+  bundler = args.bundler.override { inherit ruby; };
 
   src = fetchgit {
     rev = "refs/tags/v${version}";
diff --git a/pkgs/applications/version-management/git-and-tools/git/default.nix b/pkgs/applications/version-management/git-and-tools/git/default.nix
index 1045724090ff..49ecce0456b2 100644
--- a/pkgs/applications/version-management/git-and-tools/git/default.nix
+++ b/pkgs/applications/version-management/git-and-tools/git/default.nix
@@ -34,7 +34,8 @@ stdenv.mkDerivation {
     ++ stdenv.lib.optionals guiSupport [tcl tk];
 
   # required to support pthread_cancel()
-  NIX_LDFLAGS = stdenv.lib.optionalString (!stdenv.isDarwin) "-lgcc_s";
+  NIX_LDFLAGS = stdenv.lib.optionalString (!stdenv.cc.isClang) "-lgcc_s"
+              + stdenv.lib.optionalString (stdenv.isFreeBSD) "-lthr";
 
   # without this, git fails when trying to check for /etc/gitconfig existence
   propagatedSandboxProfile = stdenv.lib.sandbox.allowDirectoryList "/etc";
diff --git a/pkgs/build-support/cc-wrapper/cc-wrapper.sh b/pkgs/build-support/cc-wrapper/cc-wrapper.sh
index e374e1656a47..5bd59f8c5850 100644
--- a/pkgs/build-support/cc-wrapper/cc-wrapper.sh
+++ b/pkgs/build-support/cc-wrapper/cc-wrapper.sh
@@ -90,14 +90,6 @@ fi
 extraAfter=($NIX_CFLAGS_COMPILE)
 extraBefore=()
 
-# When enforcing purity, pretend gcc can't find the current date and
-# time
-if [ "$NIX_ENFORCE_PURITY" = 1 ]; then
-    extraAfter+=('-D__DATE__="Jan 01 1970"'
-        '-D__TIME__="00:00:01"'
-        -Wno-builtin-macro-redefined)
-fi
-
 
 if [ "$dontLink" != 1 ]; then
 
diff --git a/pkgs/build-support/setup-hooks/set-source-date-epoch-to-latest.sh b/pkgs/build-support/setup-hooks/set-source-date-epoch-to-latest.sh
new file mode 100644
index 000000000000..9e325106f821
--- /dev/null
+++ b/pkgs/build-support/setup-hooks/set-source-date-epoch-to-latest.sh
@@ -0,0 +1,31 @@
+updateSourceDateEpoch() {
+    local path="$1"
+
+    # Get the last modification time of all regular files, sort them,
+    # and get the most recent. Maybe we should use
+    # https://github.com/0-wiz-0/findnewest here.
+    local -a res=($(find "$path" -type f -print0 | xargs -0 -r stat -c '%Y %n' | sort -n | tail -n1))
+    local time="${res[0]}"
+    local newestFile="${res[1]}"
+
+    # Update $SOURCE_DATE_EPOCH if the most recent file we found is newer.
+    if [ "$time" -gt "$SOURCE_DATE_EPOCH" ]; then
+        echo "setting SOURCE_DATE_EPOCH to timestamp $time of file $newestFile"
+        export SOURCE_DATE_EPOCH="$time"
+
+        # Warn if the new timestamp is too close to the present. This
+        # may indicate that we were being applied to a file generated
+        # during the build, or that an unpacker didn't restore
+        # timestamps properly.
+        local now="$(date +%s)"
+        if [ "$time" -gt $((now - 60)) ]; then
+            echo "warning: file $newestFile may be generated; SOURCE_DATE_EPOCH may be non-deterministic"
+        fi
+    fi
+}
+
+postUnpackHooks+=(_updateSourceDateEpochFromSourceRoot)
+
+_updateSourceDateEpochFromSourceRoot() {
+    updateSourceDateEpoch "$sourceRoot"
+}
diff --git a/pkgs/development/compilers/gcc/4.9/default.nix b/pkgs/development/compilers/gcc/4.9/default.nix
index fecdd85cd415..add9b30fb629 100644
--- a/pkgs/development/compilers/gcc/4.9/default.nix
+++ b/pkgs/development/compilers/gcc/4.9/default.nix
@@ -63,7 +63,8 @@ let version = "4.9.3";
 
     enableParallelBuilding = true;
 
-    patches = [ ]
+    patches =
+      [ ../use-source-date-epoch.patch ]
       ++ optionals enableParallelBuilding [ ../parallel-bconfig.patch ./parallel-strsignal.patch ]
       ++ optional (cross != null) ../libstdc++-target.patch
       ++ optional noSysDirs ../no-sys-dirs.patch
diff --git a/pkgs/development/compilers/gcc/5/default.nix b/pkgs/development/compilers/gcc/5/default.nix
index f3dda7d13f7c..3b105143c0bf 100644
--- a/pkgs/development/compilers/gcc/5/default.nix
+++ b/pkgs/development/compilers/gcc/5/default.nix
@@ -64,7 +64,8 @@ let version = "5.3.0";
 
     enableParallelBuilding = true;
 
-    patches = [ ]
+    patches =
+      [ ../use-source-date-epoch.patch ]
       ++ optional (cross != null) ../libstdc++-target.patch
       ++ optional noSysDirs ../no-sys-dirs.patch
       # The GNAT Makefiles did not pay attention to CFLAGS_FOR_TARGET for its
diff --git a/pkgs/development/compilers/gcc/use-source-date-epoch.patch b/pkgs/development/compilers/gcc/use-source-date-epoch.patch
new file mode 100644
index 000000000000..65a5ab028c1c
--- /dev/null
+++ b/pkgs/development/compilers/gcc/use-source-date-epoch.patch
@@ -0,0 +1,52 @@
+https://gcc.gnu.org/ml/gcc-patches/2015-06/msg02210.html
+
+diff --git a/libcpp/macro.c b/libcpp/macro.c
+index 1e0a0b5..a52e3cb 100644
+--- a/libcpp/macro.c
++++ b/libcpp/macro.c
+@@ -349,14 +349,38 @@ _cpp_builtin_macro_text (cpp_reader *pfile, cpp_hashnode *node)
+ 	     slow on some systems.  */
+ 	  time_t tt;
+ 	  struct tm *tb = NULL;
++	  char *source_date_epoch;
+ 
+-	  /* (time_t) -1 is a legitimate value for "number of seconds
+-	     since the Epoch", so we have to do a little dance to
+-	     distinguish that from a genuine error.  */
+-	  errno = 0;
+-	  tt = time(NULL);
+-	  if (tt != (time_t)-1 || errno == 0)
+-	    tb = localtime (&tt);
++	  /* Allow the date and time to be set externally by an exported
++	     environment variable to enable reproducible builds. */
++	  source_date_epoch = getenv ("SOURCE_DATE_EPOCH");
++	  if (source_date_epoch)
++	    {
++	      errno = 0;
++	      tt = (time_t) strtol (source_date_epoch, NULL, 10);
++	      if (errno == 0)
++	        {
++		  tb = gmtime (&tt);
++		  if (tb == NULL)
++		    cpp_error (pfile, CPP_DL_ERROR,
++			       "SOURCE_DATE_EPOCH=\"%s\" is not a valid date",
++			       source_date_epoch);
++	        }
++	      else
++		cpp_error (pfile, CPP_DL_ERROR,
++			   "SOURCE_DATE_EPOCH=\"%s\" is not a valid number",
++			   source_date_epoch);
++	    }
++	  else
++	    {
++	    /* (time_t) -1 is a legitimate value for "number of seconds
++	       since the Epoch", so we have to do a little dance to
++	       distinguish that from a genuine error.  */
++	    errno = 0;
++	    tt = time(NULL);
++	    if (tt != (time_t)-1 || errno == 0)
++	      tb = localtime (&tt);
++	  }
+ 
+ 	  if (tb)
+ 	    {
diff --git a/pkgs/development/compilers/llvm/3.7/clang/default.nix b/pkgs/development/compilers/llvm/3.7/clang/default.nix
index 9fb212b9c054..e6369b1167e7 100644
--- a/pkgs/development/compilers/llvm/3.7/clang/default.nix
+++ b/pkgs/development/compilers/llvm/3.7/clang/default.nix
@@ -6,7 +6,7 @@ in stdenv.mkDerivation {
   name = "clang-${version}";
 
   unpackPhase = ''
-    unpackFile ${fetch "cfe" "1k517b0jj74c4vgnnd4ikbrpb96na541bi8q845ckw8xm72l1msf"}
+    unpackFile ${fetch "cfe" "0x065d0w9b51xvdjxwfzjxng0gzpbx45fgiaxpap45ragi61dqjn"}
     mv cfe-${version}.src clang
     sourceRoot=$PWD/clang
     unpackFile ${clang-tools-extra_src}
diff --git a/pkgs/development/compilers/llvm/3.7/default.nix b/pkgs/development/compilers/llvm/3.7/default.nix
index cbd0f89ae086..d7864d11d7bf 100644
--- a/pkgs/development/compilers/llvm/3.7/default.nix
+++ b/pkgs/development/compilers/llvm/3.7/default.nix
@@ -2,7 +2,7 @@
 let
   callPackage = newScope (self // { inherit stdenv isl version fetch; });
 
-  version = "3.7.0";
+  version = "3.7.1";
 
   fetch = fetch_v version;
   fetch_v = ver: name: sha256: fetchurl {
@@ -10,8 +10,8 @@ let
     inherit sha256;
   };
 
-  compiler-rt_src = fetch "compiler-rt" "02rbsqdnj1dw9q3d8w5wwmvz5gfraiv8xp18lis4kj8baacajzr2";
-  clang-tools-extra_src = fetch "clang-tools-extra" "1k894zkx4w8grigmgv5y4q9zrcic2ypz0zfn28270ykbm6is1s4a";
+  compiler-rt_src = fetch "compiler-rt" "10c1mz2q4bdq9bqfgr3dirc6hz1h3sq8573srd5q5lr7m7j6jiwx";
+  clang-tools-extra_src = fetch "clang-tools-extra" "0sxw2l3q5msbrwxv1ck72arggdw6n5ysi929gi69ikniranfv4aa";
 
   self = {
     llvm = callPackage ./llvm.nix {
diff --git a/pkgs/development/compilers/llvm/3.7/libc++/default.nix b/pkgs/development/compilers/llvm/3.7/libc++/default.nix
index db1475cfc14f..00bfb3518b10 100644
--- a/pkgs/development/compilers/llvm/3.7/libc++/default.nix
+++ b/pkgs/development/compilers/llvm/3.7/libc++/default.nix
@@ -3,7 +3,7 @@
 stdenv.mkDerivation rec {
   name = "libc++-${version}";
 
-  src = fetch "libcxx" "13nh78zp5d2jf732mxnalw679zjywbjpz9942j66fznd6f1kr3y1";
+  src = fetch "libcxx" "0i7iyzk024krda5spfpfi8jksh83yp3bxqkal0xp76ffi11bszrm";
 
   postUnpack = ''
     unpackFile ${libcxxabi.src}
diff --git a/pkgs/development/compilers/llvm/3.7/libc++abi.nix b/pkgs/development/compilers/llvm/3.7/libc++abi.nix
index 97f182a9af81..ec0be51a11cf 100644
--- a/pkgs/development/compilers/llvm/3.7/libc++abi.nix
+++ b/pkgs/development/compilers/llvm/3.7/libc++abi.nix
@@ -3,9 +3,9 @@
 stdenv.mkDerivation {
   name = "libc++abi-${version}";
 
-  src = fetch "libcxxabi" "1swvnhrf9g67579c5picg0l869f8l2bwi4xqpbcb4n296gyp9c28";
+  src = fetch "libcxxabi" "0ambfcmr2nh88hx000xb7yjm9lsqjjz49w5mlf6dlxzmj3nslzx4";
 
-  buildInputs = [ cmake ] ++ stdenv.lib.optional (!stdenv.isDarwin) libunwind;
+  buildInputs = [ cmake ] ++ stdenv.lib.optional (!stdenv.isDarwin && !stdenv.isFreeBSD) libunwind;
 
   postUnpack = ''
     unpackFile ${libcxx.src}
diff --git a/pkgs/development/compilers/llvm/3.7/lldb.nix b/pkgs/development/compilers/llvm/3.7/lldb.nix
index 60f1550dd447..fe69130e71a7 100644
--- a/pkgs/development/compilers/llvm/3.7/lldb.nix
+++ b/pkgs/development/compilers/llvm/3.7/lldb.nix
@@ -15,7 +15,7 @@
 stdenv.mkDerivation {
   name = "lldb-${version}";
 
-  src = fetch "lldb" "1sbi9c6c4m73wfw249dn0n2974p444i03brk82m4w10iq5dm1mzl";
+  src = fetch "lldb" "008fdbyza13ym3v0xpans4z4azw4y16hcbgrrnc4rx2mxwaw62ws";
 
   patchPhase = ''
     sed -i 's|/usr/bin/env||' \
diff --git a/pkgs/development/compilers/llvm/3.7/llvm.nix b/pkgs/development/compilers/llvm/3.7/llvm.nix
index bbeb0c858e57..393e889024be 100644
--- a/pkgs/development/compilers/llvm/3.7/llvm.nix
+++ b/pkgs/development/compilers/llvm/3.7/llvm.nix
@@ -18,15 +18,10 @@
 }:
 
 let
-  src = fetch "llvm" "0lrirklh4nrcb078qc2f6vbmmc34kxqgsy9s18a1xbfdkmgqjidb";
+  src = fetch "llvm" "1masakdp9g2dan1yrazg7md5am2vacbkb3nahb3dchpc1knr8xxy";
 in stdenv.mkDerivation rec {
   name = "llvm-${version}";
 
-  patches = [
-    # Backport for Rust, remove when 3.7.1 is released
-    ./r242372-fix-LLVMBuildLandingPad.patch
-  ];
-
   unpackPhase = ''
     unpackFile ${src}
     mv llvm-${version}.src llvm
diff --git a/pkgs/development/compilers/llvm/3.7/r242372-fix-LLVMBuildLandingPad.patch b/pkgs/development/compilers/llvm/3.7/r242372-fix-LLVMBuildLandingPad.patch
deleted file mode 100644
index 749de6e9b6a1..000000000000
--- a/pkgs/development/compilers/llvm/3.7/r242372-fix-LLVMBuildLandingPad.patch
+++ /dev/null
@@ -1,60 +0,0 @@
-Index: llvm/bindings/ocaml/llvm/llvm_ocaml.c
-===================================================================
---- llvm/bindings/ocaml/llvm/llvm_ocaml.c	(revision 242371)
-+++ llvm/bindings/ocaml/llvm/llvm_ocaml.c	(revision 242372)
-@@ -1745,7 +1745,7 @@
- CAMLprim LLVMValueRef llvm_build_landingpad(LLVMTypeRef Ty, LLVMValueRef PersFn,
-                                             value NumClauses,  value Name,
-                                             value B) {
--    return LLVMBuildLandingPad(Builder_val(B), Ty, Int_val(NumClauses),
-+    return LLVMBuildLandingPad(Builder_val(B), Ty, PersFn, Int_val(NumClauses),
-                                String_val(Name));
- }
- 
-Index: llvm/bindings/go/llvm/ir.go
-===================================================================
---- llvm/bindings/go/llvm/ir.go	(revision 242371)
-+++ llvm/bindings/go/llvm/ir.go	(revision 242372)
-@@ -1731,7 +1731,7 @@
- func (b Builder) CreateLandingPad(t Type, nclauses int, name string) (l Value) {
- 	cname := C.CString(name)
- 	defer C.free(unsafe.Pointer(cname))
--	l.C = C.LLVMBuildLandingPad(b.C, t.C, C.unsigned(nclauses), cname)
-+	l.C = C.LLVMBuildLandingPad(b.C, t.C, nil, C.unsigned(nclauses), cname)
- 	return l
- }
- 
-Index: llvm/lib/IR/Core.cpp
-===================================================================
---- llvm/lib/IR/Core.cpp	(revision 242371)
-+++ llvm/lib/IR/Core.cpp	(revision 242372)
-@@ -2257,7 +2257,14 @@
- }
- 
- LLVMValueRef LLVMBuildLandingPad(LLVMBuilderRef B, LLVMTypeRef Ty,
--                                 unsigned NumClauses, const char *Name) {
-+                                 LLVMValueRef PersFn, unsigned NumClauses,
-+                                 const char *Name) {
-+  // The personality used to live on the landingpad instruction, but now it
-+  // lives on the parent function. For compatibility, take the provided
-+  // personality and put it on the parent function.
-+  if (PersFn)
-+    unwrap(B)->GetInsertBlock()->getParent()->setPersonalityFn(
-+        cast<Function>(unwrap(PersFn)));
-   return wrap(unwrap(B)->CreateLandingPad(unwrap(Ty), NumClauses, Name));
- }
- 
-Index: llvm/include/llvm-c/Core.h
-===================================================================
---- llvm/include/llvm-c/Core.h	(revision 242371)
-+++ llvm/include/llvm-c/Core.h	(revision 242372)
-@@ -2675,7 +2675,8 @@
-                              LLVMBasicBlockRef Then, LLVMBasicBlockRef Catch,
-                              const char *Name);
- LLVMValueRef LLVMBuildLandingPad(LLVMBuilderRef B, LLVMTypeRef Ty,
--                                 unsigned NumClauses, const char *Name);
-+                                 LLVMValueRef PersFn, unsigned NumClauses,
-+                                 const char *Name);
- LLVMValueRef LLVMBuildResume(LLVMBuilderRef B, LLVMValueRef Exn);
- LLVMValueRef LLVMBuildUnreachable(LLVMBuilderRef);
- 
diff --git a/pkgs/development/compilers/rustc/head.nix b/pkgs/development/compilers/rustc/head.nix
index ccbfc51b671a..2cefc4cfc137 100644
--- a/pkgs/development/compilers/rustc/head.nix
+++ b/pkgs/development/compilers/rustc/head.nix
@@ -2,11 +2,11 @@
 { stdenv, callPackage }:
 
 callPackage ./generic.nix {
-  shortVersion = "2015-12-09";
+  shortVersion = "2016-01-10";
   isRelease = false;
-  forceBundledLLVM = true;
-  srcRev = "462ec0576";
-  srcSha = "1mci0hxwnqb24j4k68rgffqk8ccznz2iddfmyhi8wxa094hqgghp";
+  forceBundledLLVM = false;
+  srcRev = "d70ab2bdf16c22b9f3ff0230089b44855e3f1593";
+  srcSha = "13ssis1bdgg8sdkgrvxcbd1qcfmf7q6bv4akfxrjgdm44l1n1l97";
 
   /* Rust is bootstrapped from an earlier built version. We need
   to fetch these earlier versions, which vary per platform.
@@ -15,12 +15,12 @@ callPackage ./generic.nix {
   with the set you want at the top.
   */
 
-  snapshotHashLinux686 = "e2553bf399cd134a08ef3511a0a6ab0d7a667216";
-  snapshotHashLinux64 = "7df8ba9dec63ec77b857066109d4b6250f3d222f";
-  snapshotHashDarwin686 = "29750870c82a0347f8b8b735a4e2e0da26f5098d";
-  snapshotHashDarwin64 = "c9f2c588238b4c6998190c3abeb33fd6164099a2";
-  snapshotDate = "2015-08-11";
-  snapshotRev = "1af31d4";
+  snapshotHashLinux686 = "a09c4a4036151d0cb28e265101669731600e01f2";
+  snapshotHashLinux64 = "97e2a5eb8904962df8596e95d6e5d9b574d73bf4";
+  snapshotHashDarwin686 = "ca52d2d3ba6497ed007705ee3401cf7efc136ca1";
+  snapshotHashDarwin64 = "3c44ffa18f89567c2b81f8d695e711c86d81ffc7";
+  snapshotDate = "2015-12-18";
+  snapshotRev = "3391630";
 
   patches = [ ./patches/remove-uneeded-git.patch ]
     ++ stdenv.lib.optional stdenv.needsPax ./patches/grsec.patch;
diff --git a/pkgs/development/compilers/sbcl/bootstrap.nix b/pkgs/development/compilers/sbcl/bootstrap.nix
index 0114f014a51e..f8352f0a362e 100644
--- a/pkgs/development/compilers/sbcl/bootstrap.nix
+++ b/pkgs/development/compilers/sbcl/bootstrap.nix
@@ -24,6 +24,11 @@ let
     };
     armv6l-linux = armv7l-linux;
     x86_64-solaris = x86_64-linux;
+    x86_64-freebsd = rec {
+      version = "1.2.7";
+      system = "x86-64-freebsd";
+      sha256 = "14k42xiqd2rrim4pd5k5pjcrpkac09qnpynha8j1v4jngrvmw7y6";
+    };
   };
   cfg = options.${stdenv.system};
 in
diff --git a/pkgs/development/interpreters/perl/5.20/default.nix b/pkgs/development/interpreters/perl/5.20/default.nix
index 9cc8af5f427d..c91a43963d49 100644
--- a/pkgs/development/interpreters/perl/5.20/default.nix
+++ b/pkgs/development/interpreters/perl/5.20/default.nix
@@ -93,6 +93,14 @@ stdenv.mkDerivation rec {
       substituteInPlace dist/PathTools/Cwd.pm --replace "'/bin/pwd'" "'$(type -tP pwd)'"
     '';
 
+  # Inspired by nuke-references, which I can't depend on because it uses perl. Perhaps it should just use sed :)
+  postInstall = ''
+    self=$(echo $out | sed -n "s|^$NIX_STORE/\\([a-z0-9]\{32\}\\)-.*|\1|p")
+
+    sed -i "/$self/b; s|$NIX_STORE/[a-z0-9]\{32\}-|$NIX_STORE/eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee-|g" "$out"/lib/perl5/*/*/Config.pm
+    sed -i "/$self/b; s|$NIX_STORE/[a-z0-9]\{32\}-|$NIX_STORE/eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee-|g" "$out"/lib/perl5/*/*/Config_heavy.pl
+  '';
+
   setupHook = ./setup-hook.sh;
 
   passthru.libPrefix = "lib/perl5/site_perl";
diff --git a/pkgs/development/interpreters/ruby/build-ruby-gem/default.nix b/pkgs/development/interpreters/ruby/build-ruby-gem/default.nix
new file mode 100644
index 000000000000..d050faca2454
--- /dev/null
+++ b/pkgs/development/interpreters/ruby/build-ruby-gem/default.nix
@@ -0,0 +1,208 @@
+# This builds gems in a way that is compatible with bundler.
+#
+# Bundler installs gems from git sources _very_ differently from how RubyGems
+# installes gem packages, though they both install gem packages similarly.
+#
+# We monkey-patch Bundler to remove any impurities and then drive its internals
+# to install git gems.
+#
+# For the sake of simplicity, gem packages are installed with the standard `gem`
+# program.
+#
+# Note that bundler does not support multiple prefixes; it assumes that all
+# gems are installed in a common prefix, and has no support for specifying
+# otherwise. Therefore, if you want to be able to use the resulting derivations
+# with bundler, you need to create a symlink forrest first, which is what
+# `bundlerEnv` does for you.
+#
+# Normal gem packages can be used outside of bundler; a binstub is created in
+# $out/bin.
+
+{ lib, ruby, rubygems, bundler, fetchurl, fetchgit, makeWrapper, git, buildRubyGem
+} @ defs:
+
+lib.makeOverridable (
+
+{ name ? null
+, gemName
+, version ? null
+, type ? "gem"
+, document ? [] # e.g. [ "ri" "rdoc" ]
+, platform ? "ruby"
+, ruby ? defs.ruby
+, stdenv ? ruby.stdenv
+, namePrefix ? "${ruby.name}" + "-"
+, buildInputs ? []
+, doCheck ? false
+, meta ? {}
+, patches ? []
+, gemPath ? []
+, dontStrip ? true
+, remotes ? ["https://rubygems.org"]
+# Assume we don't have to build unless strictly necessary (e.g. the source is a
+# git checkout).
+# If you need to apply patches, make sure to set `dontBuild = false`;
+, dontBuild ? true
+, propagatedBuildInputs ? []
+, propagatedUserEnvPkgs ? []
+, buildFlags ? null
+, passthru ? {}
+, ...} @ attrs:
+
+if ! builtins.elem type [ "git" "gem" ]
+then throw "buildRubyGem: don't know how to build a gem of type \"${type}\""
+else
+
+let
+  shellEscape = x: "'${lib.replaceChars ["'"] [("'\\'" + "'")] x}'";
+  rubygems = (attrs.rubygems or defs.rubygems).override {
+    inherit ruby;
+  };
+  src = attrs.src or (
+    if type == "gem"
+    then fetchurl {
+      urls = map (remote: "${remote}/gems/${gemName}-${version}.gem") remotes;
+      inherit (attrs) sha256;
+    } else fetchgit {
+      inherit (attrs) url rev sha256 fetchSubmodules;
+      leaveDotGit = true;
+    }
+  );
+  documentFlag =
+    if document == []
+    then "-N"
+    else "--document ${lib.concatStringsSep "," document}";
+
+in
+
+stdenv.mkDerivation (attrs // {
+  inherit ruby rubygems;
+  inherit doCheck;
+  inherit dontBuild;
+  inherit dontStrip;
+  inherit type;
+
+  buildInputs = [
+    ruby rubygems makeWrapper
+  ] ++ lib.optionals (type == "git") [ git bundler ]
+    ++ buildInputs;
+
+  name = attrs.name or (namePrefix + gemName);
+
+  inherit src;
+
+  phases = attrs.phases or [ "unpackPhase" "patchPhase" "buildPhase" "installPhase" "fixupPhase" ];
+
+  unpackPhase = attrs.unpackPhase or ''
+    runHook preUnpack
+
+    if [[ -f $src && $src == *.gem ]]; then
+      if [[ -z "$dontBuild" ]]; then
+        # we won't know the name of the directory that RubyGems creates,
+        # so we'll just use a glob to find it and move it over.
+        gempkg="$src"
+        sourceRoot=source
+        gem unpack $gempkg --target=container
+        cp -r container/* $sourceRoot
+        rm -r container
+
+        # copy out the original gemspec, for convenience during patching /
+        # overrides.
+        gem specification $gempkg  --ruby > original.gemspec
+        gemspec=$(readlink -f .)/original.gemspec
+      else
+        gempkg="$src"
+      fi
+    else
+      # Fall back to the original thing for everything else.
+      dontBuild=""
+      preUnpack="" postUnpack="" unpackPhase
+    fi
+
+    runHook postUnpack
+  '';
+
+  buildPhase = attrs.buildPhase or ''
+    runHook preBuild
+
+    if [[ "$type" == "gem" ]]; then
+      if [[ -z "$gemspec" ]]; then
+        gemspec="$(find . -name '*.gemspec')"
+        echo "found the following gemspecs:"
+        echo "$gemspec"
+        gemspec="$(echo "$gemspec" | head -n1)"
+      fi
+
+      exec 3>&1
+      output="$(gem build $gemspec | tee >(cat - >&3))"
+      exec 3>&-
+
+      gempkg=$(echo "$output" | grep -oP 'File: \K(.*)')
+
+      echo "gem package built: $gempkg"
+    fi
+
+    runHook postBuild
+  '';
+
+  # Note:
+  #   We really do need to keep the $out/${ruby.gemPath}/cache.
+  #   This is very important in order for many parts of RubyGems/Bundler to not blow up.
+  #   See https://github.com/bundler/bundler/issues/3327
+  installPhase = attrs.installPhase or ''
+    runHook preInstall
+
+    export GEM_HOME=$out/${ruby.gemPath}
+    mkdir -p $GEM_HOME
+
+    echo "buildFlags: $buildFlags"
+
+    ${lib.optionalString (type == "git") ''
+    ruby ${./nix-bundle-install.rb} \
+      ${gemName} \
+      ${attrs.url} \
+      ${src} \
+      ${attrs.rev} \
+      ${version} \
+      ${shellEscape (toString buildFlags)}
+    ''}
+
+    ${lib.optionalString (type == "gem") ''
+    if [[ -z "$gempkg" ]]; then
+      echo "failure: \$gempkg path unspecified" 1>&2
+      exit 1
+    elif [[ ! -f "$gempkg" ]]; then
+      echo "failure: \$gempkg path invalid" 1>&2
+      exit 1
+    fi
+
+    gem install \
+      --local \
+      --force \
+      --http-proxy 'http://nodtd.invalid' \
+      --ignore-dependencies \
+      --build-root '/' \
+      --backtrace \
+      ${documentFlag} \
+      $gempkg $gemFlags -- $buildFlags
+
+    # looks like useless files which break build repeatability and consume space
+    rm -fv $out/${ruby.gemPath}/doc/*/*/created.rid || true
+    rm -fv $out/${ruby.gemPath}/gems/*/ext/*/mkmf.log || true
+
+    # write out metadata and binstubs
+    spec=$(echo $out/${ruby.gemPath}/specifications/*.gemspec)
+    ruby ${./gem-post-build.rb} "$spec"
+    ''}
+
+    runHook postInstall
+  '';
+
+  propagatedBuildInputs = gemPath ++ propagatedBuildInputs;
+  propagatedUserEnvPkgs = gemPath ++ propagatedUserEnvPkgs;
+
+  passthru = passthru // { isRubyGem = true; };
+  inherit meta;
+})
+
+)
diff --git a/pkgs/development/interpreters/ruby/build-ruby-gem/gem-post-build.rb b/pkgs/development/interpreters/ruby/build-ruby-gem/gem-post-build.rb
new file mode 100644
index 000000000000..112a9accc335
--- /dev/null
+++ b/pkgs/development/interpreters/ruby/build-ruby-gem/gem-post-build.rb
@@ -0,0 +1,77 @@
+require 'rbconfig'
+require 'rubygems'
+require 'rubygems/specification'
+require 'fileutils'
+
+ruby = File.join(ENV["ruby"], "bin", RbConfig::CONFIG['ruby_install_name'])
+out = ENV["out"]
+bin_path = File.join(ENV["out"], "bin")
+gem_home = ENV["GEM_HOME"]
+gem_path = ENV["GEM_PATH"].split(":")
+install_path = Dir.glob("#{gem_home}/gems/*").first
+gemspec_path = ARGV[0]
+
+if defined?(Encoding.default_internal)
+  Encoding.default_internal = Encoding::UTF_8
+  Encoding.default_external = Encoding::UTF_8
+end
+
+gemspec_content = File.read(gemspec_path)
+spec = nil
+if gemspec_content[0..2] == "---" # YAML header
+  spec = Gem::Specification.from_yaml(gemspec_content)
+else
+  spec = Gem::Specification.load(gemspec_path)
+end
+
+FileUtils.mkdir_p("#{out}/nix-support")
+
+# write meta-data
+meta = "#{out}/nix-support/gem-meta"
+FileUtils.mkdir_p(meta)
+FileUtils.ln_s(gemspec_path, "#{meta}/spec")
+File.open("#{meta}/name", "w") do |f|
+  f.write(spec.name)
+end
+File.open("#{meta}/install-path", "w") do |f|
+  f.write(install_path)
+end
+File.open("#{meta}/require-paths", "w") do |f|
+  f.write(spec.require_paths.join(" "))
+end
+File.open("#{meta}/executables", "w") do |f|
+  f.write(spec.executables.join(" "))
+end
+
+# add this gem to the GEM_PATH for dependencies
+File.open("#{out}/nix-support/setup-hook", "a") do |f|
+  f.puts("addToSearchPath GEM_PATH #{gem_home}")
+  spec.require_paths.each do |dir|
+    f.puts("addToSearchPath RUBYLIB #{install_path}/#{dir}")
+  end
+end
+
+# create regular rubygems binstubs
+FileUtils.mkdir_p(bin_path)
+spec.executables.each do |exe|
+  File.open("#{bin_path}/#{exe}", "w") do |f|
+    f.write(<<-EOF)
+#!#{ruby}
+#
+# This file was generated by Nix.
+#
+# The application '#{exe}' is installed as part of a gem, and
+# this file is here to facilitate running it.
+#
+
+gem_path = ENV["GEM_PATH"]
+ENV["GEM_PATH"] = "\#{gem_path}\#{":" unless gem_path.nil? || gem_path.empty?}#{(gem_path+[gem_home]).join(":")}"
+
+require 'rubygems'
+
+load Gem.bin_path(#{spec.name.inspect}, #{exe.inspect})
+    EOF
+  end
+
+  FileUtils.chmod("+x", "#{bin_path}/#{exe}")
+end
diff --git a/pkgs/development/interpreters/ruby/build-ruby-gem/nix-bundle-install.rb b/pkgs/development/interpreters/ruby/build-ruby-gem/nix-bundle-install.rb
new file mode 100644
index 000000000000..647b83b52c38
--- /dev/null
+++ b/pkgs/development/interpreters/ruby/build-ruby-gem/nix-bundle-install.rb
@@ -0,0 +1,153 @@
+require 'rbconfig'
+require 'bundler/vendored_thor'
+require 'bundler'
+require 'rubygems/command'
+require 'fileutils'
+require 'pathname'
+require 'tmpdir'
+
+# Options:
+#
+#   name        - the gem name
+#   uri         - git repo uri
+#   repo        - path to local checkout
+#   ref         - the commit hash
+#   version     - gem version
+#   build-flags - build arguments
+
+ruby = File.join(ENV["ruby"], "bin", RbConfig::CONFIG['ruby_install_name'])
+out = ENV["out"]
+bin_dir = File.join(ENV["out"], "bin")
+
+name        = ARGV[0]
+uri         = ARGV[1]
+REPO        = ARGV[2]
+ref         = ARGV[3]
+version     = ARGV[4]
+build_flags = ARGV[5]
+
+# options to pass to bundler
+options = {
+  "name"    => name,
+  "uri"     => uri,
+  "ref"     => ref,
+  "version" => version,
+}
+
+# Monkey-patch Bundler to use our local checkout.
+# I wish we didn't have to do this, but bundler does not expose an API to do
+# these kinds of things.
+Bundler.module_eval do
+  def self.requires_sudo?
+    false
+  end
+
+  def self.root
+    # we don't have a Gemfile, so it doesn't make sense to try to make paths
+    # relative to the (non existent) parent directory thereof, so we give a
+    # nonsense path here.
+    Pathname.new("/no-root-path")
+  end
+
+  def self.bundle_path
+    Pathname.new(ENV["GEM_HOME"])
+  end
+
+  def self.locked_gems
+    nil
+  end
+end
+
+Bundler::Source::Git.class_eval do
+  def allow_git_ops?
+    true
+  end
+end
+
+Bundler::Source::Git::GitProxy.class_eval do
+  def checkout
+    unless path.exist?
+      FileUtils.mkdir_p(path.dirname)
+      FileUtils.cp_r(File.join(REPO, ".git"), path)
+      system("chmod -R +w #{path}")
+    end
+  end
+
+  def copy_to(destination, submodules=false)
+    unless File.exist?(destination.join(".git"))
+      FileUtils.mkdir_p(destination.dirname)
+      FileUtils.cp_r(REPO, destination)
+      system("chmod -R +w #{destination}")
+    end
+  end
+end
+
+# UI
+verbose = false
+no_color = false
+Bundler.ui = Bundler::UI::Shell.new({"no-color" => no_color})
+Bundler.ui.level = "debug" if verbose
+
+# Install
+source = Bundler::Source::Git.new(options)
+spec = source.specs.search_all(name).first
+Bundler.rubygems.with_build_args [build_flags] do
+  source.install(spec)
+end
+
+msg = spec.post_install_message
+if msg
+  Bundler.ui.confirm "Post-install message from #{name}:"
+  Bundler.ui.info msg
+end
+
+# Write out the binstubs
+if spec.executables.any?
+  FileUtils.mkdir_p(bin_dir)
+  spec.executables.each do |exe|
+    wrapper = File.join(bin_dir, exe)
+    File.open(wrapper, "w") do |f|
+      stub = generate_stub(spec.name, exe)
+      f.write(<<-EOF)
+#!#{ruby}
+#
+# This file was generated by Nix.
+#
+# The application '#{exe}' is installed as part of a gem, and
+# this file is here to facilitate running it.
+#
+
+require 'rubygems'
+require 'bundler/setup'
+
+load Gem.bin_path(#{spec.name.inspect}, #{exe.inspect})
+EOF
+    end
+
+    FileUtils.chmod("+x", wrapper)
+  end
+end
+
+# Write out metadata
+meta = "#{out}/nix-support/gem-meta"
+FileUtils.mkdir_p(meta)
+FileUtils.ln_s(spec.loaded_from.to_s, "#{meta}/spec")
+File.open("#{meta}/name", "w") do |f|
+  f.write spec.name
+end
+File.open("#{meta}/install-path", "w") do |f|
+  f.write source.install_path.to_s
+end
+File.open("#{meta}/require-paths", "w") do |f|
+  f.write spec.require_paths.join(" ")
+end
+File.open("#{meta}/executables", "w") do |f|
+  f.write spec.executables.join(" ")
+end
+
+# make the lib available during bundler/git installs
+File.open("#{out}/nix-support/setup-hook", "a") do |f|
+  spec.require_paths.each do |dir|
+    f.puts("addToSearchPath RUBYLIB #{source.install_path}/#{dir}")
+  end
+end
diff --git a/pkgs/development/interpreters/ruby/bundix/Gemfile b/pkgs/development/interpreters/ruby/bundix/Gemfile
deleted file mode 100644
index 4899cafc3738..000000000000
--- a/pkgs/development/interpreters/ruby/bundix/Gemfile
+++ /dev/null
@@ -1,4 +0,0 @@
-source "http://rubygems.org"
-gem "bundix",
-  :git => "https://github.com/cstrahan/bundix.git",
-  :ref => "v1.0.3"
diff --git a/pkgs/development/interpreters/ruby/bundix/Gemfile.lock b/pkgs/development/interpreters/ruby/bundix/Gemfile.lock
deleted file mode 100644
index f241a3bafd4f..000000000000
--- a/pkgs/development/interpreters/ruby/bundix/Gemfile.lock
+++ /dev/null
@@ -1,18 +0,0 @@
-GIT
-  remote: https://github.com/cstrahan/bundix.git
-  revision: c879cf901ff8084b4c97aaacfb5ecbdb0f95cc03
-  ref: v1.0.3
-  specs:
-    bundix (1.0.2)
-      thor (~> 0.19.1)
-
-GEM
-  remote: http://rubygems.org/
-  specs:
-    thor (0.19.1)
-
-PLATFORMS
-  ruby
-
-DEPENDENCIES
-  bundix!
diff --git a/pkgs/development/interpreters/ruby/bundix/default.nix b/pkgs/development/interpreters/ruby/bundix/default.nix
index 0196adb8f4c8..b5a49043c60b 100644
--- a/pkgs/development/interpreters/ruby/bundix/default.nix
+++ b/pkgs/development/interpreters/ruby/bundix/default.nix
@@ -1,9 +1,20 @@
-{ ruby, bundlerEnv }:
+{ ruby, fetchgit, buildRubyGem, bundler }:
 
-bundlerEnv {
-  name = "bundix";
-  inherit ruby;
-  gemset = ./gemset.nix;
-  gemfile = ./Gemfile;
-  lockfile = ./Gemfile.lock;
+let
+  thor = buildRubyGem {
+    gemName = "thor";
+    version = "0.19.1";
+    type = "gem";
+    sha256 = "08p5gx18yrbnwc6xc0mxvsfaxzgy2y9i78xq7ds0qmdm67q39y4z";
+  };
+
+in buildRubyGem {
+  gemName = "bundix";
+  version = "1.0.4";
+  gemPath = [ thor bundler ];
+  src = fetchgit {
+    url = "https://github.com/cstrahan/bundix.git";
+    rev = "6dcf1f71c61584f5c9b919ee9df7b0c554862076";
+    sha256 = "1w17bvc9srcgr4ry81ispcj35g9kxihbyknmqp8rnd4h5090b7b2";
+  };
 }
diff --git a/pkgs/development/interpreters/ruby/bundix/gemset.nix b/pkgs/development/interpreters/ruby/bundix/gemset.nix
deleted file mode 100644
index f8f6546671d9..000000000000
--- a/pkgs/development/interpreters/ruby/bundix/gemset.nix
+++ /dev/null
@@ -1,22 +0,0 @@
-{
-  "bundix" = {
-    version = "1.0.2";
-    source = {
-      type = "git";
-      url = "https://github.com/cstrahan/bundix.git";
-      rev = "c879cf901ff8084b4c97aaacfb5ecbdb0f95cc03";
-      sha256 = "05kmdnq4qa5h8l3asv05cjpnyplnqqx6hrqybj2cjlzmdxnkkgyj";
-      fetchSubmodules = false;
-    };
-    dependencies = [
-      "thor"
-    ];
-  };
-  "thor" = {
-    version = "0.19.1";
-    source = {
-      type = "gem";
-      sha256 = "08p5gx18yrbnwc6xc0mxvsfaxzgy2y9i78xq7ds0qmdm67q39y4z";
-    };
-  };
-}
\ No newline at end of file
diff --git a/pkgs/development/interpreters/ruby/bundler-env/default.nix b/pkgs/development/interpreters/ruby/bundler-env/default.nix
index 9fa6e52c4557..c7570d815e3b 100644
--- a/pkgs/development/interpreters/ruby/bundler-env/default.nix
+++ b/pkgs/development/interpreters/ruby/bundler-env/default.nix
@@ -1,312 +1,75 @@
 { stdenv, runCommand, writeText, writeScript, writeScriptBin, ruby, lib
-, callPackage, defaultGemConfig, fetchurl, fetchgit, buildRubyGem , bundler_HEAD
+, callPackage, defaultGemConfig, fetchurl, fetchgit, buildRubyGem, buildEnv
+, rubygems
 , git
+, makeWrapper
+, bundler
+, tree
 }@defs:
 
-# This is a work-in-progress.
-# The idea is that his will replace load-ruby-env.nix.
-
 { name, gemset, gemfile, lockfile, ruby ? defs.ruby, gemConfig ? defaultGemConfig
-, enableParallelBuilding ? false # TODO: this might not work, given the env-var shinanigans.
-, postInstall ? null
-, documentation ? false
+, postBuild ? null
+, document ? []
 , meta ? {}
+, ignoreCollisions ? false
 , ...
 }@args:
 
 let
 
   shellEscape = x: "'${lib.replaceChars ["'"] [("'\\'" + "'")] x}'";
-  const = x: y: x;
-  bundler = bundler_HEAD.override { inherit ruby; };
-  inherit (builtins) attrValues;
-
-  gemName = attrs: "${attrs.name}-${attrs.version}.gem";
-
-  fetchers.path = attrs: attrs.source.path;
-  fetchers.gem = attrs: fetchurl {
-    url = "${attrs.source.source or "https://rubygems.org"}/downloads/${gemName attrs}";
-    inherit (attrs.source) sha256;
-  };
-  fetchers.git = attrs: fetchgit {
-    inherit (attrs.source) url rev sha256 fetchSubmodules;
-    leaveDotGit = true;
-  };
-
-  applySrc = attrs:
-    attrs // {
-      src = (fetchers."${attrs.source.type}" attrs);
-    };
-
+  importedGemset = import gemset;
   applyGemConfigs = attrs:
-    if gemConfig ? "${attrs.name}"
-    then attrs // gemConfig."${attrs.name}" attrs
-    else attrs;
-
-  needsPatch = attrs:
-    (attrs ? patches) || (attrs ? prePatch) || (attrs ? postPatch);
-
-  # patch a gem or source tree.
-  # for gems, the gem is unpacked, patched, and then repacked.
-  # see: https://github.com/fedora-ruby/gem-patch/blob/master/lib/rubygems/patcher.rb
-  applyPatches = attrs:
-    if !needsPatch attrs
-    then attrs
-    else attrs // { src =
-      stdenv.mkDerivation {
-        name = gemName attrs;
-        phases = [ "unpackPhase" "patchPhase" "installPhase" ];
-        buildInputs = [ ruby ] ++ attrs.buildInputs or [];
-        patches = attrs.patches or [ ];
-        prePatch = attrs.prePatch or "true";
-        postPatch = attrs.postPatch or "true";
-        unpackPhase = ''
-          runHook preUnpack
-
-          if [[ -f ${attrs.src} ]]; then
-            isGem=1
-            # we won't know the name of the directory that RubyGems creates,
-            # so we'll just use a glob to find it and move it over.
-            gem unpack ${attrs.src} --target=container
-            cp -r container/* contents
-            rm -r container
-          else
-            cp -r ${attrs.src} contents
-            chmod -R +w contents
-          fi
-
-          cd contents
-          runHook postUnpack
-        '';
-        installPhase = ''
-          runHook preInstall
-
-          if [[ -n "$isGem" ]]; then
-            ${writeScript "repack.rb" ''
-              #!${ruby}/bin/ruby
-              require 'rubygems'
-              require 'rubygems/package'
-              require 'fileutils'
-
-              Encoding.default_internal = Encoding::UTF_8
-              Encoding.default_external = Encoding::UTF_8
-
-              if Gem::VERSION < '2.0'
-                load "${./package-1.8.rb}"
-              end
-
-              out = ENV['out']
-              files = Dir['**/{.[^\.]*,*}']
-
-              package = Gem::Package.new("${attrs.src}")
-              patched_package = Gem::Package.new(package.spec.file_name)
-              patched_package.spec = package.spec.clone
-              patched_package.spec.files = files
-
-              patched_package.build(false)
-
-              FileUtils.cp(patched_package.spec.file_name, out)
-            ''}
-          else
-            cp -r . $out
-          fi
-
-          runHook postInstall
-        '';
-      };
-    };
-
-  instantiate = (attrs:
-    applyPatches (applyGemConfigs (applySrc attrs))
-  );
-
-  instantiated = lib.flip lib.mapAttrs (import gemset) (name: attrs:
-    instantiate (attrs // { inherit name; })
+    (if gemConfig ? "${attrs.gemName}"
+    then attrs // gemConfig."${attrs.gemName}" attrs
+    else attrs);
+  configuredGemset = lib.flip lib.mapAttrs importedGemset (name: attrs:
+    applyGemConfigs (attrs // { gemName = name; })
   );
-
-  needsPreInstall = attrs:
-    (attrs ? preInstall) || (attrs ? buildInputs) || (attrs ? nativeBuildInputs);
-
-  # TODO: support cross compilation? look at stdenv/generic/default.nix.
-  runPreInstallers = lib.fold (next: acc:
-    if !needsPreInstall next
-    then acc
-    else acc + ''
-      ${writeScript "${next.name}-pre-install" ''
-        #!${stdenv.shell}
-
-        export nativeBuildInputs="${toString ((next.nativeBuildInputs or []) ++ (next.buildInputs or []))}"
-
-        source ${stdenv}/setup
-
-        header "running pre-install script for ${next.name}"
-
-        ${next.preInstall or ""}
-
-        ${ruby}/bin/ruby -e 'print ENV.inspect' > env/${next.name}
-
-        stopNest
-      ''}
-    ''
-  ) "" (attrValues instantiated);
-
-  # copy *.gem to ./gems
-  copyGems = lib.fold (next: acc:
-    if next.source.type == "gem"
-    then acc + "cp ${next.src} gems/${gemName next}\n"
-    else acc
-  ) "" (attrValues instantiated);
-
-  runRuby = name: env: command:
-    runCommand name env ''
-      ${ruby}/bin/ruby ${writeText name command}
-    '';
-
-  # TODO: include json_pure, so the version of ruby doesn't matter.
-  # not all rubies have support for JSON built-in,
-  # so we'll convert JSON to ruby expressions.
-  json2rb = writeScript "json2rb" ''
-    #!${ruby}/bin/ruby
-    begin
-      require 'json'
-    rescue LoadError => ex
-      require 'json_pure'
-    end
-
-    puts JSON.parse(STDIN.read).inspect
-  '';
-
-  # dump the instantiated gemset as a ruby expression.
-  serializedGemset = runCommand "gemset.rb" { json = builtins.toJSON instantiated; } ''
-    printf '%s' "$json" | ${json2rb} > $out
-  '';
-
-  # this is a mapping from a source type and identifier (uri/path/etc)
-  # to the pure store path.
-  # we'll use this from the patched bundler to make fetching sources pure.
-  sources = runRuby "sources.rb" { gemset = serializedGemset; } ''
-    out    = ENV['out']
-    gemset = eval(File.read(ENV['gemset']))
-
-    sources = {
-      "git"  => { },
-      "path" => { },
-      "gem"  => { },
-      "svn"  => { }
-    }
-
-    gemset.each_value do |spec|
-      type = spec["source"]["type"]
-      val = spec["src"]
-      key =
-        case type
-        when "gem"
-          spec["name"]
-        when "git"
-          spec["source"]["url"]
-        when "path"
-          spec["source"]["originalPath"]
-        when "svn"
-          nil # TODO
-        end
-
-      sources[type][key] = val if key
-    end
-
-    File.open(out, "wb") do |f|
-      f.print sources.inspect
-    end
+  hasBundler = builtins.hasAttr "bundler" importedGemset;
+  bundler = if hasBundler then gems.bundler else defs.bundler.override (attrs: { inherit ruby; });
+  rubygems = defs.rubygems.override (attrs: { inherit ruby; });
+  gems = lib.flip lib.mapAttrs configuredGemset (name: attrs:
+    buildRubyGem ((removeAttrs attrs ["source"]) // attrs.source // {
+      inherit ruby rubygems;
+      gemName = name;
+      gemPath = map (gemName: gems."${gemName}") (attrs.dependencies or []);
+    }));
+  # We have to normalize the Gemfile.lock, otherwise bundler tries to be
+  # helpful by doing so at run time, causing executables to immediately bail
+  # out. Yes, I'm serious.
+  confFiles = runCommand "gemfile-and-lockfile" {} ''
+    mkdir -p $out
+    cp ${gemfile} $out/Gemfile
+    cp ${lockfile} $out/Gemfile.lock
+
+    cd $out
+    chmod +w Gemfile.lock
+    source ${rubygems}/nix-support/setup-hook
+    export GEM_PATH=${bundler}/${ruby.gemPath}
+    ${ruby}/bin/ruby -rubygems -e \
+      "require 'bundler'; Bundler.definition.lock('Gemfile.lock')"
   '';
-
-  # rewrite PATH sources to point into the nix store.
-  purifiedLockfile = runRuby "purifiedLockfile" {} ''
-    out     = ENV['out']
-    sources = eval(File.read("${sources}"))
-    paths   = sources["path"]
-
-    lockfile = File.read("${lockfile}")
-
-    paths.each_pair do |impure, pure|
-      lockfile.gsub!(/^  remote: #{Regexp.escape(impure)}/, "  remote: #{pure}")
-    end
-
-    File.open(out, "wb") do |f|
-      f.print lockfile
-    end
-  '';
-
-  needsBuildFlags = attrs: attrs ? buildFlags;
-
-  mkBuildFlags = spec:
-    "export BUNDLE_BUILD__${lib.toUpper spec.name}='${lib.concatStringsSep " " (map shellEscape spec.buildFlags)}'";
-
-  allBuildFlags =
-    lib.concatStringsSep "\n"
-      (map mkBuildFlags
-        (lib.filter needsBuildFlags (attrValues instantiated)));
-
-  derivation = stdenv.mkDerivation {
-    inherit name;
-
-    buildInputs = [
-      ruby
-      bundler
-      git
-    ] ++ args.buildInputs or [];
-
-    phases = [ "installPhase" "fixupPhase" ];
-
-    outputs = [
-      "out"    # the installed libs/bins
-      "bundle" # supporting files for bundler
-    ];
-
-    installPhase = ''
-      mkdir -p $bundle
-      export BUNDLE_GEMFILE=$bundle/Gemfile
-      cp ${gemfile} $BUNDLE_GEMFILE
-      cp ${purifiedLockfile} $BUNDLE_GEMFILE.lock
-
-      export NIX_GEM_SOURCES=${sources}
-      export NIX_BUNDLER_GEMPATH=${bundler}/${ruby.gemPath}
-
-      export GEM_HOME=$out/${ruby.gemPath}
-      export GEM_PATH=$NIX_BUNDLER_GEMPATH:$GEM_HOME
-      mkdir -p $GEM_HOME
-
-      ${allBuildFlags}
-
-      mkdir gems
-      cp ${bundler}/${bundler.ruby.gemPath}/cache/bundler-*.gem gems
-      ${copyGems}
-
-      ${lib.optionalString (!documentation) ''
-        mkdir home
-        HOME="$(pwd -P)/home"
-        echo "gem: --no-rdoc --no-ri" > $HOME/.gemrc
-      ''}
-
-      mkdir env
-      ${runPreInstallers}
-
-      mkdir $out/bin
-      cp ${./monkey_patches.rb} monkey_patches.rb
-      export RUBYOPT="-rmonkey_patches.rb -I $(pwd -P)"
-      bundler install --frozen --binstubs ${lib.optionalString enableParallelBuilding "--jobs $NIX_BUILD_CORES"}
-      RUBYOPT=""
-
-      runHook postInstall
-    '';
-
-    inherit postInstall;
-
+  envPaths = lib.attrValues gems ++ lib.optional (!hasBundler) bundler;
+  bundlerEnv = buildEnv {
+    inherit name ignoreCollisions;
+    paths = envPaths;
+    pathsToLink = [ "/lib" ];
+    postBuild = ''
+      source ${rubygems}/nix-support/setup-hook
+
+      ${ruby}/bin/ruby ${./gen-bin-stubs.rb} \
+        "${ruby}/bin/ruby" \
+        "${confFiles}/Gemfile" \
+        "$out/${ruby.gemPath}" \
+        "${bundler}/${ruby.gemPath}" \
+        ${shellEscape (toString envPaths)}
+    '' + lib.optionalString (postBuild != null) postBuild;
     passthru = {
-      inherit ruby;
-      inherit bundler;
-
+      inherit ruby bundler meta gems;
       env = let
         irbrc = builtins.toFile "irbrc" ''
-          if not ENV["OLD_IRBRC"].empty?
+          if !(ENV["OLD_IRBRC"].nil? || ENV["OLD_IRBRC"].empty?)
             require ENV["OLD_IRBRC"]
           end
           require 'rubygems'
@@ -314,12 +77,12 @@ let
         '';
         in stdenv.mkDerivation {
           name = "interactive-${name}-environment";
-          nativeBuildInputs = [ ruby derivation ];
+          nativeBuildInputs = [ ruby bundlerEnv ];
           shellHook = ''
-            export BUNDLE_GEMFILE=${derivation.bundle}/Gemfile
-            export GEM_HOME=${derivation}/${ruby.gemPath}
-            export NIX_BUNDLER_GEMPATH=${bundler}/${ruby.gemPath}
-            export GEM_PATH=$NIX_BUNDLER_GEMPATH:$GEM_HOME
+            export BUNDLE_GEMFILE=${confFiles}/Gemfile
+            export BUNDLE_PATH=${bundlerEnv}/${ruby.gemPath}
+            export GEM_HOME=${bundlerEnv}/${ruby.gemPath}
+            export GEM_PATH=${bundlerEnv}/${ruby.gemPath}
             export OLD_IRBRC="$IRBRC"
             export IRBRC=${irbrc}
           '';
@@ -331,8 +94,8 @@ let
           '';
         };
     };
-
-    inherit meta;
   };
 
-in derivation
+in
+
+bundlerEnv
diff --git a/pkgs/development/interpreters/ruby/bundler-env/gen-bin-stubs.rb b/pkgs/development/interpreters/ruby/bundler-env/gen-bin-stubs.rb
new file mode 100644
index 000000000000..fac9c9ad9446
--- /dev/null
+++ b/pkgs/development/interpreters/ruby/bundler-env/gen-bin-stubs.rb
@@ -0,0 +1,46 @@
+require 'rbconfig'
+require 'rubygems'
+require 'rubygems/specification'
+require 'fileutils'
+
+# args/settings
+out = ENV["out"]
+ruby = ARGV[0]
+gemfile = ARGV[1]
+bundle_path = ARGV[2]
+bundler_gem_path = ARGV[3]
+paths = ARGV[4].split
+
+# generate binstubs
+FileUtils.mkdir_p("#{out}/bin")
+paths.each do |path|
+  next unless File.directory?("#{path}/nix-support/gem-meta")
+
+  name = File.read("#{path}/nix-support/gem-meta/name")
+  executables = File.read("#{path}/nix-support/gem-meta/executables").split
+  executables.each do |exe|
+    File.open("#{out}/bin/#{exe}", "w") do |f|
+      f.write(<<-EOF)
+#!#{ruby}
+#
+# This file was generated by Nix.
+#
+# The application '#{exe}' is installed as part of a gem, and
+# this file is here to facilitate running it.
+#
+
+ENV["BUNDLE_GEMFILE"] = "#{gemfile}"
+ENV["BUNDLE_PATH"] = "#{bundle_path}"
+
+gem_path = ENV["GEM_PATH"]
+ENV["GEM_PATH"] = "\#{gem_path}\#{":" unless gem_path.nil? || gem_path.empty?}#{bundler_gem_path}"
+
+require 'rubygems'
+require 'bundler/setup'
+
+load Gem.bin_path(#{name.inspect}, #{exe.inspect})
+EOF
+      FileUtils.chmod("+x", "#{out}/bin/#{exe}")
+    end
+  end
+end
diff --git a/pkgs/development/interpreters/ruby/bundler-env/monkey_patches.rb b/pkgs/development/interpreters/ruby/bundler-env/monkey_patches.rb
deleted file mode 100644
index f68a20212cee..000000000000
--- a/pkgs/development/interpreters/ruby/bundler-env/monkey_patches.rb
+++ /dev/null
@@ -1,246 +0,0 @@
-require 'bundler'
-
-# Undo the RUBYOPT trickery.
-opt = ENV['RUBYOPT'].dup
-opt.gsub!(/-rmonkey_patches.rb -I [^ ]*/, '')
-ENV['RUBYOPT'] = opt
-
-Bundler.module_eval do
-  class << self
-    # mappings from original uris to store paths.
-    def nix_gem_sources
-      @nix_gem_sources ||=
-        begin
-          src = ENV['NIX_GEM_SOURCES']
-          eval(Bundler.read_file(src))
-        end
-    end
-
-    # extract the gemspecs from the gems pulled from Rubygems.
-    def nix_gemspecs
-      @nix_gemspecs ||= Dir.glob("gems/*.gem").map do |path|
-        Bundler.rubygems.spec_from_gem(path)
-      end
-    end
-
-    # swap out ENV
-    def nix_with_env(env, &block)
-      if env
-        old_env = ENV.to_hash
-        begin
-          ENV.replace(env)
-          block.call
-        ensure
-          ENV.replace(old_env)
-        end
-      else
-        block.call
-      end
-    end
-
-    # map a git uri to a fetchgit store path.
-    def nix_git(uri)
-      Pathname.new(nix_gem_sources["git"][uri])
-    end
-  end
-end
-
-Bundler::Source::Git::GitProxy.class_eval do
-  def checkout
-    unless path.exist?
-      FileUtils.mkdir_p(path.dirname)
-      FileUtils.cp_r(Bundler.nix_git(@uri).join(".git"), path)
-      system("chmod -R +w #{path}")
-    end
-  end
-
-  def copy_to(destination, submodules=false)
-    unless File.exist?(destination.join(".git"))
-      FileUtils.mkdir_p(destination.dirname)
-      FileUtils.cp_r(Bundler.nix_git(@uri), destination)
-      system("chmod -R +w #{destination}")
-    end
-  end
-end
-
-Bundler::Fetcher.class_eval do
-  def use_api
-    true
-  end
-
-  def fetch_dependency_remote_specs(gem_names)
-    Bundler.ui.debug "Query Gemcutter Dependency Endpoint API: #{gem_names.join(',')}"
-    deps_list = []
-
-    spec_list = gem_names.map do |name|
-      spec = Bundler.nix_gemspecs.detect {|spec| spec.name == name }
-      if spec.nil?
-        msg = "WARNING: Could not find gemspec for '#{name}'"
-        Bundler.ui.warn msg
-        nil
-      else
-        dependencies = spec.dependencies.
-          select {|dep| dep.type != :development}.
-          map do |dep|
-            deps_list << dep.name
-            dep
-          end
-
-        [spec.name, spec.version, spec.platform, dependencies]
-      end
-    end
-
-    spec_list.compact!
-
-    [spec_list, deps_list.uniq]
-  end
-end
-
-Bundler::Source::Rubygems.class_eval do
-  # We copy all gems into $PWD/gems, and this allows RubyGems to find those
-  # gems during installation.
-  def fetchers
-    @fetchers ||= [
-      Bundler::Fetcher.new(URI.parse("file://#{File.expand_path(Dir.pwd)}"))
-    ]
-  end
-
-  # Look-up gems that were originally from RubyGems.
-  def remote_specs
-    @remote_specs ||=
-      begin
-        lockfile = Bundler::LockfileParser.new(Bundler.read_file(Bundler.default_lockfile))
-        gem_names = lockfile.specs.
-          select {|spec| spec.source.is_a?(Bundler::Source::Rubygems)}.
-          map {|spec| spec.name}
-        idx = Bundler::Index.new
-        api_fetchers.each do |f|
-          Bundler.ui.info "Fetching source index from #{f.uri}"
-          idx.use f.specs(gem_names, self)
-        end
-        idx
-      end
-  end
-end
-
-Bundler::Installer.class_eval do
-
-  # WHY:
-  # This allows us to provide a typical Nix experience, where
-  # `buildInputs` and/or `preInstall` may set up the $PATH and other env-vars
-  # as needed. By swapping out the environment per install, we can have finer
-  # grained control than we would have otherwise.
-  #
-  # HOW:
-  # This is a wrapper around the original `install_gem_from_spec`.
-  # We expect that a "pre-installer" might exist at `pre-installers/<gem-name>`,
-  # and if it does, we execute it.
-  # The pre-installer is expected to dump its environment variables as a Ruby
-  # hash to `env/<gem-name>`.
-  # We then swap out the environment for the duration of the install,
-  # and then set it back to what it was originally.
-  alias original_install_gem_from_spec install_gem_from_spec
-  def install_gem_from_spec(spec, standalone = false, worker = 0)
-    env_dump = "env/#{spec.name}"
-    if File.exist?(env_dump)
-      env = eval(Bundler.read_file(env_dump))
-      unless env
-        Bundler.ui.error "The environment variables for #{spec.name} could not be loaded!"
-        exit 1
-      end
-      Bundler.nix_with_env(env) do
-        original_install_gem_from_spec(spec, standalone, worker)
-      end
-    else
-      original_install_gem_from_spec(spec, standalone, worker)
-    end
-  end
-
-  def generate_bundler_executable_stubs(spec, options = {})
-    return if spec.executables.empty?
-
-    out = ENV['out']
-
-    spec.executables.each do |executable|
-      next if executable == "bundle" || executable == "bundler"
-
-      binstub_path = "#{out}/bin/#{executable}"
-
-      File.open(binstub_path, 'w', 0777 & ~File.umask) do |f|
-        f.print <<-TEXT
-#!#{RbConfig.ruby}
-
-old_gemfile  = ENV["BUNDLE_GEMFILE"]
-old_gem_home = ENV["GEM_HOME"]
-old_gem_path = ENV["GEM_PATH"]
-
-ENV["BUNDLE_GEMFILE"] =
-  "#{ENV["BUNDLE_GEMFILE"]}"
-ENV["GEM_HOME"] =
-  "#{ENV["GEM_HOME"]}"
-ENV["GEM_PATH"] =
-  "#{ENV["NIX_BUNDLER_GEMPATH"]}:\#{ENV["GEM_HOME"]}\#{old_gem_path ? ":\#{old_gem_path}" : ""}}"
-
-require 'rubygems'
-require 'bundler/setup'
-
-ENV["BUNDLE_GEMFILE"] = old_gemfile
-ENV["GEM_HOME"]       = old_gem_home
-ENV["GEM_PATH"]       = old_gem_path
-
-load Gem.bin_path('#{spec.name}', '#{executable}')
-TEXT
-      end
-    end
-  end
-end
-
-Gem::Installer.class_eval do
-  # Make the wrappers automagically use bundler.
-  #
-  # Stage 1.
-  #   Set $BUNDLE_GEMFILE so bundler knows what gems to load.
-  #   Set $GEM_HOME to the installed gems, because bundler looks there for
-  #     non-Rubygems installed gems (e.g. git/svn/path sources).
-  #   Set $GEM_PATH to include both bundler and installed gems.
-  #
-  # Stage 2.
-  #   Setup bundler, locking down the gem versions.
-  #
-  # Stage 3.
-  #   Reset $BUNDLE_GEMFILE, $GEM_HOME, $GEM_PATH.
-  #
-  # Stage 4.
-  #   Run the actual executable.
-  def app_script_text(bin_file_name)
-    return <<-TEXT
-#!#{RbConfig.ruby}
-#
-# This file was generated by Nix's RubyGems.
-#
-# The application '#{spec.name}' is installed as part of a gem, and
-# this file is here to facilitate running it.
-#
-
-old_gemfile  = ENV["BUNDLE_GEMFILE"]
-old_gem_home = ENV["GEM_HOME"]
-old_gem_path = ENV["GEM_PATH"]
-
-ENV["BUNDLE_GEMFILE"] =
-  "#{ENV["BUNDLE_GEMFILE"]}"
-ENV["GEM_HOME"] =
-  "#{ENV["GEM_HOME"]}"
-ENV["GEM_PATH"] =
-  "#{ENV["NIX_BUNDLER_GEMPATH"]}:\#{ENV["GEM_HOME"]}\#{old_gem_path ? ":\#{old_gem_path}" : ""}}"
-
-require 'rubygems'
-require 'bundler/setup'
-
-ENV["BUNDLE_GEMFILE"] = old_gemfile
-ENV["GEM_HOME"]       = old_gem_home
-ENV["GEM_PATH"]       = old_gem_path
-
-load Gem.bin_path('#{spec.name}', '#{bin_file_name}')
-TEXT
-  end
-end
diff --git a/pkgs/development/interpreters/ruby/bundler-env/package-1.8.rb b/pkgs/development/interpreters/ruby/bundler-env/package-1.8.rb
deleted file mode 100644
index 079b65f97ece..000000000000
--- a/pkgs/development/interpreters/ruby/bundler-env/package-1.8.rb
+++ /dev/null
@@ -1,29 +0,0 @@
-require 'rubygems/installer'
-require 'rubygems/builder'
-
-# Simulate RubyGems 2.0 behavior.
-
-module Gem::Package
-  def self.new(gem)
-    @gem = gem
-    self
-  end
-
-  def self.extract_files(dir)
-    installer = Gem::Installer.new @gem
-    installer.unpack(dir)
-  end
-
-  def self.build(skip_validation=false)
-    builder = Gem::Builder.new(spec)
-    builder.build
-  end
-
-  def self.spec=(spec)
-    @spec = spec
-  end
-
-  def self.spec
-    @spec ||= Gem::Installer.new(@gem).spec
-  end
-end
diff --git a/pkgs/development/interpreters/ruby/bundler.nix b/pkgs/development/interpreters/ruby/bundler.nix
index 3789170f57fe..cdcd12990e27 100644
--- a/pkgs/development/interpreters/ruby/bundler.nix
+++ b/pkgs/development/interpreters/ruby/bundler.nix
@@ -1,17 +1,10 @@
 { buildRubyGem, makeWrapper, ruby, coreutils }:
 
-buildRubyGem {
-  name = "bundler-1.10.6";
-  namePrefix = "";
+buildRubyGem rec {
+  inherit ruby;
+  name = "${gemName}-${version}";
+  gemName = "bundler";
+  version = "1.10.6";
   sha256 = "1vlzfq0bkkj4jyq6av0y55mh5nj5n0f3mfbmmifwgkh44g8k6agv";
   dontPatchShebangs = true;
-  postInstall = ''
-    find $out -type f -perm -0100 | while read f; do
-      substituteInPlace $f \
-         --replace "/usr/bin/env" "${coreutils}/bin/env"
-    done
-
-    wrapProgram $out/bin/bundler \
-      --prefix PATH ":" ${ruby}/bin
-  '';
 }
diff --git a/pkgs/development/interpreters/ruby/gem.nix b/pkgs/development/interpreters/ruby/gem.nix
deleted file mode 100644
index bbc38226266b..000000000000
--- a/pkgs/development/interpreters/ruby/gem.nix
+++ /dev/null
@@ -1,136 +0,0 @@
-{ lib, ruby, rubygemsFun, fetchurl, makeWrapper, git } @ defs:
-
-lib.makeOverridable (
-
-{ name
-, ruby ? defs.ruby
-, rubygems ? (rubygemsFun ruby)
-, stdenv ? ruby.stdenv
-, namePrefix ? "${lib.replaceStrings ["-"] ["_"] ruby.name}" + "-"
-, buildInputs ? []
-, doCheck ? false
-, dontBuild ? true
-, meta ? {}
-, gemPath ? []
-, ...} @ attrs:
-
-stdenv.mkDerivation (attrs // {
-  inherit ruby rubygems;
-  inherit doCheck;
-
-  buildInputs = [ ruby rubygems makeWrapper git ] ++ buildInputs;
-
-  name = namePrefix + name;
-
-  src = if attrs ? src
-    then attrs.src
-    else fetchurl {
-      url = "http://rubygems.org/downloads/${attrs.name}.gem";
-      inherit (attrs) sha256;
-    };
-
-  phases = [ "unpackPhase" "patchPhase" "buildPhase" "checkPhase" "installPhase" "fixupPhase" ];
-
-  # The source is expected to either be a gem package or a directory.
-  #
-  # - Gem packages are already built, so they don't even need to be unpacked.
-  #   They will skip the buildPhase.
-  # - A directory containing the sources will need to go through all of the
-  #   usual phases.
-  unpackPhase= ''
-    gemRegex="\.gem"
-    if [[ $src =~ $gemRegex ]]
-    then
-      runHook preUnpack
-      echo "source is a gem package, won't unpack"
-      gempkg=$src
-      dontBuild=1
-      runHook postUnpack
-    else
-      # Fall back to the original thing for everything else.
-      unpackPhase
-    fi
-  '';
-
-  checkPhase = "true";
-
-  buildPhase = ''
-    runHook preBuild
-
-    # TODO: Investigate. The complete working tree is touched by fetchgit.
-    if [ -d .git ]; then
-      git reset
-    fi
-
-    gemspec=$(find . -name '*.gemspec')
-    echo "found the following gemspecs:"
-    echo "$gemspec"
-
-    gemspec=$(echo "$gemspec" | head -n1)
-    echo "building $gemspec"
-
-    exec 3>&1
-    output=$(gem build $gemspec | tee >(cat - >&3))
-    exec 3>&-
-
-    gempkg=$(echo "$output" | grep -oP 'File: \K(.*)')
-
-    echo "gem package built: $gempkg"
-
-    runHook postBuild
-  '';
-
-  installPhase = ''
-    runHook preInstall
-
-    # NOTE: This does NOT build the unpacked gem, but installs $src directly.
-    #       Gems that have not been downloaded from rubygems.org may need a
-    #       separate buildPhase.
-    #       --ignore-dependencies is necessary as rubygems otherwise always
-    #       connects to the repository, thus breaking pure builds.
-    GEM_HOME=$out/${ruby.gemPath} \
-      gem install \
-      --local \
-      --force \
-      --http-proxy "http://nodtd.invalid" \
-      --ignore-dependencies \
-      --build-root "/" \
-      --backtrace \
-      $gempkg $gemFlags -- $buildFlags
-
-    # Yes, we really do need the $out/${ruby.gemPath}/cache.
-    # This is very important in order for many parts of RubyGems/Bundler to not blow up.
-    # See https://github.com/bundler/bundler/issues/3327
-
-    mkdir -p $out/bin
-    for prog in $out/${ruby.gemPath}/gems/*/bin/*; do
-      makeWrapper $prog $out/bin/$(basename $prog) \
-        --prefix GEM_PATH : "$out/${ruby.gemPath}:$GEM_PATH" \
-        --prefix RUBYLIB : "${rubygems}/lib" \
-        $extraWrapperFlags ''${extraWrapperFlagsArray[@]}
-    done
-        #--prefix RUBYOPT rubygems \
-
-    # looks like useless files which break build repeatability and consume space
-    rm -fv $out/${ruby.gemPath}/doc/*/*/created.rid || true
-    rm -fv $out/${ruby.gemPath}/gems/*/ext/*/mkmf.log || true
-
-    mkdir -p $out/nix-support
-
-    cat > $out/nix-support/setup-hook <<EOF
-    if [[ "\$GEM_PATH" != *$out* ]]; then
-      addToSearchPath GEM_PATH $out/${ruby.gemPath}
-    fi
-    EOF
-
-    runHook postInstall
-  '';
-
-  propagatedBuildInputs = gemPath;
-  propagatedUserEnvPkgs = gemPath;
-
-  passthru.isRubyGem = true;
-  inherit meta;
-})
-
-)
diff --git a/pkgs/development/interpreters/ruby/bundler-env/default-gem-config.nix b/pkgs/development/interpreters/ruby/gemconfig/default.nix
index 36925bcdf558..ae8c0ee6e6ad 100644
--- a/pkgs/development/interpreters/ruby/bundler-env/default-gem-config.nix
+++ b/pkgs/development/interpreters/ruby/gemconfig/default.nix
@@ -20,7 +20,7 @@
 { lib, fetchurl, writeScript, ruby, kerberos, libxml2, libxslt, python, stdenv, which
 , libiconv, postgresql, v8_3_16_14, clang, sqlite, zlib, imagemagick
 , pkgconfig , ncurses, xapian, gpgme, utillinux, fetchpatch, tzdata, icu, libffi
-, cmake, libssh2, openssl, mysql, darwin
+, cmake, libssh2, openssl, mysql, darwin, git, perl, gecode_3, curl
 }:
 
 let
@@ -32,6 +32,14 @@ in
     buildInputs = [ which icu zlib ];
   };
 
+  dep-selector-libgecode = attrs: {
+    USE_SYSTEM_GECODE = true;
+    postInstall = ''
+      installPath=$(cat $out/nix-support/gem-meta/install-path)
+      sed -i $installPath/lib/dep-selector-libgecode.rb -e 's@VENDORED_GECODE_DIR =.*@VENDORED_GECODE_DIR = "${gecode_3}"@'
+    '';
+  };
+
   ffi = attrs: {
     buildInputs = [ libffi pkgconfig ];
   };
@@ -40,11 +48,12 @@ in
     buildInputs = [ gpgme ];
   };
 
+  # note that you need version >= v3.16.14.8,
+  # otherwise the gem will fail to link to the libv8 binary.
+  # see: https://github.com/cowboyd/libv8/pull/161
   libv8 = attrs: {
     buildInputs = [ which v8 python ];
-    buildFlags = [
-      "--with-system-v8=true"
-    ];
+    buildFlags = [ "--with-system-v8=true" ];
   };
 
   mysql2 = attrs: {
@@ -73,12 +82,20 @@ in
     buildInputs = lib.optional stdenv.isDarwin darwin.libobjc;
   };
 
+  patron = attrs: {
+    buildInputs = [ curl ];
+  };
+
   pg = attrs: {
     buildFlags = [
       "--with-pg-config=${postgresql}/bin/pg_config"
     ];
   };
 
+  puma = attrs: {
+    buildInputs = [ openssl ];
+  };
+
   rmagick = attrs: {
     buildInputs = [ imagemagick pkgconfig ];
   };
@@ -95,6 +112,7 @@ in
   };
 
   sup = attrs: {
+    dontBuild = false;
     # prevent sup from trying to dynamically install `xapian-ruby`.
     postPatch = ''
       cp ${./mkrf_conf_xapian.rb} ext/mkrf_conf_xapian.rb
@@ -118,6 +136,7 @@ in
   };
 
   tzinfo = attrs: {
+    dontBuild = false;
     postPatch = ''
       substituteInPlace lib/tzinfo/zoneinfo_data_source.rb \
         --replace "/usr/share/zoneinfo" "${tzdata}/share/zoneinfo"
@@ -130,6 +149,7 @@ in
 
   xapian-ruby = attrs: {
     # use the system xapian
+    dontBuild = false;
     buildInputs = [ xapian pkgconfig zlib ];
     postPatch = ''
       cp ${./xapian-Rakefile} Rakefile
diff --git a/pkgs/development/interpreters/ruby/bundler-env/mkrf_conf_xapian.rb b/pkgs/development/interpreters/ruby/gemconfig/mkrf_conf_xapian.rb
index e19f06e23ac2..e19f06e23ac2 100644
--- a/pkgs/development/interpreters/ruby/bundler-env/mkrf_conf_xapian.rb
+++ b/pkgs/development/interpreters/ruby/gemconfig/mkrf_conf_xapian.rb
diff --git a/pkgs/development/interpreters/ruby/bundler-env/xapian-Rakefile b/pkgs/development/interpreters/ruby/gemconfig/xapian-Rakefile
index 9f0b8e72f08c..9f0b8e72f08c 100644
--- a/pkgs/development/interpreters/ruby/bundler-env/xapian-Rakefile
+++ b/pkgs/development/interpreters/ruby/gemconfig/xapian-Rakefile
diff --git a/pkgs/development/interpreters/ruby/load-ruby-env.nix b/pkgs/development/interpreters/ruby/load-ruby-env.nix
deleted file mode 100644
index c4356ed5f50f..000000000000
--- a/pkgs/development/interpreters/ruby/load-ruby-env.nix
+++ /dev/null
@@ -1,69 +0,0 @@
-{ ruby, lib, callPackage, gemFixes, fetchurl, fetchgit, buildRubyGem }@defs:
-
-# This function builds a set of gems. You first convert your Gemfile to an attrset
-# called a "gemset", and then use this function to build the gemset.
-#
-# A gemset looks like the following:
-#
-#   {
-#     libv8 = {
-#       version = "3.16.14.7";
-#       src = {
-#         type = "gem";
-#         sha256 = "...";
-#       };
-#     };
-#     therubyracer = {
-#       version = "0.12.1";
-#       dependencies = [ "libv8" ];
-#       src = {
-#         type = "gem";
-#         sha256 = "...";
-#       };
-#     };
-#   }
-#
-# If you use these gems as build inputs, the GEM_PATH will be updated
-# appropriately, and command like `bundle exec` should work out of the box.
-
-{ gemset, ruby ? defs.ruby, fixes ? gemFixes }@args:
-
-let
-  const = x: y: x;
-
-  fetchers.path = attrs: attrs.src.path;
-  fetchers.gem = attrs: fetchurl {
-    url = "${attrs.src.source or "https://rubygems.org"}/downloads/${attrs.name}-${attrs.version}.gem";
-    inherit (attrs.src) sha256;
-  };
-  fetchers.git = attrs: fetchgit {
-    inherit (attrs.src) url rev sha256 fetchSubmodules;
-    leaveDotGit = true;
-  };
-
-  instantiate = (attrs:
-    let
-      defaultAttrs = {
-        name = "${attrs.name}-${attrs.version}";
-        inherit ruby gemPath;
-      };
-      gemPath = map (name: gemset''."${name}") (attrs.dependencies or []);
-      fixedAttrs = attrs // (fixes."${attrs.name}" or (const {})) attrs;
-      withSource = fixedAttrs //
-        (if (lib.isDerivation fixedAttrs.src || builtins.isString fixedAttrs.src)
-           then {}
-           else { src = (fetchers."${fixedAttrs.src.type}" fixedAttrs); });
-
-    in
-      buildRubyGem (withSource // defaultAttrs)
-  );
-
-  gemset' = if builtins.isAttrs gemset then gemset else import gemset;
-
-  gemset'' = lib.flip lib.mapAttrs gemset' (name: attrs:
-    if (lib.isDerivation attrs)
-      then attrs
-      else instantiate (attrs // { inherit name; })
-  );
-
-in gemset''
diff --git a/pkgs/development/interpreters/ruby/rubygems.nix b/pkgs/development/interpreters/ruby/rubygems.nix
index f4942b840919..b6ac04808979 100644
--- a/pkgs/development/interpreters/ruby/rubygems.nix
+++ b/pkgs/development/interpreters/ruby/rubygems.nix
@@ -1,37 +1,35 @@
-args @ { makeWrapper, ruby, ... }: with args;
+{ stdenv, lib, fetchurl, makeWrapper, ruby }:
 
-rec {
-  name = "rubygems-" + version;
+stdenv.mkDerivation rec {
+  name = "rubygems-${version}";
   version = "2.4.1";
   src = fetchurl {
     url = "http://production.cf.rubygems.org/rubygems/${name}.tgz";
     sha256 = "0cpr6cx3h74ykpb0cp4p4xg7a8j0bhz3sk271jq69l4mm4zy4h4f";
   };
 
+  patches = [ ./gem_hook.patch ];
+
   buildInputs = [ruby makeWrapper];
-  configureFlags = [];
 
-  doInstall = fullDepEntry (''
+  buildPhase = ":";
+
+  installPhase = ''
     ruby setup.rb --prefix=$out/
+
     wrapProgram $out/bin/gem --prefix RUBYLIB : $out/lib
-    find $out -type f -name "*.rb" | xargs sed -i "s@/usr/bin/env@$(type -p env)@g"
+
+    find $out -type f -name "*.rb" |
+      xargs sed -i "s@/usr/bin/env@$(type -p env)@g"
+
     mkdir -pv $out/nix-support
     cat > $out/nix-support/setup-hook <<EOF
     export RUBYOPT=rubygems
     addToSearchPath RUBYLIB $out/lib
-    EOF'') ["minInit" "addInputs" "doUnpack" "defEnsureDir"];
-
-  /* doConfigure should be specified separately */
-  phaseNames = ["doPatch" "doInstall"];
+    EOF
+  '';
 
   meta = {
-    description = "Ruby gems package collection";
-    longDescription = ''
-      Nix can create nix packages from gems.
-
-      To use it by installing gem-nix package.
-    '';
+    description = "A package management framework for Ruby";
   };
-
-  patches = [ ./gem_hook.patch ];
 }
diff --git a/pkgs/development/libraries/apr-util/default.nix b/pkgs/development/libraries/apr-util/default.nix
index c35520f22fd3..c123740f5c12 100644
--- a/pkgs/development/libraries/apr-util/default.nix
+++ b/pkgs/development/libraries/apr-util/default.nix
@@ -3,6 +3,7 @@
 , bdbSupport ? false, db
 , ldapSupport ? !stdenv.isCygwin, openldap
 , libiconv
+, cyrus_sasl, autoreconfHook
 }:
 
 assert sslSupport -> openssl != null;
@@ -19,19 +20,25 @@ stdenv.mkDerivation rec {
     sha256 = "0bn81pfscy9yjvbmyx442svf43s6dhrdfcsnkpxz43fai5qk5kx6";
   };
 
-  configureFlags = ''
-    --with-apr=${apr} --with-expat=${expat}
-    ${optionalString (!stdenv.isCygwin) "--with-crypto"}
-    ${stdenv.lib.optionalString sslSupport "--with-openssl=${openssl}"}
-    ${stdenv.lib.optionalString bdbSupport "--with-berkeley-db=${db}"}
-    ${stdenv.lib.optionalString ldapSupport "--with-ldap"}${
-      optionalString stdenv.isCygwin "--without-pgsql --without-sqlite2 --without-sqlite3 --without-freetds --without-berkeley-db --without-crypto"}
-  '';
+  patches = optional stdenv.isFreeBSD ./include-static-dependencies.patch;
+
+  buildInputs = optional stdenv.isFreeBSD autoreconfHook;
+
+  configureFlags = [ "--with-apr=${apr}" "--with-expat=${expat}" ]
+    ++ optional (!stdenv.isCygwin) "--with-crypto"
+    ++ optional sslSupport "--with-openssl=${openssl}"
+    ++ optional bdbSupport "--with-berkeley-db=${db}"
+    ++ optional ldapSupport "--with-ldap=ldap"
+    ++ optionals stdenv.isCygwin
+      [ "--without-pgsql" "--without-sqlite2" "--without-sqlite3"
+        "--without-freetds" "--without-berkeley-db" "--without-crypto" ]
+    ;
 
   propagatedBuildInputs = [ makeWrapper apr expat libiconv ]
     ++ optional sslSupport openssl
     ++ optional bdbSupport db
-    ++ optional ldapSupport openldap;
+    ++ optional ldapSupport openldap
+    ++ optional stdenv.isFreeBSD cyrus_sasl;
 
   # Give apr1 access to sed for runtime invocations
   postInstall = ''
diff --git a/pkgs/development/libraries/apr-util/include-static-dependencies.patch b/pkgs/development/libraries/apr-util/include-static-dependencies.patch
new file mode 100644
index 000000000000..1813c7217810
--- /dev/null
+++ b/pkgs/development/libraries/apr-util/include-static-dependencies.patch
@@ -0,0 +1,12 @@
+diff --git a/build/apu-conf.m4 b/build/apu-conf.m4
+index 8943f10..aa44305 100644
+--- a/build/apu-conf.m4
++++ b/build/apu-conf.m4
+@@ -279,6 +279,7 @@ AC_ARG_WITH(ldap,[  --with-ldap=library     ldap library to use],
+         APU_FIND_LDAPLIB("ldap", "-llber -lresolv -lsocket -lnsl")
+         APU_FIND_LDAPLIB("ldap", "-ldl -lpthread")
+       else
++        APU_FIND_LDAPLIB($LIBLDAP, "-llber -lcrypto -lssl -lsasl2")
+         APU_FIND_LDAPLIB($LIBLDAP)
+         APU_FIND_LDAPLIB($LIBLDAP, "-lresolv")
+         APU_FIND_LDAPLIB($LIBLDAP, "-lresolv -lsocket -lnsl")
diff --git a/pkgs/development/libraries/at-spi2-atk/default.nix b/pkgs/development/libraries/at-spi2-atk/default.nix
index f5d806ff67a5..f3538a122218 100644
--- a/pkgs/development/libraries/at-spi2-atk/default.nix
+++ b/pkgs/development/libraries/at-spi2-atk/default.nix
@@ -3,13 +3,13 @@
 
 stdenv.mkDerivation rec {
   versionMajor = "2.18";
-  versionMinor = "0";
+  versionMinor = "1";
   moduleName   = "at-spi2-atk";
   name = "${moduleName}-${versionMajor}.${versionMinor}";
 
   src = fetchurl {
     url = "mirror://gnome/sources/${moduleName}/${versionMajor}/${name}.tar.xz";
-    sha256 = "0xgkrnx04vaklbkzc7bzym9s0qhj8aiz4knqlxgx3vxnacsb6vaa";
+    sha256 = "0bf1g5cj84rmx7p1q547vwbc0hlpcs2wrxnmv96lckfkhs9mzcf4";
   };
 
   buildInputs = [ python pkgconfig popt atk libX11 libICE xorg.libXtst libXi
diff --git a/pkgs/development/libraries/at-spi2-core/default.nix b/pkgs/development/libraries/at-spi2-core/default.nix
index b49d1ddb8040..808de07c52fd 100644
--- a/pkgs/development/libraries/at-spi2-core/default.nix
+++ b/pkgs/development/libraries/at-spi2-core/default.nix
@@ -3,13 +3,13 @@
 
 stdenv.mkDerivation rec {
   versionMajor = "2.18";
-  versionMinor = "0";
+  versionMinor = "3";
   moduleName   = "at-spi2-core";
   name = "${moduleName}-${versionMajor}.${versionMinor}";
 
   src = fetchurl {
     url = "mirror://gnome/sources/${moduleName}/${versionMajor}/${name}.tar.xz";
-    sha256 = "0xna0gnlqvzy6209klirywcm7ianazshg6pkk828g07bnrywgvhs";
+    sha256 = "0afn4x04j5l352vj0dccb2hkpzg3l2vhr8h1yv89fpqmjkfnm8md";
   };
 
   outputs = [ "out" "doc" ];
diff --git a/pkgs/development/libraries/avahi/default.nix b/pkgs/development/libraries/avahi/default.nix
index 6c8fe6e112b7..199379ad401f 100644
--- a/pkgs/development/libraries/avahi/default.nix
+++ b/pkgs/development/libraries/avahi/default.nix
@@ -36,12 +36,15 @@ stdenv.mkDerivation rec {
     avahi-core/socket.c
   '';
 
-  postInstall = ''
+  postInstall =
     # Maintain compat for mdnsresponder and howl
-    ${if withLibdnssdCompat then "ln -s avahi-compat-libdns_sd/dns_sd.h $out/include/dns_sd.h" else ""}
+    stdenv.lib.optionalString withLibdnssdCompat ''
+      ln -s avahi-compat-libdns_sd/dns_sd.h "$out/include/dns_sd.h"
+    '';
+  /*  # these don't exist (anymore?)
     ln -s avahi-compat-howl $out/include/howl
     ln -s avahi-compat-howl.pc $out/lib/pkgconfig/howl.pc
-  '';
+  */
 
   meta = with stdenv.lib; {
     description = "mDNS/DNS-SD implementation";
diff --git a/pkgs/development/libraries/boost/generic.nix b/pkgs/development/libraries/boost/generic.nix
index 2a83d7c4142d..90e60d59da0c 100644
--- a/pkgs/development/libraries/boost/generic.nix
+++ b/pkgs/development/libraries/boost/generic.nix
@@ -1,5 +1,5 @@
 { stdenv, icu, expat, zlib, bzip2, python, fixDarwinDylibNames
-, toolset ? if stdenv.isDarwin then "clang" else null
+, toolset ? if stdenv.cc.isClang then "clang" else null
 , enableRelease ? true
 , enableDebug ? false
 , enableSingleThreaded ? false
diff --git a/pkgs/development/libraries/cyrus-sasl/default.nix b/pkgs/development/libraries/cyrus-sasl/default.nix
index 2be98f3d5e87..059b0ab0042a 100644
--- a/pkgs/development/libraries/cyrus-sasl/default.nix
+++ b/pkgs/development/libraries/cyrus-sasl/default.nix
@@ -1,4 +1,4 @@
-{ lib, stdenv, fetchurl, openssl, kerberos, db, gettext, pam, fixDarwinDylibNames }:
+{ lib, stdenv, fetchurl, openssl, kerberos, db, gettext, pam, fixDarwinDylibNames, autoreconfHook }:
 
 with stdenv.lib;
 stdenv.mkDerivation rec {
@@ -11,11 +11,18 @@ stdenv.mkDerivation rec {
 
   buildInputs =
     [ openssl db gettext kerberos ]
+    ++ lib.optional stdenv.isFreeBSD autoreconfHook
     ++ lib.optional stdenv.isLinux pam
     ++ lib.optional stdenv.isDarwin fixDarwinDylibNames;
 
-  patches = [ ./missing-size_t.patch ]; # https://bugzilla.redhat.com/show_bug.cgi?id=906519
-  patchFlags = "-p0";
+  patches = [
+    ./missing-size_t.patch # https://bugzilla.redhat.com/show_bug.cgi?id=906519
+  ] ++ lib.optional stdenv.isFreeBSD (
+      fetchurl {
+        url = "http://www.linuxfromscratch.org/patches/blfs/svn/cyrus-sasl-2.1.26-fixes-3.patch";
+        sha256 = "1vh4pc2rxxm6yvykx0b7kg09jbcwcxwv5rs6yq2ag3y8p6a9x86w";
+      }
+    );
 
   configureFlags = [
     "--with-openssl=${openssl}"
diff --git a/pkgs/development/libraries/cyrus-sasl/missing-size_t.patch b/pkgs/development/libraries/cyrus-sasl/missing-size_t.patch
index 42f20fb8096b..da96818ca267 100644
--- a/pkgs/development/libraries/cyrus-sasl/missing-size_t.patch
+++ b/pkgs/development/libraries/cyrus-sasl/missing-size_t.patch
@@ -1,6 +1,6 @@
 Gentoo bug #458790
---- include/sasl.h	2012-10-12 17:05:48.000000000 +0300
-+++ include/sasl.h	2013-02-23 16:56:44.648786268 +0200
+--- a/include/sasl.h	2012-10-12 17:05:48.000000000 +0300
++++ b/include/sasl.h	2013-02-23 16:56:44.648786268 +0200
 @@ -121,6 +121,9 @@
  #ifndef SASL_H
  #define SASL_H 1
diff --git a/pkgs/development/libraries/db/clang-4.8.patch b/pkgs/development/libraries/db/clang-4.8.patch
new file mode 100644
index 000000000000..c53160a82970
--- /dev/null
+++ b/pkgs/development/libraries/db/clang-4.8.patch
@@ -0,0 +1,22 @@
+diff --git a/dbinc/atomic.h b/dbinc/atomic.h
+index 0034dcc..fa7ba93 100644
+--- a/dbinc/atomic.h
++++ b/dbinc/atomic.h
+@@ -144,7 +144,7 @@ typedef LONG volatile *interlocked_val;
+ #define	atomic_inc(env, p)	__atomic_inc(p)
+ #define	atomic_dec(env, p)	__atomic_dec(p)
+ #define	atomic_compare_exchange(env, p, o, n)	\
+-	__atomic_compare_exchange((p), (o), (n))
++	__db_atomic_compare_exchange((p), (o), (n))
+ static inline int __atomic_inc(db_atomic_t *p)
+ {
+ 	int	temp;
+@@ -176,7 +176,7 @@ static inline int __atomic_dec(db_atomic_t *p)
+  * http://gcc.gnu.org/onlinedocs/gcc-4.1.0/gcc/Atomic-Builtins.html
+  * which configure could be changed to use.
+  */
+-static inline int __atomic_compare_exchange(
++static inline int __db_atomic_compare_exchange(
+ 	db_atomic_t *p, atomic_value_t oldval, atomic_value_t newval)
+ {
+ 	atomic_value_t was;
diff --git a/pkgs/development/libraries/db/osx.patch b/pkgs/development/libraries/db/clang-5.3.patch
index 438fa7eedd71..438fa7eedd71 100644
--- a/pkgs/development/libraries/db/osx.patch
+++ b/pkgs/development/libraries/db/clang-5.3.patch
diff --git a/pkgs/development/libraries/db/db-4.8.nix b/pkgs/development/libraries/db/db-4.8.nix
index 9b5e8cb39bda..6a161b0b72d8 100644
--- a/pkgs/development/libraries/db/db-4.8.nix
+++ b/pkgs/development/libraries/db/db-4.8.nix
@@ -2,6 +2,7 @@
 
 import ./generic.nix (args // rec {
   version = "4.8.30";
+  extraPatches = [ ./clang-4.8.patch ];
   sha256 = "0ampbl2f0hb1nix195kz1syrqqxpmvnvnfvphambj7xjrl3iljg0";
   branch = "4.8";
 })
diff --git a/pkgs/development/libraries/db/db-5.3.nix b/pkgs/development/libraries/db/db-5.3.nix
index b5e62ee686f0..98002c244612 100644
--- a/pkgs/development/libraries/db/db-5.3.nix
+++ b/pkgs/development/libraries/db/db-5.3.nix
@@ -3,6 +3,6 @@
 import ./generic.nix (args // rec {
   version = "5.3.28";
   sha256 = "0a1n5hbl7027fbz5lm0vp0zzfp1hmxnz14wx3zl9563h83br5ag0";
-  extraPatches = [ ./osx.patch ];
+  extraPatches = [ ./clang-5.3.patch ];
   branch = "5.3";
 })
diff --git a/pkgs/development/libraries/db/generic.nix b/pkgs/development/libraries/db/generic.nix
index 077bd4e03a32..f5ee4e440ff0 100644
--- a/pkgs/development/libraries/db/generic.nix
+++ b/pkgs/development/libraries/db/generic.nix
@@ -23,6 +23,7 @@ stdenv.mkDerivation rec {
     (if cxxSupport then "--enable-cxx" else "--disable-cxx")
     (if compat185 then "--enable-compat185" else "--disable-compat185")
     "--enable-dbm"
+    (stdenv.lib.optionalString stdenv.isFreeBSD "--with-pic")
   ];
 
   preConfigure = ''
diff --git a/pkgs/development/libraries/exiv2/default.nix b/pkgs/development/libraries/exiv2/default.nix
index 0702d24a80b8..e1af46cc3ed0 100644
--- a/pkgs/development/libraries/exiv2/default.nix
+++ b/pkgs/development/libraries/exiv2/default.nix
@@ -1,28 +1,20 @@
-{stdenv, fetchurl, fetchpatch, zlib, expat}:
+{ stdenv, fetchurl, fetchpatch, zlib, expat, gettext }:
 
 stdenv.mkDerivation rec {
-  name = "exiv2-0.24";
+  name = "exiv2-0.25";
 
   src = fetchurl {
     url = "http://www.exiv2.org/${name}.tar.gz";
-    sha256 = "13pgvz14kyapxl89pxjaq3274k56d5lzfckpg1g9z7gvqzk4797l";
+    sha256 = "197g6vgcpyf9p2cwn5p5hb1r714xsk1v4p96f5pv1z8mi9vzq2y8";
   };
+  postPatch = "patchShebangs ./src/svn_version.sh";
 
-  patches = [(fetchpatch {
-    name = "CVE-2014-9449.diff";
-    url = "http://dev.exiv2.org/projects/exiv2/repository/revisions/3264/diff?format=diff&rev_to=3263";
-    sha256 = "02w0fksl966d4v6bkg6rq3wmvv8xjpvfp47qr0nv1xq0bphxqzag";
-  })];
-
-  propagatedBuildInputs = [zlib expat];
-
-# configure script finds zlib&expat but it thinks that they're in /usr
-  configureFlags = "--with-zlib=${zlib} --with-expat=${expat}";
+  nativeBuildInputs = [ gettext ];
+  propagatedBuildInputs = [ zlib expat ];
 
   meta = {
     homepage = http://www.exiv2.org/;
     description = "A library and command-line utility to manage image metadata";
-    maintainers = [stdenv.lib.maintainers.urkud];
     platforms = stdenv.lib.platforms.all;
   };
 }
diff --git a/pkgs/development/libraries/expat/default.nix b/pkgs/development/libraries/expat/default.nix
index 05cfeaee4232..96d46649d916 100644
--- a/pkgs/development/libraries/expat/default.nix
+++ b/pkgs/development/libraries/expat/default.nix
@@ -10,6 +10,8 @@ stdenv.mkDerivation rec {
 
   patches = [ ./CVE-2015-1283.patch ];
 
+  configureFlags = stdenv.lib.optional stdenv.isFreeBSD "--with-pic";
+
   meta = with stdenv.lib; {
     homepage = http://www.libexpat.org/;
     description = "A stream-oriented XML parser library written in C";
diff --git a/pkgs/development/libraries/ffmpeg-full/default.nix b/pkgs/development/libraries/ffmpeg-full/default.nix
index fadb3feb4cc0..eed6a3bc763c 100644
--- a/pkgs/development/libraries/ffmpeg-full/default.nix
+++ b/pkgs/development/libraries/ffmpeg-full/default.nix
@@ -235,11 +235,11 @@ assert x11grabExtlib -> libX11 != null && libXv != null;
 
 stdenv.mkDerivation rec {
   name = "ffmpeg-full-${version}";
-  version = "2.8.1";
+  version = "2.8.5";
 
   src = fetchurl {
     url = "https://www.ffmpeg.org/releases/ffmpeg-${version}.tar.bz2";
-    sha256 = "1qk6g2h993i0wgs9d2p3ahdc5bqr03mp74bk6r1zj6pfinr5mvg2";
+    sha256 = "0nk1j3i7qc1k3dygpq74pxq382vqg9kaf2hxl9jfw8rkad8rjv9v";
   };
 
   patchPhase = ''patchShebangs .'';
diff --git a/pkgs/development/libraries/ffmpeg/2.8.nix b/pkgs/development/libraries/ffmpeg/2.8.nix
index e585ea14997f..2f911b26ca19 100644
--- a/pkgs/development/libraries/ffmpeg/2.8.nix
+++ b/pkgs/development/libraries/ffmpeg/2.8.nix
@@ -1,7 +1,7 @@
 { callPackage, ... } @ args:
 
 callPackage ./generic.nix (args // rec {
-  version = "${branch}.1";
+  version = "${branch}.5";
   branch = "2.8";
-  sha256 = "1qk6g2h993i0wgs9d2p3ahdc5bqr03mp74bk6r1zj6pfinr5mvg2";
+  sha256 = "0nk1j3i7qc1k3dygpq74pxq382vqg9kaf2hxl9jfw8rkad8rjv9v";
 })
diff --git a/pkgs/development/libraries/gdk-pixbuf/default.nix b/pkgs/development/libraries/gdk-pixbuf/default.nix
index dbd3a679d482..18562d1d12e3 100644
--- a/pkgs/development/libraries/gdk-pixbuf/default.nix
+++ b/pkgs/development/libraries/gdk-pixbuf/default.nix
@@ -3,14 +3,14 @@
 
 let
   ver_maj = "2.32";
-  ver_min = "1";
+  ver_min = "3";
 in
 stdenv.mkDerivation rec {
   name = "gdk-pixbuf-${ver_maj}.${ver_min}";
 
   src = fetchurl {
     url = "mirror://gnome/sources/gdk-pixbuf/${ver_maj}/${name}.tar.xz";
-    sha256 = "1g7kjxv67jcdasi14n7jan4icrnnppd1m99wrdmpv32k4m7vfcj4";
+    sha256 = "0cfh87aqyqbfcwpbv1ihgmgfcn66il5q2n8yjyl8gxkjmkqp2rrb";
   };
 
   setupHook = ./setup-hook.sh;
diff --git a/pkgs/development/libraries/gecode/3.nix b/pkgs/development/libraries/gecode/3.nix
new file mode 100644
index 000000000000..a0f3dc636f92
--- /dev/null
+++ b/pkgs/development/libraries/gecode/3.nix
@@ -0,0 +1,21 @@
+{ stdenv, fetchurl, perl }:
+
+stdenv.mkDerivation rec {
+  name = "gecode-${version}";
+  version = "3.7.3";
+
+  src = fetchurl {
+    url = "http://www.gecode.org/download/${name}.tar.gz";
+    sha256 = "0k45jas6p3cyldgyir1314ja3174sayn2h2ly3z9b4dl3368pk77";
+  };
+
+  buildInputs = [ perl ];
+
+  meta = with stdenv.lib; {
+    license = licenses.mit;
+    homepage = http://www.gecode.org;
+    description = "Toolkit for developing constraint-based systems";
+    platforms = platforms.all;
+    maintainers = [ maintainers.manveru ];
+  };
+}
diff --git a/pkgs/development/libraries/glib/default.nix b/pkgs/development/libraries/glib/default.nix
index e53775464e03..538a40615f14 100644
--- a/pkgs/development/libraries/glib/default.nix
+++ b/pkgs/development/libraries/glib/default.nix
@@ -7,7 +7,7 @@
 
 with stdenv.lib;
 
-assert !stdenv.isDarwin -> stdenv.cc.isGNU;
+assert stdenv.isFreeBSD || stdenv.isDarwin || stdenv.cc.isGNU;
 
 # TODO:
 # * Add gio-module-fam
@@ -63,8 +63,12 @@ stdenv.mkDerivation rec {
   propagatedBuildInputs = [ pcre zlib libffi libiconv ]
     ++ libintlOrEmpty;
 
+  LIBELF_CFLAGS = optional stdenv.isFreeBSD "-I${libelf}";
+  LIBELF_LIBS = optional stdenv.isFreeBSD "-L${libelf} -lelf";
+
   configureFlags =
     optional stdenv.isDarwin "--disable-compile-warnings"
+    ++ optional stdenv.isFreeBSD "--with-libiconv=gnu"
     ++ optional stdenv.isSunOS ["--disable-modular-tests" "--with-libiconv"];
 
   NIX_CFLAGS_COMPILE = optionalString stdenv.isDarwin " -lintl"
diff --git a/pkgs/development/libraries/gnutls/generic.nix b/pkgs/development/libraries/gnutls/generic.nix
index f1eb62e0083e..ebaef47ca140 100644
--- a/pkgs/development/libraries/gnutls/generic.nix
+++ b/pkgs/development/libraries/gnutls/generic.nix
@@ -30,7 +30,7 @@ stdenv.mkDerivation {
   enableParallelBuilding = !guileBindings;
 
   buildInputs = [ lzo lzip nettle libtasn1 libidn p11_kit zlib gmp autogen ]
-    ++ lib.optional (stdenv.isDarwin) libiconv
+    ++ lib.optional (stdenv.isFreeBSD || stdenv.isDarwin) libiconv
     ++ lib.optional (tpmSupport && stdenv.isLinux) trousers
     ++ [ unbound ]
     ++ lib.optional guileBindings guile;
diff --git a/pkgs/development/libraries/gtk+/2.x.nix b/pkgs/development/libraries/gtk+/2.x.nix
index e821e693b0ce..8830e1425b68 100644
--- a/pkgs/development/libraries/gtk+/2.x.nix
+++ b/pkgs/development/libraries/gtk+/2.x.nix
@@ -8,11 +8,11 @@ assert xineramaSupport -> xorg.libXinerama != null;
 assert cupsSupport -> cups != null;
 
 stdenv.mkDerivation rec {
-  name = "gtk+-2.24.28";
+  name = "gtk+-2.24.29";
 
   src = fetchurl {
     url = "mirror://gnome/sources/gtk+/2.24/${name}.tar.xz";
-    sha256 = "0mj6xn40py9r9lvzg633fal81xfwfm89d9mvz7jk4lmwk0g49imj";
+    sha256 = "1f1ifv1ijrda4jx831l24d3ww65v5gf56r464fi11n6k02bcah87";
   };
 
   enableParallelBuilding = true;
diff --git a/pkgs/development/libraries/harfbuzz/default.nix b/pkgs/development/libraries/harfbuzz/default.nix
index 26c5d2fa8254..d2546ebd496d 100644
--- a/pkgs/development/libraries/harfbuzz/default.nix
+++ b/pkgs/development/libraries/harfbuzz/default.nix
@@ -8,11 +8,11 @@
 # (icu is a ~30 MB dependency, the rest is very small in comparison)
 
 stdenv.mkDerivation rec {
-  name = "harfbuzz-1.0.6";
+  name = "harfbuzz-1.1.2";
 
   src = fetchurl {
     url = "http://www.freedesktop.org/software/harfbuzz/release/${name}.tar.bz2";
-    sha256 = "09ivk5m4y09ar4zi9r6db7gp234cy05h0ach7w22g9kqvkxsf5pn";
+    sha256 = "07s6z3hbrb4rdfgzmln169wxz4nm5y7qbr02ik5c7drxpn85fb2a";
   };
 
   outputs = [ "out" "doc" ];
diff --git a/pkgs/development/libraries/icu/default.nix b/pkgs/development/libraries/icu/default.nix
index a2196d26524e..148e4f02a94f 100644
--- a/pkgs/development/libraries/icu/default.nix
+++ b/pkgs/development/libraries/icu/default.nix
@@ -30,7 +30,7 @@ stdenv.mkDerivation {
   '';
 
   configureFlags = "--disable-debug" +
-    stdenv.lib.optionalString stdenv.isDarwin " --enable-rpath";
+    stdenv.lib.optionalString (stdenv.isFreeBSD || stdenv.isDarwin) " --enable-rpath";
 
   # remove dependency on bootstrap-tools in early stdenv build
   postInstall = stdenv.lib.optionalString stdenv.isDarwin ''
diff --git a/pkgs/development/libraries/kerberos/heimdal.nix b/pkgs/development/libraries/kerberos/heimdal.nix
index 0569c0bf5b31..175d0c7bc3b2 100644
--- a/pkgs/development/libraries/kerberos/heimdal.nix
+++ b/pkgs/development/libraries/kerberos/heimdal.nix
@@ -23,7 +23,8 @@ stdenv.mkDerivation rec {
   nativeBuildInputs = [ autoreconfHook pkgconfig python perl yacc flex ]
     ++ (with perlPackages; [ JSON ])
     ++ optional (!libOnly) texinfo;
-  buildInputs = [ libcap_ng sqlite openssl db libedit ]
+  buildInputs = optionals (!stdenv.isFreeBSD) [ libcap_ng db ]
+    ++ [ sqlite openssl libedit ]
     ++ optionals (!libOnly) [ openldap pam ];
 
   ## ugly, X should be made an option
@@ -31,14 +32,15 @@ stdenv.mkDerivation rec {
     "--sysconfdir=/etc"
     "--localstatedir=/var"
     "--enable-hdb-openldap-module"
-    "--with-capng"
     "--with-sqlite3=${sqlite}"
-    "--with-berkeley-db=${db}"
     "--with-libedit=${libedit}"
     "--with-openssl=${openssl}"
     "--without-x"
+    "--with-berkeley-db=${db}"
   ] ++ optionals (!libOnly) [
     "--with-openldap=${openldap}"
+  ] ++ optionals (!stdenv.isFreeBSD) [
+    "--with-capng"
   ];
 
   buildPhase = optionalString libOnly ''
@@ -83,7 +85,7 @@ stdenv.mkDerivation rec {
   meta = {
     description = "An implementation of Kerberos 5 (and some more stuff)";
     license = licenses.bsd3;
-    platforms = platforms.linux;
+    platforms = platforms.linux ++ platforms.freebsd;
     maintainers = with maintainers; [ wkennington ];
   };
 
diff --git a/pkgs/development/libraries/kerberos/krb5.nix b/pkgs/development/libraries/kerberos/krb5.nix
index 2e5e48891b82..5b2b09542037 100644
--- a/pkgs/development/libraries/kerberos/krb5.nix
+++ b/pkgs/development/libraries/kerberos/krb5.nix
@@ -11,24 +11,22 @@ in
 with stdenv.lib;
 stdenv.mkDerivation rec {
   name = "${type}krb5-${version}";
-  version = "1.13.2";
+  version = "1.14";
 
   src = fetchurl {
-    url = "${meta.homepage}dist/krb5/1.13/krb5-${version}-signed.tar";
-    sha256 = "1qbdzyrws7d0q4filsibh28z54pd5l987jr0ygv43iq9085w6a75";
+    url = "${meta.homepage}dist/krb5/1.14/krb5-${version}.tar.gz";
+    sha256 = "1sgr61cnkgc5xazijaww6wpn5fnxl9vyj9ixk3r3y7ikv3x0gnyf";
   };
 
+  configureFlags = optional stdenv.isFreeBSD ''WARN_CFLAGS=""'';
+
   nativeBuildInputs = [ pkgconfig perl yacc ]
     # Provides the mig command used by the build scripts
-    ++ stdenv.lib.optional stdenv.isDarwin bootstrap_cmds;
+    ++ optional stdenv.isDarwin bootstrap_cmds;
   buildInputs = [ openssl ]
     ++ optionals (!libOnly) [ openldap libedit ];
 
-  unpackPhase = ''
-    tar -xf $src
-    tar -xzf krb5-${version}.tar.gz
-    cd krb5-${version}/src
-  '';
+  preConfigure = "cd ./src";
 
   buildPhase = optionalString libOnly ''
     (cd util; make -j $NIX_BUILD_CORES)
diff --git a/pkgs/development/libraries/libdrm/default.nix b/pkgs/development/libraries/libdrm/default.nix
index 533512e9b689..154277f9cc66 100644
--- a/pkgs/development/libraries/libdrm/default.nix
+++ b/pkgs/development/libraries/libdrm/default.nix
@@ -1,11 +1,11 @@
 { stdenv, fetchurl, pkgconfig, libpthreadstubs, libpciaccess, udev, valgrind }:
 
 stdenv.mkDerivation rec {
-  name = "libdrm-2.4.65";
+  name = "libdrm-2.4.66";
 
   src = fetchurl {
     url = "http://dri.freedesktop.org/libdrm/${name}.tar.bz2";
-    sha256 = "71960ac8bde7d710992b1bc8879935e8300a870c36bd06f22412d0447e3d96c4";
+    sha256 = "79cb8e988749794edfb2d777b298d5292eff353bbbb71ed813589e61d2bc2d76";
   };
 
   nativeBuildInputs = [ pkgconfig ];
diff --git a/pkgs/development/libraries/libedit/default.nix b/pkgs/development/libraries/libedit/default.nix
index dc8ecf7e95d8..6e8d85cb88d9 100644
--- a/pkgs/development/libraries/libedit/default.nix
+++ b/pkgs/development/libraries/libedit/default.nix
@@ -11,23 +11,21 @@ stdenv.mkDerivation rec {
   # Have `configure' avoid `/usr/bin/nroff' in non-chroot builds.
   NROFF = "${groff}/bin/nroff";
 
-  patches = if stdenv.isCygwin then [
-    ./01-cygwin.patch
-  ] else null;
+  patches = [ ./01-cygwin.patch ./freebsd-wchar.patch ];
+
+  propagatedBuildInputs = [ ncurses ];
+
+  configureFlags = [ "--enable-widec" ];
 
   postInstall = ''
     find $out/lib -type f | grep '\.\(la\|pc\)''$' | xargs sed -i \
       -e 's,-lncurses[a-z]*,-L${ncurses}/lib -lncursesw,g'
   '';
 
-  configureFlags = [ "--enable-widec" ];
-
-  propagatedBuildInputs = [ ncurses ];
-
   meta = with stdenv.lib; {
     homepage = "http://www.thrysoee.dk/editline/";
     description = "A port of the NetBSD Editline library (libedit)";
-    license = licenses.bsd3; 
+    license = licenses.bsd3;
     platforms = platforms.all;
   };
 }
diff --git a/pkgs/development/libraries/libedit/freebsd-wchar.patch b/pkgs/development/libraries/libedit/freebsd-wchar.patch
new file mode 100644
index 000000000000..6bf7fb0ef69a
--- /dev/null
+++ b/pkgs/development/libraries/libedit/freebsd-wchar.patch
@@ -0,0 +1,13 @@
+diff --git a/src/chartype.h b/src/chartype.h
+index 0beee17..4ac86f3 100644
+--- a/src/chartype.h
++++ b/src/chartype.h
+@@ -44,7 +44,7 @@
+  * supports non-BMP code points without requiring UTF-16, but nothing
+  * seems to actually advertise this properly, despite Unicode 3.1 having
+  * been around since 2001... */
+-#if !defined(__NetBSD__) && !defined(__sun) && !(defined(__APPLE__) && defined(__MACH__)) && !defined(__OpenBSD__)
++#if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__sun) && !(defined(__APPLE__) && defined(__MACH__)) && !defined(__OpenBSD__)
+ #ifndef __STDC_ISO_10646__
+ /* In many places it is assumed that the first 127 code points are ASCII
+  * compatible, so ensure wchar_t indeed does ISO 10646 and not some other
diff --git a/pkgs/development/libraries/libelf-freebsd/default.nix b/pkgs/development/libraries/libelf-freebsd/default.nix
new file mode 100644
index 000000000000..26fe2d90963a
--- /dev/null
+++ b/pkgs/development/libraries/libelf-freebsd/default.nix
@@ -0,0 +1,37 @@
+{ fetchsvn, stdenv, gnum4, tet }:
+
+stdenv.mkDerivation (rec {
+  version = "3258";
+  name = "libelf-freebsd-${version}";
+
+  src = fetchsvn {
+    url = svn://svn.code.sf.net/p/elftoolchain/code/trunk;
+    rev = (stdenv.lib.strings.toInt version);
+    name = "elftoolchain-${version}";
+  };
+
+  buildInputs = [ gnum4 tet ];
+
+  buildPhase = ''
+    PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin:$PATH # use BSD install(1) instead of coreutils and make(1) instead of GNU Make
+    cp -vr ${tet} test/tet/tet3.8
+    chmod -R a+w test/tet/tet3.8
+    make libelf
+  '';
+
+  installPhase = ''
+    cp -vr libelf $out
+    cp -vr common/. $out/
+  '';
+
+  meta = {
+    description = "Essential compilation tools and libraries for building and analyzing ELF based program images";
+
+    homepage = https://sourceforge.net/p/elftoolchain/wiki/Home/;
+
+    license = stdenv.lib.licenses.bsd2;
+
+    platforms = stdenv.lib.platforms.freebsd;
+    maintainers = [ ];
+  };
+})
diff --git a/pkgs/development/libraries/libiconv/default.nix b/pkgs/development/libraries/libiconv/default.nix
index 70b0574a7b46..f5818c3bf4c9 100644
--- a/pkgs/development/libraries/libiconv/default.nix
+++ b/pkgs/development/libraries/libiconv/default.nix
@@ -1,4 +1,4 @@
-{ fetchurl, stdenv }:
+{ fetchurl, stdenv, lib }:
 
 assert (!stdenv.isLinux);
 
@@ -10,16 +10,18 @@ stdenv.mkDerivation rec {
     sha256 = "04q6lgl3kglmmhw59igq1n7v3rp1rpkypl366cy1k1yn2znlvckj";
   };
 
-  patches = if stdenv.isCygwin then [
+  patches = lib.optionals stdenv.isCygwin [
     ./libiconv-1.14-reloc.patch
     ./libiconv-1.14-wchar.patch
-  ] else null;
+  ];
 
+  configureFlags =
   # On Cygwin, Libtool produces a `.dll.a', which is not a "real" DLL
   # (Windows' linker would need to be used somehow to produce an actual
   # DLL.)  Thus, build the static library too, and this is what Gettext
   # will actually use.
-  configureFlags = if stdenv.isCygwin then [ "--enable-static" ] else null;
+    lib.optional stdenv.isCygwin "--enable-static"
+    ++ lib.optional stdenv.isFreeBSD "--with-pic";
 
   crossAttrs = {
     # Disable stripping to avoid "libiconv.a: Archive has no index" (MinGW).
@@ -41,11 +43,11 @@ stdenv.mkDerivation rec {
     '';
 
     homepage = http://www.gnu.org/software/libiconv/;
-    license = stdenv.lib.licenses.lgpl2Plus;
+    license = lib.licenses.lgpl2Plus;
 
     maintainers = [ ];
 
     # This library is not needed on GNU platforms.
-    hydraPlatforms = stdenv.lib.platforms.cygwin ++ stdenv.lib.platforms.darwin ++ stdenv.lib.platforms.freebsd;
+    hydraPlatforms = with lib.platforms; cygwin ++ darwin ++ freebsd;
   };
 }
diff --git a/pkgs/development/libraries/libossp-uuid/default.nix b/pkgs/development/libraries/libossp-uuid/default.nix
index 119f41116668..ddfc2a5132c7 100644
--- a/pkgs/development/libraries/libossp-uuid/default.nix
+++ b/pkgs/development/libraries/libossp-uuid/default.nix
@@ -10,6 +10,8 @@ stdenv.mkDerivation {
     sha256= "11a615225baa5f8bb686824423f50e4427acd3f70d394765bdff32801f0fd5b0";
   };
 
+  configureFlags = stdenv.lib.optional stdenv.isFreeBSD "--with-pic";
+
   meta = with stdenv.lib; {
     homepage = http://www.ossp.org/pkg/lib/uuid/;
     description = "OSSP uuid ISO-C and C++ shared library";
diff --git a/pkgs/development/libraries/libxml2/default.nix b/pkgs/development/libraries/libxml2/default.nix
index 2fdc198aa115..cac8f10d37aa 100644
--- a/pkgs/development/libraries/libxml2/default.nix
+++ b/pkgs/development/libraries/libxml2/default.nix
@@ -4,16 +4,13 @@ assert pythonSupport -> python != null;
 
 #TODO: share most stuff between python and non-python builds, perhaps via multiple-output
 
-let
-  version = "2.9.2";
-in
-
 stdenv.mkDerivation (rec {
   name = "libxml2-${version}";
+  version = "2.9.3";
 
   src = fetchurl {
     url = "http://xmlsoft.org/sources/${name}.tar.gz";
-    sha256 = "1g6mf03xcabmk5ing1lwqmasr803616gb2xhn7pll10x2l5w6y2i";
+    sha256 = "0bd17g6znn2r98gzpjppsqjg33iraky4px923j3k8kdl8qgy7sad";
   };
 
   outputs = [ "out" "doc" ];
@@ -48,4 +45,3 @@ stdenv.mkDerivation (rec {
 } // stdenv.lib.optionalAttrs (!pythonSupport) {
   configureFlags = "--with-python=no"; # otherwise build impurity bites us
 })
-
diff --git a/pkgs/development/libraries/openldap/default.nix b/pkgs/development/libraries/openldap/default.nix
index 253f74ecc6a8..7d836cd5a0df 100644
--- a/pkgs/development/libraries/openldap/default.nix
+++ b/pkgs/development/libraries/openldap/default.nix
@@ -9,7 +9,16 @@ stdenv.mkDerivation rec {
   };
 
   # Should be removed with >=2.4.43
-  patches = [ ./CVE-2015-6908.patch ];
+  patches = [
+    ./CVE-2015-6908.patch
+    (
+      fetchurl {
+        sha256 = "5bcb3f9fb7186b380efa0a1c2d31ad755e190134b5c4dac07c65bbf7c0b6b3b3";
+        url = "https://github.com/LMDB/lmdb/commit/3360cbad668f678fb23c064ca4efcc5c9ae95d10.patch";
+        name = "openldap-clang-compilation.patch";
+      }
+    )
+  ];
 
   outputs = [ "out" "man" ];
 
@@ -19,7 +28,8 @@ stdenv.mkDerivation rec {
     [ "--enable-overlays"
       "--disable-dependency-tracking"   # speeds up one-time build
     ] ++ stdenv.lib.optional (openssl == null) "--without-tls"
-      ++ stdenv.lib.optional (cyrus_sasl == null) "--without-cyrus-sasl";
+      ++ stdenv.lib.optional (cyrus_sasl == null) "--without-cyrus-sasl"
+      ++ stdenv.lib.optional stdenv.isFreeBSD "--with-pic";
 
   dontPatchELF = 1; # !!!
 
diff --git a/pkgs/development/libraries/pango/default.nix b/pkgs/development/libraries/pango/default.nix
index e7106b9877e0..07a987c8ff66 100644
--- a/pkgs/development/libraries/pango/default.nix
+++ b/pkgs/development/libraries/pango/default.nix
@@ -4,14 +4,14 @@
 
 let
   ver_maj = "1.38";
-  ver_min = "0";
+  ver_min = "1";
 in
 stdenv.mkDerivation rec {
   name = "pango-${ver_maj}.${ver_min}";
 
   src = fetchurl {
     url = "mirror://gnome/sources/pango/${ver_maj}/${name}.tar.xz";
-    sha256 = "0v12gi7f01iq3z852pclpnmkbcksbvpcmiazmklkx1dd9fbpakhx";
+    sha256 = "1dsf45m51i4rcyvh5wlxxrjfhvn5b67d5ckjc6vdcxbddjgmc80k";
   };
 
   buildInputs = with stdenv.lib; [ gobjectIntrospection ]
diff --git a/pkgs/development/libraries/qt-4.x/4.8/default.nix b/pkgs/development/libraries/qt-4.x/4.8/default.nix
index 25b547bf1cf6..17e0485b29fe 100644
--- a/pkgs/development/libraries/qt-4.x/4.8/default.nix
+++ b/pkgs/development/libraries/qt-4.x/4.8/default.nix
@@ -85,7 +85,7 @@ stdenv.mkDerivation rec {
       -datadir $out/share/${name}
       -translationdir $out/share/${name}/translations
     "
-  '' + optionalString stdenv.isDarwin ''
+  '' + optionalString stdenv.cc.isClang ''
     sed -i 's/QMAKE_CC = gcc/QMAKE_CC = clang/' mkspecs/common/g++-base.conf
     sed -i 's/QMAKE_CXX = g++/QMAKE_CXX = clang++/' mkspecs/common/g++-base.conf
   '';
@@ -95,7 +95,7 @@ stdenv.mkDerivation rec {
     ''
       -v -no-separate-debug-info -release -no-fast -confirm-license -opensource
 
-      -opengl -xrender -xrandr -xinerama -xcursor -xinput -xfixes -fontconfig
+      -${if stdenv.isFreeBSD then "no-" else ""}opengl -xrender -xrandr -xinerama -xcursor -xinput -xfixes -fontconfig
       -qdbus -${if cups == null then "no-" else ""}cups -glib -dbus-linked -openssl-linked
 
       ${if mysql != null then "-plugin" else "-no"}-sql-mysql -system-sqlite
@@ -122,17 +122,18 @@ stdenv.mkDerivation rec {
   # The following libraries are only used in plugins
   buildInputs =
     [ cups # Qt dlopen's libcups instead of linking to it
-      mysql.lib postgresql sqlite libjpeg libmng libtiff icu ]
+      postgresql sqlite libjpeg libmng libtiff icu ]
+    ++ optionals (mysql != null) [ mysql.lib ]
     ++ optionals gtkStyle [ gtk gdk_pixbuf ];
 
   nativeBuildInputs = [ perl pkgconfig which ];
 
   enableParallelBuilding = false;
 
-  NIX_CFLAGS_COMPILE = optionalString stdenv.isDarwin
+  NIX_CFLAGS_COMPILE = optionalString (stdenv.isFreeBSD || stdenv.isDarwin)
     "-I${glib}/include/glib-2.0 -I${glib}/lib/glib-2.0/include";
 
-  NIX_LDFLAGS = optionalString stdenv.isDarwin
+  NIX_LDFLAGS = optionalString (stdenv.isFreeBSD || stdenv.isDarwin)
     "-lglib-2.0";
 
   preBuild = optionalString stdenv.isDarwin ''
diff --git a/pkgs/development/libraries/serf/default.nix b/pkgs/development/libraries/serf/default.nix
index 580460d5fc09..20ce1dabf9a1 100644
--- a/pkgs/development/libraries/serf/default.nix
+++ b/pkgs/development/libraries/serf/default.nix
@@ -21,7 +21,7 @@ stdenv.mkDerivation rec {
   buildPhase = ''
     scons PREFIX="$out" OPENSSL="${openssl}" ZLIB="${zlib}" APR="$(echo "${apr}"/bin/*-config)" \
         APU="$(echo "${aprutil}"/bin/*-config)" CC="${
-          if stdenv.isDarwin then "clang" else "${stdenv.cc}/bin/gcc"
+          if stdenv.cc.isClang then "clang" else "${stdenv.cc}/bin/gcc"
         }" ${
           if (stdenv.isDarwin || stdenv.isCygwin) then "" else "GSSAPI=\"${kerberos}\""
         }
diff --git a/pkgs/development/libraries/zlib/default.nix b/pkgs/development/libraries/zlib/default.nix
index 93474d14344e..7a6f480215c7 100644
--- a/pkgs/development/libraries/zlib/default.nix
+++ b/pkgs/development/libraries/zlib/default.nix
@@ -31,7 +31,8 @@ stdenv.mkDerivation (rec {
 
   # As zlib takes part in the stdenv building, we don't want references
   # to the bootstrap-tools libgcc (as uses to happen on arm/mips)
-  NIX_CFLAGS_COMPILE = stdenv.lib.optionalString (!stdenv.isDarwin) "-static-libgcc";
+  NIX_CFLAGS_COMPILE = stdenv.lib.optionalString (!stdenv.isDarwin) "-static-libgcc "
+                     + stdenv.lib.optionalString (stdenv.isFreeBSD) "-fPIC";
 
   crossAttrs = {
     dontStrip = static;
diff --git a/pkgs/development/tools/build-managers/cargo/head.nix b/pkgs/development/tools/build-managers/cargo/head.nix
new file mode 100644
index 000000000000..d5a2dce66828
--- /dev/null
+++ b/pkgs/development/tools/build-managers/cargo/head.nix
@@ -0,0 +1,39 @@
+{ stdenv, fetchgit, rustPlatform, file, curl, python, pkgconfig, openssl
+, cmake, zlib, makeWrapper }:
+
+with rustPlatform;
+
+with ((import ./common.nix) {
+  inherit stdenv rustc;
+  version = "2016-01-10";
+});
+
+buildRustPackage rec {
+  inherit name version meta passthru;
+
+  # Needs to use fetchgit instead of fetchFromGitHub to fetch submodules
+  src = fetchgit {
+    url = "git://github.com/rust-lang/cargo";
+    rev = "ca373452de159491354cf38279dbc19308c91e72";
+    sha256 = "0fx88b3ndvzhfwq159xavs0z5c7jww231kd65cbzyih9g0ab9x65";
+  };
+
+  depsSha256 = "0csagk2dnwg5z0vbxilz1kzcygd4llw7s81ka0xn1g05x30jqrnn";
+
+  buildInputs = [ file curl pkgconfig python openssl cmake zlib makeWrapper ];
+
+  configurePhase = ''
+    ./configure --enable-optimize --prefix=$out --local-cargo=${cargo}/bin/cargo
+  '';
+
+  buildPhase = "make";
+
+  # Disable check phase as there are lots of failures (some probably due to
+  # trying to access the network).
+  doCheck = false;
+
+  installPhase = ''
+    make install
+    ${postInstall}
+  '';
+}
diff --git a/pkgs/development/tools/guile/g-wrap/default.nix b/pkgs/development/tools/guile/g-wrap/default.nix
index ed492a0b82df..14777b95b85e 100644
--- a/pkgs/development/tools/guile/g-wrap/default.nix
+++ b/pkgs/development/tools/guile/g-wrap/default.nix
@@ -14,7 +14,7 @@ stdenv.mkDerivation rec {
 
   propagatedBuildInputs = [ libffi ];
 
-  doCheck = true;
+  doCheck = !stdenv.isFreeBSD; # XXX: 00-socket.test hangs
 
   meta = {
     description = "G-Wrap, a wrapper generator for Guile";
diff --git a/pkgs/development/tools/misc/gnum4/default.nix b/pkgs/development/tools/misc/gnum4/default.nix
index 7174f4b41c3c..7216e1e169d0 100644
--- a/pkgs/development/tools/misc/gnum4/default.nix
+++ b/pkgs/development/tools/misc/gnum4/default.nix
@@ -10,7 +10,8 @@ stdenv.mkDerivation rec {
 
   doCheck = !stdenv.isDarwin
     && !stdenv.isCygwin                    # XXX: `test-dup2' fails on Cygwin
-    && !stdenv.isSunOS;                    # XXX: `test-setlocale2.sh' fails
+    && !stdenv.isSunOS                     # XXX: `test-setlocale2.sh' fails
+    && !stdenv.isFreeBSD;                  # XXX: test 084 fails
 
   configureFlags = "--with-syscmd-shell=${stdenv.shell}";
 
diff --git a/pkgs/development/tools/misc/tet/default.nix b/pkgs/development/tools/misc/tet/default.nix
new file mode 100644
index 000000000000..77b362c712c2
--- /dev/null
+++ b/pkgs/development/tools/misc/tet/default.nix
@@ -0,0 +1,29 @@
+{ fetchurl, stdenv }:
+
+stdenv.mkDerivation (rec {
+  version = "3.8";
+  name = "tet-${version}";
+
+  src = fetchurl {
+    url = http://tetworks.opengroup.org/downloads/38/software/Sources/3.8/tet3.8-src.tar.gz ;
+    sha256 = "1j57hv56df38w249l595b8rsgmsyvjkbysai03a9724gax5jl9av" ;
+  };
+
+  buildInputs = [ ];
+
+  patchPhase = ''chmod +x configure'';
+
+  configurePhase = ''./configure -t lite'';
+
+  buildPhase = ''cd src; make; cd -'';
+
+  installPhase = ''cd src; make install; cd -; cp -vr $PWD $out'';
+
+  meta = {
+    description = "The Test Environment Toolkit is used in test applications like The Open Group's UNIX Certification program and the Free Standards Group's LSB Certification program";
+    homepage = http://tetworks.opengroup.org/Products/tet.htm ;
+    license = stdenv.lib.licenses.artistic1;
+    platforms = stdenv.lib.platforms.unix;
+    maintainers = [ ];
+  };
+})
diff --git a/pkgs/development/tools/vagrant/default.nix b/pkgs/development/tools/vagrant/default.nix
index b3b2040559aa..36df8bba1b9f 100644
--- a/pkgs/development/tools/vagrant/default.nix
+++ b/pkgs/development/tools/vagrant/default.nix
@@ -7,7 +7,8 @@ let
   version = "1.8.0";
   rake = buildRubyGem {
     inherit ruby;
-    name = "rake-10.4.2";
+    gemName = "rake";
+    version = "10.4.2";
     sha256 = "1rn03rqlf1iv6n87a78hkda2yqparhhaivfjpizblmxvlw2hk5r8";
   };
 
diff --git a/pkgs/os-specific/darwin/apple-source-releases/Csu/default.nix b/pkgs/os-specific/darwin/apple-source-releases/Csu/default.nix
index 893e9f2b2ebd..8dcf28a59094 100644
--- a/pkgs/os-specific/darwin/apple-source-releases/Csu/default.nix
+++ b/pkgs/os-specific/darwin/apple-source-releases/Csu/default.nix
@@ -6,7 +6,9 @@ appleDerivation {
       --replace "/usr/lib" "/lib" \
       --replace "/usr/local/lib" "/lib" \
       --replace "/usr/bin" "" \
-      --replace "/bin/" ""
+      --replace "/bin/" "" \
+      --replace "CC = " "CC = cc #" \
+      --replace "SDK_DIR = " "SDK_DIR = . #"
   '';
 
   # Mac OS didn't support rpaths back before 10.5, and this package intentionally builds stubs targeting versions prior to that
diff --git a/pkgs/os-specific/darwin/apple-source-releases/IOKit/default.nix b/pkgs/os-specific/darwin/apple-source-releases/IOKit/default.nix
index 12f38cd195fe..4b82209f176c 100644
--- a/pkgs/os-specific/darwin/apple-source-releases/IOKit/default.nix
+++ b/pkgs/os-specific/darwin/apple-source-releases/IOKit/default.nix
@@ -32,141 +32,141 @@ appleDerivation {
     popd
 
     # root: complete
-    cp IOKitUser-907.100.13/IOCFBundle.h                                       $dest
-    cp IOKitUser-907.100.13/IOCFPlugIn.h                                       $dest
-    cp IOKitUser-907.100.13/IOCFSerialize.h                                    $dest
-    cp IOKitUser-907.100.13/IOCFUnserialize.h                                  $dest
-    cp IOKitUser-907.100.13/IOCFURLAccess.h                                    $dest
-    cp IOKitUser-907.100.13/IODataQueueClient.h                                $dest
-    cp IOKitUser-907.100.13/IOKitLib.h                                         $dest
-    cp IOKitUser-907.100.13/iokitmig.h                                         $dest
+    cp IOKitUser-*/IOCFBundle.h                                       $dest
+    cp IOKitUser-*/IOCFPlugIn.h                                       $dest
+    cp IOKitUser-*/IOCFSerialize.h                                    $dest
+    cp IOKitUser-*/IOCFUnserialize.h                                  $dest
+    cp IOKitUser-*/IOCFURLAccess.h                                    $dest
+    cp IOKitUser-*/IODataQueueClient.h                                $dest
+    cp IOKitUser-*/IOKitLib.h                                         $dest
+    cp IOKitUser-*/iokitmig.h                                         $dest
     cp ${xnu}/Library/PrivateFrameworks/IOKit.framework/Versions/A/Headers/*.h $dest
 
     # audio: complete
-    cp IOAudioFamily-197.4.2/IOAudioDefines.h          $dest/audio
-    cp IOKitUser-907.100.13/audio.subproj/IOAudioLib.h $dest/audio
-    cp IOAudioFamily-197.4.2/IOAudioTypes.h            $dest/audio
+    cp IOAudioFamily-*/IOAudioDefines.h          $dest/audio
+    cp IOKitUser-*/audio.subproj/IOAudioLib.h    $dest/audio
+    cp IOAudioFamily-*/IOAudioTypes.h            $dest/audio
 
     # avc: complete
-    cp IOFireWireAVC-422.4.0/IOFireWireAVC/IOFireWireAVCConsts.h $dest/avc
-    cp IOFireWireAVC-422.4.0/IOFireWireAVCLib/IOFireWireAVCLib.h $dest/avc
+    cp IOFireWireAVC-*/IOFireWireAVC/IOFireWireAVCConsts.h $dest/avc
+    cp IOFireWireAVC-*/IOFireWireAVCLib/IOFireWireAVCLib.h $dest/avc
 
     # DV: complete
-    cp IOFWDVComponents-207.4.1/DVFamily.h $dest/DV
+    cp IOFWDVComponents-*/DVFamily.h $dest/DV
 
     # firewire: complete
-    cp IOFireWireFamily-455.4.0/IOFireWireFamily.kmodproj/IOFireWireFamilyCommon.h $dest/firewire
-    cp IOFireWireFamily-455.4.0/IOFireWireLib.CFPlugInProj/IOFireWireLib.h         $dest/firewire
-    cp IOFireWireFamily-455.4.0/IOFireWireLib.CFPlugInProj/IOFireWireLibIsoch.h    $dest/firewire
-    cp IOFireWireFamily-455.4.0/IOFireWireFamily.kmodproj/IOFWIsoch.h              $dest/firewire
+    cp IOFireWireFamily-*/IOFireWireFamily.kmodproj/IOFireWireFamilyCommon.h $dest/firewire
+    cp IOFireWireFamily-*/IOFireWireLib.CFPlugInProj/IOFireWireLib.h         $dest/firewire
+    cp IOFireWireFamily-*/IOFireWireLib.CFPlugInProj/IOFireWireLibIsoch.h    $dest/firewire
+    cp IOFireWireFamily-*/IOFireWireFamily.kmodproj/IOFWIsoch.h              $dest/firewire
 
     # graphics: missing AppleGraphicsDeviceControlUserCommand.h
-    cp IOGraphics-471.92.1/IOGraphicsFamily/IOKit/graphics/IOAccelClientConnect.h     $dest/graphics
-    cp IOGraphics-471.92.1/IOGraphicsFamily/IOKit/graphics/IOAccelSurfaceConnect.h    $dest/graphics
-    cp IOGraphics-471.92.1/IOGraphicsFamily/IOKit/graphics/IOAccelTypes.h             $dest/graphics
-    cp IOGraphics-471.92.1/IOGraphicsFamily/IOKit/graphics/IOFramebufferShared.h      $dest/graphics
-    cp IOGraphics-471.92.1/IOGraphicsFamily/IOKit/graphics/IOGraphicsEngine.h         $dest/graphics
-    cp IOGraphics-471.92.1/IOGraphicsFamily/IOKit/graphics/IOGraphicsInterface.h      $dest/graphics
-    cp IOGraphics-471.92.1/IOGraphicsFamily/IOKit/graphics/IOGraphicsInterfaceTypes.h $dest/graphics
-    cp IOKitUser-907.100.13/graphics.subproj/IOGraphicsLib.h                          $dest/graphics
-    cp IOGraphics-471.92.1/IOGraphicsFamily/IOKit/graphics/IOGraphicsTypes.h          $dest/graphics
+    cp IOGraphics-*/IOGraphicsFamily/IOKit/graphics/IOAccelClientConnect.h     $dest/graphics
+    cp IOGraphics-*/IOGraphicsFamily/IOKit/graphics/IOAccelSurfaceConnect.h    $dest/graphics
+    cp IOGraphics-*/IOGraphicsFamily/IOKit/graphics/IOAccelTypes.h             $dest/graphics
+    cp IOGraphics-*/IOGraphicsFamily/IOKit/graphics/IOFramebufferShared.h      $dest/graphics
+    cp IOGraphics-*/IOGraphicsFamily/IOKit/graphics/IOGraphicsEngine.h         $dest/graphics
+    cp IOGraphics-*/IOGraphicsFamily/IOKit/graphics/IOGraphicsInterface.h      $dest/graphics
+    cp IOGraphics-*/IOGraphicsFamily/IOKit/graphics/IOGraphicsInterfaceTypes.h $dest/graphics
+    cp IOKitUser-*/graphics.subproj/IOGraphicsLib.h                            $dest/graphics
+    cp IOGraphics-*/IOGraphicsFamily/IOKit/graphics/IOGraphicsTypes.h          $dest/graphics
 
     # hid: complete
-    cp IOKitUser-907.100.13/hid.subproj/IOHIDBase.h         $dest/hid
-    cp IOKitUser-907.100.13/hid.subproj/IOHIDDevice.h       $dest/hid
-    cp IOKitUser-907.100.13/hid.subproj/IOHIDDevicePlugIn.h $dest/hid
-    cp IOKitUser-907.100.13/hid.subproj/IOHIDElement.h      $dest/hid
-    cp IOKitUser-907.100.13/hid.subproj/IOHIDLib.h          $dest/hid
-    cp IOKitUser-907.100.13/hid.subproj/IOHIDManager.h      $dest/hid
-    cp IOKitUser-907.100.13/hid.subproj/IOHIDQueue.h        $dest/hid
-    cp IOKitUser-907.100.13/hid.subproj/IOHIDTransaction.h  $dest/hid
-    cp IOKitUser-907.100.13/hid.subproj/IOHIDValue.h        $dest/hid
-    cp IOHIDFamily-503.215.2/IOHIDFamily/IOHIDKeys.h        $dest/hid
-    cp IOHIDFamily-503.215.2/IOHIDFamily/IOHIDUsageTables.h $dest/hid
-    cp IOHIDFamily-503.215.2/IOHIDLib/IOHIDLibObsolete.h    $dest/hid
+    cp IOKitUser-*/hid.subproj/IOHIDBase.h          $dest/hid
+    cp IOKitUser-*/hid.subproj/IOHIDDevice.h        $dest/hid
+    cp IOKitUser-*/hid.subproj/IOHIDDevicePlugIn.h  $dest/hid
+    cp IOKitUser-*/hid.subproj/IOHIDElement.h       $dest/hid
+    cp IOKitUser-*/hid.subproj/IOHIDLib.h           $dest/hid
+    cp IOKitUser-*/hid.subproj/IOHIDManager.h       $dest/hid
+    cp IOKitUser-*/hid.subproj/IOHIDQueue.h         $dest/hid
+    cp IOKitUser-*/hid.subproj/IOHIDTransaction.h   $dest/hid
+    cp IOKitUser-*/hid.subproj/IOHIDValue.h         $dest/hid
+    cp IOHIDFamily-*/IOHIDFamily/IOHIDKeys.h        $dest/hid
+    cp IOHIDFamily-*/IOHIDFamily/IOHIDUsageTables.h $dest/hid
+    cp IOHIDFamily-*/IOHIDLib/IOHIDLibObsolete.h    $dest/hid
 
     # hidsystem: complete
-    cp IOHIDFamily-503.215.2/IOHIDSystem/IOKit/hidsystem/ev_keymap.h      $dest/hidsystem
-    cp IOKitUser-907.100.13/hidsystem.subproj/event_status_driver.h       $dest/hidsystem
-    cp IOKitUser-907.100.13/hidsystem.subproj/IOHIDLib.h                  $dest/hidsystem
-    cp IOHIDFamily-503.215.2/IOHIDSystem/IOKit/hidsystem/IOHIDParameter.h $dest/hidsystem
-    cp IOHIDFamily-503.215.2/IOHIDSystem/IOKit/hidsystem/IOHIDShared.h    $dest/hidsystem
-    cp IOHIDFamily-503.215.2/IOHIDSystem/IOKit/hidsystem/IOHIDTypes.h     $dest/hidsystem
-    cp IOHIDFamily-503.215.2/IOHIDSystem/IOKit/hidsystem/IOLLEvent.h      $dest/hidsystem
+    cp IOHIDFamily-*/IOHIDSystem/IOKit/hidsystem/ev_keymap.h      $dest/hidsystem
+    cp IOKitUser-*/hidsystem.subproj/event_status_driver.h        $dest/hidsystem
+    cp IOKitUser-*/hidsystem.subproj/IOHIDLib.h                   $dest/hidsystem
+    cp IOHIDFamily-*/IOHIDSystem/IOKit/hidsystem/IOHIDParameter.h $dest/hidsystem
+    cp IOHIDFamily-*/IOHIDSystem/IOKit/hidsystem/IOHIDShared.h    $dest/hidsystem
+    cp IOHIDFamily-*/IOHIDSystem/IOKit/hidsystem/IOHIDTypes.h     $dest/hidsystem
+    cp IOHIDFamily-*/IOHIDSystem/IOKit/hidsystem/IOLLEvent.h      $dest/hidsystem
 
 
     # i2c: complete
-    cp IOGraphics-471.92.1/IOGraphicsFamily/IOKit/i2c/IOI2CInterface.h $dest/i2c
+    cp IOGraphics-*/IOGraphicsFamily/IOKit/i2c/IOI2CInterface.h $dest/i2c
 
     # kext: complete
-    cp IOKitUser-907.100.13/kext.subproj/KextManager.h $dest/kext
+    cp IOKitUser-*/kext.subproj/KextManager.h $dest/kext
 
     # ndrvsupport: complete
-    cp IOGraphics-471.92.1/IONDRVSupport/IOKit/ndrvsupport/IOMacOSTypes.h $dest/ndrvsupport
-    cp IOGraphics-471.92.1/IONDRVSupport/IOKit/ndrvsupport/IOMacOSVideo.h $dest/ndrvsupport
+    cp IOGraphics-*/IONDRVSupport/IOKit/ndrvsupport/IOMacOSTypes.h $dest/ndrvsupport
+    cp IOGraphics-*/IONDRVSupport/IOKit/ndrvsupport/IOMacOSVideo.h $dest/ndrvsupport
 
     # network: complete
-    cp IONetworkingFamily-100/IOEthernetController.h       $dest/network
-    cp IONetworkingFamily-100/IOEthernetInterface.h        $dest/network
-    cp IONetworkingFamily-100/IOEthernetStats.h            $dest/network
-    cp IONetworkingFamily-100/IONetworkController.h        $dest/network
-    cp IONetworkingFamily-100/IONetworkData.h              $dest/network
-    cp IONetworkingFamily-100/IONetworkInterface.h         $dest/network
-    cp IOKitUser-907.100.13/network.subproj/IONetworkLib.h $dest/network
-    cp IONetworkingFamily-100/IONetworkMedium.h            $dest/network
-    cp IONetworkingFamily-100/IONetworkStack.h             $dest/network
-    cp IONetworkingFamily-100/IONetworkStats.h             $dest/network
-    cp IONetworkingFamily-100/IONetworkUserClient.h        $dest/network
+    cp IONetworkingFamily-*/IOEthernetController.h       $dest/network
+    cp IONetworkingFamily-*/IOEthernetInterface.h        $dest/network
+    cp IONetworkingFamily-*/IOEthernetStats.h            $dest/network
+    cp IONetworkingFamily-*/IONetworkController.h        $dest/network
+    cp IONetworkingFamily-*/IONetworkData.h              $dest/network
+    cp IONetworkingFamily-*/IONetworkInterface.h         $dest/network
+    cp IOKitUser-*/network.subproj/IONetworkLib.h        $dest/network
+    cp IONetworkingFamily-*/IONetworkMedium.h            $dest/network
+    cp IONetworkingFamily-*/IONetworkStack.h             $dest/network
+    cp IONetworkingFamily-*/IONetworkStats.h             $dest/network
+    cp IONetworkingFamily-*/IONetworkUserClient.h        $dest/network
 
     # ps: missing IOUPSPlugIn.h
-    cp IOKitUser-907.100.13/ps.subproj/IOPowerSources.h $dest/ps
-    cp IOKitUser-907.100.13/ps.subproj/IOPSKeys.h       $dest/ps
+    cp IOKitUser-*/ps.subproj/IOPowerSources.h $dest/ps
+    cp IOKitUser-*/ps.subproj/IOPSKeys.h       $dest/ps
 
     # pwr_mgt: complete
-    cp IOKitUser-907.100.13/pwr_mgt.subproj/IOPMKeys.h                                 $dest/pwr_mgt
-    cp IOKitUser-907.100.13/pwr_mgt.subproj/IOPMLib.h                                  $dest/pwr_mgt
+    cp IOKitUser-*/pwr_mgt.subproj/IOPMKeys.h                                          $dest/pwr_mgt
+    cp IOKitUser-*/pwr_mgt.subproj/IOPMLib.h                                           $dest/pwr_mgt
     cp ${xnu}/Library/PrivateFrameworks/IOKit.framework/Versions/A/Headers/pwr_mgt/*.h $dest/pwr_mgt
-    cp IOKitUser-907.100.13/pwr_mgt.subproj/IOPMLibPrivate.h                           $dest/pwr_mgt # Private
+    cp IOKitUser-*/pwr_mgt.subproj/IOPMLibPrivate.h                                    $dest/pwr_mgt # Private
 
     # sbp2: complete
-    cp IOFireWireSBP2-426.4.1/IOFireWireSBP2Lib/IOFireWireSBP2Lib.h $dest/sbp2
+    cp IOFireWireSBP2-*/IOFireWireSBP2Lib/IOFireWireSBP2Lib.h $dest/sbp2
 
     # scsi: omitted for now
 
     # serial: complete
-    cp IOSerialFamily-64.1.1/IOSerialFamily.kmodproj/IOSerialKeys.h $dest/serial
-    cp IOSerialFamily-64.1.1/IOSerialFamily.kmodproj/ioss.h         $dest/serial
+    cp IOSerialFamily-*/IOSerialFamily.kmodproj/IOSerialKeys.h $dest/serial
+    cp IOSerialFamily-*/IOSerialFamily.kmodproj/ioss.h         $dest/serial
 
     # storage: complete
     # Needs ata subdirectory
-    cp IOStorageFamily-172/IOAppleLabelScheme.h                                        $dest/storage
-    cp IOStorageFamily-172/IOApplePartitionScheme.h                                    $dest/storage
-    cp IOBDStorageFamily-14/IOBDBlockStorageDevice.h                                   $dest/storage
-    cp IOBDStorageFamily-14/IOBDMedia.h                                                $dest/storage
-    cp IOBDStorageFamily-14/IOBDMediaBSDClient.h                                       $dest/storage
-    cp IOBDStorageFamily-14/IOBDTypes.h                                                $dest/storage
-    cp IOStorageFamily-172/IOBlockStorageDevice.h                                      $dest/storage
-    cp IOStorageFamily-172/IOBlockStorageDriver.h                                      $dest/storage
-    cp IOCDStorageFamily-51/IOCDBlockStorageDevice.h                                   $dest/storage
-    cp IOCDStorageFamily-51/IOCDMedia.h                                                $dest/storage
-    cp IOCDStorageFamily-51/IOCDMediaBSDClient.h                                       $dest/storage
-    cp IOCDStorageFamily-51/IOCDPartitionScheme.h                                      $dest/storage
-    cp IOCDStorageFamily-51/IOCDTypes.h                                                $dest/storage
-    cp IODVDStorageFamily-35/IODVDBlockStorageDevice.h                                 $dest/storage
-    cp IODVDStorageFamily-35/IODVDMedia.h                                              $dest/storage
-    cp IODVDStorageFamily-35/IODVDMediaBSDClient.h                                     $dest/storage
-    cp IODVDStorageFamily-35/IODVDTypes.h                                              $dest/storage
-    cp IOStorageFamily-172/IOFDiskPartitionScheme.h                                    $dest/storage
-    cp IOStorageFamily-172/IOFilterScheme.h                                            $dest/storage
-    cp IOFireWireSerialBusProtocolTransport-251.0.1/IOFireWireStorageCharacteristics.h $dest/storage
-    cp IOStorageFamily-172/IOGUIDPartitionScheme.h                                     $dest/storage
-    cp IOStorageFamily-172/IOMedia.h                                                   $dest/storage
-    cp IOStorageFamily-172/IOMediaBSDClient.h                                          $dest/storage
-    cp IOStorageFamily-172/IOPartitionScheme.h                                         $dest/storage
-    cp IOStorageFamily-172/IOStorage.h                                                 $dest/storage
-    cp IOStorageFamily-172/IOStorageCardCharacteristics.h                              $dest/storage
-    cp IOStorageFamily-172/IOStorageDeviceCharacteristics.h                            $dest/storage
-    cp IOStorageFamily-172/IOStorageProtocolCharacteristics.h                          $dest/storage
+    cp IOStorageFamily-*/IOAppleLabelScheme.h                                    $dest/storage
+    cp IOStorageFamily-*/IOApplePartitionScheme.h                                $dest/storage
+    cp IOBDStorageFamily-*/IOBDBlockStorageDevice.h                              $dest/storage
+    cp IOBDStorageFamily-*/IOBDMedia.h                                           $dest/storage
+    cp IOBDStorageFamily-*/IOBDMediaBSDClient.h                                  $dest/storage
+    cp IOBDStorageFamily-*/IOBDTypes.h                                           $dest/storage
+    cp IOStorageFamily-*/IOBlockStorageDevice.h                                  $dest/storage
+    cp IOStorageFamily-*/IOBlockStorageDriver.h                                  $dest/storage
+    cp IOCDStorageFamily-*/IOCDBlockStorageDevice.h                              $dest/storage
+    cp IOCDStorageFamily-*/IOCDMedia.h                                           $dest/storage
+    cp IOCDStorageFamily-*/IOCDMediaBSDClient.h                                  $dest/storage
+    cp IOCDStorageFamily-*/IOCDPartitionScheme.h                                 $dest/storage
+    cp IOCDStorageFamily-*/IOCDTypes.h                                           $dest/storage
+    cp IODVDStorageFamily-*/IODVDBlockStorageDevice.h                            $dest/storage
+    cp IODVDStorageFamily-*/IODVDMedia.h                                         $dest/storage
+    cp IODVDStorageFamily-*/IODVDMediaBSDClient.h                                $dest/storage
+    cp IODVDStorageFamily-*/IODVDTypes.h                                         $dest/storage
+    cp IOStorageFamily-*/IOFDiskPartitionScheme.h                                $dest/storage
+    cp IOStorageFamily-*/IOFilterScheme.h                                        $dest/storage
+    cp IOFireWireSerialBusProtocolTransport-*/IOFireWireStorageCharacteristics.h $dest/storage
+    cp IOStorageFamily-*/IOGUIDPartitionScheme.h                                 $dest/storage
+    cp IOStorageFamily-*/IOMedia.h                                               $dest/storage
+    cp IOStorageFamily-*/IOMediaBSDClient.h                                      $dest/storage
+    cp IOStorageFamily-*/IOPartitionScheme.h                                     $dest/storage
+    cp IOStorageFamily-*/IOStorage.h                                             $dest/storage
+    cp IOStorageFamily-*/IOStorageCardCharacteristics.h                          $dest/storage
+    cp IOStorageFamily-*/IOStorageDeviceCharacteristics.h                        $dest/storage
+    cp IOStorageFamily-*/IOStorageProtocolCharacteristics.h                      $dest/storage
 
     # stream: missing altogether
 
diff --git a/pkgs/os-specific/darwin/apple-source-releases/Libsystem/default.nix b/pkgs/os-specific/darwin/apple-source-releases/Libsystem/default.nix
index 95c1ca73e511..42adab1c887c 100644
--- a/pkgs/os-specific/darwin/apple-source-releases/Libsystem/default.nix
+++ b/pkgs/os-specific/darwin/apple-source-releases/Libsystem/default.nix
@@ -113,7 +113,7 @@ appleDerivation rec {
        -o $out/lib/libSystem.dylib \
        CompatibilityHacks.o init.o \
        -compatibility_version 1.0 \
-       -current_version ${version} \
+       -current_version 1197.1.1 \
        -reexport_library $out/lib/system/libsystem_c.dylib \
        -reexport_library $out/lib/system/libsystem_kernel.dylib \
         ${stdenv.lib.concatStringsSep " "
diff --git a/pkgs/os-specific/darwin/apple-source-releases/default.nix b/pkgs/os-specific/darwin/apple-source-releases/default.nix
index f1b72b4123ff..ce128f14530b 100644
--- a/pkgs/os-specific/darwin/apple-source-releases/default.nix
+++ b/pkgs/os-specific/darwin/apple-source-releases/default.nix
@@ -1,8 +1,130 @@
 { stdenv, fetchurl, pkgs }:
 
 let
+  # This attrset can in theory be computed automatically, but for that to work nicely we need
+  # import-from-derivation to work properly. Currently it's rather ugly when we try to bootstrap
+  # a stdenv out of something like this. With some care we can probably get rid of this, but for
+  # now it's staying here.
+  versions = {
+    "osx-10.11.2" = {
+      dtrace = "168";
+      xnu    = "3248.20.55";
+    };
+    "osx-10.10.5" = {
+      adv_cmds      = "158";
+      architecture  = "266";
+      CF            = "1153.18";
+      CommonCrypto  = "60061.30.1";
+      copyfile      = "118.1.2";
+      Csu           = "85";
+      dyld          = "353.2.3";
+      eap8021x      = "198.30.1";
+      libauto       = "186";
+      Libc          = "1044.40.1";
+      libclosure    = "65";
+      libdispatch   = "442.1.4";
+      libiconv      = "42";
+      Libinfo       = "459.40.1";
+      Libnotify     = "133.1.1";
+      libpthread    = "105.40.1";
+      libresolv     = "57";
+      Libsystem     = "1213";
+      libunwind     = "35.3";
+      libutil       = "38";
+      mDNSResponder = "576.30.4";
+      objc4         = "647";
+      ppp           = "786.40.2";
+      removefile    = "35";
+      Security      = "57031.40.6";
+      xnu           = "2782.40.9";
+
+      IOAudioFamily                        = "203.3";
+      IOFireWireFamily                     = "458";
+      IOFWDVComponents                     = "207.4.1";
+      IOFireWireAVC                        = "423";
+      IOFireWireSBP2                       = "427";
+      IOFireWireSerialBusProtocolTransport = "251.0.1";
+      IOGraphics                           = "485.40.1";
+      IOHIDFamily                          = "606.40.1";
+      IONetworkingFamily                   = "101";
+      IOSerialFamily                       = "74.20.1";
+      IOStorageFamily                      = "182.1.1";
+      IOBDStorageFamily                    = "14";
+      IOCDStorageFamily                    = "51";
+      IODVDStorageFamily                   = "35";
+      IOKitUser                            = "1050.20.2";
+    };
+    "osx-10.9.5" = {
+      CF                 = "855.17";
+      launchd            = "842.92.1";
+      libauto            = "185.5";
+      Libc               = "997.90.3";
+      libdispatch        = "339.92.1";
+      libiconv           = "41";
+      Libnotify          = "121.20.1";
+      Libsystem          = "1197.1.1";
+      objc4              = "551.1";
+      Security           = "55471.14.18";
+      security_dotmac_tp = "55107.1";
+      xnu                = "2422.115.4";
+
+      IOStorageFamily = "172";
+    };
+    "osx-10.8.5" = {
+      configd     = "453.19";
+      Libc        = "825.40.1";
+      IOUSBFamily = "630.4.5";
+    };
+    "osx-10.8.4" = {
+      IOUSBFamily = "560.4.2";
+    };
+    "osx-10.7.5" = {
+      libsecurity_apple_csp      = "55003";
+      libsecurity_apple_cspdl    = "55000";
+      libsecurity_apple_file_dl  = "55000";
+      libsecurity_apple_x509_cl  = "55004";
+      libsecurity_apple_x509_tp  = "55009.3";
+      libsecurity_asn1           = "55000.2";
+      libsecurity_cdsa_client    = "55000";
+      libsecurity_cdsa_plugin    = "55001";
+      libsecurity_cdsa_utilities = "55006";
+      libsecurity_cdsa_utils     = "55000";
+      libsecurity_codesigning    = "55037.15";
+      libsecurity_cssm           = "55005.5";
+      libsecurity_filedb         = "55016.1";
+      libsecurity_keychain       = "55050.9";
+      libsecurity_mds            = "55000";
+      libsecurity_ocspd          = "55010";
+      libsecurity_pkcs12         = "55000";
+      libsecurity_sd_cspdl       = "55003";
+      libsecurity_utilities      = "55030.3";
+      libsecurityd               = "55004";
+    };
+    "osx-10.7.4" = {
+      Libm = "2026";
+    };
+    "osx-10.6.2" = {
+      CarbonHeaders = "18.1";
+    };
+    "osx-10.5.8" = {
+      adv_cmds = "119";
+    };
+    "osx-10.5" = {
+      CoreOSMakeFiles = "40";
+    };
+    "dev-tools-7.0" = {
+      bootstrap_cmds = "93";
+    };
+    "dev-tools-5.1" = {
+      bootstrap_cmds = "86";
+    };
+    "dev-tools-3.2.6" = {
+      bsdmake = "24";
+    };
+  };
+
   fetchApple = version: sha256: name: fetchurl {
-    url = "http://www.opensource.apple.com/tarballs/${name}/${name}-${version}.tar.gz";
+    url = "http://www.opensource.apple.com/tarballs/${name}/${name}-${versions.${version}.${name}}.tar.gz";
     inherit sha256;
   };
 
@@ -25,90 +147,101 @@ let
   };
 
   IOKitSpecs = {
-    IOAudioFamily                        = fetchApple "197.4.2"    "1dmrczdmbdkvnhjbv233wx4xczgpf5wjrhr83aizrwpks5avkxbr";
-    IOFireWireFamily                     = fetchApple "455.4.0"    "034n2v6z7lf1cx3sp3309z4sn8mkchjcrsf177iag46yzlzcjgfl";
-    IOFWDVComponents                     = fetchApple "207.4.1"    "1brr0yn6mxgapw3bvlhyissfksifzj2mqsvj9vmps6zwcsxjfw7m";
-    IOFireWireAVC                        = fetchApple "422.4.0"    "1anw8cfmwkavnrs28bzshwa3cwk4r1p3x72561zljx57d0na9164";
-    IOFireWireSBP2                       = fetchApple "426.4.1"    "0asik6qjhf3jjp22awsiyyd6rj02zwnx47l0afbwmxpn5bchfk60";
-    IOFireWireSerialBusProtocolTransport = fetchApple "251.0.1"    "09kiq907qpk94zbij1mrcfcnyyc5ncvlxavxjrj4v5braxm78lhi";
-    IOGraphics                           = fetchApple "471.92.1"   "1c110c9chafy5ilvnc08my9ka530aljggbn66gh3sjsg7lzck9nb";
-    IOHIDFamily                          = fetchApple "503.215.2"  "0nx9mzdw848y6ppcfvip3ybczd1fxkr413zhi9qhw7gnpvac5g3n";
-    IONetworkingFamily                   = fetchApple "100"        "10r769mqq7aiksdsvyz76xjln0lg7dj4pkg2x067ygyf9md55hlz";
-    IOSerialFamily                       = fetchApple "64.1.1"     "1bfkqmg7clwm23byr3iji812j7v1p6565b1ri6p78zviqxnxh7cx";
-    IOStorageFamily                      = fetchApple "172"        "0w5yr8ppl82anwph2zba0ppjji6ipf5x410zhcm1drzwn4bbkxrj";
-    IOBDStorageFamily                    = fetchApple "14"         "1rbvmh311n853j5qb6hfda94vym9wkws5w736w2r7dwbrjyppc1q";
-    IOCDStorageFamily                    = fetchApple "51"         "1905sxwmpxdcnm6yggklc5zimx1558ygm3ycj6b34f9h48xfxzgy";
-    IODVDStorageFamily                   = fetchApple "35"         "1fv82rn199mi998l41c0qpnlp3irhqp2rb7v53pxbx7cra4zx3i6";
+    IOAudioFamily                        = fetchApple "osx-10.10.5" "0ggq7za3iq8g02j16rj67prqhrw828jsw3ah3bxq8a1cvr55aqnq";
+    IOFireWireFamily                     = fetchApple "osx-10.10.5" "059qa1m668kwvchl90cqcx35b31zaqdg61zi11y1imn5s389y2g1";
+    IOFWDVComponents                     = fetchApple "osx-10.10.5" "1brr0yn6mxgapw3bvlhyissfksifzj2mqsvj9vmps6zwcsxjfw7m";
+    IOFireWireAVC                        = fetchApple "osx-10.10.5" "194an37gbqs9s5s891lmw6prvd1m2362602s8lj5m89fp9h8mbal";
+    IOFireWireSBP2                       = fetchApple "osx-10.10.5" "1mym158kp46y1vfiq625b15ihh4jjbpimfm7d56wlw6l2syajqvi";
+    IOFireWireSerialBusProtocolTransport = fetchApple "osx-10.10.5" "09kiq907qpk94zbij1mrcfcnyyc5ncvlxavxjrj4v5braxm78lhi";
+    IOGraphics                           = fetchApple "osx-10.10.5" "1z0x3yrv0p8pfdqnvwf8rvrf9wip593lhm9q6yzbclz3fn53ad0p";
+    IOHIDFamily                          = fetchApple "osx-10.10.5" "0yibagwk74imp3j3skjycm703s5ybdqw0qlsmnml6zwjpbrz5894";
+    IONetworkingFamily                   = fetchApple "osx-10.10.5" "04as1hc8avncijf61mp9dmplz8vb1inhirkd1g74gah08lgrfs9j";
+    IOSerialFamily                       = fetchApple "osx-10.10.5" "0jh12aanxcigqi9w6wqzbwjdin9m48zwrhdj3n4ki0h41sg89y91";
+    IOStorageFamily                      = fetchApple "osx-10.9.5"  "0w5yr8ppl82anwph2zba0ppjji6ipf5x410zhcm1drzwn4bbkxrj";
+    IOBDStorageFamily                    = fetchApple "osx-10.10.5" "1rbvmh311n853j5qb6hfda94vym9wkws5w736w2r7dwbrjyppc1q";
+    IOCDStorageFamily                    = fetchApple "osx-10.10.5" "1905sxwmpxdcnm6yggklc5zimx1558ygm3ycj6b34f9h48xfxzgy";
+    IODVDStorageFamily                   = fetchApple "osx-10.10.5" "1fv82rn199mi998l41c0qpnlp3irhqp2rb7v53pxbx7cra4zx3i6";
     # There should be an IOStreamFamily project here, but they haven't released it :(
-    IOUSBFamily                          = fetchApple "630.4.5"    "1znqb6frxgab9mkyv7csa08c26p9p0ip6hqb4wm9c7j85kf71f4j"; # This is from 10.8 :(
-    IOUSBFamily_older                    = fetchApple "560.4.2"    "113lmpz8n6sibd27p42h8bl7a6c3myc6zngwri7gnvf8qlajzyml" "IOUSBFamily"; # This is even older :(
-    IOKitUser                            = fetchApple "907.100.13" "0kcbrlyxcyirvg5p95hjd9k8a01k161zg0bsfgfhkb90kh2s8x0m";
+    IOUSBFamily                          = fetchApple "osx-10.8.5"  "1znqb6frxgab9mkyv7csa08c26p9p0ip6hqb4wm9c7j85kf71f4j"; # This is from 10.8 :(
+    IOUSBFamily_older                    = fetchApple "osx-10.8.4"  "113lmpz8n6sibd27p42h8bl7a6c3myc6zngwri7gnvf8qlajzyml" "IOUSBFamily"; # This is even older :(
+    IOKitUser                            = fetchApple "osx-10.10.5" "1jzndziv97bhjxmla8nib5fpcswbvsxr04447g251ls81rw313lb";
     # There should be an IOVideo here, but they haven't released it :(
   };
 
   IOKitSrcs = stdenv.lib.mapAttrs (name: value: if builtins.isFunction value then value name else value) IOKitSpecs;
 
-  adv_cmds        = applePackage "adv_cmds"          "119"         "102ssayxbg9wb35mdmhswbnw0bg7js3pfd8fcbic83c5q3bqa6c6" {};
+  adv_cmds = applePackage "adv_cmds" "osx-10.5.8" "102ssayxbg9wb35mdmhswbnw0bg7js3pfd8fcbic83c5q3bqa6c6" {};
 
   packages = {
     inherit (adv_cmds) ps locale;
-    architecture    = applePackage "architecture"      "265"         "05wz8wmxlqssfp29x203fwfb8pgbdjj1mpz12v508658166yzqj8" {};
-    bootstrap_cmds  = applePackage "bootstrap_cmds"    "86"          "0xr0296jm1r3q7kbam98h85g23qlfi763z54ahj563n636kyk2wb" {};
-    bsdmake         = applePackage "bsdmake"           "24"          "11a9kkhz5bfgi1i8kpdkis78lhc6b5vxmhd598fcdgra1jw4iac2" {};
-    CarbonHeaders   = applePackage "CarbonHeaders"     "9A581"       "1hc0yijlpwq39x5bic6nnywqp2m1wj1f11j33m2q7p505h1h740c" {};
-    CF              = applePackage "CF"                "855.17"      "1sadmxi9fsvsmdyxvg2133sdzvkzwil5fvyyidxsyk1iyfzqsvln" {};
-    CommonCrypto    = applePackage "CommonCrypto"      "60049"       "1azin6w7cnzl0iv8kd2qzgwcp6a45zy64y5z1i6jysjcl6xmlw2h" {};
-    configd         = applePackage "configd"           "453.19"      "1gxakahk8gallf16xmhxhprdxkh3prrmzxnmxfvj0slr0939mmr2" {};
-    copyfile        = applePackage "copyfile"          "103.92.1"    "15i2hw5aqx0fklvmq6avin5s00adacvzqc740vviwc2y742vrdcd" {};
-    CoreOSMakefiles = applePackage "CoreOSMakefiles"   "40"          "0kxp53spbn7109l7cvhi88pmfsi81lwmbws819b6wr3hm16v84f4" {};
-    Csu             = applePackage "Csu"               "79"          "1hif4dz23isgx85sgh11yg8amvp2ksvvhz3y5v07zppml7df2lnh" {};
-    dtrace          = applePackage "dtrace"            "118.1"       "0pp5x8dgvzmg9vvg32hpy2brm17dpmbwrcr4prsmdmfvd4767wcf" {};
-    dyld            = applePackage "dyld"              "239.4"       "07z7lyv6x0f6gllb5hymccl31zisrdhz4gqp722xcs9nhsqaqvn7" {};
-    eap8021x        = applePackage "eap8021x"          "180"         "1ynkq8zmhgqhpkdg2syj085lzya0fz55d3423hvf9kcgpbjcd9ic" {};
-    IOKit           = applePackage "IOKit"             "907.100.13"  "0kcbrlyxcyirvg5p95hjd9k8a01k161zg0bsfgfhkb90kh2s8x0m" { inherit IOKitSrcs; };
-    launchd         = applePackage "launchd"           "842.92.1"    "0w30hvwqq8j5n90s3qyp0fccxflvrmmjnicjri4i1vd2g196jdgj" {};
-    libauto         = applePackage "libauto"           "185.5"       "17z27yq5d7zfkwr49r7f0vn9pxvj95884sd2k6lq6rfaz9gxqhy3" {};
-    Libc            = applePackage "Libc"              "997.90.3"    "1jz5bx9l4q484vn28c6n9b28psja3rpxiqbj6zwrwvlndzmq1yz5" {};
-    Libc_old        = applePackage "Libc/825_40_1.nix" "825.40.1"    "0xsx1im52gwlmcrv4lnhhhn9dyk5ci6g27k6yvibn9vj8fzjxwcf" {};
-    libclosure      = applePackage "libclosure"        "63"          "083v5xhihkkajj2yvz0dwgbi0jl2qvzk22p7pqq1zp3ry85xagrx" {};
-    libdispatch     = applePackage "libdispatch"       "339.92.1"    "1lc5033cmkwxy3r26gh9plimxshxfcbgw6i0j7mgjlnpk86iy5bk" {};
-    libiconv        = applePackage "libiconv"          "41"          "0sni1gx6i2h7r4r4hhwbxdir45cp039m4wi74izh4l0pfw7gywad" {};
-    Libinfo         = applePackage "Libinfo"           "449.1.3"     "1ix6f7xwjnq9bqgv8w27k4j64bqn1mfhh91nc7ciiv55axpdb9hq" {};
-    Libm            = applePackage "Libm"              "2026"        "02sd82ig2jvvyyfschmb4gpz6psnizri8sh6i982v341x6y4ysl7" {}; # This is from 10.7 !! :(
-    Libnotify       = applePackage "Libnotify"         "121.20.1"    "164rx4za5z74s0mk9x0m1815r1m9kfal8dz3bfaw7figyjd6nqad" {};
-    libpthread      = applePackage "libpthread"        "105.1.4"     "09vwwahcvmxvx2xl0890gkp91n61dld29j73y2pa597bqkag2qpg" {};
-    libresolv       = applePackage "libresolv"         "54"          "028mp2smd744ryxwl8cqz4njv8h540sdw3an1yl7yxqcs04r0p4b" {};
-    Libsystem       = applePackage "Libsystem"         "1197.1.1"    "1yfj2qdrf9vrzs7p9m4wlb7zzxcrim1gw43x4lvz4qydpp5kg2rh" {};
-    libutil         = applePackage "libutil"           "38"          "12gsvmj342n5d81kqwba68bmz3zf2757442g1sz2y5xmcapa3g5f" {};
-    libunwind       = applePackage "libunwind"         "35.3"        "0miffaa41cv0lzf8az5k1j1ng8jvqvxcr4qrlkf3xyj479arbk1b" {};
-    mDNSResponder   = applePackage "mDNSResponder"     "522.92.1"    "1cp87qda1s7brriv413i71yggm8yqfwv64vknrnqv24fcb8hzbmy" {};
-    objc4           = applePackage "objc4"             "551.1"       "1jrdb6yyb5jwwj27c1r0nr2y2ihqjln8ynj61mpkvp144c1cm5bg" {};
-    #objc4_pure      = applePackage "objc4/pure.nix"    "551.1"       "1jrdb6yyb5jwwj27c1r0nr2y2ihqjln8ynj61mpkvp144c1cm5bg" {};
-    ppp             = applePackage "ppp"               "727.90.1"    "166xz1q7al12hm3q3drlp2r6fgdrsq3pmazjp3nsqg3vnglyh4gk" {};
-    removefile      = applePackage "removefile"        "33"          "0ycvp7cnv40952a1jyhm258p6gg5xzh30x86z5gb204x80knw30y" {};
-    Security        = applePackage "Security"          "55471.14.18" "1nv0dczf67dhk17hscx52izgdcyacgyy12ag0jh6nl5hmfzsn8yy" {};
-    xnu             = applePackage "xnu"               "2422.115.4"  "1ssw5fzvgix20bw6y13c39ib0zs7ykpig3irlwbaccpjpci5jl0s" {};
+    architecture    = applePackage "architecture"      "osx-10.10.5"     "0fc9s1f4mnzaixrmkkq9y8276g8i5grryh2dggi4h347i33kd097" {};
+    bootstrap_cmds  = applePackage "bootstrap_cmds"    "dev-tools-7.0"   "1v5dv2q3af1xwj5kz0a5g54fd5dm6j4c9dd2g66n4kc44ixyrhp3" {};
+    bsdmake         = applePackage "bsdmake"           "dev-tools-3.2.6" "11a9kkhz5bfgi1i8kpdkis78lhc6b5vxmhd598fcdgra1jw4iac2" {};
+    CarbonHeaders   = applePackage "CarbonHeaders"     "osx-10.6.2"      "1zam29847cxr6y9rnl76zqmkbac53nx0szmqm9w5p469a6wzjqar" {};
+    CF              = applePackage "CF"                "osx-10.9.5"      "1sadmxi9fsvsmdyxvg2133sdzvkzwil5fvyyidxsyk1iyfzqsvln" {};
+    CommonCrypto    = applePackage "CommonCrypto"      "osx-10.10.5"     "0rm1r552i3mhyik2y3309dw90ap6vlhk583237jxfmdkip4c6mdr" {};
+    configd         = applePackage "configd"           "osx-10.8.5"      "1gxakahk8gallf16xmhxhprdxkh3prrmzxnmxfvj0slr0939mmr2" {};
+    copyfile        = applePackage "copyfile"          "osx-10.10.5"     "1s90wv9jsi6ismdnc1my3rxaa83k3s5ialrs5xlrmyb7s0pgvz7j" {};
+    CoreOSMakefiles = applePackage "CoreOSMakefiles"   "osx-10.5"        "0kxp53spbn7109l7cvhi88pmfsi81lwmbws819b6wr3hm16v84f4" {};
+    Csu             = applePackage "Csu"               "osx-10.10.5"     "0yh5mslyx28xzpv8qww14infkylvc1ssi57imhi471fs91sisagj" {};
+    dtrace          = applePackage "dtrace"            "osx-10.10.5"     "0pp5x8dgvzmg9vvg32hpy2brm17dpmbwrcr4prsmdmfvd4767wcf" {};
+    dtracen         = applePackage "dtrace"            "osx-10.11.2"     "04mi0jy8gy0w59rk9i9dqznysv6fzz1v5mq779s41cp308yi0h1c" {};
+    dyld            = applePackage "dyld"              "osx-10.10.5"     "167f74ln8pmfimwn6kwh199ylvy3fw72fd15da94mf34ii0zar6k" {};
+    eap8021x        = applePackage "eap8021x"          "osx-10.10.5"     "1f37dpbcgrd1b14nrv2lpqrkap74myjbparz9masx92df6kcn7l2" {};
+    IOKit           = applePackage "IOKit"             "osx-10.10.5"     "0kcbrlyxcyirvg5p95hjd9k8a01k161zg0bsfgfhkb90kh2s8x0m" { inherit IOKitSrcs; };
+    launchd         = applePackage "launchd"           "osx-10.9.5"      "0w30hvwqq8j5n90s3qyp0fccxflvrmmjnicjri4i1vd2g196jdgj" {};
+    libauto         = applePackage "libauto"           "osx-10.9.5"      "17z27yq5d7zfkwr49r7f0vn9pxvj95884sd2k6lq6rfaz9gxqhy3" {};
+    Libc            = applePackage "Libc"              "osx-10.9.5"      "1jz5bx9l4q484vn28c6n9b28psja3rpxiqbj6zwrwvlndzmq1yz5" {};
+    Libc_old        = applePackage "Libc/825_40_1.nix" "osx-10.8.5"      "0xsx1im52gwlmcrv4lnhhhn9dyk5ci6g27k6yvibn9vj8fzjxwcf" {};
+    libclosure      = applePackage "libclosure"        "osx-10.10.5"     "1zqy1zvra46cmqv6vsf1mcsz3a76r9bky145phfwh4ab6y15vjpq" {};
+    libdispatch     = applePackage "libdispatch"       "osx-10.9.5"      "1lc5033cmkwxy3r26gh9plimxshxfcbgw6i0j7mgjlnpk86iy5bk" {};
+    libiconv        = applePackage "libiconv"          "osx-10.9.5"      "0sni1gx6i2h7r4r4hhwbxdir45cp039m4wi74izh4l0pfw7gywad" {};
+    Libinfo         = applePackage "Libinfo"           "osx-10.10.5"     "19n72s652rrqnc9hzlh4xq3h7xsfyjyklmcgyzyj0v0z68ww3z6h" {};
+    Libm            = applePackage "Libm"              "osx-10.7.4"      "02sd82ig2jvvyyfschmb4gpz6psnizri8sh6i982v341x6y4ysl7" {};
+    Libnotify       = applePackage "Libnotify"         "osx-10.9.5"      "164rx4za5z74s0mk9x0m1815r1m9kfal8dz3bfaw7figyjd6nqad" {};
+    libpthread      = applePackage "libpthread"        "osx-10.10.5"     "1p2y6xvsfqyakivr6d48fgrd163b5m9r045cxyfwrf8w0r33nfn3" {};
+    libresolv       = applePackage "libresolv"         "osx-10.10.5"     "0nvssf4qaqgs1dxwayzdy66757k99969f6c7n68n58n2yh6f5f6a" {};
+    Libsystem       = applePackage "Libsystem"         "osx-10.9.5"      "1yfj2qdrf9vrzs7p9m4wlb7zzxcrim1gw43x4lvz4qydpp5kg2rh" {};
+    libutil         = applePackage "libutil"           "osx-10.10.5"     "12gsvmj342n5d81kqwba68bmz3zf2757442g1sz2y5xmcapa3g5f" {};
+    libunwind       = applePackage "libunwind"         "osx-10.10.5"     "0miffaa41cv0lzf8az5k1j1ng8jvqvxcr4qrlkf3xyj479arbk1b" {};
+    mDNSResponder   = applePackage "mDNSResponder"     "osx-10.10.5"     "1h4jin7ya1ih7v0hksi7gfmbv767pv8wsyyv1qfy2xw36x8wnds7" {};
+    objc4           = applePackage "objc4"             "osx-10.9.5"      "1jrdb6yyb5jwwj27c1r0nr2y2ihqjln8ynj61mpkvp144c1cm5bg" {};
+    ppp             = applePackage "ppp"               "osx-10.10.5"     "01v7i0xds185glv8psvlffylfcfhbx1wgsfg74kx5rh3lyrigwrb" {};
+    removefile      = applePackage "removefile"        "osx-10.10.5"     "1f2jw5irq6fz2jv5pag1w2ivfp8659v74f0h8kh0yx0rqw4asm33" {};
+    Security        = applePackage "Security"          "osx-10.9.5"      "1nv0dczf67dhk17hscx52izgdcyacgyy12ag0jh6nl5hmfzsn8yy" {};
+    xnu             = applePackage "xnu"               "osx-10.9.5"      "1ssw5fzvgix20bw6y13c39ib0zs7ykpig3irlwbaccpjpci5jl0s" {};
+
+    # Pending work... we can't change the above packages in place because the bootstrap depends on them, so we detach the expressions
+    # here so we can work on them.
+    CF_new          = applePackage "CF/new.nix"          "osx-10.10.5"     "1sadmxi9fsvsmdyxvg2133sdzvkzwil50vyyidxsyk1iyfzqsvln" {};
+    Libc_new        = applePackage "Libc/new.nix"        "osx-10.10.5"     "1jz5bx9l4q484vn08c6n9b28psja3rpxiqbj6zwrwvlndzmq1yz5" {};
+    libdispatch_new = applePackage "libdispatch/new.nix" "osx-10.10.5"     "1lc5033cmkwxy0r26gh9plimxshxfcbgw6i0j7mgjlnpk86iy5bk" {};
+    libiconv_new    = applePackage "libiconv/new.nix"    "osx-10.10.5"     "0sni1gx6i2h7r404hhwbxdir45cp039m4wi74izh4l0pfw7gywad" {};
+    Libnotify_new   = applePackage "Libnotify/new.nix"   "osx-10.10.5"     "0sni1gx6i2h7r404hhwbxdir45cp039m4wi70izh4l0pfw7gywad" {};
+    Libsystem_new   = applePackage "Libsystem/new.nix"   "osx-10.10.5"     "1yfj2qdrf9vrzs7p9m4wlb7zzxcrim10w43x4lvz4qydpp5kg2rh" {};
+    objc4_new       = applePackage "objc4/new.nix"       "osx-10.10.5"     "0r0797ckmgv19if4i14dzyjh7i5klkm9jpacjif9v3rpycyyx1n3" {};
+    xnu_new         = applePackage "xnu/new.nix"         "osx-10.11.2"     "1ax280jblz7laqam8fcwrffrrz26am10p1va9mlg9mklvbqarhqh" {};
 
-    libsecurity_apple_csp      = libsecPackage "libsecurity_apple_csp"      "55003"    "1ngyn1ik27n4x981px3kfd1z1n8zx7r5w812b6qfjpy5nw4h746w" {};
-    libsecurity_apple_cspdl    = libsecPackage "libsecurity_apple_cspdl"    "55000"    "1svqa5fhw7p7njzf8bzg7zgc5776aqjhdbnlhpwmr5hmz5i0x8r7" {};
-    libsecurity_apple_file_dl  = libsecPackage "libsecurity_apple_file_dl"  "55000"    "1dfqani3n135i3iqmafc1k9awmz6s0a78zifhk15rx5a8ps870bl" {};
-    libsecurity_apple_x509_cl  = libsecPackage "libsecurity_apple_x509_cl"  "55004"    "1gji2i080560s08k1nigsla1zdmi6slyv97xaj5vqxjpxb0g1xf5" {};
-    libsecurity_apple_x509_tp  = libsecPackage "libsecurity_apple_x509_tp"  "55009.3"  "1bsms3nvi62wbvjviwjhjhzhylad8g6vmvlj3ngd0wyd0ywxrs46" {};
-    libsecurity_asn1           = libsecPackage "libsecurity_asn1"           "55000.2"  "0i8aakjxdfj0lqcgqmbip32g7r4h57xhs8w0sxfvfl45q22s782w" {};
-    libsecurity_cdsa_client    = libsecPackage "libsecurity_cdsa_client"    "55000"    "127jxnypkycy8zqwicfv333h11318m00gd37jnswbrpg44xd1wdy" {};
-    libsecurity_cdsa_plugin    = libsecPackage "libsecurity_cdsa_plugin"    "55001"    "0ifmx85rs51i7zjm015s8kc2dqyrlvbr39lw9xzxgd2ds33i4lfj" {};
-    libsecurity_cdsa_utilities = libsecPackage "libsecurity_cdsa_utilities" "55006"    "1kzsl0prvfa8a0m3j3pcxq06aix1csgayd3lzx27iqg84c8mhzan" {};
-    libsecurity_cdsa_utils     = libsecPackage "libsecurity_cdsa_utils"     "55000"    "0q55jizav6n0lkj7lcmcr2mjdhnbnnn525fa9ipwgvzbspihw0g6" {};
-    libsecurity_codesigning    = libsecPackage "libsecurity_codesigning"    "55037.15" "0vf5nj2g383b4hknlp51qll5pm8z4qbf56dnc16n3wm8gj82iasy" {};
-    libsecurity_cssm           = libsecPackage "libsecurity_cssm"           "55005.5"  "0l6ia533bhr8kqp2wa712bnzzzisif3kbn7h3bzzf4nps4wmwzn4" {};
-    libsecurity_filedb         = libsecPackage "libsecurity_filedb"         "55016.1"  "1r0ik95xapdl6l2lhd079vpq41jjgshz2hqb8490gpy5wyc49cxb" {};
-    libsecurity_keychain       = libsecPackage "libsecurity_keychain"       "55050.9"  "15wf2slcgyns61kk7jndgm9h22vidyphh9x15x8viyprra9bkhja" {};
-    libsecurity_mds            = libsecPackage "libsecurity_mds"            "55000"    "0vin5hnzvkx2rdzaaj2gxmx38amxlyh6j24a8gc22y09d74p5lzs" {};
-    libsecurity_ocspd          = libsecPackage "libsecurity_ocspd"          "55010"    "1bxzpihc6w0ji4x8810a4lfkq83787yhjl60xm24bv1prhqcm73b" {};
-    libsecurity_pkcs12         = libsecPackage "libsecurity_pkcs12"         "55000"    "1yq8p2sp39q40fxshb256b7jn9lvmpymgpm8yz9kqrf980xddgsg" {};
-    libsecurity_sd_cspdl       = libsecPackage "libsecurity_sd_cspdl"       "55003"    "10v76xycfnvz1n0zqfbwn3yh4w880lbssqhkn23iim3ihxgm5pbd" {};
-    libsecurity_utilities      = libsecPackage "libsecurity_utilities"      "55030.3"  "0ayycfy9jm0n0c7ih9f3m69ynh8hs80v8yicq47aa1h9wclbxg8r" {};
-    libsecurityd               = libsecPackage "libsecurityd"               "55004"    "1ywm2qj8l7rhaxy5biwxsyavd0d09d4bzchm03nlvwl313p2747x" {};
-    security_dotmac_tp         = libsecPackage "security_dotmac_tp"         "55107.1"  "1l4fi9qhrghj0pkvywi8da22bh06c5bv3l40a621b5g258na50pl" {};
+    libsecurity_apple_csp      = libsecPackage "libsecurity_apple_csp"      "osx-10.7.5" "1ngyn1ik27n4x981px3kfd1z1n8zx7r5w812b6qfjpy5nw4h746w" {};
+    libsecurity_apple_cspdl    = libsecPackage "libsecurity_apple_cspdl"    "osx-10.7.5" "1svqa5fhw7p7njzf8bzg7zgc5776aqjhdbnlhpwmr5hmz5i0x8r7" {};
+    libsecurity_apple_file_dl  = libsecPackage "libsecurity_apple_file_dl"  "osx-10.7.5" "1dfqani3n135i3iqmafc1k9awmz6s0a78zifhk15rx5a8ps870bl" {};
+    libsecurity_apple_x509_cl  = libsecPackage "libsecurity_apple_x509_cl"  "osx-10.7.5" "1gji2i080560s08k1nigsla1zdmi6slyv97xaj5vqxjpxb0g1xf5" {};
+    libsecurity_apple_x509_tp  = libsecPackage "libsecurity_apple_x509_tp"  "osx-10.7.5" "1bsms3nvi62wbvjviwjhjhzhylad8g6vmvlj3ngd0wyd0ywxrs46" {};
+    libsecurity_asn1           = libsecPackage "libsecurity_asn1"           "osx-10.7.5" "0i8aakjxdfj0lqcgqmbip32g7r4h57xhs8w0sxfvfl45q22s782w" {};
+    libsecurity_cdsa_client    = libsecPackage "libsecurity_cdsa_client"    "osx-10.7.5" "127jxnypkycy8zqwicfv333h11318m00gd37jnswbrpg44xd1wdy" {};
+    libsecurity_cdsa_plugin    = libsecPackage "libsecurity_cdsa_plugin"    "osx-10.7.5" "0ifmx85rs51i7zjm015s8kc2dqyrlvbr39lw9xzxgd2ds33i4lfj" {};
+    libsecurity_cdsa_utilities = libsecPackage "libsecurity_cdsa_utilities" "osx-10.7.5" "1kzsl0prvfa8a0m3j3pcxq06aix1csgayd3lzx27iqg84c8mhzan" {};
+    libsecurity_cdsa_utils     = libsecPackage "libsecurity_cdsa_utils"     "osx-10.7.5" "0q55jizav6n0lkj7lcmcr2mjdhnbnnn525fa9ipwgvzbspihw0g6" {};
+    libsecurity_codesigning    = libsecPackage "libsecurity_codesigning"    "osx-10.7.5" "0vf5nj2g383b4hknlp51qll5pm8z4qbf56dnc16n3wm8gj82iasy" {};
+    libsecurity_cssm           = libsecPackage "libsecurity_cssm"           "osx-10.7.5" "0l6ia533bhr8kqp2wa712bnzzzisif3kbn7h3bzzf4nps4wmwzn4" {};
+    libsecurity_filedb         = libsecPackage "libsecurity_filedb"         "osx-10.7.5" "1r0ik95xapdl6l2lhd079vpq41jjgshz2hqb8490gpy5wyc49cxb" {};
+    libsecurity_keychain       = libsecPackage "libsecurity_keychain"       "osx-10.7.5" "15wf2slcgyns61kk7jndgm9h22vidyphh9x15x8viyprra9bkhja" {};
+    libsecurity_mds            = libsecPackage "libsecurity_mds"            "osx-10.7.5" "0vin5hnzvkx2rdzaaj2gxmx38amxlyh6j24a8gc22y09d74p5lzs" {};
+    libsecurity_ocspd          = libsecPackage "libsecurity_ocspd"          "osx-10.7.5" "1bxzpihc6w0ji4x8810a4lfkq83787yhjl60xm24bv1prhqcm73b" {};
+    libsecurity_pkcs12         = libsecPackage "libsecurity_pkcs12"         "osx-10.7.5" "1yq8p2sp39q40fxshb256b7jn9lvmpymgpm8yz9kqrf980xddgsg" {};
+    libsecurity_sd_cspdl       = libsecPackage "libsecurity_sd_cspdl"       "osx-10.7.5" "10v76xycfnvz1n0zqfbwn3yh4w880lbssqhkn23iim3ihxgm5pbd" {};
+    libsecurity_utilities      = libsecPackage "libsecurity_utilities"      "osx-10.7.5" "0ayycfy9jm0n0c7ih9f3m69ynh8hs80v8yicq47aa1h9wclbxg8r" {};
+    libsecurityd               = libsecPackage "libsecurityd"               "osx-10.7.5" "1ywm2qj8l7rhaxy5biwxsyavd0d09d4bzchm03nlvwl313p2747x" {};
+    security_dotmac_tp         = libsecPackage "security_dotmac_tp"         "osx-10.9.5" "1l4fi9qhrghj0pkvywi8da22bh06c5bv3l40a621b5g258na50pl" {};
   };
 in packages
diff --git a/pkgs/os-specific/darwin/apple-source-releases/xnu/default.nix b/pkgs/os-specific/darwin/apple-source-releases/xnu/default.nix
index 8276d2f4b425..4933f94d4a93 100644
--- a/pkgs/os-specific/darwin/apple-source-releases/xnu/default.nix
+++ b/pkgs/os-specific/darwin/apple-source-releases/xnu/default.nix
@@ -81,6 +81,8 @@ appleDerivation {
     export HOST_CODESIGN='echo dummy_codesign'
     export HOST_CODESIGN_ALLOCATE=echo
 
+    export BUILT_PRODUCTS_DIR=.
+
     export DSTROOT=$out
     make installhdrs
 
diff --git a/pkgs/os-specific/darwin/cctools/port.nix b/pkgs/os-specific/darwin/cctools/port.nix
index e7165875aa4e..bc6492f243fa 100644
--- a/pkgs/os-specific/darwin/cctools/port.nix
+++ b/pkgs/os-specific/darwin/cctools/port.nix
@@ -1,4 +1,4 @@
-{ stdenv, fetchurl, autoconf, automake, libtool_2
+{ stdenv, fetchFromGitHub, autoconf, automake, libtool_2
 , llvm, libcxx, libcxxabi, clang, openssl, libuuid
 , libobjc ? null
 }:
@@ -6,16 +6,13 @@
 let
   baseParams = rec {
     name = "cctools-port-${version}";
-    version = "862";
+    version = "877.5";
 
-    src = let
-      # Should be fetchFromGitHub but it was whining so this will do for now
+    src = fetchFromGitHub {
       owner  = "tpoechtrager";
       repo   = "cctools-port";
-      rev    = "59d21d2c793c51d205c8b4ab14b9b28e63c72445";
-    in fetchurl {
-      url    = "https://github.com/${owner}/${repo}/archive/${rev}.tar.gz";
-      sha256 = "01f31ijpnplbiyp7ldwzy8vbkn3j3m56n5blsvsav5nlp4lp2g71";
+      rev    = "7d405492b09fa27546caaa989b8493829365deab";
+      sha256 = "0nj1q5bqdx5jm68dispybxc7wnkb6p8p2igpnap9q6qyv2r9p07w";
     };
 
     buildInputs = [ autoconf automake libtool_2 openssl libuuid ] ++
@@ -59,6 +56,8 @@ let
       sed -i -e 's|clang++|& -I${libcxx}/include/c++/v1|' cctools/autogen.sh
     '';
 
+    # TODO: this builds an ld without support for LLVM's LTO. We need to teach it, but that's rather
+    # hairy to handle during bootstrap. Perhaps it could be optional?
     preConfigure = ''
       cd cctools
       sh autogen.sh
diff --git a/pkgs/servers/shishi/default.nix b/pkgs/servers/shishi/default.nix
index a97e6847a450..e26fd6ca749e 100644
--- a/pkgs/servers/shishi/default.nix
+++ b/pkgs/servers/shishi/default.nix
@@ -29,7 +29,7 @@ stdenv.mkDerivation rec {
   };
 
   # Fixes support for gcrypt 1.6+
-  patches = [ ./gcrypt-fix.patch ];
+  patches = [ ./gcrypt-fix.patch ./freebsd-unistd.patch ];
 
   buildInputs = [ libgcrypt libgpgerror libtasn1 optPam optLibidn optGnutls ];
 
diff --git a/pkgs/servers/shishi/freebsd-unistd.patch b/pkgs/servers/shishi/freebsd-unistd.patch
new file mode 100644
index 000000000000..9399e20205b9
--- /dev/null
+++ b/pkgs/servers/shishi/freebsd-unistd.patch
@@ -0,0 +1,12 @@
+diff --git a/gl/unistd.in.h b/gl/unistd.in.h
+index 2ea9af4..ed58960 100644
+--- a/gl/unistd.in.h
++++ b/gl/unistd.in.h
+@@ -116,6 +116,7 @@
+ # include <getopt.h>
+ #endif
+ 
++#include "config.h"
+ _GL_INLINE_HEADER_BEGIN
+ #ifndef _GL_UNISTD_INLINE
+ # define _GL_UNISTD_INLINE _GL_INLINE
diff --git a/pkgs/servers/x11/xorg/default.nix b/pkgs/servers/x11/xorg/default.nix
index 29653b6f1e15..b9ea5d7c5828 100644
--- a/pkgs/servers/x11/xorg/default.nix
+++ b/pkgs/servers/x11/xorg/default.nix
@@ -787,6 +787,16 @@ let
     meta.platforms = stdenv.lib.platforms.unix;
   }) // {inherit libfontenc fontsproto freetype xproto xtrans zlib ;};
 
+  libXfont2 = (mkDerivation "libXfont2" {
+    name = "libXfont2-2.0.1";
+    builder = ./builder.sh;
+    src = fetchurl {
+      url = mirror://xorg/individual/lib/libXfont2-2.0.1.tar.bz2;
+      sha256 = "0znvwk36nhmyqpmhbm9mzisgixp1mp5qkfald8x1n5yxbm3vpyz9";
+    };
+    buildInputs = [pkgconfig libfontenc fontsproto freetype xproto xtrans zlib ];
+  }) // {inherit libfontenc fontsproto freetype xproto xtrans zlib ;};
+
   libXft = (mkDerivation "libXft" {
     name = "libXft-2.3.2";
     builder = ./builder.sh;
@@ -799,11 +809,11 @@ let
   }) // {inherit fontconfig freetype libX11 xproto libXrender ;};
 
   libXi = (mkDerivation "libXi" {
-    name = "libXi-1.7.5";
+    name = "libXi-1.7.6";
     builder = ./builder.sh;
     src = fetchurl {
-      url = mirror://xorg/individual/lib/libXi-1.7.5.tar.bz2;
-      sha256 = "0ad21jy40d8b2f9ldadx7lkspmvka1i9r5jqqfwxdxyqnpgdfr6r";
+      url = mirror://xorg/individual/lib/libXi-1.7.6.tar.bz2;
+      sha256 = "1b5p0l19ynmd6blnqr205wyngh6fagl35nqb4v05dw60rr9aachz";
     };
     buildInputs = [pkgconfig inputproto libX11 libXext xextproto libXfixes xproto ];
     meta.platforms = stdenv.lib.platforms.unix;
@@ -1591,11 +1601,11 @@ let
   }) // {inherit inputproto xorgserver xproto ;};
 
   xf86inputlibinput = (mkDerivation "xf86inputlibinput" {
-    name = "xf86-input-libinput-0.15.0";
+    name = "xf86-input-libinput-0.16.0";
     builder = ./builder.sh;
     src = fetchurl {
-      url = mirror://xorg/individual/driver/xf86-input-libinput-0.15.0.tar.bz2;
-      sha256 = "0hcs05zx9mpyi9wajsps9qsbyq4v0c9wysp2l48qnr4l8587qw18";
+      url = mirror://xorg/individual/driver/xf86-input-libinput-0.16.0.tar.bz2;
+      sha256 = "0jbgnxsbr3g4g9vkspcc6pqy7av59zx5bb78vkvaqy8yx4qybbgx";
     };
     buildInputs = [pkgconfig inputproto xorgserver xproto ];
     meta.platforms = stdenv.lib.platforms.unix;
@@ -1855,11 +1865,11 @@ let
   }) // {inherit fontsproto randrproto renderproto videoproto xorgserver xproto ;};
 
   xf86videonouveau = (mkDerivation "xf86videonouveau" {
-    name = "xf86-video-nouveau-1.0.11";
+    name = "xf86-video-nouveau-1.0.12";
     builder = ./builder.sh;
     src = fetchurl {
-      url = mirror://xorg/individual/driver/xf86-video-nouveau-1.0.11.tar.bz2;
-      sha256 = "0j3847rnffy81iaxxi6vnd8saadrc9jahfmckr0sjgkzg2rf4kzq";
+      url = mirror://xorg/individual/driver/xf86-video-nouveau-1.0.12.tar.bz2;
+      sha256 = "07irv1zkk0rkyn1d7f2gn1icgcz2ix0pwv74sjian763gynmg80f";
     };
     buildInputs = [pkgconfig dri2proto fontsproto libdrm udev libpciaccess randrproto renderproto videoproto xextproto xorgserver xproto ];
     meta.platforms = stdenv.lib.platforms.unix;
@@ -1909,6 +1919,16 @@ let
     meta.platforms = stdenv.lib.platforms.unix;
   }) // {inherit fontsproto libdrm libpciaccess randrproto renderproto videoproto xextproto xf86driproto xf86miscproto xorgserver xproto ;};
 
+  xf86videorendition = (mkDerivation "xf86videorendition" {
+    name = "xf86-video-rendition-4.2.6";
+    builder = ./builder.sh;
+    src = fetchurl {
+      url = mirror://xorg/individual/driver/xf86-video-rendition-4.2.6.tar.bz2;
+      sha256 = "1a7rqafxzc2hd0s5pnq8s8j9d3jg64ndc0xnq4160kasyqhwy3k6";
+    };
+    buildInputs = [pkgconfig fontsproto libpciaccess randrproto renderproto xextproto xorgserver xproto ];
+  }) // {inherit fontsproto libpciaccess randrproto renderproto xextproto xorgserver xproto ;};
+
   xf86videos3virge = (mkDerivation "xf86videos3virge" {
     name = "xf86-video-s3virge-1.10.7";
     builder = ./builder.sh;
@@ -2207,11 +2227,11 @@ let
   }) // {inherit inputproto libX11 libXaw xproto libXt ;};
 
   xkeyboardconfig = (mkDerivation "xkeyboardconfig" {
-    name = "xkeyboard-config-2.15";
+    name = "xkeyboard-config-2.16";
     builder = ./builder.sh;
     src = fetchurl {
-      url = mirror://xorg/individual/data/xkeyboard-config/xkeyboard-config-2.15.tar.bz2;
-      sha256 = "1grqdy5a9f2dii3y24fn0p3kz4q5g9j2kh3jcj2402rgrbvkqi0f";
+      url = mirror://xorg/individual/data/xkeyboard-config/xkeyboard-config-2.16.tar.bz2;
+      sha256 = "0n0xinsljc5mww1qw7dfp8knv0f1r9hs6pdhl0fggdwn5hhiz2hy";
     };
     buildInputs = [pkgconfig libX11 xproto ];
     meta.platforms = stdenv.lib.platforms.unix;
@@ -2295,11 +2315,11 @@ let
   }) // {inherit libX11 xproto ;};
 
   xorgcffiles = (mkDerivation "xorgcffiles" {
-    name = "xorg-cf-files-1.0.5";
+    name = "xorg-cf-files-1.0.6";
     builder = ./builder.sh;
     src = fetchurl {
-      url = mirror://xorg/individual/util/xorg-cf-files-1.0.5.tar.bz2;
-      sha256 = "1m3ypq0xcy46ghxc0svl1rbhpy3zvgmy0aa2mn7w7v7d8d8bh8zd";
+      url = mirror://xorg/individual/util/xorg-cf-files-1.0.6.tar.bz2;
+      sha256 = "0kckng0zs1viz0nr84rdl6dswgip7ndn4pnh5nfwnviwpsfmmksd";
     };
     buildInputs = [pkgconfig ];
     meta.platforms = stdenv.lib.platforms.unix;
diff --git a/pkgs/servers/x11/xorg/old.list b/pkgs/servers/x11/xorg/old.list
index 92fed797d70f..801f6e0b7971 100644
--- a/pkgs/servers/x11/xorg/old.list
+++ b/pkgs/servers/x11/xorg/old.list
@@ -12,4 +12,4 @@ mirror://xorg/individual/proto/xf86miscproto-0.9.3.tar.bz2
 mirror://xorg/individual/util/gccmakedep-1.0.3.tar.bz2
 mirror://xorg/individual/util/imake-1.0.7.tar.bz2
 mirror://xorg/individual/util/lndir-1.0.3.tar.bz2
-mirror://xorg/individual/util/xorg-cf-files-1.0.5.tar.bz2
+mirror://xorg/individual/util/xorg-cf-files-1.0.6.tar.bz2
diff --git a/pkgs/servers/x11/xorg/tarballs-7.7.list b/pkgs/servers/x11/xorg/tarballs-7.7.list
index 7292c6711444..ddda39c76f7f 100644
--- a/pkgs/servers/x11/xorg/tarballs-7.7.list
+++ b/pkgs/servers/x11/xorg/tarballs-7.7.list
@@ -69,8 +69,9 @@ mirror://xorg/individual/lib/libXdmcp-1.1.2.tar.bz2
 mirror://xorg/individual/lib/libXext-1.3.3.tar.bz2
 mirror://xorg/individual/lib/libXfixes-5.0.1.tar.bz2
 mirror://xorg/individual/lib/libXfont-1.5.1.tar.bz2
+mirror://xorg/individual/lib/libXfont2-2.0.1.tar.bz2
 mirror://xorg/individual/lib/libXft-2.3.2.tar.bz2
-mirror://xorg/individual/lib/libXi-1.7.5.tar.bz2
+mirror://xorg/individual/lib/libXi-1.7.6.tar.bz2
 mirror://xorg/individual/lib/libXinerama-1.1.3.tar.bz2
 mirror://xorg/individual/lib/libxkbfile-1.0.9.tar.bz2
 mirror://xorg/individual/lib/libXmu-1.1.2.tar.bz2
@@ -118,19 +119,19 @@ mirror://xorg/individual/proto/xextproto-7.3.0.tar.bz2
 mirror://xorg/X11R7.7/src/everything/xf86bigfontproto-1.2.0.tar.bz2
 mirror://xorg/X11R7.7/src/everything/xf86dgaproto-2.1.tar.bz2
 mirror://xorg/X11R7.7/src/everything/xf86driproto-2.1.1.tar.bz2
-mirror://xorg/individual/driver/xf86-input-evdev-2.9.2.tar.bz2
+mirror://xorg/individual/driver/xf86-input-evdev-2.10.0.tar.bz2
 mirror://xorg/individual/driver/xf86-input-joystick-1.6.2.tar.bz2
 mirror://xorg/individual/driver/xf86-input-keyboard-1.8.1.tar.bz2
-mirror://xorg/individual/driver/xf86-input-libinput-0.14.0.tar.bz2
+mirror://xorg/individual/driver/xf86-input-libinput-0.16.0.tar.bz2
 mirror://xorg/individual/driver/xf86-input-mouse-1.9.1.tar.bz2
-mirror://xorg/individual/driver/xf86-input-synaptics-1.8.2.tar.bz2
+mirror://xorg/individual/driver/xf86-input-synaptics-1.8.3.tar.bz2
 mirror://xorg/individual/driver/xf86-input-vmmouse-13.1.0.tar.bz2
 mirror://xorg/individual/driver/xf86-input-void-1.4.1.tar.bz2
 mirror://xorg/individual/driver/xf86-video-ark-0.7.5.tar.bz2
 mirror://xorg/individual/driver/xf86-video-ast-1.1.5.tar.bz2
-mirror://xorg/individual/driver/xf86-video-ati-7.5.0.tar.bz2
+mirror://xorg/individual/driver/xf86-video-ati-7.6.1.tar.bz2
 mirror://xorg/individual/driver/glamor-egl-0.6.0.tar.bz2
-mirror://xorg/individual/driver/xf86-video-nouveau-1.0.11.tar.bz2
+mirror://xorg/individual/driver/xf86-video-nouveau-1.0.12.tar.bz2
 mirror://xorg/individual/driver/xf86-video-chips-1.2.6.tar.bz2
 mirror://xorg/individual/driver/xf86-video-cirrus-1.5.3.tar.bz2
 mirror://xorg/individual/driver/xf86-video-dummy-0.3.7.tar.bz2
@@ -150,6 +151,7 @@ mirror://xorg/X11R7.7/src/everything/xf86-video-newport-0.2.4.tar.bz2
 mirror://xorg/individual/driver/xf86-video-nv-2.1.20.tar.bz2
 mirror://xorg/individual/driver/xf86-video-openchrome-0.3.3.tar.bz2
 mirror://xorg/individual/driver/xf86-video-r128-6.10.0.tar.bz2
+mirror://xorg/individual/driver/xf86-video-rendition-4.2.6.tar.bz2
 mirror://xorg/individual/driver/xf86-video-s3virge-1.10.7.tar.bz2
 mirror://xorg/individual/driver/xf86-video-savage-2.3.8.tar.bz2
 mirror://xorg/individual/driver/xf86-video-siliconmotion-1.7.8.tar.bz2
@@ -170,11 +172,11 @@ mirror://xorg/individual/app/xgamma-1.0.6.tar.bz2
 mirror://xorg/individual/app/xgc-1.0.5.tar.bz2
 mirror://xorg/individual/app/xhost-1.0.7.tar.bz2
 mirror://xorg/X11R7.7/src/everything/xineramaproto-1.2.1.tar.bz2
-mirror://xorg/individual/app/xinput-1.6.1.tar.bz2
-mirror://xorg/individual/app/xkbcomp-1.3.0.tar.bz2
+mirror://xorg/individual/app/xinput-1.6.2.tar.bz2
+mirror://xorg/individual/app/xkbcomp-1.3.1.tar.bz2
 mirror://xorg/individual/app/xkbevd-1.1.4.tar.bz2
 mirror://xorg/individual/app/xkbutils-1.0.4.tar.bz2
-mirror://xorg/individual/data/xkeyboard-config/xkeyboard-config-2.15.tar.bz2
+mirror://xorg/individual/data/xkeyboard-config/xkeyboard-config-2.16.tar.bz2
 mirror://xorg/individual/app/xkill-1.0.4.tar.bz2
 mirror://xorg/individual/app/xlsatoms-1.1.2.tar.bz2
 mirror://xorg/individual/app/xlsclients-1.1.3.tar.bz2
@@ -182,7 +184,7 @@ mirror://xorg/individual/app/xlsfonts-1.0.5.tar.bz2
 mirror://xorg/individual/app/xmag-1.0.6.tar.bz2
 mirror://xorg/individual/app/xmodmap-1.0.9.tar.bz2
 mirror://xorg/individual/doc/xorg-docs-1.7.1.tar.bz2
-mirror://xorg/individual/xserver/xorg-server-1.17.2.tar.bz2
+mirror://xorg/individual/xserver/xorg-server-1.17.4.tar.bz2
 mirror://xorg/X11R7.7/src/everything/xorg-sgml-doctools-1.11.tar.bz2
 mirror://xorg/X11R7.7/src/everything/xpr-1.0.4.tar.bz2
 mirror://xorg/individual/app/xprop-1.2.2.tar.bz2
diff --git a/pkgs/stdenv/default.nix b/pkgs/stdenv/default.nix
index 9ea69fe88e93..96f07ae9fc6f 100644
--- a/pkgs/stdenv/default.nix
+++ b/pkgs/stdenv/default.nix
@@ -33,6 +33,8 @@ rec {
     pkgs = stdenvNativePkgs;
   };
 
+  stdenvFreeBSD = (import ./freebsd { inherit system allPackages platform config; }).stdenvFreeBSD;
+
   # Linux standard environment.
   stdenvLinux = (import ./linux { inherit system allPackages platform config lib; }).stdenvLinux;
 
@@ -51,5 +53,6 @@ rec {
     if system == "x86_64-solaris" then stdenvNix else
     if system == "i686-cygwin" then stdenvNative else
     if system == "x86_64-cygwin" then stdenvNative else
+    if system == "x86_64-freebsd" then stdenvFreeBSD else
     stdenvNative;
 }
diff --git a/pkgs/stdenv/freebsd/default.nix b/pkgs/stdenv/freebsd/default.nix
new file mode 100644
index 000000000000..3c4e2bb97661
--- /dev/null
+++ b/pkgs/stdenv/freebsd/default.nix
@@ -0,0 +1,65 @@
+{ system      ? builtins.currentSystem
+, allPackages ? import ../../top-level/all-packages.nix
+, platform    ? null
+, config      ? {}
+}:
+
+rec {
+  allPackages = import ../../top-level/all-packages.nix;
+
+  bootstrapTools = derivation {
+    inherit system;
+
+    name    = "trivial-bootstrap-tools";
+    builder = "/usr/local/bin/bash";
+    args    = [ ./trivial-bootstrap.sh ];
+
+    mkdir   = "/bin/mkdir";
+    ln      = "/bin/ln";
+  };
+
+  fetchurl = import ../../build-support/fetchurl {
+    stdenv = import ../generic {
+      name = "stdenv-freebsd-boot-1";
+      inherit system config;
+
+      initialPath  = [ "/" "/usr" ];
+      shell        = "${bootstrapTools}/bin/bash";
+      fetchurlBoot = null;
+      cc = null;
+    };
+    curl = bootstrapTools;
+  };
+
+  stdenvFreeBSD = import ../generic {
+    name = "stdenv-freebsd-boot-3";
+
+    inherit system config;
+
+    initialPath  = [ bootstrapTools ];
+    shell        = "${bootstrapTools}/bin/bash";
+    fetchurlBoot = fetchurl;
+
+    cc = import ../../build-support/cc-wrapper {
+      nativeTools  = true;
+      nativePrefix = "/usr";
+      nativeLibc   = true;
+      stdenv = import ../generic {
+        inherit system config;
+        name         = "stdenv-freebsd-boot-0";
+        initialPath  = [ bootstrapTools ];
+        shell = stdenvFreeBSD.shell;
+        fetchurlBoot = fetchurl;
+        cc           = null;
+      };
+      cc           = {
+        name    = "clang-9.9.9";
+        cc      = "/usr";
+        outPath = "/usr";
+      };
+      isClang      = true;
+    };
+
+    preHook = ''export NIX_NO_SELF_RPATH=1'';
+  };
+}
diff --git a/pkgs/stdenv/freebsd/trivial-bootstrap.sh b/pkgs/stdenv/freebsd/trivial-bootstrap.sh
new file mode 100644
index 000000000000..fbff4575e5a4
--- /dev/null
+++ b/pkgs/stdenv/freebsd/trivial-bootstrap.sh
@@ -0,0 +1,204 @@
+set -e
+set -o nounset
+set -o pipefail
+
+echo Building the trivial bootstrap environment...
+echo
+echo Needed FreeBSD packages:
+echo findutils gcpio gawk gnugrep coreutils bash gsed gtar gmake xar binutils gpatch lbzip2 diffutils
+
+$mkdir -p $out/bin
+
+ln () {
+  if [ ! -z "${2:-}" ]; then
+    if [ -f "$out/bin/$2" ]; then
+      echo "$2 exists"
+      exit 1
+    fi
+  fi
+  if test ! -f "$1"; then
+    echo Target "$2" does not exist
+    exit 1
+  fi
+  # TODO: check that destination directory exists
+  if [ ! -z "${2:-}" ]; then
+    $ln -s "$1" "$out/bin/$2"
+  else
+    $ln -s "$1" "$out/bin/"
+  fi
+}
+
+ln /usr/local/bin/bash
+ln /bin/sh
+
+ln /usr/local/bin/gmake make
+
+ln /usr/local/bin/lbzip2
+
+ln /usr/local/bin/gdiff diff
+
+ln /usr/bin/locale
+
+ln /usr/bin/more
+
+ln /usr/bin/hexdump # for bitcoin
+
+ln /usr/bin/bzip2
+ln /usr/bin/bunzip2
+ln /usr/bin/bzcat
+ln /usr/bin/bzip2recover
+
+ln /usr/bin/xz
+ln /usr/bin/unxz
+ln /usr/bin/xzcat
+ln /usr/bin/lzma
+ln /usr/bin/unlzma
+ln /usr/bin/lzcat
+
+ln /usr/local/bin/gcp cp
+ln /usr/local/bin/gdd dd
+ln /usr/local/bin/gmv mv
+ln /usr/local/bin/grm rm
+ln /usr/local/bin/gls ls
+ln /bin/ps ps
+ln /usr/local/bin/gcat cat
+ln /usr/local/bin/gecho echo
+ln /usr/local/bin/gexpr expr
+ln /usr/local/bin/gtest test
+ln /usr/local/bin/gdate date
+ln /usr/local/bin/gchmod chmod
+ln /usr/local/bin/grmdir rmdir
+ln /usr/local/bin/gsleep sleep
+ln /bin/hostname hostname
+
+ln /usr/local/bin/gid id
+ln /usr/local/bin/god od
+ln /usr/local/bin/gtr tr
+ln /usr/local/bin/gwc wc
+ln /usr/local/bin/gcut cut
+ln /usr/bin/cmp cmp
+ln /usr/local/bin/gsed sed
+ln /usr/local/bin/gtar tar
+ln /usr/local/bin/xar xar
+ln /usr/local/bin/gawk awk
+ln /usr/local/bin/genv env
+ln /usr/local/bin/gtee tee
+ln /usr/local/bin/gcomm comm
+ln /usr/local/bin/gcpio cpio
+ln /usr/local/bin/curl curl
+ln /usr/local/bin/gfind find
+ln /usr/local/bin/grep grep # other grep is in /usr/bin
+ln /usr/bin/gzip
+ln /usr/bin/gunzip
+ln /usr/bin/zcat
+ln /usr/local/bin/ghead head
+ln /usr/bin/tail tail # note that we are not using gtail!!!
+ln /usr/local/bin/guniq uniq
+ln /usr/bin/less less
+ln /usr/local/bin/gtrue true
+# ln /usr/bin/diff diff # we are using gdiff (see above)
+ln /usr/local/bin/egrep egrep
+ln /usr/local/bin/fgrep fgrep
+ln /usr/local/bin/gpatch patch
+ln /usr/local/bin/guname uname
+ln /usr/local/bin/gtouch touch
+ln /usr/local/bin/gsplit split
+ln /usr/local/bin/gxargs xargs
+ln /usr/bin/which which
+ln /usr/local/bin/ginstall install
+ln /usr/local/bin/gbasename basename
+ln /usr/local/bin/gdirname dirname
+ln /usr/local/bin/greadlink readlink
+
+ln /usr/local/bin/gln ln
+ln /usr/local/bin/gyes yes
+ln /usr/local/bin/gwhoami whoami
+ln /usr/local/bin/gvdir vdir
+ln /usr/local/bin/gusers users
+ln /usr/local/bin/guptime uptime
+ln /usr/local/bin/gunlink unlink
+ln /usr/local/bin/gtty tty
+ln /usr/local/bin/gunexpand unexpand
+ln /usr/local/bin/gtsort tsort
+ln /usr/local/bin/gtruncate truncate
+ln /usr/local/bin/gtimeout timeout
+ln /usr/local/bin/gtac tac
+ln /usr/local/bin/gsync sync
+ln /usr/local/bin/gsum sum
+ln /usr/local/bin/gstty stty
+ln /usr/local/bin/gstdbuf stdbuf
+ln /usr/local/bin/gsort sort
+ln /usr/local/bin/gruncon runcon
+ln /usr/local/bin/gseq seq
+ln /usr/local/bin/gsha1sum sha1sum
+ln /usr/local/bin/gsha224sum sha224sum
+ln /usr/local/bin/gsha256sum sha256sum
+ln /usr/local/bin/gsha384sum sha384sum
+ln /usr/local/bin/gsha512sum sha512sum
+ln /usr/local/bin/gshred shred
+ln /usr/local/bin/gshuf shuf
+ln /usr/local/bin/grealpath realpath
+ln "/usr/local/bin/g[" "["
+ln /usr/local/bin/gbase64 base64
+ln /usr/local/bin/gchcon chcon
+ln /usr/local/bin/gchgrp chgrp
+ln /usr/local/bin/gchown chown
+ln /usr/local/bin/gchroot chroot
+ln /usr/local/bin/gcksum cksum
+ln /usr/local/bin/gcsplit csplit
+ln /usr/local/bin/gdf df
+ln /usr/local/bin/gdircolors dircolors
+ln /usr/local/bin/gdu du
+ln /usr/local/bin/gexpand expand
+ln /usr/local/bin/gfactor factor
+ln /usr/local/bin/gfalse false
+ln /usr/local/bin/gfmt fmt
+ln /usr/local/bin/gfold fold
+ln /usr/local/bin/ggroups groups
+ln /usr/local/bin/ghostid hostid
+ln /usr/local/bin/gjoin join
+ln /usr/local/bin/gkill kill
+ln /usr/local/bin/glink link
+ln /usr/local/bin/glogname logname
+ln /usr/local/bin/gmd5sum md5sum
+ln /usr/local/bin/gmkdir mkdir
+ln /usr/local/bin/gmkfifo mkfifo
+ln /usr/local/bin/gmknod mknod
+ln /usr/local/bin/gmktemp mktemp
+ln /usr/local/bin/gnice nice
+ln /usr/local/bin/gnl nl
+ln /usr/local/bin/gnohup nohup
+ln /usr/local/bin/gnproc nproc
+ln /usr/local/bin/gnumfmt numfmt
+ln /usr/local/bin/gnustat nustat
+ln /usr/local/bin/gpaste paste
+ln /usr/local/bin/gpathchk pathchk
+ln /usr/local/bin/gpinky pinky
+ln /usr/local/bin/gpr pr
+ln /usr/local/bin/gprintenv printenv
+ln /usr/local/bin/gprintf printf
+ln /usr/local/bin/gptx ptx
+ln /usr/local/bin/gpwd pwd
+
+# binutils
+# pkg info -l binutils | grep usr/local/bin
+ln /usr/local/bin/addr2line
+ln /usr/local/bin/ar
+ln /usr/local/bin/as
+ln /usr/local/bin/c++filt
+ln /usr/local/bin/dwp
+ln /usr/local/bin/elfedit
+ln /usr/local/bin/gprof
+ln /usr/local/bin/ld
+ln /usr/local/bin/ld.bfd
+ln /usr/local/bin/ld.gold
+ln /usr/local/bin/nm
+ln /usr/local/bin/objcopy
+ln /usr/local/bin/objdump
+ln /usr/local/bin/ranlib
+ln /usr/local/bin/readelf
+ln /usr/local/bin/size
+ln /usr/local/bin/strings
+ln /usr/local/bin/strip
+
+#pkg info -l llvm37 | grep usr/local/bin
diff --git a/pkgs/stdenv/generic/default.nix b/pkgs/stdenv/generic/default.nix
index 2fb1f8b39ae4..6dc2553db386 100644
--- a/pkgs/stdenv/generic/default.nix
+++ b/pkgs/stdenv/generic/default.nix
@@ -84,6 +84,7 @@ let
       ../../build-support/setup-hooks/patch-shebangs.sh
       ../../build-support/setup-hooks/move-sbin.sh
       ../../build-support/setup-hooks/move-lib64.sh
+      ../../build-support/setup-hooks/set-source-date-epoch-to-latest.sh
       cc
     ];
 
diff --git a/pkgs/stdenv/generic/setup.sh b/pkgs/stdenv/generic/setup.sh
index a01af7db70a3..d8de9ab2390b 100644
--- a/pkgs/stdenv/generic/setup.sh
+++ b/pkgs/stdenv/generic/setup.sh
@@ -184,6 +184,14 @@ installBin() {
 # Initialisation.
 
 
+# Set a fallback default value for SOURCE_DATE_EPOCH, used by some
+# build tools to provide a deterministic substitute for the "current"
+# time. Note that 1 = 1970-01-01 00:00:01. We don't use 0 because it
+# confuses some applications.
+export SOURCE_DATE_EPOCH
+: ${SOURCE_DATE_EPOCH:=1}
+
+
 # Wildcard expansions that don't match should expand to an empty list.
 # This ensures that, for instance, "for i in *; do ...; done" does the
 # right thing.
@@ -612,12 +620,8 @@ fixLibtool() {
 configurePhase() {
     runHook preConfigure
 
-    if [ -z "$configureScript" ]; then
+    if [ -z "$configureScript" -a -x ./configure ]; then
         configureScript=./configure
-        if ! [ -x $configureScript ]; then
-            echo "no configure script, doing nothing"
-            return
-        fi
     fi
 
     if [ -z "$dontFixLibtool" ]; then
@@ -645,8 +649,12 @@ configurePhase() {
         fi
     fi
 
-    echo "configure flags: $configureFlags ${configureFlagsArray[@]}"
-    $configureScript $configureFlags "${configureFlagsArray[@]}"
+    if [ -n "$configureScript" ]; then
+        echo "configure flags: $configureFlags ${configureFlagsArray[@]}"
+        $configureScript $configureFlags "${configureFlagsArray[@]}"
+    else
+        echo "no configure script, doing nothing"
+    fi
 
     runHook postConfigure
 }
@@ -657,17 +665,16 @@ buildPhase() {
 
     if [ -z "$makeFlags" ] && ! [ -n "$makefile" -o -e "Makefile" -o -e "makefile" -o -e "GNUmakefile" ]; then
         echo "no Makefile, doing nothing"
-        return
-    fi
-
-    # See https://github.com/NixOS/nixpkgs/pull/1354#issuecomment-31260409
-    makeFlags="SHELL=$SHELL $makeFlags"
+    else
+        # See https://github.com/NixOS/nixpkgs/pull/1354#issuecomment-31260409
+        makeFlags="SHELL=$SHELL $makeFlags"
 
-    echo "make flags: $makeFlags ${makeFlagsArray[@]} $buildFlags ${buildFlagsArray[@]}"
-    make ${makefile:+-f $makefile} \
-        ${enableParallelBuilding:+-j${NIX_BUILD_CORES} -l${NIX_BUILD_CORES}} \
-        $makeFlags "${makeFlagsArray[@]}" \
-        $buildFlags "${buildFlagsArray[@]}"
+        echo "make flags: $makeFlags ${makeFlagsArray[@]} $buildFlags ${buildFlagsArray[@]}"
+        make ${makefile:+-f $makefile} \
+            ${enableParallelBuilding:+-j${NIX_BUILD_CORES} -l${NIX_BUILD_CORES}} \
+            $makeFlags "${makeFlagsArray[@]}" \
+            $buildFlags "${buildFlagsArray[@]}"
+    fi
 
     runHook postBuild
 }
diff --git a/pkgs/tools/archivers/sharutils/default.nix b/pkgs/tools/archivers/sharutils/default.nix
index a7135346d2fc..e806a962eabb 100644
--- a/pkgs/tools/archivers/sharutils/default.nix
+++ b/pkgs/tools/archivers/sharutils/default.nix
@@ -11,7 +11,7 @@ stdenv.mkDerivation rec {
   preConfigure = ''
      # Fix for building on Glibc 2.16.  Won't be needed once the
      # gnulib in sharutils is updated.
-     sed -i ${stdenv.lib.optionalString ((stdenv.isFreeBSD || stdenv.isOpenBSD) && stdenv.cc.nativeTools) "''"} '/gets is a security hole/d' lib/stdio.in.h
+     sed -i ${stdenv.lib.optionalString (stdenv.isOpenBSD && stdenv.cc.nativeTools) "''"} '/gets is a security hole/d' lib/stdio.in.h
   '';
 
   # GNU Gettext is needed on non-GNU platforms.
diff --git a/pkgs/tools/audio/mpdcron/default.nix b/pkgs/tools/audio/mpdcron/default.nix
index d368ee321afe..f113eaf8145e 100644
--- a/pkgs/tools/audio/mpdcron/default.nix
+++ b/pkgs/tools/audio/mpdcron/default.nix
@@ -1,4 +1,4 @@
-{ stdenv, fetchgit, autoconf, automake, libtool, pkgconfig, glib, libdaemon, buildRubyGem
+{ stdenv, fetchgit, autoconf, automake, libtool, pkgconfig, glib, libdaemon
 , mpd_clientlib, curl, sqlite, ruby, bundlerEnv, libnotify, pandoc }:
 
 let
diff --git a/pkgs/tools/compression/bzip2/default.nix b/pkgs/tools/compression/bzip2/default.nix
index 3e835c30e3d7..bb04049d8a66 100644
--- a/pkgs/tools/compression/bzip2/default.nix
+++ b/pkgs/tools/compression/bzip2/default.nix
@@ -58,8 +58,9 @@ in stdenv.mkDerivation {
     ln -s bzip2 $out/bin/bzcat
   '';
 
-  patchPhase = stdenv.lib.optionalString stdenv.isDarwin ''
-    substituteInPlace Makefile --replace 'CC=gcc' 'CC=clang'
+  patchPhase = ''
+    substituteInPlace Makefile --replace CC=gcc CC=cc
+    substituteInPlace Makefile-libbz2_so --replace CC=gcc CC=cc
   '';
 
   preConfigure = ''
diff --git a/pkgs/tools/compression/lz4/default.nix b/pkgs/tools/compression/lz4/default.nix
index 6c5d28d6bcc2..13236da5ab44 100644
--- a/pkgs/tools/compression/lz4/default.nix
+++ b/pkgs/tools/compression/lz4/default.nix
@@ -20,6 +20,8 @@ stdenv.mkDerivation rec {
   doCheck = false; # tests take a very long time
   checkTarget = "test";
 
+  patches = [ ./install-on-freebsd.patch ] ;
+
   meta = with stdenv.lib; {
     inherit version;
     description = "Extremely fast compression algorithm";
diff --git a/pkgs/tools/compression/lz4/install-on-freebsd.patch b/pkgs/tools/compression/lz4/install-on-freebsd.patch
new file mode 100644
index 000000000000..12a2bf72f4ed
--- /dev/null
+++ b/pkgs/tools/compression/lz4/install-on-freebsd.patch
@@ -0,0 +1,54 @@
+diff --git a/Makefile b/Makefile
+index d1b0d0c..f8d6a2d 100644
+--- a/Makefile
++++ b/Makefile
+@@ -80,8 +80,6 @@ clean:
+ 
+ 
+ #------------------------------------------------------------------------
+-#make install is validated only for Linux, OSX, kFreeBSD and Hurd targets
+-ifneq (,$(filter $(shell uname),Linux Darwin GNU/kFreeBSD GNU))
+ 
+ install:
+ 	@cd $(LZ4DIR); $(MAKE) -e install
+@@ -129,4 +127,3 @@ examples:
+ prg-travis:
+ 	@cd $(PRGDIR); $(MAKE) -e test-travis
+ 
+-endif
+diff --git a/lib/Makefile b/lib/Makefile
+index 02ddd3b..26ed18f 100644
+--- a/lib/Makefile
++++ b/lib/Makefile
+@@ -80,8 +80,6 @@ clean:
+ 
+ 
+ #------------------------------------------------------------------------
+-#make install is validated only for Linux, OSX, kFreeBSD and Hurd targets
+-ifneq (,$(filter $(shell uname),Linux Darwin GNU/kFreeBSD GNU))
+ 
+ liblz4.pc: liblz4.pc.in Makefile
+ 	@echo creating pkgconfig
+@@ -114,4 +112,3 @@ uninstall:
+ 	@[ -f $(DESTDIR)$(INCLUDEDIR)/lz4frame.h ] && rm -f $(DESTDIR)$(INCLUDEDIR)/lz4frame.h
+ 	@echo lz4 libraries successfully uninstalled
+ 
+-endif
+diff --git a/programs/Makefile b/programs/Makefile
+index f422902..6943363 100644
+--- a/programs/Makefile
++++ b/programs/Makefile
+@@ -113,8 +113,6 @@ clean:
+ 
+ 
+ #------------------------------------------------------------------------
+-#make install is validated only for Linux, OSX, kFreeBSD and Hurd targets
+-ifneq (,$(filter $(shell uname),Linux Darwin GNU/kFreeBSD GNU))
+ 
+ install: lz4 lz4c
+ 	@echo Installing binaries
+@@ -307,4 +305,3 @@ test-mem: lz4 datagen fuzzer frametest fullbench
+ test-mem32: lz4c32 datagen
+ # unfortunately, valgrind doesn't seem to work with non-native binary. If someone knows how to do a valgrind-test on a 32-bits exe with a 64-bits system...
+ 
+-endif
diff --git a/pkgs/tools/misc/fluentd/default.nix b/pkgs/tools/misc/fluentd/default.nix
index 800e1c6f67a1..1a1871e22da6 100644
--- a/pkgs/tools/misc/fluentd/default.nix
+++ b/pkgs/tools/misc/fluentd/default.nix
@@ -8,8 +8,6 @@ bundlerEnv {
   lockfile = ./Gemfile.lock;
   gemset = ./gemset.nix;
 
-  buildInputs = [ curl ];
-
   meta = with lib; {
     description = "A data collector";
     homepage    = http://www.fluentd.org/;
diff --git a/pkgs/tools/networking/miniupnpc/default.nix b/pkgs/tools/networking/miniupnpc/default.nix
index a0ae90da4463..e5b6ea396fe4 100644
--- a/pkgs/tools/networking/miniupnpc/default.nix
+++ b/pkgs/tools/networking/miniupnpc/default.nix
@@ -10,7 +10,9 @@ stdenv.mkDerivation rec {
     name = "${name}.tar.gz";
   };
 
-  doCheck = true;
+  patches = stdenv.lib.optional stdenv.isFreeBSD ./freebsd.patch;
+
+  doCheck = !stdenv.isFreeBSD;
 
   installFlags = "PREFIX=$(out) INSTALLPREFIX=$(out)";
 
@@ -18,6 +20,6 @@ stdenv.mkDerivation rec {
     inherit version;
     homepage = http://miniupnp.free.fr/;
     description = "A client that implements the UPnP Internet Gateway Device (IGD) specification";
-    platforms = stdenv.lib.platforms.linux;
+    platforms = with stdenv.lib.platforms; linux ++ freebsd;
   };
 }
diff --git a/pkgs/tools/networking/miniupnpc/freebsd.patch b/pkgs/tools/networking/miniupnpc/freebsd.patch
new file mode 100644
index 000000000000..42ae85a8e6b1
--- /dev/null
+++ b/pkgs/tools/networking/miniupnpc/freebsd.patch
@@ -0,0 +1,11 @@
+diff --git a/minihttptestserver.c b/minihttptestserver.c
+index bbfdac3..a43999d 100644
+--- a/minihttptestserver.c
++++ b/minihttptestserver.c
+@@ -1,3 +1,6 @@
++#ifndef INADDR_LOOPBACK
++#define INADDR_LOOPBACK         0x7f000001
++#endif
+ /* $Id: minihttptestserver.c,v 1.17 2015/02/06 10:31:19 nanard Exp $ */
+  /* Project : miniUPnP
+    * Author : Thomas Bernard
diff --git a/pkgs/tools/text/gawk/default.nix b/pkgs/tools/text/gawk/default.nix
index f865b69cfeda..e2856b7acaa4 100644
--- a/pkgs/tools/text/gawk/default.nix
+++ b/pkgs/tools/text/gawk/default.nix
@@ -13,6 +13,7 @@ stdenv.mkDerivation rec {
        stdenv.isCygwin # XXX: `test-dup2' segfaults on Cygwin 6.1
     || stdenv.isDarwin # XXX: `locale' segfaults
     || stdenv.isSunOS  # XXX: `_backsmalls1' fails, locale stuff?
+    || stdenv.isFreeBSD
   );
 
   buildInputs = stdenv.lib.optional (stdenv.system != "x86_64-cygwin") libsigsegv
diff --git a/pkgs/tools/text/gnugrep/default.nix b/pkgs/tools/text/gnugrep/default.nix
index 242ce36780d1..8ef67674cd21 100644
--- a/pkgs/tools/text/gnugrep/default.nix
+++ b/pkgs/tools/text/gnugrep/default.nix
@@ -15,7 +15,10 @@ stdenv.mkDerivation {
   buildInputs = [ pcre libiconv ];
 
   # cygwin: FAIL: multibyte-white-space
-  doCheck = !stdenv.isDarwin && !stdenv.isSunOS && !stdenv.isCygwin;
+  # freebsd: FAIL mb-non-UTF8-performance
+  # all platforms: timing sensitivity in long-pattern-perf 
+  #doCheck = !stdenv.isDarwin && !stdenv.isSunOS && !stdenv.isCygwin && !stdenv.isFreeBSD;
+  doCheck = false;
 
   # On Mac OS X, force use of mkdir -p, since Grep's fallback
   # (./install-sh) is broken.
diff --git a/pkgs/top-level/all-packages.nix b/pkgs/top-level/all-packages.nix
index 1b4a0ee76051..b9962f495d19 100644
--- a/pkgs/top-level/all-packages.nix
+++ b/pkgs/top-level/all-packages.nix
@@ -4893,8 +4893,7 @@ let
   rustPlatform = rustStable;
 
   rustStable = recurseIntoAttrs (makeRustPlatform cargo rustStable);
-  rustUnstable = recurseIntoAttrs (makeRustPlatform
-    (cargo.override { rustPlatform = rustUnstableCargoPlatform; }) rustUnstable);
+  rustUnstable = recurseIntoAttrs (makeRustPlatform cargoUnstable rustUnstable);
 
   # rust platform to build cargo itself (with cargoSnapshot)
   rustCargoPlatform = makeRustPlatform (cargoSnapshot rustc) rustCargoPlatform;
@@ -5330,11 +5329,9 @@ let
     ruby = ruby_2_1_3;
   };
   bundler = callPackage ../development/interpreters/ruby/bundler.nix { };
-  bundler_HEAD = import ../development/interpreters/ruby/bundler-head.nix {
-    inherit buildRubyGem coreutils fetchgit;
-  };
-  defaultGemConfig = callPackage ../development/interpreters/ruby/bundler-env/default-gem-config.nix { };
-  buildRubyGem = callPackage ../development/interpreters/ruby/gem.nix { };
+  bundler_HEAD = bundler;
+  defaultGemConfig = callPackage ../development/interpreters/ruby/gemconfig/default.nix { };
+  buildRubyGem = callPackage ../development/interpreters/ruby/build-ruby-gem { };
   bundlerEnv = callPackage ../development/interpreters/ruby/bundler-env { };
 
   inherit (callPackage ../development/interpreters/ruby {})
@@ -5350,10 +5347,7 @@ let
   ruby_2_1 = ruby_2_1_7;
   ruby_2_2 = ruby_2_2_3;
 
-  rubygemsFun = ruby: builderDefsPackage (callPackage ../development/interpreters/ruby/rubygems.nix) {
-    inherit ruby;
-  };
-  rubygems = hiPrio (rubygemsFun ruby);
+  rubygems = hiPrio (callPackage ../development/interpreters/ruby/rubygems.nix {});
 
   rq = callPackage ../applications/networking/cluster/rq { };
 
@@ -5564,6 +5558,10 @@ let
     rustPlatform = rustCargoPlatform;
   };
 
+  cargoUnstable = callPackage ../development/tools/build-managers/cargo/head.nix {
+    rustPlatform = rustUnstableCargoPlatform;
+  };
+
   cargoSnapshot = rustc:
     callPackage ../development/tools/build-managers/cargo/snapshot.nix {
       inherit rustc;
@@ -6145,6 +6143,9 @@ let
 
   aprutil = callPackage ../development/libraries/apr-util {
     bdbSupport = true;
+    db = if stdenv.isFreeBSD then db47 else db;
+    # XXX: only the db_185 interface was available through
+    #      apr with db58 on freebsd (nov 2015), for unknown reasons
   };
 
   assimp = callPackage ../development/libraries/assimp { };
@@ -6319,7 +6320,9 @@ let
 
   cwiid = callPackage ../development/libraries/cwiid { };
 
-  cyrus_sasl = callPackage ../development/libraries/cyrus-sasl { };
+  cyrus_sasl = callPackage ../development/libraries/cyrus-sasl {
+    kerberos = if stdenv.isFreeBSD then libheimdal else kerberos;
+  };
 
   # Make bdb5 the default as it is the last release under the custom
   # bsd-like license
@@ -6505,7 +6508,9 @@ let
 
   gdbm = callPackage ../development/libraries/gdbm { };
 
-  gecode = callPackage ../development/libraries/gecode { };
+  gecode_3 = callPackage ../development/libraries/gecode/3.nix { };
+  gecode_4 = callPackage ../development/libraries/gecode { };
+  gecode = gecode_4;
 
   gegl = callPackage ../development/libraries/gegl { };
 
@@ -7158,7 +7163,9 @@ let
 
   libedit = callPackage ../development/libraries/libedit { };
 
-  libelf = callPackage ../development/libraries/libelf { };
+  libelf = if stdenv.isFreeBSD
+  then callPackage ../development/libraries/libelf-freebsd { }
+  else callPackage ../development/libraries/libelf { };
 
   libetpan = callPackage ../development/libraries/libetpan { };
 
@@ -8179,6 +8186,9 @@ let
     mesa = mesa_noglu;
     inherit (pkgs.gnome) libgnomeui GConf gnome_vfs;
     cups = if stdenv.isLinux then cups else null;
+
+    # XXX: mariadb doesn't built on fbsd as of nov 2015
+    mysql = if (!stdenv.isFreeBSD) then mysql else null;
   };
 
   qt48Full = appendToName "full" (qt48.override {
@@ -8547,6 +8557,8 @@ let
     python = python2;
   };
 
+  tet = callPackage ../development/tools/misc/tet { };
+
   thrift = callPackage ../development/libraries/thrift {
     inherit (pythonPackages) twisted;
   };
@@ -9582,7 +9594,10 @@ let
     ruby = ruby_2_1;
   };
 
-  shishi = callPackage ../servers/shishi { };
+  shishi = callPackage ../servers/shishi {
+      pam = if stdenv.isLinux then pam else null;
+      # see also openssl, which has/had this same trick
+  };
 
   sipcmd = callPackage ../applications/networking/sipcmd { };
 
diff --git a/pkgs/top-level/perl-packages.nix b/pkgs/top-level/perl-packages.nix
index 501a2d26c4eb..1e8dfa91d2d2 100644
--- a/pkgs/top-level/perl-packages.nix
+++ b/pkgs/top-level/perl-packages.nix
@@ -6661,8 +6661,8 @@ let self = _self // overrides; _self = with self; {
 
   LocaleGettext = buildPerlPackage {
     name = "LocaleGettext-1.05";
-    buildInputs = stdenv.lib.optional (stdenv.isDarwin || stdenv.isCygwin) pkgs.gettext;
-    NIX_CFLAGS_LINK = if (stdenv.isDarwin || stdenv.isCygwin) then "-lintl" else null;
+    buildInputs = stdenv.lib.optional (stdenv.isFreeBSD || stdenv.isDarwin || stdenv.isCygwin) pkgs.gettext;
+    NIX_CFLAGS_LINK = stdenv.lib.optional (stdenv.isFreeBSD || stdenv.isDarwin || stdenv.isCygwin) "-lintl";
     src = fetchurl {
       url = mirror://cpan/authors/id/P/PV/PVANDRY/gettext-1.05.tar.gz;
       sha256 = "15262a00vx714szpx8p2z52wxkz46xp7acl72znwjydyq4ypydi7";
@@ -6891,10 +6891,10 @@ let self = _self // overrides; _self = with self; {
     };
     patches = [ ../development/perl-modules/lwp-test-with-localhost.patch ];
     propagatedBuildInputs = [ EncodeLocale FileListing HTMLParser HTTPCookies HTTPDaemon HTTPDate HTTPMessage HTTPNegotiate LWPMediaTypes NetHTTP URI WWWRobotRules ];
-    meta = {
+    meta = with stdenv.lib; {
       description = "The World-Wide Web library for Perl";
-      license = with stdenv.lib.licenses; [ artistic1 gpl1Plus ];
-      platforms = stdenv.lib.platforms.linux ++ stdenv.lib.platforms.darwin ++ stdenv.lib.platforms.illumos;
+      license = with licenses; [ artistic1 gpl1Plus ];
+      platforms = platforms.unix;
     };
   };