summary refs log tree commit diff
path: root/pkgs
diff options
context:
space:
mode:
authorVladimír Čunát <vcunat@gmail.com>2016-06-29 07:47:04 +0200
committerVladimír Čunát <vcunat@gmail.com>2016-06-29 07:47:04 +0200
commit3afa2460386b1472128e302d1db13dba54e68e12 (patch)
tree1bc0a79319449f29cbd5a1715c0135db1bed9337 /pkgs
parentd9036a02b5c5ef31e18e913ce7e2eb56999d311e (diff)
parentf4792cdc0cffc0d1843f5d8bb3e458546646f67c (diff)
downloadnixlib-3afa2460386b1472128e302d1db13dba54e68e12.tar
nixlib-3afa2460386b1472128e302d1db13dba54e68e12.tar.gz
nixlib-3afa2460386b1472128e302d1db13dba54e68e12.tar.bz2
nixlib-3afa2460386b1472128e302d1db13dba54e68e12.tar.lz
nixlib-3afa2460386b1472128e302d1db13dba54e68e12.tar.xz
nixlib-3afa2460386b1472128e302d1db13dba54e68e12.tar.zst
nixlib-3afa2460386b1472128e302d1db13dba54e68e12.zip
Merge branch 'staging'
This includes a security update of expat.
Diffstat (limited to 'pkgs')
-rw-r--r--pkgs/applications/graphics/leocad/default.nix1
-rw-r--r--pkgs/applications/graphics/photivo/default.nix12
-rw-r--r--pkgs/applications/misc/cli-visualizer/default.nix4
-rw-r--r--pkgs/applications/misc/termite/default.nix2
-rw-r--r--pkgs/applications/science/robotics/qgroundcontrol/default.nix5
-rw-r--r--pkgs/applications/video/simplescreenrecorder/default.nix4
-rw-r--r--pkgs/applications/virtualization/virtualbox/default.nix9
-rw-r--r--pkgs/build-support/cc-wrapper/default.nix1
-rw-r--r--pkgs/build-support/gcc-cross-wrapper/builder.sh1
-rw-r--r--pkgs/build-support/gcc-cross-wrapper/default.nix4
-rw-r--r--pkgs/build-support/setup-hooks/make-wrapper.sh2
-rw-r--r--pkgs/build-support/trivial-builders.nix1
-rw-r--r--pkgs/data/sgml+xml/stylesheets/xslt/docbook-xsl/default.nix6
-rw-r--r--pkgs/desktops/kde-5/plasma-5.6/plasma-desktop/default.nix3
-rw-r--r--pkgs/development/compilers/gcc/4.5/default.nix38
-rw-r--r--pkgs/development/compilers/gcc/4.6/builder.sh4
-rw-r--r--pkgs/development/compilers/gcc/4.6/default.nix36
-rw-r--r--pkgs/development/compilers/gcc/4.8/default.nix50
-rw-r--r--pkgs/development/compilers/gcc/4.9/default.nix47
-rw-r--r--pkgs/development/compilers/gcc/5/default.nix52
-rw-r--r--pkgs/development/compilers/gcc/6/default.nix46
-rw-r--r--pkgs/development/compilers/gcc/builder.sh45
-rw-r--r--pkgs/development/interpreters/pypy/default.nix11
-rw-r--r--pkgs/development/libraries/botan/generic.nix2
-rw-r--r--pkgs/development/libraries/botan/unstable.nix1
-rw-r--r--pkgs/development/libraries/expat/CVE-2015-1283-refix.patch37
-rw-r--r--pkgs/development/libraries/expat/CVE-2016-0718-v2-2-1.patch755
-rw-r--r--pkgs/development/libraries/expat/default.nix6
-rw-r--r--pkgs/development/libraries/gettext/default.nix2
-rw-r--r--pkgs/development/libraries/glibc/builder.sh58
-rw-r--r--pkgs/development/libraries/glibc/common.nix1
-rw-r--r--pkgs/development/libraries/glibc/default.nix65
-rw-r--r--pkgs/development/libraries/glibc/fix_warnings.patch36
-rw-r--r--pkgs/development/libraries/gnutls/3.4.nix4
-rw-r--r--pkgs/development/libraries/gnutls/3.5.nix17
-rw-r--r--pkgs/development/libraries/gnutls/generic.nix8
-rw-r--r--pkgs/development/libraries/kerberos/krb5.nix2
-rw-r--r--pkgs/development/libraries/kerberos/path_char_fix.patch38
-rw-r--r--pkgs/development/libraries/libelf/default.nix6
-rw-r--r--pkgs/development/libraries/libmicrohttpd/default.nix24
-rw-r--r--pkgs/development/libraries/libxkbcommon/default.nix9
-rw-r--r--pkgs/development/libraries/xgboost/default.nix2
-rw-r--r--pkgs/development/python-modules/generic/wrap.sh13
-rw-r--r--pkgs/development/tools/analysis/rr/default.nix3
-rw-r--r--pkgs/development/tools/misc/hydra/default.nix8
-rw-r--r--pkgs/games/cataclysm-dda/default.nix3
-rw-r--r--pkgs/games/dwarf-fortress/dfhack/default.nix1
-rw-r--r--pkgs/games/dwarf-fortress/unfuck.nix2
-rw-r--r--pkgs/games/openspades/default.nix6
-rw-r--r--pkgs/games/openspades/git.nix2
-rw-r--r--pkgs/games/the-butterfly-effect/default.nix3
-rw-r--r--pkgs/misc/emulators/higan/default.nix1
-rw-r--r--pkgs/misc/emulators/pcsx2/default.nix4
-rw-r--r--pkgs/os-specific/linux/sysdig/default.nix3
-rw-r--r--pkgs/servers/nosql/arangodb/default.nix13
-rw-r--r--pkgs/stdenv/darwin/make-bootstrap-tools.nix6
-rw-r--r--pkgs/stdenv/generic/setup.sh4
-rw-r--r--pkgs/stdenv/linux/make-bootstrap-tools-cross.nix42
-rw-r--r--pkgs/stdenv/linux/make-bootstrap-tools.nix4
-rw-r--r--pkgs/tools/misc/coreutils/default.nix6
-rw-r--r--pkgs/tools/misc/file/default.nix4
-rw-r--r--pkgs/tools/typesetting/xmlto/default.nix9
-rw-r--r--pkgs/top-level/all-packages.nix4
63 files changed, 526 insertions, 1072 deletions
diff --git a/pkgs/applications/graphics/leocad/default.nix b/pkgs/applications/graphics/leocad/default.nix
index 884dc1158534..96384765bd03 100644
--- a/pkgs/applications/graphics/leocad/default.nix
+++ b/pkgs/applications/graphics/leocad/default.nix
@@ -17,6 +17,7 @@ stdenv.mkDerivation rec {
   buildInputs = [ qt4 qmake4Hook zlib ];
 
   postPatch = ''
+    sed '1i#include <cmath>' -i common/camera.cpp
     substituteInPlace common/camera.cpp --replace "isnan(" "std::isnan("
     export qmakeFlags="$qmakeFlags INSTALL_PREFIX=$out"
   '';
diff --git a/pkgs/applications/graphics/photivo/default.nix b/pkgs/applications/graphics/photivo/default.nix
index 12816ba96af4..d84363df899e 100644
--- a/pkgs/applications/graphics/photivo/default.nix
+++ b/pkgs/applications/graphics/photivo/default.nix
@@ -10,15 +10,19 @@ stdenv.mkDerivation rec {
     sha256 = "0f6y18k7db2ci6xn664zcwm1g1k04sdv7gg1yd5jk41bndjb7z8h";
   };
 
-  nativeBuildInputs = [ cmake pkgconfig ];
-
-  buildInputs = [ qt4 fftw graphicsmagick_q16 lcms2 lensfun libjpeg exiv2 liblqr1 ];
-  patchPhase = '' # kinda icky
+  postPatch = '' # kinda icky
     sed -e '/("@INSTALL@")/d' \
         -e s,@INSTALL@,$out/share/photivo, \
         -i Sources/ptSettings.cpp
+    sed '1i#include <math.h>' -i Sources/filters/ptFilter_StdCurve.cpp
   '';
 
+  nativeBuildInputs = [ cmake pkgconfig ];
+
+  buildInputs = [ qt4 fftw graphicsmagick_q16 lcms2 lensfun libjpeg exiv2 liblqr1 ];
+
+  enableParallelBuilding = true;
+
   meta = with stdenv.lib; {
       platforms = platforms.linux;
       maintainers = [ maintainers.mornfall ];
diff --git a/pkgs/applications/misc/cli-visualizer/default.nix b/pkgs/applications/misc/cli-visualizer/default.nix
index 6b9856a996ac..1c7fd62f8ecc 100644
--- a/pkgs/applications/misc/cli-visualizer/default.nix
+++ b/pkgs/applications/misc/cli-visualizer/default.nix
@@ -10,6 +10,10 @@ stdenv.mkDerivation rec {
     sha256 = "16768gyi85mkizfn874q2q9xf32knw08z27si3k5bk99492dxwzw";
   };
 
+  postPatch = ''
+    sed '1i#include <cmath>' -i src/Transformer/SpectrumCircleTransformer.cpp
+  '';
+
   buildInputs = [ fftw ncurses libpulseaudio ];
 
   buildFlags = [ "ENABLE_PULSE=1" ];
diff --git a/pkgs/applications/misc/termite/default.nix b/pkgs/applications/misc/termite/default.nix
index 33bc29f871c7..33c42e3dc1dd 100644
--- a/pkgs/applications/misc/termite/default.nix
+++ b/pkgs/applications/misc/termite/default.nix
@@ -13,6 +13,8 @@ let
       sha256 = "1cw4yw7n9m2si8b7zcfyz9pyihncabxm5g39v1mxslfajxgwzmd8";
     };
 
+    postPatch = "sed '1i#include <math.h>' -i termite.cc";
+
     makeFlags = [ "VERSION=v${version}" "PREFIX=" "DESTDIR=$(out)" ];
 
     buildInputs = [ pkgconfig vte gtk3 ncurses ];
diff --git a/pkgs/applications/science/robotics/qgroundcontrol/default.nix b/pkgs/applications/science/robotics/qgroundcontrol/default.nix
index 1e33a1be8567..81f5accd4780 100644
--- a/pkgs/applications/science/robotics/qgroundcontrol/default.nix
+++ b/pkgs/applications/science/robotics/qgroundcontrol/default.nix
@@ -27,6 +27,11 @@ stdenv.mkDerivation rec {
  ] ++ qtInputs;
 
   patches = [ ./0001-fix-gcc-cmath-namespace-issues.patch ];
+  postPatch = ''
+    sed '1i#include <cmath>' -i src/Vehicle/Vehicle.cc \
+      -i src/comm/{QGCFlightGearLink,QGCJSBSimLink}.cc \
+      -i src/{uas/UAS,ui/QGCDataPlot2D}.cc
+  '';
 
   preConfigure = ''
     mkdir build
diff --git a/pkgs/applications/video/simplescreenrecorder/default.nix b/pkgs/applications/video/simplescreenrecorder/default.nix
index a5fb122cf897..3ea04a39393b 100644
--- a/pkgs/applications/video/simplescreenrecorder/default.nix
+++ b/pkgs/applications/video/simplescreenrecorder/default.nix
@@ -11,11 +11,15 @@ stdenv.mkDerivation rec {
     sha256 = "1d89ncspjd8c4mckf0nb6y3hrxpv4rjpbj868pznhvfmdgr5nvql";
   };
 
+  postPatch = "sed '1i#include <random>' -i src/Benchmark.cpp";
+
   buildInputs = [
     alsaLib ffmpeg libjack2 libX11 libXext libXfixes mesa pkgconfig
     libpulseaudio qt4
   ];
 
+  enableParallelBuilding = true;
+
   meta = with stdenv.lib; {
     description = "A screen recorder for Linux";
     homepage = http://www.maartenbaert.be/simplescreenrecorder;
diff --git a/pkgs/applications/virtualization/virtualbox/default.nix b/pkgs/applications/virtualization/virtualbox/default.nix
index df7b555e0487..ebdac411b113 100644
--- a/pkgs/applications/virtualization/virtualbox/default.nix
+++ b/pkgs/applications/virtualization/virtualbox/default.nix
@@ -97,7 +97,14 @@ in stdenv.mkDerivation {
     set +x
   '';
 
-  patches = optional enableHardening ./hardened.patch;
+  patches = optional enableHardening ./hardened.patch
+    ++ [
+      (fetchurl rec {
+        name = "fix-detect-gcc-5.4.patch";
+        url = "https://bugs.debian.org/cgi-bin/bugreport.cgi?att=1;bug=827193;filename=${name};msg=5";
+        sha256 = "0y6v5dc6fqj9iv27cl8q2g87v1kxg19129mpas4vjg7g0529v4g9";
+      })
+    ];
 
   postPatch = ''
     sed -i -e 's|/sbin/ifconfig|${nettools}/bin/ifconfig|' \
diff --git a/pkgs/build-support/cc-wrapper/default.nix b/pkgs/build-support/cc-wrapper/default.nix
index da114fdb347f..a37c806905fd 100644
--- a/pkgs/build-support/cc-wrapper/default.nix
+++ b/pkgs/build-support/cc-wrapper/default.nix
@@ -96,6 +96,7 @@ stdenv.mkDerivation {
       echo "-L${libc_lib}/lib" > $out/nix-support/libc-ldflags
 
       echo "${libc_lib}" > $out/nix-support/orig-libc
+      echo "${libc_dev}" > $out/nix-support/orig-libc-dev
     ''
 
     + (if nativeTools then ''
diff --git a/pkgs/build-support/gcc-cross-wrapper/builder.sh b/pkgs/build-support/gcc-cross-wrapper/builder.sh
index c6bc2a7c8bf9..9396ace84f11 100644
--- a/pkgs/build-support/gcc-cross-wrapper/builder.sh
+++ b/pkgs/build-support/gcc-cross-wrapper/builder.sh
@@ -111,6 +111,7 @@ chmod +x "$out/bin/$crossConfig-ld"
 # Glibc.
 test -n "$gcc" && echo $gcc > $out/nix-support/orig-cc
 test -n "$libc" && echo $libc > $out/nix-support/orig-libc
+test -n "$libc_dev" && echo $libc_dev > $out/nix-support/orig-libc-dev
 
 doSubstitute "$addFlags" "$out/nix-support/add-flags"
 
diff --git a/pkgs/build-support/gcc-cross-wrapper/default.nix b/pkgs/build-support/gcc-cross-wrapper/default.nix
index d3494b83a87b..505d80a6b2ac 100644
--- a/pkgs/build-support/gcc-cross-wrapper/default.nix
+++ b/pkgs/build-support/gcc-cross-wrapper/default.nix
@@ -44,7 +44,9 @@ stdenv.mkDerivation {
   ldWrapper = ./ld-wrapper.sh;
   utils = ./utils.sh;
   addFlags = ./add-flags;
-  inherit nativeTools nativeLibc nativePrefix gcc libc binutils;
+  inherit nativeTools nativeLibc nativePrefix gcc binutils;
+  libc = if libc ? out then libc.out else libc;
+  libc_dev = if libc ? dev then libc.dev else libc;
   crossConfig = if cross != null then cross.config else null;
   osxMinVersion = cross.osxMinVersion or null;
   gccLibs = if gcc != null then gccLibs else null;
diff --git a/pkgs/build-support/setup-hooks/make-wrapper.sh b/pkgs/build-support/setup-hooks/make-wrapper.sh
index 7d0f88abb855..d922db5ccf58 100644
--- a/pkgs/build-support/setup-hooks/make-wrapper.sh
+++ b/pkgs/build-support/setup-hooks/make-wrapper.sh
@@ -16,7 +16,7 @@ makeWrapper() {
             varName=${params[$((n + 1))]}
             value=${params[$((n + 2))]}
             n=$((n + 2))
-            echo "export $varName=$value" >> $wrapper
+            echo "export $varName=\"$value\"" >> $wrapper
         fi
 
         if test "$p" = "--unset"; then
diff --git a/pkgs/build-support/trivial-builders.nix b/pkgs/build-support/trivial-builders.nix
index 73f4d7783c43..18e49105ae78 100644
--- a/pkgs/build-support/trivial-builders.nix
+++ b/pkgs/build-support/trivial-builders.nix
@@ -8,6 +8,7 @@ rec {
   runCommand = name: env: buildCommand:
     stdenv.mkDerivation ({
       inherit name buildCommand;
+      passAsFile = [ "buildCommand" ];
     } // env);
 
 
diff --git a/pkgs/data/sgml+xml/stylesheets/xslt/docbook-xsl/default.nix b/pkgs/data/sgml+xml/stylesheets/xslt/docbook-xsl/default.nix
index 77cd666b8c6d..a955f5cf8a48 100644
--- a/pkgs/data/sgml+xml/stylesheets/xslt/docbook-xsl/default.nix
+++ b/pkgs/data/sgml+xml/stylesheets/xslt/docbook-xsl/default.nix
@@ -3,7 +3,7 @@
 let
 
   common = { pname, sha256 }: stdenv.mkDerivation rec {
-    name = "${pname}-1.78.1";
+    name = "${pname}-1.79.1";
 
     src = fetchurl {
       url = "mirror://sourceforge/docbook/${name}.tar.bz2";
@@ -35,12 +35,12 @@ in {
 
   docbook_xsl = common {
     pname = "docbook-xsl";
-    sha256 = "0rxl013ncmz1n6ymk2idvx3hix9pdabk8xn01cpcv32wmfb753y9";
+    sha256 = "0s59lihif2fr7rznckxr2kfyrvkirv76r1zvidp9b5mj28p4apvj";
   };
 
   docbook_xsl_ns = common {
     pname = "docbook-xsl-ns";
-    sha256 = "1x3sc0axk9z3i6n0jhlsmzlmb723a4sjgslm9g12by6phirdx3ng";
+    sha256 = "170ggf5dgjar65kkn5n33kvjr3pdinpj66nnxfx8b2avw0k91jin";
   };
 
 }
diff --git a/pkgs/desktops/kde-5/plasma-5.6/plasma-desktop/default.nix b/pkgs/desktops/kde-5/plasma-5.6/plasma-desktop/default.nix
index 618e7387e62c..2a1d95806c10 100644
--- a/pkgs/desktops/kde-5/plasma-5.6/plasma-desktop/default.nix
+++ b/pkgs/desktops/kde-5/plasma-5.6/plasma-desktop/default.nix
@@ -34,6 +34,9 @@ plasmaPackage rec {
     })
     ./0003-tzdir.patch
   ];
+  postPatch = ''
+    sed '1i#include <cmath>' -i kcms/touchpad/src/backends/x11/synapticstouchpad.cpp
+  '';
   NIX_CFLAGS_COMPILE = [ "-I${xorgserver.dev}/include/xorg" ];
   cmakeFlags = [
     "-DEvdev_INCLUDE_DIRS=${xf86inputevdev.dev}/include/xorg"
diff --git a/pkgs/development/compilers/gcc/4.5/default.nix b/pkgs/development/compilers/gcc/4.5/default.nix
index b1eedf7707df..69ff590a6314 100644
--- a/pkgs/development/compilers/gcc/4.5/default.nix
+++ b/pkgs/development/compilers/gcc/4.5/default.nix
@@ -179,11 +179,11 @@ stdenv.mkDerivation ({
            sed -i "${gnu_h}" \
                -es'|LIB_SPEC *"\(.*\)$|LIB_SPEC "${extraLibSpec} \1|g'
 
-           echo "setting \`NATIVE_SYSTEM_HEADER_DIR' and \`STANDARD_INCLUDE_DIR' to \`${libc}/include'..."
+           echo "setting \`NATIVE_SYSTEM_HEADER_DIR' and \`STANDARD_INCLUDE_DIR' to \`${libc.dev}/include'..."
            sed -i "${gnu_h}" \
-               -es'|#define STANDARD_INCLUDE_DIR.*$|#define STANDARD_INCLUDE_DIR "${libc}/include"|g'
+               -es'|#define STANDARD_INCLUDE_DIR.*$|#define STANDARD_INCLUDE_DIR "${libc.dev}/include"|g'
            sed -i gcc/config/t-gnu \
-               -es'|NATIVE_SYSTEM_HEADER_DIR.*$|NATIVE_SYSTEM_HEADER_DIR = ${libc}/include|g'
+               -es'|NATIVE_SYSTEM_HEADER_DIR.*$|NATIVE_SYSTEM_HEADER_DIR = ${libc.dev}/include|g'
         ''
     else if cross != null || stdenv.cc.libc != null then
       # On NixOS, use the right path to the dynamic linker instead of
@@ -197,7 +197,7 @@ stdenv.mkDerivation ({
              grep -q LIBC_DYNAMIC_LINKER "$header" || continue
              echo "  fixing \`$header'..."
              sed -i "$header" \
-                 -e 's|define[[:blank:]]*\([UCG]\+\)LIBC_DYNAMIC_LINKER\([0-9]*\)[[:blank:]]"\([^\"]\+\)"$|define \1LIBC_DYNAMIC_LINKER\2 "${libc}\3"|g'
+                 -e 's|define[[:blank:]]*\([UCG]\+\)LIBC_DYNAMIC_LINKER\([0-9]*\)[[:blank:]]"\([^\"]\+\)"$|define \1LIBC_DYNAMIC_LINKER\2 "${libc.out}\3"|g'
            done
         ''
     else null;
@@ -205,10 +205,10 @@ stdenv.mkDerivation ({
   inherit noSysDirs profiledCompiler staticCompiler langJava crossStageStatic
     libcCross crossMingw;
 
-  nativeBuildInputs = [ texinfo which ]
+  nativeBuildInputs = [ texinfo which gettext ]
     ++ optional (perl != null) perl;
     
-  buildInputs = [ gmp mpfr libmpc libelf gettext ]
+  buildInputs = [ gmp mpfr libmpc libelf ]
     ++ (optional (ppl != null) ppl)
     ++ (optional (cloogppl != null) cloogppl)
     ++ (optional (zlib != null) zlib)
@@ -284,6 +284,7 @@ stdenv.mkDerivation ({
       ${if langJava && javaAntlr != null then "--with-antlr-jar=${javaAntlr.crossDrv}" else ""}
       --with-gmp=${gmp.crossDrv}
       --with-mpfr=${mpfr.crossDrv}
+      --with-mpc=${libmpc.crossDrv}
       --disable-libstdcxx-pch
       --without-included-gettext
       --with-system-zlib
@@ -346,15 +347,28 @@ stdenv.mkDerivation ({
                                           ++ optional (libpthread != null) libpthread)));
 
   EXTRA_TARGET_CFLAGS =
-    if cross != null && libcCross != null
-    then "-idirafter ${libcCross}/include"
+    if cross != null && libcCross != null then [
+        "-idirafter ${libcCross.dev}/include"
+      ]
+      ++ optionals (! crossStageStatic) [
+        "-B${libcCross.out}/lib"
+      ]
     else null;
 
   EXTRA_TARGET_LDFLAGS =
-    if cross != null && libcCross != null
-    then "-B${libcCross}/lib -Wl,-L${libcCross}/lib" +
-         (optionalString (libpthreadCross != null)
-           " -L${libpthreadCross}/lib -Wl,${libpthreadCross.TARGET_LDFLAGS}")
+    if cross != null && libcCross != null then [
+        "-Wl,-L${libcCross.out}/lib"
+      ]
+      ++ (if crossStageStatic then [
+        "-B${libcCross.out}/lib"
+      ] else [
+        "-Wl,-rpath,${libcCross.out}/lib"
+        "-Wl,-rpath-link,${libcCross.out}/lib"
+      ])
+      ++ optionals (libpthreadCross != null) [
+        "-L${libpthreadCross}/lib"
+        "-Wl,${libpthreadCross.TARGET_LDFLAGS}"
+      ]
     else null;
 
   passthru = { inherit langC langCC langAda langFortran langVhdl
diff --git a/pkgs/development/compilers/gcc/4.6/builder.sh b/pkgs/development/compilers/gcc/4.6/builder.sh
index af36ec33b70a..6087bb30cfb2 100644
--- a/pkgs/development/compilers/gcc/4.6/builder.sh
+++ b/pkgs/development/compilers/gcc/4.6/builder.sh
@@ -209,7 +209,9 @@ postInstall() {
     # Move runtime libraries to $lib.
     mkdir -p $lib/lib
     ln -s lib $lib/lib64
-    mv -v $out/lib/lib*.so $out/lib/lib*.so.*[0-9] $out/lib/*.la $lib/lib/
+    moveToOutput "lib/lib*.so"        "$lib"
+    moveToOutput "lib/lib*.so.*[0-9]" "$lib"
+    moveToOutput "lib/*.la"           "$lib"
     for i in $lib/lib/*.la; do
         substituteInPlace $i --replace $out $lib
     done
diff --git a/pkgs/development/compilers/gcc/4.6/default.nix b/pkgs/development/compilers/gcc/4.6/default.nix
index 7003f4335c8a..fad198b1f5c8 100644
--- a/pkgs/development/compilers/gcc/4.6/default.nix
+++ b/pkgs/development/compilers/gcc/4.6/default.nix
@@ -170,7 +170,7 @@ let version = "4.6.4";
       "-stage-final";
     crossNameAddon = if cross != null then "-${cross.config}" + stageNameAddon else "";
 
-    bootstrap = cross == null && !stdenv.isArm && !stdenv.isMips;
+    bootstrap = cross == null && !stdenv.isArm && !stdenv.isMips && !stdenv.isDarwin;
 
 in
 
@@ -229,11 +229,11 @@ stdenv.mkDerivation ({
            sed -i "${gnu_h}" \
                -es'|LIB_SPEC *"\(.*\)$|LIB_SPEC "${extraLibSpec} \1|g'
 
-           echo "setting \`NATIVE_SYSTEM_HEADER_DIR' and \`STANDARD_INCLUDE_DIR' to \`${libc}/include'..."
+           echo "setting \`NATIVE_SYSTEM_HEADER_DIR' and \`STANDARD_INCLUDE_DIR' to \`${libc.dev}/include'..."
            sed -i "${gnu_h}" \
-               -es'|#define STANDARD_INCLUDE_DIR.*$|#define STANDARD_INCLUDE_DIR "${libc}/include"|g'
+               -es'|#define STANDARD_INCLUDE_DIR.*$|#define STANDARD_INCLUDE_DIR "${libc.dev}/include"|g'
            sed -i gcc/config/t-gnu \
-               -es'|NATIVE_SYSTEM_HEADER_DIR.*$|NATIVE_SYSTEM_HEADER_DIR = ${libc}/include|g'
+               -es'|NATIVE_SYSTEM_HEADER_DIR.*$|NATIVE_SYSTEM_HEADER_DIR = ${libc.dev}/include|g'
         ''
     else if cross != null || stdenv.cc.libc != null then
       # On NixOS, use the right path to the dynamic linker instead of
@@ -247,7 +247,7 @@ stdenv.mkDerivation ({
              grep -q LIBC_DYNAMIC_LINKER "$header" || continue
              echo "  fixing \`$header'..."
              sed -i "$header" \
-                 -e 's|define[[:blank:]]*\([UCG]\+\)LIBC_DYNAMIC_LINKER\([0-9]*\)[[:blank:]]"\([^\"]\+\)"$|define \1LIBC_DYNAMIC_LINKER\2 "${libc}\3"|g'
+                 -e 's|define[[:blank:]]*\([UCG]\+\)LIBC_DYNAMIC_LINKER\([0-9]*\)[[:blank:]]"\([^\"]\+\)"$|define \1LIBC_DYNAMIC_LINKER\2 "${libc.out}\3"|g'
            done
         ''
     else null;
@@ -357,6 +357,7 @@ stdenv.mkDerivation ({
       ${if langJava && javaAntlr != null then "--with-antlr-jar=${javaAntlr.crossDrv}" else ""}
       --with-gmp=${gmp.crossDrv}
       --with-mpfr=${mpfr.crossDrv}
+      --with-mpc=${libmpc.crossDrv}
       --disable-libstdcxx-pch
       --without-included-gettext
       --with-system-zlib
@@ -421,15 +422,28 @@ stdenv.mkDerivation ({
                                           ++ optional (libpthread != null) libpthread)));
 
   EXTRA_TARGET_CFLAGS =
-    if cross != null && libcCross != null
-    then "-idirafter ${libcCross}/include"
+    if cross != null && libcCross != null then [
+        "-idirafter ${libcCross.dev}/include"
+      ]
+      ++ optionals (! crossStageStatic) [
+        "-B${libcCross.out}/lib"
+      ]
     else null;
 
   EXTRA_TARGET_LDFLAGS =
-    if cross != null && libcCross != null
-    then "-B${libcCross}/lib -Wl,-L${libcCross}/lib" +
-         (optionalString (libpthreadCross != null)
-           " -L${libpthreadCross}/lib -Wl,${libpthreadCross.TARGET_LDFLAGS}")
+    if cross != null && libcCross != null then [
+        "-Wl,-L${libcCross.out}/lib"
+      ]
+      ++ (if crossStageStatic then [
+        "-B${libcCross.out}/lib"
+      ] else [
+        "-Wl,-rpath,${libcCross.out}/lib"
+        "-Wl,-rpath-link,${libcCross.out}/lib"
+      ])
+      ++ optionals (libpthreadCross != null) [
+        "-L${libpthreadCross}/lib"
+        "-Wl,${libpthreadCross.TARGET_LDFLAGS}"
+      ]
     else null;
 
   passthru = { inherit langC langCC langAda langFortran langVhdl
diff --git a/pkgs/development/compilers/gcc/4.8/default.nix b/pkgs/development/compilers/gcc/4.8/default.nix
index 6810b52574c6..42fd4bec2ebc 100644
--- a/pkgs/development/compilers/gcc/4.8/default.nix
+++ b/pkgs/development/compilers/gcc/4.8/default.nix
@@ -70,7 +70,8 @@ let version = "4.8.5";
       # The GNAT Makefiles did not pay attention to CFLAGS_FOR_TARGET for its
       # target libraries and tools.
       ++ optional langAda ../gnat-cflags.patch
-      ++ optional langFortran ../gfortran-driving.patch;
+      ++ optional langFortran ../gfortran-driving.patch
+      ++ optional stdenv.isDarwin ../gfortran-darwin-NXConstStr.patch;
 
     javaEcj = fetchurl {
       # The `$(top_srcdir)/ecj.jar' file is automatically picked up at
@@ -164,8 +165,8 @@ let version = "4.8.5";
           " --disable-libatomic " +  # libatomic requires libc
           " --disable-decimal-float" # libdecnumber requires libc
           else
-          (if crossDarwin then " --with-sysroot=${libcCross}/share/sysroot"
-           else                " --with-headers=${libcCross}/include") +
+          (if crossDarwin then " --with-sysroot=${libcCross.out}/share/sysroot"
+           else                " --with-headers=${libcCross.dev}/include") +
           # Ensure that -print-prog-name is able to find the correct programs.
           (stdenv.lib.optionalString (crossMingw || crossDarwin) (
             " --with-as=${binutilsCross}/bin/${cross.config}-as" +
@@ -197,7 +198,7 @@ let version = "4.8.5";
     stageNameAddon = if crossStageStatic then "-stage-static" else "-stage-final";
     crossNameAddon = if cross != null then "-${cross.config}" + stageNameAddon else "";
 
-    bootstrap = cross == null && !stdenv.isArm && !stdenv.isMips;
+    bootstrap = cross == null && !stdenv.isArm && !stdenv.isMips && !stdenv.isDarwin;
 
 in
 
@@ -255,9 +256,9 @@ stdenv.mkDerivation ({
            sed -i "${gnu_h}" \
                -es'|LIB_SPEC *"\(.*\)$|LIB_SPEC "${extraLibSpec} \1|g'
 
-           echo "setting \`NATIVE_SYSTEM_HEADER_DIR' and \`STANDARD_INCLUDE_DIR' to \`${libc}/include'..."
+           echo "setting \`NATIVE_SYSTEM_HEADER_DIR' and \`STANDARD_INCLUDE_DIR' to \`${libc.dev}/include'..."
            sed -i "${gnu_h}" \
-               -es'|#define STANDARD_INCLUDE_DIR.*$|#define STANDARD_INCLUDE_DIR "${libc}/include"|g'
+               -es'|#define STANDARD_INCLUDE_DIR.*$|#define STANDARD_INCLUDE_DIR "${libc.dev}/include"|g'
         ''
     else if cross != null || stdenv.cc.libc != null then
       # On NixOS, use the right path to the dynamic linker instead of
@@ -271,7 +272,7 @@ stdenv.mkDerivation ({
              grep -q LIBC_DYNAMIC_LINKER "$header" || continue
              echo "  fixing \`$header'..."
              sed -i "$header" \
-                 -e 's|define[[:blank:]]*\([UCG]\+\)LIBC_DYNAMIC_LINKER\([0-9]*\)[[:blank:]]"\([^\"]\+\)"$|define \1LIBC_DYNAMIC_LINKER\2 "${libc}\3"|g'
+                 -e 's|define[[:blank:]]*\([UCG]\+\)LIBC_DYNAMIC_LINKER\([0-9]*\)[[:blank:]]"\([^\"]\+\)"$|define \1LIBC_DYNAMIC_LINKER\2 "${libc.out}\3"|g'
            done
         ''
     else null;
@@ -304,15 +305,6 @@ stdenv.mkDerivation ({
     export LDFLAGS_FOR_TARGET="-Wl,-rpath,$prefix/lib/amd64 $LDFLAGS_FOR_TARGET"
     export CXXFLAGS_FOR_TARGET="-Wl,-rpath,$prefix/lib/amd64 $CXXFLAGS_FOR_TARGET"
     export CFLAGS_FOR_TARGET="-Wl,-rpath,$prefix/lib/amd64 $CFLAGS_FOR_TARGET"
-  '' + stdenv.lib.optionalString stdenv.isDarwin ''
-    if SDKROOT=$(/usr/bin/xcrun --show-sdk-path); then
-      configureFlagsArray+=(--with-native-system-header-dir=$SDKROOT/usr/include)
-      makeFlagsArray+=( \
-       CFLAGS_FOR_BUILD=-F$SDKROOT/System/Library/Frameworks \
-       CFLAGS_FOR_TARGET=-F$SDKROOT/System/Library/Frameworks \
-       FLAGS_FOR_TARGET=-F$SDKROOT/System/Library/Frameworks \
-      )
-    fi
   '';
 
   dontDisableStatic = true;
@@ -415,6 +407,7 @@ stdenv.mkDerivation ({
       ${if langJava && javaAntlr != null then "--with-antlr-jar=${javaAntlr.crossDrv}" else ""}
       --with-gmp=${gmp.crossDrv}
       --with-mpfr=${mpfr.crossDrv}
+      --with-mpc=${libmpc.crossDrv}
       --disable-libstdcxx-pch
       --without-included-gettext
       --with-system-zlib
@@ -482,15 +475,28 @@ stdenv.mkDerivation ({
                                           ++ optional (libpthread != null) libpthread)));
 
   EXTRA_TARGET_CFLAGS =
-    if cross != null && libcCross != null
-    then "-idirafter ${libcCross}/include"
+    if cross != null && libcCross != null then [
+        "-idirafter ${libcCross.dev}/include"
+      ]
+      ++ optionals (! crossStageStatic) [
+        "-B${libcCross.out}/lib"
+      ]
     else null;
 
   EXTRA_TARGET_LDFLAGS =
-    if cross != null && libcCross != null
-    then "-B${libcCross}/lib -Wl,-L${libcCross}/lib" +
-         (optionalString (libpthreadCross != null)
-           " -L${libpthreadCross}/lib -Wl,${libpthreadCross.TARGET_LDFLAGS}")
+    if cross != null && libcCross != null then [
+        "-Wl,-L${libcCross.out}/lib"
+      ]
+      ++ (if crossStageStatic then [
+        "-B${libcCross.out}/lib"
+      ] else [
+        "-Wl,-rpath,${libcCross.out}/lib"
+        "-Wl,-rpath-link,${libcCross.out}/lib"
+      ])
+      ++ optionals (libpthreadCross != null) [
+        "-L${libpthreadCross}/lib"
+        "-Wl,${libpthreadCross.TARGET_LDFLAGS}"
+      ]
     else null;
 
   passthru =
diff --git a/pkgs/development/compilers/gcc/4.9/default.nix b/pkgs/development/compilers/gcc/4.9/default.nix
index 195a7b03eed4..475349ed4ba9 100644
--- a/pkgs/development/compilers/gcc/4.9/default.nix
+++ b/pkgs/development/compilers/gcc/4.9/default.nix
@@ -166,8 +166,8 @@ let version = "4.9.3";
           " --disable-libatomic " +  # libatomic requires libc
           " --disable-decimal-float" # libdecnumber requires libc
           else
-          (if crossDarwin then " --with-sysroot=${libcCross}/share/sysroot"
-           else                " --with-headers=${libcCross}/include") +
+          (if crossDarwin then " --with-sysroot=${libcCross.out}/share/sysroot"
+           else                " --with-headers=${libcCross.dev}/include") +
           # Ensure that -print-prog-name is able to find the correct programs.
           (stdenv.lib.optionalString (crossMingw || crossDarwin) (
             " --with-as=${binutilsCross}/bin/${cross.config}-as" +
@@ -199,7 +199,7 @@ let version = "4.9.3";
     stageNameAddon = if crossStageStatic then "-stage-static" else "-stage-final";
     crossNameAddon = if cross != null then "-${cross.config}" + stageNameAddon else "";
 
-  bootstrap = cross == null;
+  bootstrap = cross == null && !stdenv.isDarwin;
 
 in
 
@@ -258,9 +258,9 @@ stdenv.mkDerivation ({
            sed -i "${gnu_h}" \
                -es'|LIB_SPEC *"\(.*\)$|LIB_SPEC "${extraLibSpec} \1|g'
 
-           echo "setting \`NATIVE_SYSTEM_HEADER_DIR' and \`STANDARD_INCLUDE_DIR' to \`${libc}/include'..."
+           echo "setting \`NATIVE_SYSTEM_HEADER_DIR' and \`STANDARD_INCLUDE_DIR' to \`${libc.dev}/include'..."
            sed -i "${gnu_h}" \
-               -es'|#define STANDARD_INCLUDE_DIR.*$|#define STANDARD_INCLUDE_DIR "${libc}/include"|g'
+               -es'|#define STANDARD_INCLUDE_DIR.*$|#define STANDARD_INCLUDE_DIR "${libc.dev}/include"|g'
         ''
     else if cross != null || stdenv.cc.libc != null then
       # On NixOS, use the right path to the dynamic linker instead of
@@ -274,7 +274,7 @@ stdenv.mkDerivation ({
              grep -q LIBC_DYNAMIC_LINKER "$header" || continue
              echo "  fixing \`$header'..."
              sed -i "$header" \
-                 -e 's|define[[:blank:]]*\([UCG]\+\)LIBC_DYNAMIC_LINKER\([0-9]*\)[[:blank:]]"\([^\"]\+\)"$|define \1LIBC_DYNAMIC_LINKER\2 "${libc}\3"|g'
+                 -e 's|define[[:blank:]]*\([UCG]\+\)LIBC_DYNAMIC_LINKER\([0-9]*\)[[:blank:]]"\([^\"]\+\)"$|define \1LIBC_DYNAMIC_LINKER\2 "${libc.out}\3"|g'
            done
         ''
     else null;
@@ -307,15 +307,6 @@ stdenv.mkDerivation ({
     export LDFLAGS_FOR_TARGET="-Wl,-rpath,$prefix/lib/amd64 $LDFLAGS_FOR_TARGET"
     export CXXFLAGS_FOR_TARGET="-Wl,-rpath,$prefix/lib/amd64 $CXXFLAGS_FOR_TARGET"
     export CFLAGS_FOR_TARGET="-Wl,-rpath,$prefix/lib/amd64 $CFLAGS_FOR_TARGET"
-  '' + stdenv.lib.optionalString stdenv.isDarwin ''
-    if SDKROOT=$(/usr/bin/xcrun --show-sdk-path); then
-      configureFlagsArray+=(--with-native-system-header-dir=$SDKROOT/usr/include)
-      makeFlagsArray+=( \
-       CFLAGS_FOR_BUILD=-F$SDKROOT/System/Library/Frameworks \
-       CFLAGS_FOR_TARGET=-F$SDKROOT/System/Library/Frameworks \
-       FLAGS_FOR_TARGET=-F$SDKROOT/System/Library/Frameworks \
-      )
-    fi
   ''
   + stdenv.lib.optionalString (langJava || langGo) ''
     export lib=$out;
@@ -422,6 +413,7 @@ stdenv.mkDerivation ({
       ${if langJava && javaAntlr != null then "--with-antlr-jar=${javaAntlr.crossDrv}" else ""}
       --with-gmp=${gmp.crossDrv}
       --with-mpfr=${mpfr.crossDrv}
+      --with-mpc=${libmpc.crossDrv}
       --disable-libstdcxx-pch
       --without-included-gettext
       --with-system-zlib
@@ -489,15 +481,28 @@ stdenv.mkDerivation ({
                                           ++ optional (libpthread != null) libpthread)));
 
   EXTRA_TARGET_CFLAGS =
-    if cross != null && libcCross != null
-    then "-idirafter ${libcCross}/include"
+    if cross != null && libcCross != null then [
+        "-idirafter ${libcCross.dev}/include"
+      ]
+      ++ optionals (! crossStageStatic) [
+        "-B${libcCross.out}/lib"
+      ]
     else null;
 
   EXTRA_TARGET_LDFLAGS =
-    if cross != null && libcCross != null
-    then "-B${libcCross}/lib -Wl,-L${libcCross}/lib" +
-         (optionalString (libpthreadCross != null)
-           " -L${libpthreadCross}/lib -Wl,${libpthreadCross.TARGET_LDFLAGS}")
+    if cross != null && libcCross != null then [
+        "-Wl,-L${libcCross.out}/lib"
+      ]
+      ++ (if crossStageStatic then [
+        "-B${libcCross.out}/lib"
+      ] else [
+        "-Wl,-rpath,${libcCross.out}/lib"
+        "-Wl,-rpath-link,${libcCross.out}/lib"
+      ])
+      ++ optionals (libpthreadCross != null) [
+        "-L${libpthreadCross}/lib"
+        "-Wl,${libpthreadCross.TARGET_LDFLAGS}"
+      ]
     else null;
 
   passthru =
diff --git a/pkgs/development/compilers/gcc/5/default.nix b/pkgs/development/compilers/gcc/5/default.nix
index 9e0220ffc728..4802c3fe2782 100644
--- a/pkgs/development/compilers/gcc/5/default.nix
+++ b/pkgs/development/compilers/gcc/5/default.nix
@@ -58,7 +58,8 @@ assert langGo -> langCC;
 with stdenv.lib;
 with builtins;
 
-let version = "5.3.0";
+let version = "5.4.0";
+    sha256 = "0fihlcy5hnksdxk0sn6bvgnyq8gfrgs8m794b1jxwd1dxinzg3b0";
 
     # Whether building a cross-compiler for GNU/Hurd.
     crossGNU = cross != null && cross.config == "i586-pc-gnu";
@@ -165,8 +166,8 @@ let version = "5.3.0";
           " --disable-libatomic " +  # libatomic requires libc
           " --disable-decimal-float" # libdecnumber requires libc
           else
-          (if crossDarwin then " --with-sysroot=${libcCross}/share/sysroot"
-           else                " --with-headers=${libcCross}/include") +
+          (if crossDarwin then " --with-sysroot=${getLib libcCross}/share/sysroot"
+           else                " --with-headers=${getDev libcCross}/include") +
           # Ensure that -print-prog-name is able to find the correct programs.
           (stdenv.lib.optionalString (crossMingw || crossDarwin) (
             " --with-as=${binutilsCross}/bin/${cross.config}-as" +
@@ -198,7 +199,7 @@ let version = "5.3.0";
     stageNameAddon = if crossStageStatic then "-stage-static" else "-stage-final";
     crossNameAddon = if cross != null then "-${cross.config}" + stageNameAddon else "";
 
-  bootstrap = cross == null;
+  bootstrap = cross == null && !stdenv.isDarwin;
 
 in
 
@@ -212,7 +213,7 @@ stdenv.mkDerivation ({
 
   src = fetchurl {
     url = "mirror://gnu/gcc/gcc-${version}/gcc-${version}.tar.bz2";
-    sha256 = "1ny4smkp5bzs3cp8ss7pl6lk8yss0d9m4av1mvdp72r1x695akxq";
+    inherit sha256;
   };
 
   inherit patches;
@@ -256,9 +257,9 @@ stdenv.mkDerivation ({
            sed -i "${gnu_h}" \
                -es'|LIB_SPEC *"\(.*\)$|LIB_SPEC "${extraLibSpec} \1|g'
 
-           echo "setting \`NATIVE_SYSTEM_HEADER_DIR' and \`STANDARD_INCLUDE_DIR' to \`${libc}/include'..."
+           echo "setting \`NATIVE_SYSTEM_HEADER_DIR' and \`STANDARD_INCLUDE_DIR' to \`${libc.dev}/include'..."
            sed -i "${gnu_h}" \
-               -es'|#define STANDARD_INCLUDE_DIR.*$|#define STANDARD_INCLUDE_DIR "${libc}/include"|g'
+               -es'|#define STANDARD_INCLUDE_DIR.*$|#define STANDARD_INCLUDE_DIR "${libc.dev}/include"|g'
         ''
     else if cross != null || stdenv.cc.libc != null then
       # On NixOS, use the right path to the dynamic linker instead of
@@ -272,7 +273,7 @@ stdenv.mkDerivation ({
              grep -q LIBC_DYNAMIC_LINKER "$header" || continue
              echo "  fixing \`$header'..."
              sed -i "$header" \
-                 -e 's|define[[:blank:]]*\([UCG]\+\)LIBC_DYNAMIC_LINKER\([0-9]*\)[[:blank:]]"\([^\"]\+\)"$|define \1LIBC_DYNAMIC_LINKER\2 "${libc}\3"|g'
+                 -e 's|define[[:blank:]]*\([UCG]\+\)LIBC_DYNAMIC_LINKER\([0-9]*\)[[:blank:]]"\([^\"]\+\)"$|define \1LIBC_DYNAMIC_LINKER\2 "${libc.out}\3"|g'
            done
         ''
     else null;
@@ -306,15 +307,6 @@ stdenv.mkDerivation ({
     export LDFLAGS_FOR_TARGET="-Wl,-rpath,$prefix/lib/amd64 $LDFLAGS_FOR_TARGET"
     export CXXFLAGS_FOR_TARGET="-Wl,-rpath,$prefix/lib/amd64 $CXXFLAGS_FOR_TARGET"
     export CFLAGS_FOR_TARGET="-Wl,-rpath,$prefix/lib/amd64 $CFLAGS_FOR_TARGET"
-  '' + stdenv.lib.optionalString stdenv.isDarwin ''
-    if SDKROOT=$(/usr/bin/xcrun --show-sdk-path); then
-      configureFlagsArray+=(--with-native-system-header-dir=$SDKROOT/usr/include)
-      makeFlagsArray+=( \
-       CFLAGS_FOR_BUILD=-F$SDKROOT/System/Library/Frameworks \
-       CFLAGS_FOR_TARGET=-F$SDKROOT/System/Library/Frameworks \
-       FLAGS_FOR_TARGET=-F$SDKROOT/System/Library/Frameworks \
-      )
-    fi
   '';
 
   dontDisableStatic = true;
@@ -415,6 +407,7 @@ stdenv.mkDerivation ({
       ${if langJava && javaAntlr != null then "--with-antlr-jar=${javaAntlr.crossDrv}" else ""}
       --with-gmp=${gmp.crossDrv}
       --with-mpfr=${mpfr.crossDrv}
+      --with-mpc=${libmpc.crossDrv}
       --disable-libstdcxx-pch
       --without-included-gettext
       --with-system-zlib
@@ -482,15 +475,28 @@ stdenv.mkDerivation ({
                                           ++ optional (libpthread != null) libpthread)));
 
   EXTRA_TARGET_CFLAGS =
-    if cross != null && libcCross != null
-    then "-idirafter ${libcCross}/include"
+    if cross != null && libcCross != null then [
+        "-idirafter ${getDev libcCross}/include"
+      ]
+      ++ optionals (! crossStageStatic) [
+        "-B${libcCross.out}/lib"
+      ]
     else null;
 
   EXTRA_TARGET_LDFLAGS =
-    if cross != null && libcCross != null
-    then "-B${libcCross}/lib -Wl,-L${libcCross}/lib" +
-         (optionalString (libpthreadCross != null)
-           " -L${libpthreadCross}/lib -Wl,${libpthreadCross.TARGET_LDFLAGS}")
+    if cross != null && libcCross != null then [
+        "-Wl,-L${libcCross.out}/lib"
+      ]
+      ++ (if crossStageStatic then [
+        "-B${libcCross.out}/lib"
+      ] else [
+        "-Wl,-rpath,${libcCross.out}/lib"
+        "-Wl,-rpath-link,${libcCross.out}/lib"
+      ])
+      ++ optionals (libpthreadCross != null) [
+        "-L${libpthreadCross}/lib"
+        "-Wl,${libpthreadCross.TARGET_LDFLAGS}"
+      ]
     else null;
 
   passthru =
diff --git a/pkgs/development/compilers/gcc/6/default.nix b/pkgs/development/compilers/gcc/6/default.nix
index 6ca0f2f59f44..e87554c25ab8 100644
--- a/pkgs/development/compilers/gcc/6/default.nix
+++ b/pkgs/development/compilers/gcc/6/default.nix
@@ -165,8 +165,8 @@ let version = "6.1.0";
           " --disable-libatomic " +  # libatomic requires libc
           " --disable-decimal-float" # libdecnumber requires libc
           else
-          (if crossDarwin then " --with-sysroot=${libcCross}/share/sysroot"
-           else                " --with-headers=${libcCross}/include") +
+          (if crossDarwin then " --with-sysroot=${libcCross.out}/share/sysroot"
+           else                " --with-headers=${libcCross.dev}/include") +
           # Ensure that -print-prog-name is able to find the correct programs.
           (stdenv.lib.optionalString (crossMingw || crossDarwin) (
             " --with-as=${binutilsCross}/bin/${cross.config}-as" +
@@ -198,7 +198,7 @@ let version = "6.1.0";
     stageNameAddon = if crossStageStatic then "-stage-static" else "-stage-final";
     crossNameAddon = if cross != null then "-${cross.config}" + stageNameAddon else "";
 
-  bootstrap = cross == null;
+  bootstrap = cross == null && !stdenv.isDarwin;
 
 in
 
@@ -256,9 +256,9 @@ stdenv.mkDerivation ({
            sed -i "${gnu_h}" \
                -es'|LIB_SPEC *"\(.*\)$|LIB_SPEC "${extraLibSpec} \1|g'
 
-           echo "setting \`NATIVE_SYSTEM_HEADER_DIR' and \`STANDARD_INCLUDE_DIR' to \`${libc}/include'..."
+           echo "setting \`NATIVE_SYSTEM_HEADER_DIR' and \`STANDARD_INCLUDE_DIR' to \`${libc.dev}/include'..."
            sed -i "${gnu_h}" \
-               -es'|#define STANDARD_INCLUDE_DIR.*$|#define STANDARD_INCLUDE_DIR "${libc}/include"|g'
+               -es'|#define STANDARD_INCLUDE_DIR.*$|#define STANDARD_INCLUDE_DIR "${libc.dev}/include"|g'
         ''
     else if cross != null || stdenv.cc.libc != null then
       # On NixOS, use the right path to the dynamic linker instead of
@@ -272,7 +272,7 @@ stdenv.mkDerivation ({
              grep -q LIBC_DYNAMIC_LINKER "$header" || continue
              echo "  fixing \`$header'..."
              sed -i "$header" \
-                 -e 's|define[[:blank:]]*\([UCG]\+\)LIBC_DYNAMIC_LINKER\([0-9]*\)[[:blank:]]"\([^\"]\+\)"$|define \1LIBC_DYNAMIC_LINKER\2 "${libc}\3"|g'
+                 -e 's|define[[:blank:]]*\([UCG]\+\)LIBC_DYNAMIC_LINKER\([0-9]*\)[[:blank:]]"\([^\"]\+\)"$|define \1LIBC_DYNAMIC_LINKER\2 "${libc.out}\3"|g'
            done
         ''
     else null;
@@ -306,15 +306,6 @@ stdenv.mkDerivation ({
     export LDFLAGS_FOR_TARGET="-Wl,-rpath,$prefix/lib/amd64 $LDFLAGS_FOR_TARGET"
     export CXXFLAGS_FOR_TARGET="-Wl,-rpath,$prefix/lib/amd64 $CXXFLAGS_FOR_TARGET"
     export CFLAGS_FOR_TARGET="-Wl,-rpath,$prefix/lib/amd64 $CFLAGS_FOR_TARGET"
-  '' + stdenv.lib.optionalString stdenv.isDarwin ''
-    if SDKROOT=$(/usr/bin/xcrun --show-sdk-path); then
-      configureFlagsArray+=(--with-native-system-header-dir=$SDKROOT/usr/include)
-      makeFlagsArray+=( \
-       CFLAGS_FOR_BUILD=-F$SDKROOT/System/Library/Frameworks \
-       CFLAGS_FOR_TARGET=-F$SDKROOT/System/Library/Frameworks \
-       FLAGS_FOR_TARGET=-F$SDKROOT/System/Library/Frameworks \
-      )
-    fi
   '';
 
   dontDisableStatic = true;
@@ -482,15 +473,28 @@ stdenv.mkDerivation ({
                                           ++ optional (libpthread != null) libpthread)));
 
   EXTRA_TARGET_CFLAGS =
-    if cross != null && libcCross != null
-    then "-idirafter ${libcCross}/include"
+    if cross != null && libcCross != null then [
+        "-idirafter ${libcCross.dev}/include"
+      ]
+      ++ optionals (! crossStageStatic) [
+        "-B${libcCross.out}/lib"
+      ]
     else null;
 
   EXTRA_TARGET_LDFLAGS =
-    if cross != null && libcCross != null
-    then "-B${libcCross}/lib -Wl,-L${libcCross}/lib" +
-         (optionalString (libpthreadCross != null)
-           " -L${libpthreadCross}/lib -Wl,${libpthreadCross.TARGET_LDFLAGS}")
+    if cross != null && libcCross != null then [
+        "-Wl,-L${libcCross.out}/lib"
+      ]
+      ++ (if crossStageStatic then [
+        "-B${libcCross.out}/lib"
+      ] else [
+        "-Wl,-rpath,${libcCross.out}/lib"
+        "-Wl,-rpath-link,${libcCross.out}/lib"
+      ])
+      ++ optionals (libpthreadCross != null) [
+        "-L${libpthreadCross}/lib"
+        "-Wl,${libpthreadCross.TARGET_LDFLAGS}"
+      ]
     else null;
 
   passthru =
diff --git a/pkgs/development/compilers/gcc/builder.sh b/pkgs/development/compilers/gcc/builder.sh
index 22107e72ef70..0371630f3f69 100644
--- a/pkgs/development/compilers/gcc/builder.sh
+++ b/pkgs/development/compilers/gcc/builder.sh
@@ -70,10 +70,6 @@ if test "$noSysDirs" = "1"; then
         # gcj in.
         unset LIBRARY_PATH
         unset CPATH
-        if test -z "$crossStageStatic"; then
-            EXTRA_TARGET_CFLAGS="-B${libcCross}/lib -idirafter ${libcCross}/include"
-            EXTRA_TARGET_LDFLAGS="-Wl,-L${libcCross}/lib -Wl,-rpath,${libcCross}/lib -Wl,-rpath-link,${libcCross}/lib"
-        fi
     else
         if test -z "$NIX_CC_CROSS"; then
             EXTRA_TARGET_CFLAGS="$EXTRA_FLAGS"
@@ -90,15 +86,16 @@ if test "$noSysDirs" = "1"; then
             extraFlags="$(cat $NIX_CC_CROSS/nix-support/libc-cflags)"
             extraLDFlags="$(cat $NIX_CC_CROSS/nix-support/libc-ldflags) $(cat $NIX_CC_CROSS/nix-support/libc-ldflags-before)"
 
-            # Use *real* header files, otherwise a limits.h is generated
-            # that does not include Glibc's limits.h (notably missing
-            # SSIZE_MAX, which breaks the build).
-            NIX_FIXINC_DUMMY_CROSS=$(cat $NIX_CC_CROSS/nix-support/orig-libc)/include
-
             # The path to the Glibc binaries such as `crti.o'.
             glibc_dir="$(cat $NIX_CC_CROSS/nix-support/orig-libc)"
             glibc_libdir="$glibc_dir/lib"
-            configureFlags="$configureFlags --with-native-system-header-dir=$glibc_dir/include"
+            glibc_devdir="$(cat $NIX_CC_CROSS/nix-support/orig-libc-dev)"
+            configureFlags="$configureFlags --with-native-system-header-dir=$glibc_devdir/include"
+
+            # Use *real* header files, otherwise a limits.h is generated
+            # that does not include Glibc's limits.h (notably missing
+            # SSIZE_MAX, which breaks the build).
+            NIX_FIXINC_DUMMY_CROSS="$glibc_devdir/include"
 
             extraFlags="-I$NIX_FIXINC_DUMMY_CROSS $extraFlags"
             extraLDFlags="-L$glibc_libdir -rpath $glibc_libdir $extraLDFlags"
@@ -229,19 +226,21 @@ postInstall() {
     # More dependencies with the previous gcc or some libs (gccbug stores the build command line)
     rm -rf $out/bin/gccbug
 
-    # Take out the bootstrap-tools from the rpath, as it's not needed at all having $out
-    for i in $(find "$out"/libexec/gcc/*/*/* -type f -a \! -name '*.la'); do
-        PREV_RPATH=`patchelf --print-rpath "$i"`
-        NEW_RPATH=`echo "$PREV_RPATH" | sed 's,:[^:]*bootstrap-tools/lib,,g'`
-        patchelf --set-rpath "$NEW_RPATH" "$i" && echo OK
-    done
-
-    # For some reason the libs retain RPATH to $out
-    for i in "$lib"/lib/{libtsan,libasan,libubsan}.so.*.*.*; do
-        PREV_RPATH=`patchelf --print-rpath "$i"`
-        NEW_RPATH=`echo "$PREV_RPATH" | sed "s,:${out}[^:]*,,g"`
-        patchelf --set-rpath "$NEW_RPATH" "$i" && echo OK
-    done
+    if type "patchelf"; then
+	# Take out the bootstrap-tools from the rpath, as it's not needed at all having $out
+	for i in $(find "$out"/libexec/gcc/*/*/* -type f -a \! -name '*.la'); do
+            PREV_RPATH=`patchelf --print-rpath "$i"`
+            NEW_RPATH=`echo "$PREV_RPATH" | sed 's,:[^:]*bootstrap-tools/lib,,g'`
+            patchelf --set-rpath "$NEW_RPATH" "$i" && echo OK
+	done
+
+	# For some reason the libs retain RPATH to $out
+	for i in "$lib"/lib/{libtsan,libasan,libubsan}.so.*.*.*; do
+            PREV_RPATH=`patchelf --print-rpath "$i"`
+            NEW_RPATH=`echo "$PREV_RPATH" | sed "s,:${out}[^:]*,,g"`
+            patchelf --set-rpath "$NEW_RPATH" "$i" && echo OK
+	done
+    fi
 
     # Get rid of some "fixed" header files
     rm -rfv $out/lib/gcc/*/*/include-fixed/{root,linux}
diff --git a/pkgs/development/interpreters/pypy/default.nix b/pkgs/development/interpreters/pypy/default.nix
index 708c251e4aff..f07e53e592f5 100644
--- a/pkgs/development/interpreters/pypy/default.nix
+++ b/pkgs/development/interpreters/pypy/default.nix
@@ -21,6 +21,17 @@ let
       sha256 = "1dmckvffanmh0b50pq34shnw05r55gjxn43kgvnkz5kkvvsbxdg1";
     };
 
+   # http://bugs.python.org/issue27369
+    postPatch = let
+      expatch = fetchurl {
+        name = "tests-expat-2.2.0.patch";
+        url = "http://bugs.python.org/file43514/0001-Fix-Python-2.7.11-tests-for-Expat-2.2.0.patch";
+        sha256 = "1j3pa7ly9xrhp8jjwg5l77z7i3y68gx8f8jchqk6zc39d9glq3il";
+      };
+      in ''
+      patch lib-python/2.7/test/test_pyexpat.py < '${expatch}'
+    '';
+
     buildInputs = [ bzip2 openssl pkgconfig pythonFull libffi ncurses expat sqlite tk tcl xlibsWrapper libX11 makeWrapper gdbm db ]
       ++ stdenv.lib.optional (stdenv ? cc && stdenv.cc.libc != null) stdenv.cc.libc
       ++ stdenv.lib.optional zlibSupport zlib;
diff --git a/pkgs/development/libraries/botan/generic.nix b/pkgs/development/libraries/botan/generic.nix
index 823e50e32272..4a4ec5d9fe9c 100644
--- a/pkgs/development/libraries/botan/generic.nix
+++ b/pkgs/development/libraries/botan/generic.nix
@@ -2,6 +2,7 @@
 # Passed by version specific builders
 , baseVersion, revision, sha256
 , extraConfigureFlags ? ""
+, postPatch ? null
 , ...
 }:
 
@@ -17,6 +18,7 @@ stdenv.mkDerivation rec {
     ];
     inherit sha256;
   };
+  inherit postPatch;
 
   buildInputs = [ python bzip2 zlib gmp openssl boost ];
 
diff --git a/pkgs/development/libraries/botan/unstable.nix b/pkgs/development/libraries/botan/unstable.nix
index dd185f21035d..d952b50aeb8e 100644
--- a/pkgs/development/libraries/botan/unstable.nix
+++ b/pkgs/development/libraries/botan/unstable.nix
@@ -5,4 +5,5 @@ callPackage ./generic.nix (args // {
   revision = "29";
   sha256 = "157bp8716h17agrxyj7xpsj2i5sqhafj1nfx4gpzccx7y2kyq176";
   openssl = null;
+  postPatch = "sed '1i#include <cmath>' -i src/tests/test_bigint.cpp";
 })
diff --git a/pkgs/development/libraries/expat/CVE-2015-1283-refix.patch b/pkgs/development/libraries/expat/CVE-2015-1283-refix.patch
deleted file mode 100644
index db9747ea0b38..000000000000
--- a/pkgs/development/libraries/expat/CVE-2015-1283-refix.patch
+++ /dev/null
@@ -1,37 +0,0 @@
-From 29a11774d8ebbafe8418b4a5ffb4cc1160b194a1 Mon Sep 17 00:00:00 2001
-From: Pascal Cuoq <cuoq@trust-in-soft.com>
-Date: Sun, 15 May 2016 09:05:46 +0200
-Subject: [PATCH] Avoid relying on undefined behavior in CVE-2015-1283 fix. It
- does not really work: https://godbolt.org/g/Zl8gdF
-
----
- expat/lib/xmlparse.c | 6 ++++--
- 1 file changed, 4 insertions(+), 2 deletions(-)
-
-diff --git a/lib/xmlparse.c b/lib/xmlparse.c
-index 13e080d..cdb12ef 100644
---- a/lib/xmlparse.c
-+++ b/lib/xmlparse.c
-@@ -1693,7 +1693,8 @@ XML_GetBuffer(XML_Parser parser, int len)
-   }
- 
-   if (len > bufferLim - bufferEnd) {
--    int neededSize = len + (int)(bufferEnd - bufferPtr);
-+    /* Do not invoke signed arithmetic overflow: */
-+    int neededSize = (int) ((unsigned)len + (unsigned)(bufferEnd - bufferPtr));
-     if (neededSize < 0) {
-       errorCode = XML_ERROR_NO_MEMORY;
-       return NULL;
-@@ -1725,7 +1726,8 @@ XML_GetBuffer(XML_Parser parser, int len)
-       if (bufferSize == 0)
-         bufferSize = INIT_BUFFER_SIZE;
-       do {
--        bufferSize *= 2;
-+        /* Do not invoke signed arithmetic overflow: */
-+        bufferSize = (int) (2U * (unsigned) bufferSize);
-       } while (bufferSize < neededSize && bufferSize > 0);
-       if (bufferSize <= 0) {
-         errorCode = XML_ERROR_NO_MEMORY;
--- 
-2.8.2
-
diff --git a/pkgs/development/libraries/expat/CVE-2016-0718-v2-2-1.patch b/pkgs/development/libraries/expat/CVE-2016-0718-v2-2-1.patch
deleted file mode 100644
index 92ff2682684e..000000000000
--- a/pkgs/development/libraries/expat/CVE-2016-0718-v2-2-1.patch
+++ /dev/null
@@ -1,755 +0,0 @@
-From cdfcb1b5c95e93b00ae9e9d25708b4a3bee72c15 Mon Sep 17 00:00:00 2001
-From: Sebastian Pipping <sebastian@pipping.org>
-Date: Mon, 2 May 2016 00:02:44 +0200
-Subject: [PATCH] Address CVE-2016-0718 (/patch/ version 2.2.1)
-
-* Out of bounds memory access when doing text conversion on malformed input
-* Integer overflow related to memory allocation
-
-Reported by Gustavo Grieco
-
-Patch credits go to
-* Christian Heimes
-* Karl Waclawek
-* Gustavo Grieco
-* Sebastian Pipping
-* Pascal Cuoq
----
- expat/lib/xmlparse.c    |  34 +++++++++-----
- expat/lib/xmltok.c      | 115 +++++++++++++++++++++++++++++++++++-------------
- expat/lib/xmltok.h      |  10 ++++-
- expat/lib/xmltok_impl.c |  62 +++++++++++++-------------
- 4 files changed, 146 insertions(+), 75 deletions(-)
-
-diff --git a/lib/xmlparse.c b/lib/xmlparse.c
-index e308c79..13e080d 100644
---- a/lib/xmlparse.c
-+++ b/lib/xmlparse.c
-@@ -2426,11 +2426,11 @@ doContent(XML_Parser parser,
-           for (;;) {
-             int bufSize;
-             int convLen;
--            XmlConvert(enc,
-+            const enum XML_Convert_Result convert_res = XmlConvert(enc,
-                        &fromPtr, rawNameEnd,
-                        (ICHAR **)&toPtr, (ICHAR *)tag->bufEnd - 1);
-             convLen = (int)(toPtr - (XML_Char *)tag->buf);
--            if (fromPtr == rawNameEnd) {
-+            if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE)) {
-               tag->name.strLen = convLen;
-               break;
-             }
-@@ -2651,11 +2651,11 @@ doContent(XML_Parser parser,
-           if (MUST_CONVERT(enc, s)) {
-             for (;;) {
-               ICHAR *dataPtr = (ICHAR *)dataBuf;
--              XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)dataBufEnd);
-+              const enum XML_Convert_Result convert_res = XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)dataBufEnd);
-               *eventEndPP = s;
-               charDataHandler(handlerArg, dataBuf,
-                               (int)(dataPtr - (ICHAR *)dataBuf));
--              if (s == next)
-+              if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
-                 break;
-               *eventPP = s;
-             }
-@@ -3261,11 +3261,11 @@ doCdataSection(XML_Parser parser,
-           if (MUST_CONVERT(enc, s)) {
-             for (;;) {
-               ICHAR *dataPtr = (ICHAR *)dataBuf;
--              XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)dataBufEnd);
-+              const enum XML_Convert_Result convert_res = XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)dataBufEnd);
-               *eventEndPP = next;
-               charDataHandler(handlerArg, dataBuf,
-                               (int)(dataPtr - (ICHAR *)dataBuf));
--              if (s == next)
-+              if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
-                 break;
-               *eventPP = s;
-             }
-@@ -5342,6 +5342,7 @@ reportDefault(XML_Parser parser, const ENCODING *enc,
-               const char *s, const char *end)
- {
-   if (MUST_CONVERT(enc, s)) {
-+    enum XML_Convert_Result convert_res;
-     const char **eventPP;
-     const char **eventEndPP;
-     if (enc == encoding) {
-@@ -5354,11 +5355,11 @@ reportDefault(XML_Parser parser, const ENCODING *enc,
-     }
-     do {
-       ICHAR *dataPtr = (ICHAR *)dataBuf;
--      XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)dataBufEnd);
-+      convert_res = XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)dataBufEnd);
-       *eventEndPP = s;
-       defaultHandler(handlerArg, dataBuf, (int)(dataPtr - (ICHAR *)dataBuf));
-       *eventPP = s;
--    } while (s != end);
-+    } while ((convert_res != XML_CONVERT_COMPLETED) && (convert_res != XML_CONVERT_INPUT_INCOMPLETE));
-   }
-   else
-     defaultHandler(handlerArg, (XML_Char *)s, (int)((XML_Char *)end - (XML_Char *)s));
-@@ -6163,8 +6164,8 @@ poolAppend(STRING_POOL *pool, const ENCODING *enc,
-   if (!pool->ptr && !poolGrow(pool))
-     return NULL;
-   for (;;) {
--    XmlConvert(enc, &ptr, end, (ICHAR **)&(pool->ptr), (ICHAR *)pool->end);
--    if (ptr == end)
-+    const enum XML_Convert_Result convert_res = XmlConvert(enc, &ptr, end, (ICHAR **)&(pool->ptr), (ICHAR *)pool->end);
-+    if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
-       break;
-     if (!poolGrow(pool))
-       return NULL;
-@@ -6248,8 +6249,13 @@ poolGrow(STRING_POOL *pool)
-     }
-   }
-   if (pool->blocks && pool->start == pool->blocks->s) {
--    int blockSize = (int)(pool->end - pool->start)*2;
--    BLOCK *temp = (BLOCK *)
-+    BLOCK *temp;
-+    int blockSize = (int)((unsigned)(pool->end - pool->start)*2U);
-+
-+    if (blockSize < 0)
-+      return XML_FALSE;
-+
-+    temp = (BLOCK *)
-       pool->mem->realloc_fcn(pool->blocks,
-                              (offsetof(BLOCK, s)
-                               + blockSize * sizeof(XML_Char)));
-@@ -6264,6 +6270,10 @@ poolGrow(STRING_POOL *pool)
-   else {
-     BLOCK *tem;
-     int blockSize = (int)(pool->end - pool->start);
-+
-+    if (blockSize < 0)
-+      return XML_FALSE;
-+
-     if (blockSize < INIT_BLOCK_SIZE)
-       blockSize = INIT_BLOCK_SIZE;
-     else
-diff --git a/lib/xmltok.c b/lib/xmltok.c
-index bf09dfc..cb98ce1 100644
---- a/lib/xmltok.c
-+++ b/lib/xmltok.c
-@@ -318,39 +318,55 @@ enum {  /* UTF8_cvalN is value of masked first byte of N byte sequence */
-   UTF8_cval4 = 0xf0
- };
- 
--static void PTRCALL
-+static enum XML_Convert_Result PTRCALL
- utf8_toUtf8(const ENCODING *enc,
-             const char **fromP, const char *fromLim,
-             char **toP, const char *toLim)
- {
-+  enum XML_Convert_Result res = XML_CONVERT_COMPLETED;
-   char *to;
-   const char *from;
-   if (fromLim - *fromP > toLim - *toP) {
-     /* Avoid copying partial characters. */
-+    res = XML_CONVERT_OUTPUT_EXHAUSTED;
-     for (fromLim = *fromP + (toLim - *toP); fromLim > *fromP; fromLim--)
-       if (((unsigned char)fromLim[-1] & 0xc0) != 0x80)
-         break;
-   }
--  for (to = *toP, from = *fromP; from != fromLim; from++, to++)
-+  for (to = *toP, from = *fromP; (from < fromLim) && (to < toLim); from++, to++)
-     *to = *from;
-   *fromP = from;
-   *toP = to;
-+
-+  if ((to == toLim) && (from < fromLim))
-+    return XML_CONVERT_OUTPUT_EXHAUSTED;
-+  else
-+    return res;
- }
- 
--static void PTRCALL
-+static enum XML_Convert_Result PTRCALL
- utf8_toUtf16(const ENCODING *enc,
-              const char **fromP, const char *fromLim,
-              unsigned short **toP, const unsigned short *toLim)
- {
-+  enum XML_Convert_Result res = XML_CONVERT_COMPLETED;
-   unsigned short *to = *toP;
-   const char *from = *fromP;
--  while (from != fromLim && to != toLim) {
-+  while (from < fromLim && to < toLim) {
-     switch (((struct normal_encoding *)enc)->type[(unsigned char)*from]) {
-     case BT_LEAD2:
-+      if (fromLim - from < 2) {
-+        res = XML_CONVERT_INPUT_INCOMPLETE;
-+        break;
-+      }
-       *to++ = (unsigned short)(((from[0] & 0x1f) << 6) | (from[1] & 0x3f));
-       from += 2;
-       break;
-     case BT_LEAD3:
-+      if (fromLim - from < 3) {
-+        res = XML_CONVERT_INPUT_INCOMPLETE;
-+        break;
-+      }
-       *to++ = (unsigned short)(((from[0] & 0xf) << 12)
-                                | ((from[1] & 0x3f) << 6) | (from[2] & 0x3f));
-       from += 3;
-@@ -358,8 +374,14 @@ utf8_toUtf16(const ENCODING *enc,
-     case BT_LEAD4:
-       {
-         unsigned long n;
--        if (to + 1 == toLim)
-+        if (toLim - to < 2) {
-+          res = XML_CONVERT_OUTPUT_EXHAUSTED;
-           goto after;
-+        }
-+        if (fromLim - from < 4) {
-+          res = XML_CONVERT_INPUT_INCOMPLETE;
-+          goto after;
-+        }
-         n = ((from[0] & 0x7) << 18) | ((from[1] & 0x3f) << 12)
-             | ((from[2] & 0x3f) << 6) | (from[3] & 0x3f);
-         n -= 0x10000;
-@@ -377,6 +399,7 @@ utf8_toUtf16(const ENCODING *enc,
- after:
-   *fromP = from;
-   *toP = to;
-+  return res;
- }
- 
- #ifdef XML_NS
-@@ -425,7 +448,7 @@ static const struct normal_encoding internal_utf8_encoding = {
-   STANDARD_VTABLE(sb_) NORMAL_VTABLE(utf8_)
- };
- 
--static void PTRCALL
-+static enum XML_Convert_Result PTRCALL
- latin1_toUtf8(const ENCODING *enc,
-               const char **fromP, const char *fromLim,
-               char **toP, const char *toLim)
-@@ -433,30 +456,35 @@ latin1_toUtf8(const ENCODING *enc,
-   for (;;) {
-     unsigned char c;
-     if (*fromP == fromLim)
--      break;
-+      return XML_CONVERT_COMPLETED;
-     c = (unsigned char)**fromP;
-     if (c & 0x80) {
-       if (toLim - *toP < 2)
--        break;
-+        return XML_CONVERT_OUTPUT_EXHAUSTED;
-       *(*toP)++ = (char)((c >> 6) | UTF8_cval2);
-       *(*toP)++ = (char)((c & 0x3f) | 0x80);
-       (*fromP)++;
-     }
-     else {
-       if (*toP == toLim)
--        break;
-+        return XML_CONVERT_OUTPUT_EXHAUSTED;
-       *(*toP)++ = *(*fromP)++;
-     }
-   }
- }
- 
--static void PTRCALL
-+static enum XML_Convert_Result PTRCALL
- latin1_toUtf16(const ENCODING *enc,
-                const char **fromP, const char *fromLim,
-                unsigned short **toP, const unsigned short *toLim)
- {
--  while (*fromP != fromLim && *toP != toLim)
-+  while (*fromP < fromLim && *toP < toLim)
-     *(*toP)++ = (unsigned char)*(*fromP)++;
-+
-+  if ((*toP == toLim) && (*fromP < fromLim))
-+    return XML_CONVERT_OUTPUT_EXHAUSTED;
-+  else
-+    return XML_CONVERT_COMPLETED;
- }
- 
- #ifdef XML_NS
-@@ -483,13 +511,18 @@ static const struct normal_encoding latin1_encoding = {
-   STANDARD_VTABLE(sb_)
- };
- 
--static void PTRCALL
-+static enum XML_Convert_Result PTRCALL
- ascii_toUtf8(const ENCODING *enc,
-              const char **fromP, const char *fromLim,
-              char **toP, const char *toLim)
- {
--  while (*fromP != fromLim && *toP != toLim)
-+  while (*fromP < fromLim && *toP < toLim)
-     *(*toP)++ = *(*fromP)++;
-+
-+  if ((*toP == toLim) && (*fromP < fromLim))
-+    return XML_CONVERT_OUTPUT_EXHAUSTED;
-+  else
-+    return XML_CONVERT_COMPLETED;
- }
- 
- #ifdef XML_NS
-@@ -536,13 +569,14 @@ unicode_byte_type(char hi, char lo)
- }
- 
- #define DEFINE_UTF16_TO_UTF8(E) \
--static void  PTRCALL \
-+static enum XML_Convert_Result  PTRCALL \
- E ## toUtf8(const ENCODING *enc, \
-             const char **fromP, const char *fromLim, \
-             char **toP, const char *toLim) \
- { \
--  const char *from; \
--  for (from = *fromP; from != fromLim; from += 2) { \
-+  const char *from = *fromP; \
-+  fromLim = from + (((fromLim - from) >> 1) << 1);  /* shrink to even */ \
-+  for (; from < fromLim; from += 2) { \
-     int plane; \
-     unsigned char lo2; \
-     unsigned char lo = GET_LO(from); \
-@@ -552,7 +586,7 @@ E ## toUtf8(const ENCODING *enc, \
-       if (lo < 0x80) { \
-         if (*toP == toLim) { \
-           *fromP = from; \
--          return; \
-+          return XML_CONVERT_OUTPUT_EXHAUSTED; \
-         } \
-         *(*toP)++ = lo; \
-         break; \
-@@ -562,7 +596,7 @@ E ## toUtf8(const ENCODING *enc, \
-     case 0x4: case 0x5: case 0x6: case 0x7: \
-       if (toLim -  *toP < 2) { \
-         *fromP = from; \
--        return; \
-+        return XML_CONVERT_OUTPUT_EXHAUSTED; \
-       } \
-       *(*toP)++ = ((lo >> 6) | (hi << 2) |  UTF8_cval2); \
-       *(*toP)++ = ((lo & 0x3f) | 0x80); \
-@@ -570,7 +604,7 @@ E ## toUtf8(const ENCODING *enc, \
-     default: \
-       if (toLim -  *toP < 3)  { \
-         *fromP = from; \
--        return; \
-+        return XML_CONVERT_OUTPUT_EXHAUSTED; \
-       } \
-       /* 16 bits divided 4, 6, 6 amongst 3 bytes */ \
-       *(*toP)++ = ((hi >> 4) | UTF8_cval3); \
-@@ -580,7 +614,11 @@ E ## toUtf8(const ENCODING *enc, \
-     case 0xD8: case 0xD9: case 0xDA: case 0xDB: \
-       if (toLim -  *toP < 4) { \
-         *fromP = from; \
--        return; \
-+        return XML_CONVERT_OUTPUT_EXHAUSTED; \
-+      } \
-+      if (fromLim - from < 4) { \
-+        *fromP = from; \
-+        return XML_CONVERT_INPUT_INCOMPLETE; \
-       } \
-       plane = (((hi & 0x3) << 2) | ((lo >> 6) & 0x3)) + 1; \
-       *(*toP)++ = ((plane >> 2) | UTF8_cval4); \
-@@ -596,20 +634,32 @@ E ## toUtf8(const ENCODING *enc, \
-     } \
-   } \
-   *fromP = from; \
-+  if (from < fromLim) \
-+    return XML_CONVERT_INPUT_INCOMPLETE; \
-+  else \
-+    return XML_CONVERT_COMPLETED; \
- }
- 
- #define DEFINE_UTF16_TO_UTF16(E) \
--static void  PTRCALL \
-+static enum XML_Convert_Result  PTRCALL \
- E ## toUtf16(const ENCODING *enc, \
-              const char **fromP, const char *fromLim, \
-              unsigned short **toP, const unsigned short *toLim) \
- { \
-+  enum XML_Convert_Result res = XML_CONVERT_COMPLETED; \
-+  fromLim = *fromP + (((fromLim - *fromP) >> 1) << 1);  /* shrink to even */ \
-   /* Avoid copying first half only of surrogate */ \
-   if (fromLim - *fromP > ((toLim - *toP) << 1) \
--      && (GET_HI(fromLim - 2) & 0xF8) == 0xD8) \
-+      && (GET_HI(fromLim - 2) & 0xF8) == 0xD8) { \
-     fromLim -= 2; \
--  for (; *fromP != fromLim && *toP != toLim; *fromP += 2) \
-+    res = XML_CONVERT_INPUT_INCOMPLETE; \
-+  } \
-+  for (; *fromP < fromLim && *toP < toLim; *fromP += 2) \
-     *(*toP)++ = (GET_HI(*fromP) << 8) | GET_LO(*fromP); \
-+  if ((*toP == toLim) && (*fromP < fromLim)) \
-+    return XML_CONVERT_OUTPUT_EXHAUSTED; \
-+  else \
-+    return res; \
- }
- 
- #define SET2(ptr, ch) \
-@@ -1288,7 +1338,7 @@ unknown_isInvalid(const ENCODING *enc, const char *p)
-   return (c & ~0xFFFF) || checkCharRefNumber(c) < 0;
- }
- 
--static void PTRCALL
-+static enum XML_Convert_Result PTRCALL
- unknown_toUtf8(const ENCODING *enc,
-                const char **fromP, const char *fromLim,
-                char **toP, const char *toLim)
-@@ -1299,21 +1349,21 @@ unknown_toUtf8(const ENCODING *enc,
-     const char *utf8;
-     int n;
-     if (*fromP == fromLim)
--      break;
-+      return XML_CONVERT_COMPLETED;
-     utf8 = uenc->utf8[(unsigned char)**fromP];
-     n = *utf8++;
-     if (n == 0) {
-       int c = uenc->convert(uenc->userData, *fromP);
-       n = XmlUtf8Encode(c, buf);
-       if (n > toLim - *toP)
--        break;
-+        return XML_CONVERT_OUTPUT_EXHAUSTED;
-       utf8 = buf;
-       *fromP += (AS_NORMAL_ENCODING(enc)->type[(unsigned char)**fromP]
-                  - (BT_LEAD2 - 2));
-     }
-     else {
-       if (n > toLim - *toP)
--        break;
-+        return XML_CONVERT_OUTPUT_EXHAUSTED;
-       (*fromP)++;
-     }
-     do {
-@@ -1322,13 +1372,13 @@ unknown_toUtf8(const ENCODING *enc,
-   }
- }
- 
--static void PTRCALL
-+static enum XML_Convert_Result PTRCALL
- unknown_toUtf16(const ENCODING *enc,
-                 const char **fromP, const char *fromLim,
-                 unsigned short **toP, const unsigned short *toLim)
- {
-   const struct unknown_encoding *uenc = AS_UNKNOWN_ENCODING(enc);
--  while (*fromP != fromLim && *toP != toLim) {
-+  while (*fromP < fromLim && *toP < toLim) {
-     unsigned short c = uenc->utf16[(unsigned char)**fromP];
-     if (c == 0) {
-       c = (unsigned short)
-@@ -1340,6 +1390,11 @@ unknown_toUtf16(const ENCODING *enc,
-       (*fromP)++;
-     *(*toP)++ = c;
-   }
-+
-+  if ((*toP == toLim) && (*fromP < fromLim))
-+    return XML_CONVERT_OUTPUT_EXHAUSTED;
-+  else
-+    return XML_CONVERT_COMPLETED;
- }
- 
- ENCODING *
-@@ -1503,7 +1558,7 @@ initScan(const ENCODING * const *encodingTable,
- {
-   const ENCODING **encPtr;
- 
--  if (ptr == end)
-+  if (ptr >= end)
-     return XML_TOK_NONE;
-   encPtr = enc->encPtr;
-   if (ptr + 1 == end) {
-diff --git a/lib/xmltok.h b/lib/xmltok.h
-index ca867aa..752007e 100644
---- a/lib/xmltok.h
-+++ b/lib/xmltok.h
-@@ -130,6 +130,12 @@ typedef int (PTRCALL *SCANNER)(const ENCODING *,
-                                const char *,
-                                const char **);
- 
-+enum XML_Convert_Result {
-+  XML_CONVERT_COMPLETED = 0,
-+  XML_CONVERT_INPUT_INCOMPLETE = 1,
-+  XML_CONVERT_OUTPUT_EXHAUSTED = 2  /* and therefore potentially input remaining as well */
-+};
-+
- struct encoding {
-   SCANNER scanners[XML_N_STATES];
-   SCANNER literalScanners[XML_N_LITERAL_TYPES];
-@@ -158,12 +164,12 @@ struct encoding {
-                             const char *ptr,
-                             const char *end,
-                             const char **badPtr);
--  void (PTRCALL *utf8Convert)(const ENCODING *enc,
-+  enum XML_Convert_Result (PTRCALL *utf8Convert)(const ENCODING *enc,
-                               const char **fromP,
-                               const char *fromLim,
-                               char **toP,
-                               const char *toLim);
--  void (PTRCALL *utf16Convert)(const ENCODING *enc,
-+  enum XML_Convert_Result (PTRCALL *utf16Convert)(const ENCODING *enc,
-                                const char **fromP,
-                                const char *fromLim,
-                                unsigned short **toP,
-diff --git a/lib/xmltok_impl.c b/lib/xmltok_impl.c
-index 9c2895b..6c5a3ba 100644
---- a/lib/xmltok_impl.c
-+++ b/lib/xmltok_impl.c
-@@ -93,13 +93,13 @@ static int PTRCALL
- PREFIX(scanComment)(const ENCODING *enc, const char *ptr,
-                     const char *end, const char **nextTokPtr)
- {
--  if (ptr != end) {
-+  if (ptr < end) {
-     if (!CHAR_MATCHES(enc, ptr, ASCII_MINUS)) {
-       *nextTokPtr = ptr;
-       return XML_TOK_INVALID;
-     }
-     ptr += MINBPC(enc);
--    while (ptr != end) {
-+    while (ptr < end) {
-       switch (BYTE_TYPE(enc, ptr)) {
-       INVALID_CASES(ptr, nextTokPtr)
-       case BT_MINUS:
-@@ -147,7 +147,7 @@ PREFIX(scanDecl)(const ENCODING *enc, const char *ptr,
-     *nextTokPtr = ptr;
-     return XML_TOK_INVALID;
-   }
--  while (ptr != end) {
-+  while (ptr < end) {
-     switch (BYTE_TYPE(enc, ptr)) {
-     case BT_PERCNT:
-       if (ptr + MINBPC(enc) == end)
-@@ -233,7 +233,7 @@ PREFIX(scanPi)(const ENCODING *enc, const char *ptr,
-     *nextTokPtr = ptr;
-     return XML_TOK_INVALID;
-   }
--  while (ptr != end) {
-+  while (ptr < end) {
-     switch (BYTE_TYPE(enc, ptr)) {
-     CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
-     case BT_S: case BT_CR: case BT_LF:
-@@ -242,7 +242,7 @@ PREFIX(scanPi)(const ENCODING *enc, const char *ptr,
-         return XML_TOK_INVALID;
-       }
-       ptr += MINBPC(enc);
--      while (ptr != end) {
-+      while (ptr < end) {
-         switch (BYTE_TYPE(enc, ptr)) {
-         INVALID_CASES(ptr, nextTokPtr)
-         case BT_QUEST:
-@@ -305,7 +305,7 @@ static int PTRCALL
- PREFIX(cdataSectionTok)(const ENCODING *enc, const char *ptr,
-                         const char *end, const char **nextTokPtr)
- {
--  if (ptr == end)
-+  if (ptr >= end)
-     return XML_TOK_NONE;
-   if (MINBPC(enc) > 1) {
-     size_t n = end - ptr;
-@@ -348,7 +348,7 @@ PREFIX(cdataSectionTok)(const ENCODING *enc, const char *ptr,
-     ptr += MINBPC(enc);
-     break;
-   }
--  while (ptr != end) {
-+  while (ptr < end) {
-     switch (BYTE_TYPE(enc, ptr)) {
- #define LEAD_CASE(n) \
-     case BT_LEAD ## n: \
-@@ -391,11 +391,11 @@ PREFIX(scanEndTag)(const ENCODING *enc, const char *ptr,
-     *nextTokPtr = ptr;
-     return XML_TOK_INVALID;
-   }
--  while (ptr != end) {
-+  while (ptr < end) {
-     switch (BYTE_TYPE(enc, ptr)) {
-     CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
-     case BT_S: case BT_CR: case BT_LF:
--      for (ptr += MINBPC(enc); ptr != end; ptr += MINBPC(enc)) {
-+      for (ptr += MINBPC(enc); ptr < end; ptr += MINBPC(enc)) {
-         switch (BYTE_TYPE(enc, ptr)) {
-         case BT_S: case BT_CR: case BT_LF:
-           break;
-@@ -432,7 +432,7 @@ static int PTRCALL
- PREFIX(scanHexCharRef)(const ENCODING *enc, const char *ptr,
-                        const char *end, const char **nextTokPtr)
- {
--  if (ptr != end) {
-+  if (ptr < end) {
-     switch (BYTE_TYPE(enc, ptr)) {
-     case BT_DIGIT:
-     case BT_HEX:
-@@ -441,7 +441,7 @@ PREFIX(scanHexCharRef)(const ENCODING *enc, const char *ptr,
-       *nextTokPtr = ptr;
-       return XML_TOK_INVALID;
-     }
--    for (ptr += MINBPC(enc); ptr != end; ptr += MINBPC(enc)) {
-+    for (ptr += MINBPC(enc); ptr < end; ptr += MINBPC(enc)) {
-       switch (BYTE_TYPE(enc, ptr)) {
-       case BT_DIGIT:
-       case BT_HEX:
-@@ -464,7 +464,7 @@ static int PTRCALL
- PREFIX(scanCharRef)(const ENCODING *enc, const char *ptr,
-                     const char *end, const char **nextTokPtr)
- {
--  if (ptr != end) {
-+  if (ptr < end) {
-     if (CHAR_MATCHES(enc, ptr, ASCII_x))
-       return PREFIX(scanHexCharRef)(enc, ptr + MINBPC(enc), end, nextTokPtr);
-     switch (BYTE_TYPE(enc, ptr)) {
-@@ -474,7 +474,7 @@ PREFIX(scanCharRef)(const ENCODING *enc, const char *ptr,
-       *nextTokPtr = ptr;
-       return XML_TOK_INVALID;
-     }
--    for (ptr += MINBPC(enc); ptr != end; ptr += MINBPC(enc)) {
-+    for (ptr += MINBPC(enc); ptr < end; ptr += MINBPC(enc)) {
-       switch (BYTE_TYPE(enc, ptr)) {
-       case BT_DIGIT:
-         break;
-@@ -506,7 +506,7 @@ PREFIX(scanRef)(const ENCODING *enc, const char *ptr, const char *end,
-     *nextTokPtr = ptr;
-     return XML_TOK_INVALID;
-   }
--  while (ptr != end) {
-+  while (ptr < end) {
-     switch (BYTE_TYPE(enc, ptr)) {
-     CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
-     case BT_SEMI:
-@@ -529,7 +529,7 @@ PREFIX(scanAtts)(const ENCODING *enc, const char *ptr, const char *end,
- #ifdef XML_NS
-   int hadColon = 0;
- #endif
--  while (ptr != end) {
-+  while (ptr < end) {
-     switch (BYTE_TYPE(enc, ptr)) {
-     CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
- #ifdef XML_NS
-@@ -716,7 +716,7 @@ PREFIX(scanLt)(const ENCODING *enc, const char *ptr, const char *end,
-   hadColon = 0;
- #endif
-   /* we have a start-tag */
--  while (ptr != end) {
-+  while (ptr < end) {
-     switch (BYTE_TYPE(enc, ptr)) {
-     CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
- #ifdef XML_NS
-@@ -740,7 +740,7 @@ PREFIX(scanLt)(const ENCODING *enc, const char *ptr, const char *end,
-     case BT_S: case BT_CR: case BT_LF:
-       {
-         ptr += MINBPC(enc);
--        while (ptr != end) {
-+        while (ptr < end) {
-           switch (BYTE_TYPE(enc, ptr)) {
-           CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr)
-           case BT_GT:
-@@ -785,7 +785,7 @@ static int PTRCALL
- PREFIX(contentTok)(const ENCODING *enc, const char *ptr, const char *end,
-                    const char **nextTokPtr)
- {
--  if (ptr == end)
-+  if (ptr >= end)
-     return XML_TOK_NONE;
-   if (MINBPC(enc) > 1) {
-     size_t n = end - ptr;
-@@ -832,7 +832,7 @@ PREFIX(contentTok)(const ENCODING *enc, const char *ptr, const char *end,
-     ptr += MINBPC(enc);
-     break;
-   }
--  while (ptr != end) {
-+  while (ptr < end) {
-     switch (BYTE_TYPE(enc, ptr)) {
- #define LEAD_CASE(n) \
-     case BT_LEAD ## n: \
-@@ -895,7 +895,7 @@ PREFIX(scanPercent)(const ENCODING *enc, const char *ptr, const char *end,
-     *nextTokPtr = ptr;
-     return XML_TOK_INVALID;
-   }
--  while (ptr != end) {
-+  while (ptr < end) {
-     switch (BYTE_TYPE(enc, ptr)) {
-     CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
-     case BT_SEMI:
-@@ -921,7 +921,7 @@ PREFIX(scanPoundName)(const ENCODING *enc, const char *ptr, const char *end,
-     *nextTokPtr = ptr;
-     return XML_TOK_INVALID;
-   }
--  while (ptr != end) {
-+  while (ptr < end) {
-     switch (BYTE_TYPE(enc, ptr)) {
-     CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
-     case BT_CR: case BT_LF: case BT_S:
-@@ -941,7 +941,7 @@ PREFIX(scanLit)(int open, const ENCODING *enc,
-                 const char *ptr, const char *end,
-                 const char **nextTokPtr)
- {
--  while (ptr != end) {
-+  while (ptr < end) {
-     int t = BYTE_TYPE(enc, ptr);
-     switch (t) {
-     INVALID_CASES(ptr, nextTokPtr)
-@@ -973,7 +973,7 @@ PREFIX(prologTok)(const ENCODING *enc, const char *ptr, const char *end,
-                   const char **nextTokPtr)
- {
-   int tok;
--  if (ptr == end)
-+  if (ptr >= end)
-     return XML_TOK_NONE;
-   if (MINBPC(enc) > 1) {
-     size_t n = end - ptr;
-@@ -1141,7 +1141,7 @@ PREFIX(prologTok)(const ENCODING *enc, const char *ptr, const char *end,
-     *nextTokPtr = ptr;
-     return XML_TOK_INVALID;
-   }
--  while (ptr != end) {
-+  while (ptr < end) {
-     switch (BYTE_TYPE(enc, ptr)) {
-     CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
-     case BT_GT: case BT_RPAR: case BT_COMMA:
-@@ -1204,10 +1204,10 @@ PREFIX(attributeValueTok)(const ENCODING *enc, const char *ptr,
-                           const char *end, const char **nextTokPtr)
- {
-   const char *start;
--  if (ptr == end)
-+  if (ptr >= end)
-     return XML_TOK_NONE;
-   start = ptr;
--  while (ptr != end) {
-+  while (ptr < end) {
-     switch (BYTE_TYPE(enc, ptr)) {
- #define LEAD_CASE(n) \
-     case BT_LEAD ## n: ptr += n; break;
-@@ -1262,10 +1262,10 @@ PREFIX(entityValueTok)(const ENCODING *enc, const char *ptr,
-                        const char *end, const char **nextTokPtr)
- {
-   const char *start;
--  if (ptr == end)
-+  if (ptr >= end)
-     return XML_TOK_NONE;
-   start = ptr;
--  while (ptr != end) {
-+  while (ptr < end) {
-     switch (BYTE_TYPE(enc, ptr)) {
- #define LEAD_CASE(n) \
-     case BT_LEAD ## n: ptr += n; break;
-@@ -1326,7 +1326,7 @@ PREFIX(ignoreSectionTok)(const ENCODING *enc, const char *ptr,
-       end = ptr + n;
-     }
-   }
--  while (ptr != end) {
-+  while (ptr < end) {
-     switch (BYTE_TYPE(enc, ptr)) {
-     INVALID_CASES(ptr, nextTokPtr)
-     case BT_LT:
-@@ -1373,7 +1373,7 @@ PREFIX(isPublicId)(const ENCODING *enc, const char *ptr, const char *end,
- {
-   ptr += MINBPC(enc);
-   end -= MINBPC(enc);
--  for (; ptr != end; ptr += MINBPC(enc)) {
-+  for (; ptr < end; ptr += MINBPC(enc)) {
-     switch (BYTE_TYPE(enc, ptr)) {
-     case BT_DIGIT:
-     case BT_HEX:
-@@ -1760,7 +1760,7 @@ PREFIX(updatePosition)(const ENCODING *enc,
-     case BT_CR:
-       pos->lineNumber++;
-       ptr += MINBPC(enc);
--      if (ptr != end && BYTE_TYPE(enc, ptr) == BT_LF)
-+      if (ptr < end && BYTE_TYPE(enc, ptr) == BT_LF)
-         ptr += MINBPC(enc);
-       pos->columnNumber = (XML_Size)-1;
-       break;
--- 
-2.8.2
-
diff --git a/pkgs/development/libraries/expat/default.nix b/pkgs/development/libraries/expat/default.nix
index 1b663fc21a9e..be5772798b4c 100644
--- a/pkgs/development/libraries/expat/default.nix
+++ b/pkgs/development/libraries/expat/default.nix
@@ -1,11 +1,11 @@
 { stdenv, fetchurl }:
 
 stdenv.mkDerivation rec {
-  name = "expat-2.1.1";
+  name = "expat-2.2.0";
 
   src = fetchurl {
     url = "mirror://sourceforge/expat/${name}.tar.bz2";
-    sha256 = "0ryyjgvy7jq0qb7a9mhc1giy3bzn56aiwrs8dpydqngplbjq9xdg";
+    sha256 = "1zq4lnwjlw8s9mmachwfvfjf2x3lk24jm41746ykhdcvs7r0zrfr";
   };
 
   outputs = [ "dev" "out" ]; # TODO: fix referrers
@@ -15,8 +15,6 @@ stdenv.mkDerivation rec {
 
   outputMan = "dev"; # tiny page for a dev tool
 
-  patches = [ ./CVE-2015-1283-refix.patch ./CVE-2016-0718-v2-2-1.patch ];
-
   doCheck = true;
 
   meta = with stdenv.lib; {
diff --git a/pkgs/development/libraries/gettext/default.nix b/pkgs/development/libraries/gettext/default.nix
index 78a8756b59b4..63eb086b0fb1 100644
--- a/pkgs/development/libraries/gettext/default.nix
+++ b/pkgs/development/libraries/gettext/default.nix
@@ -50,7 +50,7 @@ stdenv.mkDerivation rec {
     sed -i -e "s/\(am_libgettextlib_la_OBJECTS = \)error.lo/\\1/" gettext-tools/gnulib-lib/Makefile.in
   '';
 
-  buildInputs = [ xz xz.bin libiconv ];
+  nativeBuildInputs = [ xz xz.bin ] ++ stdenv.lib.optional (!stdenv.isLinux) libiconv; # HACK, see #10874 (and 14664)
 
   enableParallelBuilding = true;
 
diff --git a/pkgs/development/libraries/glibc/builder.sh b/pkgs/development/libraries/glibc/builder.sh
deleted file mode 100644
index 85f27c7b3559..000000000000
--- a/pkgs/development/libraries/glibc/builder.sh
+++ /dev/null
@@ -1,58 +0,0 @@
-# Glibc cannot have itself in its RPATH.
-export NIX_NO_SELF_RPATH=1
-
-source $stdenv/setup
-
-postConfigure() {
-    # Hack: get rid of the `-static' flag set by the bootstrap stdenv.
-    # This has to be done *after* `configure' because it builds some
-    # test binaries.
-    export NIX_CFLAGS_LINK=
-    export NIX_LDFLAGS_BEFORE=
-
-    export NIX_DONT_SET_RPATH=1
-    unset CFLAGS
-
-    # Apparently --bindir is not respected.
-    makeFlagsArray+=("bindir=$bin/bin" "sbindir=$bin/sbin" "rootsbindir=$bin/sbin")
-}
-
-postInstall() {
-    if test -n "$installLocales"; then
-        make -j${NIX_BUILD_CORES:-1} -l${NIX_BUILD_CORES:-1} localedata/install-locales
-    fi
-
-    test -f $out/etc/ld.so.cache && rm $out/etc/ld.so.cache
-
-    if test -n "$linuxHeaders"; then
-        # Include the Linux kernel headers in Glibc, except the `scsi'
-        # subdirectory, which Glibc provides itself.
-        (cd $dev/include && \
-         ln -sv $(ls -d $linuxHeaders/include/* | grep -v 'scsi$') .)
-    fi
-
-    # Fix for NIXOS-54 (ldd not working on x86_64).  Make a symlink
-    # "lib64" to "lib".
-    if test -n "$is64bit"; then
-        ln -s lib $out/lib64
-    fi
-
-    # Get rid of more unnecessary stuff.
-    rm -rf $out/var $out/sbin/sln
-
-    for i in $out/lib/*.a; do
-        strip -S "$i"
-    done
-    # Put libraries for static linking in a separate output.  Note
-    # that libc_nonshared.a and libpthread_nonshared.a are required
-    # for dynamically-linked applications.
-    mkdir -p $static/lib
-    mv $out/lib/*.a $static/lib
-    mv $static/lib/lib*_nonshared.a $out/lib
-
-    # Work around a Nix bug: hard links across outputs cause a build failure.
-    cp $bin/bin/getconf $bin/bin/getconf_
-    mv $bin/bin/getconf_ $bin/bin/getconf
-}
-
-genericBuild
diff --git a/pkgs/development/libraries/glibc/common.nix b/pkgs/development/libraries/glibc/common.nix
index a189edb9832d..e90fdc4ad7bd 100644
--- a/pkgs/development/libraries/glibc/common.nix
+++ b/pkgs/development/libraries/glibc/common.nix
@@ -54,6 +54,7 @@ stdenv.mkDerivation ({
       ./glob-simplify-interface.patch
       ./cve-2016-1234.patch
       ./cve-2016-3706.patch
+      ./fix_warnings.patch
     ];
 
   postPatch =
diff --git a/pkgs/development/libraries/glibc/default.nix b/pkgs/development/libraries/glibc/default.nix
index 80fc2ce1e93d..2a1652a55011 100644
--- a/pkgs/development/libraries/glibc/default.nix
+++ b/pkgs/development/libraries/glibc/default.nix
@@ -17,7 +17,21 @@ in
     inherit lib stdenv fetchurl linuxHeaders installLocales
       profilingLibraries gccCross withGd gd libpng;
 
-    builder = ./builder.sh;
+    NIX_NO_SELF_RPATH = true;
+
+    postConfigure = ''
+      # Hack: get rid of the `-static' flag set by the bootstrap stdenv.
+      # This has to be done *after* `configure' because it builds some
+      # test binaries.
+      export NIX_CFLAGS_LINK=
+      export NIX_LDFLAGS_BEFORE=
+
+      export NIX_DONT_SET_RPATH=1
+      unset CFLAGS
+
+      # Apparently --bindir is not respected.
+      makeFlagsArray+=("bindir=$bin/bin" "sbindir=$bin/sbin" "rootsbindir=$bin/sbin")
+    '';
 
     # When building glibc from bootstrap-tools, we need libgcc_s at RPATH for
     # any program we run, because the gcc will have been placed at a new
@@ -26,7 +40,7 @@ in
     # Building from a proper gcc staying in the path where it was installed,
     # libgcc_s will not be at {gcc}/lib, and gcc's libgcc will be found without
     # any special hack.
-    preInstall = if cross != null then "" else ''
+    preInstall = ''
       if [ -f ${stdenv.cc.cc}/lib/libgcc_s.so.1 ]; then
           mkdir -p $out/lib
           cp ${stdenv.cc.cc}/lib/libgcc_s.so.1 $out/lib/libgcc_s.so.1
@@ -35,6 +49,49 @@ in
       fi
     '';
 
+    postInstall = ''
+      if test -n "$installLocales"; then
+          make -j''${NIX_BUILD_CORES:-1} -l''${NIX_BUILD_CORES:-1} localedata/install-locales
+      fi
+
+      test -f $out/etc/ld.so.cache && rm $out/etc/ld.so.cache
+
+      if test -n "$linuxHeaders"; then
+          # Include the Linux kernel headers in Glibc, except the `scsi'
+          # subdirectory, which Glibc provides itself.
+          (cd $dev/include && \
+           ln -sv $(ls -d $linuxHeaders/include/* | grep -v scsi\$) .)
+      fi
+
+      # Fix for NIXOS-54 (ldd not working on x86_64).  Make a symlink
+      # "lib64" to "lib".
+      if test -n "$is64bit"; then
+          ln -s lib $out/lib64
+      fi
+
+      # Get rid of more unnecessary stuff.
+      rm -rf $out/var $out/sbin/sln
+
+      # For some reason these aren't stripped otherwise and retain reference
+      # to bootstrap-tools; on cross-arm this stripping would break objects.
+      if [ -z "$crossConfig" ]; then
+        for i in "$out"/lib/*.a; do
+            strip -S "$i"
+        done
+      fi
+
+      # Put libraries for static linking in a separate output.  Note
+      # that libc_nonshared.a and libpthread_nonshared.a are required
+      # for dynamically-linked applications.
+      mkdir -p $static/lib
+      mv $out/lib/*.a $static/lib
+      mv $static/lib/lib*_nonshared.a $out/lib
+
+      # Work around a Nix bug: hard links across outputs cause a build failure.
+      cp $bin/bin/getconf $bin/bin/getconf_
+      mv $bin/bin/getconf_ $bin/bin/getconf
+    '';
+
     separateDebugInfo = true;
 
     meta.description = "The GNU C Library";
@@ -62,6 +119,10 @@ in
         dontStrip=1
       '';
 
+      preInstall = null; # clobber the native hook
+
+      separateDebugInfo = false; # this is currently broken for crossDrv
+
       # To avoid a dependency on the build system 'bash'.
       preFixup = ''
         rm $bin/bin/{ldd,tzselect,catchsegv,xtrace}
diff --git a/pkgs/development/libraries/glibc/fix_warnings.patch b/pkgs/development/libraries/glibc/fix_warnings.patch
new file mode 100644
index 000000000000..fd75c18c84ec
--- /dev/null
+++ b/pkgs/development/libraries/glibc/fix_warnings.patch
@@ -0,0 +1,36 @@
+--- a/stdlib/setenv.c	2016-05-30 11:09:14.487180254 +0000
++++ b/stdlib/setenv.c	2016-05-30 11:08:25.560390748 +0000
+@@ -277,6 +277,7 @@
+ 
+   ep = __environ;
+   if (ep != NULL)
++    {
+     while (*ep != NULL)
+       if (!strncmp (*ep, name, len) && (*ep)[len] == '=')
+ 	{
+@@ -290,6 +291,7 @@
+ 	}
+       else
+ 	++ep;
++    }
+ 
+   UNLOCK;
+ 
+--- a/nis/nis_call.c	2016-05-30 08:05:59.359855696 -0700
++++ b/nis/nis_call.c	2016-05-30 08:05:55.679873221 -0700
+@@ -680,6 +680,7 @@
+   /* Choose which entry should be evicted from the cache.  */
+   loc = &nis_server_cache[0];
+   if (*loc != NULL)
++    {
+     for (i = 1; i < 16; ++i)
+       if (nis_server_cache[i] == NULL)
+ 	{
+@@ -690,6 +691,7 @@
+ 	       || ((*loc)->uses == nis_server_cache[i]->uses
+ 		   && (*loc)->expires > nis_server_cache[i]->expires))
+ 	loc = &nis_server_cache[i];
++    }
+   old = *loc;
+   *loc = new;
+ 
diff --git a/pkgs/development/libraries/gnutls/3.4.nix b/pkgs/development/libraries/gnutls/3.4.nix
index 71c3010467ce..4882e5dda043 100644
--- a/pkgs/development/libraries/gnutls/3.4.nix
+++ b/pkgs/development/libraries/gnutls/3.4.nix
@@ -1,11 +1,11 @@
 { callPackage, fetchurl, autoreconfHook, ... } @ args:
 
 callPackage ./generic.nix (args // rec {
-  version = "3.4.11";
+  version = "3.4.13";
 
   src = fetchurl {
     url = "ftp://ftp.gnutls.org/gcrypt/gnutls/v3.4/gnutls-${version}.tar.xz";
-    sha256 = "1f4sbb38xab46h67a3pm6kybgrahjx3vbrn66qq3cbc2jngrrvvh";
+    sha256 = "0naqs9g5b577j1j7q55ma1vcn78jl2d98h3zrl5rh997wzl8cczx";
   };
 
   # This fixes some broken parallel dependencies
diff --git a/pkgs/development/libraries/gnutls/3.5.nix b/pkgs/development/libraries/gnutls/3.5.nix
new file mode 100644
index 000000000000..82bd437d721b
--- /dev/null
+++ b/pkgs/development/libraries/gnutls/3.5.nix
@@ -0,0 +1,17 @@
+{ callPackage, fetchurl, autoreconfHook, ... } @ args:
+
+callPackage ./generic.nix (args // rec {
+  version = "3.5.1";
+
+  src = fetchurl {
+    url = "ftp://ftp.gnutls.org/gcrypt/gnutls/v3.5/gnutls-${version}.tar.xz";
+    sha256 = "1gdxr1p1sigigwvangqf3v31i8fda07d6ngawykarhr7ls00yjmw";
+  };
+
+  # This fixes some broken parallel dependencies
+  postPatch = ''
+    sed -i 's,^BUILT_SOURCES =,\0 systemkey-args.h,g' src/Makefile.am
+  '';
+
+  nativeBuildInputs = [ autoreconfHook ];
+})
diff --git a/pkgs/development/libraries/gnutls/generic.nix b/pkgs/development/libraries/gnutls/generic.nix
index b54ea52b880b..3af07f4c6f9f 100644
--- a/pkgs/development/libraries/gnutls/generic.nix
+++ b/pkgs/development/libraries/gnutls/generic.nix
@@ -1,6 +1,6 @@
 { lib, fetchurl, stdenv, zlib, lzo, libtasn1, nettle, pkgconfig, lzip
 , guileBindings, guile, perl, gmp, autogen, libidn, p11_kit, unbound, libiconv
-, tpmSupport ? false, trousers
+, tpmSupport ? false, trousers, nettools, bash
 
 # Version dependent args
 , version, src, patches ? [], postPatch ? "", nativeBuildInputs ? []
@@ -29,7 +29,7 @@ stdenv.mkDerivation {
   # for the actual fix.
   enableParallelBuilding = !guileBindings;
 
-  buildInputs = [ lzo lzip nettle libtasn1 libidn p11_kit zlib gmp autogen ]
+  buildInputs = [ lzo lzip nettle libtasn1 libidn p11_kit zlib gmp autogen nettools bash ]
     ++ lib.optional (stdenv.isFreeBSD || stdenv.isDarwin) libiconv
     ++ lib.optional (tpmSupport && stdenv.isLinux) trousers
     ++ [ unbound ]
@@ -37,6 +37,10 @@ stdenv.mkDerivation {
 
   nativeBuildInputs = [ perl pkgconfig ] ++ nativeBuildInputs;
 
+  patchPhase = ''
+    patchShebangs .
+    '';
+
   # XXX: Gnulib's `test-select' fails on FreeBSD:
   # http://hydra.nixos.org/build/2962084/nixlog/1/raw .
   doCheck = (!stdenv.isFreeBSD && !stdenv.isDarwin);
diff --git a/pkgs/development/libraries/kerberos/krb5.nix b/pkgs/development/libraries/kerberos/krb5.nix
index 332ca526b6ba..78644200e0b1 100644
--- a/pkgs/development/libraries/kerberos/krb5.nix
+++ b/pkgs/development/libraries/kerberos/krb5.nix
@@ -26,6 +26,8 @@ stdenv.mkDerivation rec {
   buildInputs = [ openssl ]
     ++ optionals (!libOnly) [ openldap libedit ];
 
+  patches = [ ./path_char_fix.patch ];
+
   preConfigure = "cd ./src";
 
   buildPhase = optionalString libOnly ''
diff --git a/pkgs/development/libraries/kerberos/path_char_fix.patch b/pkgs/development/libraries/kerberos/path_char_fix.patch
new file mode 100644
index 000000000000..2a6dc4c11c37
--- /dev/null
+++ b/pkgs/development/libraries/kerberos/path_char_fix.patch
@@ -0,0 +1,38 @@
+See https://github.com/krb5/krb5/pull/467
+diff --git a/src/include/Makefile.in b/src/include/Makefile.in
+index 4bb11e4..cb4b44b 100644
+--- a/src/include/Makefile.in
++++ b/src/include/Makefile.in
+@@ -57,19 +57,19 @@ SBINDIR = @sbindir@
+ LIBDIR  = @libdir@
+ SYSCONFCONF = @SYSCONFCONF@
+ 
+-PROCESS_REPLACE = -e "s+@KRB5RCTMPDIR+$(KRB5RCTMPDIR)+" \
+-		  -e "s+@PREFIX+$(INSTALL_PREFIX)+" \
+-		  -e "s+@EXEC_PREFIX+$(INSTALL_EXEC_PREFIX)+" \
+-		  -e "s+@BINDIR+$(BINDIR)+" \
+-		  -e "s+@LIBDIR+$(LIBDIR)+" \
+-		  -e "s+@SBINDIR+$(SBINDIR)+" \
+-		  -e "s+@MODULEDIR+$(MODULE_DIR)+" \
+-		  -e "s+@GSSMODULEDIR+$(GSS_MODULE_DIR)+" \
+-		  -e 's+@LOCALSTATEDIR+$(LOCALSTATEDIR)+' \
+-		  -e 's+@RUNSTATEDIR+$(RUNSTATEDIR)+' \
+-		  -e 's+@SYSCONFDIR+$(SYSCONFDIR)+' \
+-		  -e 's+@DYNOBJEXT+$(DYNOBJEXT)+' \
+-		  -e 's+@SYSCONFCONF+$(SYSCONFCONF)+'
++PROCESS_REPLACE = -e "s\"@KRB5RCTMPDIR\"$(KRB5RCTMPDIR)\"" \
++		  -e "s\"@PREFIX\"$(INSTALL_PREFIX)\"" \
++		  -e "s\"@EXEC_PREFIX\"$(INSTALL_EXEC_PREFIX)\"" \
++		  -e "s\"@BINDIR\"$(BINDIR)\"" \
++		  -e "s\"@LIBDIR\"$(LIBDIR)\"" \
++		  -e "s\"@SBINDIR\"$(SBINDIR)\"" \
++		  -e "s\"@MODULEDIR\"$(MODULE_DIR)\"" \
++		  -e "s\"@GSSMODULEDIR\"$(GSS_MODULE_DIR)\"" \
++		  -e "s\"@LOCALSTATEDIR\"$(LOCALSTATEDIR)\"" \
++		  -e "s\"@RUNSTATEDIR\"$(RUNSTATEDIR)\"" \
++		  -e "s\"@SYSCONFDIR\"$(SYSCONFDIR)\"" \
++		  -e "s\"@DYNOBJEXT\"$(DYNOBJEXT)\"" \
++		  -e "s\"@SYSCONFCONF\"$(SYSCONFCONF)\""
+ 
+ OSCONFSRC = $(srcdir)/osconf.hin
+ 
diff --git a/pkgs/development/libraries/libelf/default.nix b/pkgs/development/libraries/libelf/default.nix
index 623256bb6b7b..12588617d4a1 100644
--- a/pkgs/development/libraries/libelf/default.nix
+++ b/pkgs/development/libraries/libelf/default.nix
@@ -9,10 +9,10 @@ stdenv.mkDerivation rec {
   };
 
   doCheck = true;
-  
+
   # For cross-compiling, native glibc is needed for the "gencat" program.
   crossAttrs = {
-    nativeBuildInputs = [ glibc ];
+    nativeBuildInputs = [ gettext glibc ];
   };
 
   # Libelf's custom NLS macros fail to determine the catalog file extension on
@@ -20,7 +20,7 @@ stdenv.mkDerivation rec {
   # FIXME: Eventually make Gettext a build input on all platforms.
   configureFlags = stdenv.lib.optional stdenv.isDarwin "--disable-nls";
 
-  buildInputs = [ gettext ];
+  nativeBuildInputs = [ gettext ];
 
   meta = {
     description = "ELF object file access library";
diff --git a/pkgs/development/libraries/libmicrohttpd/default.nix b/pkgs/development/libraries/libmicrohttpd/default.nix
index c68187945334..7ee0cbe1bd94 100644
--- a/pkgs/development/libraries/libmicrohttpd/default.nix
+++ b/pkgs/development/libraries/libmicrohttpd/default.nix
@@ -1,29 +1,25 @@
-{ lib, stdenv, fetchurl, libgcrypt }:
+{ stdenv, fetchurl, libgcrypt, curl, gnutls, pkgconfig }:
 
 stdenv.mkDerivation rec {
-  name = "libmicrohttpd-0.9.44";
+  name = "libmicrohttpd-0.9.50";
 
   src = fetchurl {
     url = "mirror://gnu/libmicrohttpd/${name}.tar.gz";
-    sha256 = "07j1p21rvbrrfpxngk8xswzkmjkh94bp1971xfjh1p0ja709qwzj";
+    sha256 = "1mzbqr6sqisppz88mh73bbh5sw57g8l87qvhcjdx5pmbd183idni";
   };
 
   outputs = [ "dev" "out" "docdev" ];
+  buildInputs = [ libgcrypt curl gnutls pkgconfig ];
 
-  buildInputs = [ libgcrypt ];
-
-  preCheck =
+  preCheck = ''
     # Since `localhost' can't be resolved in a chroot, work around it.
-    '' for i in "src/test"*"/"*.[ch]
-       do
-         sed -i "$i" -es/localhost/127.0.0.1/g
-       done
-    '';
+    sed -ie 's/localhost/127.0.0.1/g' src/test*/*.[ch]
+  '';
 
   # Disabled because the tests can time-out.
   doCheck = false;
 
-  meta = {
+  meta = with stdenv.lib; {
     description = "Embeddable HTTP server library";
 
     longDescription = ''
@@ -31,10 +27,10 @@ stdenv.mkDerivation rec {
       it easy to run an HTTP server as part of another application.
     '';
 
-    license = lib.licenses.lgpl2Plus;
+    license = licenses.lgpl2Plus;
 
     homepage = http://www.gnu.org/software/libmicrohttpd/;
 
-    maintainers = [ lib.maintainers.eelco ];
+    maintainers = [ maintainers.eelco maintainers.vrthra ];
   };
 }
diff --git a/pkgs/development/libraries/libxkbcommon/default.nix b/pkgs/development/libraries/libxkbcommon/default.nix
index 7cfccfe05f74..7087142a2aa9 100644
--- a/pkgs/development/libraries/libxkbcommon/default.nix
+++ b/pkgs/development/libraries/libxkbcommon/default.nix
@@ -1,4 +1,4 @@
-{ stdenv, fetchurl, pkgconfig, yacc, flex, xkeyboard_config, libxcb }:
+{ stdenv, fetchurl, pkgconfig, yacc, flex, xkeyboard_config, libxcb, libX11 }:
 
 stdenv.mkDerivation rec {
   name = "libxkbcommon-0.6.1";
@@ -12,9 +12,10 @@ stdenv.mkDerivation rec {
 
   buildInputs = [ pkgconfig yacc flex xkeyboard_config libxcb ];
 
-  configureFlags = ''
-    --with-xkb-config-root=${xkeyboard_config}/etc/X11/xkb
-  '';
+  configureFlags = [
+    "--with-xkb-config-root=${xkeyboard_config}/etc/X11/xkb"
+    "--with-x-locale-root=${libX11.out}/share/X11/locale"
+  ];
 
   preBuild = stdenv.lib.optionalString stdenv.isDarwin ''
     sed -i 's/,--version-script=.*$//' Makefile
diff --git a/pkgs/development/libraries/xgboost/default.nix b/pkgs/development/libraries/xgboost/default.nix
index e3c5d7573107..4ba366be56f0 100644
--- a/pkgs/development/libraries/xgboost/default.nix
+++ b/pkgs/development/libraries/xgboost/default.nix
@@ -11,6 +11,8 @@ stdenv.mkDerivation rec {
     sha256 = "1d7lnbwxwakclqqfjwyk9w3wd2clkihdr6ljs5z08ydiaspri093";
   };
 
+  postPatch = "sed '1i#include <cmath>' -i src/tree/param.h";
+
   enableParallelBuilding = true;
 
   installPhase = ''
diff --git a/pkgs/development/python-modules/generic/wrap.sh b/pkgs/development/python-modules/generic/wrap.sh
index a67ea51f5a9b..efbb1e737876 100644
--- a/pkgs/development/python-modules/generic/wrap.sh
+++ b/pkgs/development/python-modules/generic/wrap.sh
@@ -46,16 +46,15 @@ wrapPythonProgramsIn() {
                 # wrapProgram creates the executable shell script described
                 # above. The script will set PYTHONPATH and PATH variables.!
                 # (see pkgs/build-support/setup-hooks/make-wrapper.sh)
-                local wrap_args="$f \
-                                 --prefix PYTHONPATH ':' $program_PYTHONPATH \
-                                 --prefix PATH ':' $program_PATH:$dir/bin"
+                local -a wrap_args=("$f"
+                                 --prefix PYTHONPATH ':' "$program_PYTHONPATH"
+                                 --prefix PATH ':' "$program_PATH:$dir/bin")
 
                 # Add any additional arguments provided by makeWrapperArgs
                 # argument to buildPythonPackage.
-                for arg in $makeWrapperArgs; do
-                    wrap_args="$wrap_args $arg"
-                done
-                wrapProgram $wrap_args
+                local -a user_args="($makeWrapperArgs)"
+                local -a wrapProgramArgs=("${wrap_args[@]}" "${user_args[@]}")
+                wrapProgram "${wrapProgramArgs[@]}"
             fi
         fi
     done
diff --git a/pkgs/development/tools/analysis/rr/default.nix b/pkgs/development/tools/analysis/rr/default.nix
index 926aaeb94ccc..84ab79879b41 100644
--- a/pkgs/development/tools/analysis/rr/default.nix
+++ b/pkgs/development/tools/analysis/rr/default.nix
@@ -11,8 +11,9 @@ stdenv.mkDerivation rec {
     sha256 = "03fl2wgbc1cilaw8hrhfqjsbpi05cid6k4cr3s2vmv5gx0dnrgy4";
   };
 
-  patchPhase = ''
+  postPatch = ''
     substituteInPlace src/Command.cc --replace '_BSD_SOURCE' '_DEFAULT_SOURCE'
+    sed '7i#include <math.h>' -i src/Scheduler.cc
     patchShebangs .
   '';
 
diff --git a/pkgs/development/tools/misc/hydra/default.nix b/pkgs/development/tools/misc/hydra/default.nix
index 510a0679527e..a4f1a96c6a4c 100644
--- a/pkgs/development/tools/misc/hydra/default.nix
+++ b/pkgs/development/tools/misc/hydra/default.nix
@@ -3,7 +3,7 @@
 , gitAndTools, mercurial, darcs, subversion, bazaar, openssl, bzip2, libxslt
 , guile, perl, postgresql92, aws-sdk-cpp, nukeReferences, git, boehmgc
 , docbook_xsl, openssh, gnused, coreutils, findutils, gzip, lzma, gnutar
-, rpm, dpkg, cdrkit }:
+, rpm, dpkg, cdrkit, fetchpatch }:
 
 with stdenv;
 
@@ -70,6 +70,12 @@ in releaseTools.nixBuild rec {
     sha256 = "0ngipzm2i2vz5ygfd70hh82d027snpl85r8ncn1rxlkak0g8fxsl";
   };
 
+  patches = [(fetchpatch {
+    name = "cmath.diff";
+    url = https://github.com/vcunat/hydra/commit/3c6fca1ba299.diff; # https://github.com/NixOS/hydra/pull/337
+    sha256 = "02m9q304ay45s7xfkm2y7lppakrkx3hrq39mm6348isnbqmbarc0";
+  })];
+
   buildInputs =
     [ makeWrapper autoconf automake libtool unzip nukeReferences pkgconfig sqlite libpqxx
       gitAndTools.topGit mercurial darcs subversion bazaar openssl bzip2 libxslt
diff --git a/pkgs/games/cataclysm-dda/default.nix b/pkgs/games/cataclysm-dda/default.nix
index 3956c994531e..b46114ec62be 100644
--- a/pkgs/games/cataclysm-dda/default.nix
+++ b/pkgs/games/cataclysm-dda/default.nix
@@ -21,6 +21,9 @@ stdenv.mkDerivation rec {
     sed -i Makefile \
       -e 's,-Werror,,g' \
       -e 's,\(DATA_PREFIX=$(PREFIX)/share/\)cataclysm-dda/,\1,g'
+
+    sed '1i#include <cmath>' \
+      -i src/{crafting,skill,weather_data,melee,vehicle,overmap,iuse_actor}.cpp
   '';
 
   makeFlags = "PREFIX=$(out) LUA=1 TILES=1 SOUND=1 RELEASE=1 USE_HOME_DIR=1";
diff --git a/pkgs/games/dwarf-fortress/dfhack/default.nix b/pkgs/games/dwarf-fortress/dfhack/default.nix
index 3d3b1c4d9aa8..1ee0f829571d 100644
--- a/pkgs/games/dwarf-fortress/dfhack/default.nix
+++ b/pkgs/games/dwarf-fortress/dfhack/default.nix
@@ -39,6 +39,7 @@ in stdenv.mkDerivation rec {
   };
 
   patches = [ ./use-system-libraries.patch ];
+  postPatch = "sed '1i#include <math.h>' -i plugins/3dveins.cpp";
 
   nativeBuildInputs = [ cmake perl XMLLibXML XMLLibXSLT fakegit ];
   # we can't use native Lua; upstream uses private headers
diff --git a/pkgs/games/dwarf-fortress/unfuck.nix b/pkgs/games/dwarf-fortress/unfuck.nix
index 1d6ea1196dab..5b2327c2ff54 100644
--- a/pkgs/games/dwarf-fortress/unfuck.nix
+++ b/pkgs/games/dwarf-fortress/unfuck.nix
@@ -13,6 +13,8 @@ stdenv.mkDerivation {
     sha256 = "12bqh3k4wsk1c0bz2zly8h0ilbsdmsbwr9cdjc6i7liwg9906g7i";
   };
 
+  postPatch = "sed '1i#include <math.h>' -i g_src/ttf_manager.cpp";
+
   cmakeFlags = [
     "-DGTK2_GLIBCONFIG_INCLUDE_DIR=${glib.out}/lib/glib-2.0/include"
     "-DGTK2_GDKCONFIG_INCLUDE_DIR=${gtk2.out}/lib/gtk-2.0/include"
diff --git a/pkgs/games/openspades/default.nix b/pkgs/games/openspades/default.nix
index 2203bb6337eb..143fa21ce2e5 100644
--- a/pkgs/games/openspades/default.nix
+++ b/pkgs/games/openspades/default.nix
@@ -16,7 +16,11 @@ stdenv.mkDerivation rec {
   postPatch = ''
     substituteInPlace Sources/Client/Client_Input.cpp --replace "isnan(" "std::isnan("
     substituteInPlace Sources/Client/Corpse.cpp --replace "isnan(" "std::isnan("
-    substituteInPlace Sources/Draw/SWMapRenderer.cpp --replace "isnan(" "std::isnan(" --replace "isinf(" "std::isinf("
+    substituteInPlace Sources/Draw/SWMapRenderer.cpp \
+      --replace "isnan(" "std::isnan(" --replace "isinf(" "std::isinf("
+    sed '1i#include <cmath>' -i Sources/Client/{Player,Client_Input,Corpse}.cpp \
+      -i Sources/Draw/SWMapRenderer.cpp
+    sed '1i#include <math.h>' -i Sources/Draw/SWFeatureLevel.h
   '';
 
   nativeBuildInputs = 
diff --git a/pkgs/games/openspades/git.nix b/pkgs/games/openspades/git.nix
index 8212f160cda8..7d76573f7345 100644
--- a/pkgs/games/openspades/git.nix
+++ b/pkgs/games/openspades/git.nix
@@ -14,6 +14,8 @@ stdenv.mkDerivation rec {
     sha256 = "0vyvmgim03q8pcmfa1i0njr4w1lpjq5g3b47f67v9b5c5jcjycwn";
   };
 
+  postPatch = "sed '1i#include <cmath>' -i Sources/Client/{,Client}Player.cpp";
+
   nativeBuildInputs = 
     with stdenv.lib;
     [ cmake curl glew makeWrapper mesa SDL2 SDL2_image unzip wget zlib ]
diff --git a/pkgs/games/the-butterfly-effect/default.nix b/pkgs/games/the-butterfly-effect/default.nix
index 7cd54b1b65b3..68114bb75652 100644
--- a/pkgs/games/the-butterfly-effect/default.nix
+++ b/pkgs/games/the-butterfly-effect/default.nix
@@ -10,10 +10,13 @@ stdenv.mkDerivation rec {
     sha256 = "1ag2cp346f9bz9qy6za6q54id44d2ypvkyhvnjha14qzzapwaysj";
   };
 
+  postPatch = "sed '1i#include <vector>' -i src/model/World.h";
+
   buildInputs = [
     qt5.qtbase qt5.qtsvg qt5.qttranslations box2d which cmake
     gettext
   ];
+  enableParallelBuilding = true;
 
   installPhase = ''
     make DESTDIR=.. install
diff --git a/pkgs/misc/emulators/higan/default.nix b/pkgs/misc/emulators/higan/default.nix
index b5707213530a..f180a446d055 100644
--- a/pkgs/misc/emulators/higan/default.nix
+++ b/pkgs/misc/emulators/higan/default.nix
@@ -21,6 +21,7 @@ stdenv.mkDerivation rec {
   };
 
   patches = [ ./0001-change-flags.diff ];
+  postPatch = "sed '1i#include <cmath>' -i higan/fc/ppu/ppu.cpp";
 
   buildInputs =
   [ p7zip pkgconfig libX11 libXv udev mesa SDL libao openal libpulseaudio gtk gtksourceview ];
diff --git a/pkgs/misc/emulators/pcsx2/default.nix b/pkgs/misc/emulators/pcsx2/default.nix
index 1b95bca643c7..673e4c3ed087 100644
--- a/pkgs/misc/emulators/pcsx2/default.nix
+++ b/pkgs/misc/emulators/pcsx2/default.nix
@@ -15,6 +15,8 @@ stdenv.mkDerivation rec {
     sha256 = "0s7mxq2cgzwjfsq0vhpz6ljk7wr725nxg48128iyirf85585l691";
   };
 
+  postPatch = "sed '1i#include \"x86intrin.h\"' -i common/src/x86emitter/cpudetect.cpp";
+
   configurePhase = ''
     mkdir -p build
     cd build
@@ -50,6 +52,8 @@ stdenv.mkDerivation rec {
     soundtouch wxGTK30 zlib
   ];
 
+  enableParallelBuilding = true;
+
   meta = with stdenv.lib; {
     description = "Playstation 2 emulator";
     longDescription= ''
diff --git a/pkgs/os-specific/linux/sysdig/default.nix b/pkgs/os-specific/linux/sysdig/default.nix
index 8296ec62c5b2..82e088b76c20 100644
--- a/pkgs/os-specific/linux/sysdig/default.nix
+++ b/pkgs/os-specific/linux/sysdig/default.nix
@@ -18,6 +18,9 @@ stdenv.mkDerivation {
   src = fetchurl {
     inherit (s) url sha256;
   };
+  postPatch = ''
+    sed '1i#include <cmath>' -i userspace/libsinsp/{cursesspectro,filterchecks}.cpp
+  '';
 
   cmakeFlags = [
     "-DUSE_BUNDLED_DEPS=OFF"
diff --git a/pkgs/servers/nosql/arangodb/default.nix b/pkgs/servers/nosql/arangodb/default.nix
index ffcd507653a0..8b8d1ba0ae16 100644
--- a/pkgs/servers/nosql/arangodb/default.nix
+++ b/pkgs/servers/nosql/arangodb/default.nix
@@ -11,6 +11,13 @@ stdenv.mkDerivation rec {
     sha256 = "1v07fghf2jd2mvkfqhag0xblf6sxw7kx9kmhs2xpyrpns58lirvc";
   };
 
+  postPatch = ''
+    substituteInPlace 3rdParty/V8-3.31.74.1/build/gyp/gyp --replace /bin/bash ${bash}/bin/bash
+    substituteInPlace 3rdParty/etcd/build --replace /bin/bash ${bash}/bin/bash
+    sed '1i#include <cmath>' -i arangod/Aql/Functions.cpp \
+      -i lib/Basics/string-buffer.cpp
+  '';
+
   buildInputs = [
     openssl zlib python gyp go readline
   ];
@@ -19,12 +26,6 @@ stdenv.mkDerivation rec {
 
   NIX_CFLAGS_COMPILE = "-Wno-error=strict-overflow";
 
-
-  patchPhase = ''
-    substituteInPlace 3rdParty/V8-3.31.74.1/build/gyp/gyp --replace /bin/bash ${bash}/bin/bash
-    substituteInPlace 3rdParty/etcd/build --replace /bin/bash ${bash}/bin/bash
-    '';
-
   enableParallelBuilding = true;
 
   meta = with stdenv.lib; {
diff --git a/pkgs/stdenv/darwin/make-bootstrap-tools.nix b/pkgs/stdenv/darwin/make-bootstrap-tools.nix
index 40f26dc2450b..43775d0350b8 100644
--- a/pkgs/stdenv/darwin/make-bootstrap-tools.nix
+++ b/pkgs/stdenv/darwin/make-bootstrap-tools.nix
@@ -3,9 +3,11 @@
 with import ../../.. { inherit system; };
 
 rec {
-  # We want coreutils without ACL support.
-  coreutils_ = coreutils.override (orig: {
+  coreutils_ = coreutils.override (args: {
+    # We want coreutils without ACL support.
     aclSupport = false;
+    # Our tooling currently can't handle scripts in bin/, only ELFs and symlinks.
+    singleBinary = "symlinks";
   });
 
   build = stdenv.mkDerivation {
diff --git a/pkgs/stdenv/generic/setup.sh b/pkgs/stdenv/generic/setup.sh
index 85e74461d2a4..5b50167d9b9f 100644
--- a/pkgs/stdenv/generic/setup.sh
+++ b/pkgs/stdenv/generic/setup.sh
@@ -827,6 +827,10 @@ showPhaseHeader() {
 
 
 genericBuild() {
+    if [ -f "$buildCommandPath" ]; then
+        . "$buildCommandPath"
+        return
+    fi
     if [ -n "$buildCommand" ]; then
         eval "$buildCommand"
         return
diff --git a/pkgs/stdenv/linux/make-bootstrap-tools-cross.nix b/pkgs/stdenv/linux/make-bootstrap-tools-cross.nix
index d6e024c62583..6dfe1bf41e4f 100644
--- a/pkgs/stdenv/linux/make-bootstrap-tools-cross.nix
+++ b/pkgs/stdenv/linux/make-bootstrap-tools-cross.nix
@@ -5,7 +5,7 @@ let buildFor = toolsArch: (
 let
   pkgsFun = import ../../..;
   pkgsNoParams = pkgsFun {};
-  
+
   sheevaplugCrossSystem = {
     crossSystem = rec {
       config = "armv5tel-unknown-linux-gnueabi";
@@ -18,10 +18,10 @@ let
       openssl.system = "linux-generic32";
     };
   };
-  
+
   raspberrypiCrossSystem = {
     crossSystem = rec {
-      config = "armv6l-unknown-linux-gnueabi";  
+      config = "armv6l-unknown-linux-gnueabi";
       bigEndian = false;
       arch = "arm";
       float = "hard";
@@ -33,10 +33,10 @@ let
       inherit (platform) gcc;
     };
   };
-  
+
   armv7l-hf-multiplatform-crossSystem = {
     crossSystem = rec {
-      config = "armv7l-unknown-linux-gnueabi";  
+      config = "armv7l-unknown-linux-gnueabi";
       bigEndian = false;
       arch = "arm";
       float = "hard";
@@ -48,7 +48,7 @@ let
       inherit (platform) gcc;
     };
   };
-  
+
   selectedCrossSystem =
     if toolsArch == "armv5tel" then sheevaplugCrossSystem else
     if toolsArch == "armv6l" then raspberrypiCrossSystem else
@@ -87,17 +87,19 @@ in
 
 rec {
 
-  # We want coreutils without ACL support.
   coreutilsMinimal = (pkgs.coreutils.override (args: {
+    # We want coreutils without ACL support.
     aclSupport = false;
+    # Our tooling currently can't handle scripts in bin/, only ELFs and symlinks.
+    singleBinary = "symlinks";
   })).crossDrv;
-  
+
   curlMinimal = (pkgs.curl.override {
     zlibSupport = false;
     sslSupport = false;
     scpSupport = false;
   }).crossDrv;
-  
+
   busyboxMinimal = (pkgs.busybox.override {
     # TBD: uClibc is broken.
     # useUclibc = true;
@@ -113,10 +115,10 @@ rec {
       CONFIG_UNXZ y
     '';
   }).crossDrv;
-  
+
   inherit pkgs;
 
-  build = 
+  build =
 
     stdenv.mkDerivation {
       name = "build";
@@ -126,7 +128,7 @@ rec {
       crossConfig = stdenv.cross.config;
 
       buildCommand = ''
-	set -x
+	      set -x
         mkdir -p $out/bin $out/lib $out/libexec
 
         # Copy what we need of Glibc.
@@ -142,20 +144,20 @@ rec {
         cp -d ${glibc.out}/lib/libnss*.so* $out/lib
         cp -d ${glibc.out}/lib/libresolv*.so* $out/lib
         cp -d ${glibc.out}/lib/crt?.o $out/lib
-        
+
         cp -rL ${glibc.dev}/include $out
         chmod -R u+w $out/include
-        
+
         # Hopefully we won't need these.
         rm -rf $out/include/mtd $out/include/rdma $out/include/sound $out/include/video
         find $out/include -name .install -exec rm {} \;
         find $out/include -name ..install.cmd -exec rm {} \;
         mv $out/include $out/include-glibc
-        
+
         # Copy coreutils, bash, etc.
         cp ${coreutilsMinimal}/bin/* $out/bin
         (cd $out/bin && rm vdir dir sha*sum pinky factor pathchk runcon shuf who whoami shred users)
-        
+
         cp ${bash}/bin/bash $out/bin
         cp ${findutils}/bin/find $out/bin
         cp ${findutils}/bin/xargs $out/bin
@@ -174,7 +176,7 @@ rec {
         cp -d ${curlMinimal}/lib/libcurl* $out/lib
 
         cp -d ${gnugrep.pcre.crossDrv}/lib/libpcre*.so* $out/lib # needed by grep
-        
+
         # Copy what we need of GCC.
         cp -d ${gcc}/bin/gcc $out/bin
         cp -d ${gcc}/bin/cpp $out/bin
@@ -203,12 +205,12 @@ rec {
         cp -d ${libmpc}/lib/libmpc*.so* $out/lib
         cp -d ${zlib.out}/lib/libz.so* $out/lib
         cp -d ${libelf}/lib/libelf.so* $out/lib
-        
+
         # TBD: Why are these needed for cross but not native tools?
         cp -d ${cloogppl}/lib/libcloog*.so* $out/lib
         cp -d ${cloog}/lib/libcloog*.so* $out/lib
         cp -d ${isl}/lib/libisl*.so* $out/lib
-        
+
         # Copy binutils.
         for i in as ld ar ranlib nm strip readelf objdump; do
           cp ${binutils}/bin/$i $out/bin
@@ -216,7 +218,7 @@ rec {
         cp -d ${binutils.out}/lib/lib*.so* $out/lib
 
         chmod -R u+w $out
-        
+
         # Strip executables even further.
         for i in $out/bin/* $out/libexec/gcc/*/*/*; do
             if test -x $i -a ! -L $i; then
diff --git a/pkgs/stdenv/linux/make-bootstrap-tools.nix b/pkgs/stdenv/linux/make-bootstrap-tools.nix
index 8ffeebaa962e..866906662aea 100644
--- a/pkgs/stdenv/linux/make-bootstrap-tools.nix
+++ b/pkgs/stdenv/linux/make-bootstrap-tools.nix
@@ -5,9 +5,11 @@ with import ../../.. {inherit system;};
 rec {
 
 
-  # We want coreutils without ACL support.
   coreutilsMinimal = coreutils.override (args: {
+    # We want coreutils without ACL support.
     aclSupport = false;
+    # Our tooling currently can't handle scripts in bin/, only ELFs and symlinks.
+    singleBinary = "symlinks";
   });
 
   tarMinimal = gnutar.override { acl = null; };
diff --git a/pkgs/tools/misc/coreutils/default.nix b/pkgs/tools/misc/coreutils/default.nix
index 1ad4f473e9d0..4ed43a189882 100644
--- a/pkgs/tools/misc/coreutils/default.nix
+++ b/pkgs/tools/misc/coreutils/default.nix
@@ -3,6 +3,7 @@
 , selinuxSupport? false, libselinux ? null, libsepol ? null
 , autoconf, automake114x, texinfo
 , withPrefix ? false
+, singleBinary ? true # you can also pass "symlinks", for example
 }:
 
 assert aclSupport -> acl != null;
@@ -30,7 +31,10 @@ let
     outputs = [ "out" "info" ];
 
     nativeBuildInputs = [ perl xz.bin ];
-    configureFlags = optionalString stdenv.isSunOS "ac_cv_func_inotify_init=no";
+    configureFlags =
+      optional (singleBinary != false)
+        ("--enable-single-binary" + optionalString (isString singleBinary) "=${singleBinary}")
+      ++ optional stdenv.isSunOS "ac_cv_func_inotify_init=no";
 
     buildInputs = [ gmp ]
       ++ optional aclSupport acl
diff --git a/pkgs/tools/misc/file/default.nix b/pkgs/tools/misc/file/default.nix
index 749bf59fde96..b1e9990ea7d4 100644
--- a/pkgs/tools/misc/file/default.nix
+++ b/pkgs/tools/misc/file/default.nix
@@ -1,7 +1,7 @@
 { stdenv, fetchurl, zlib }:
 
 stdenv.mkDerivation rec {
-  name = "file-5.25";
+  name = "file-5.28";
 
   buildInputs = [ zlib ];
 
@@ -10,7 +10,7 @@ stdenv.mkDerivation rec {
       "ftp://ftp.astron.com/pub/file/${name}.tar.gz"
       "http://distfiles.macports.org/file/${name}.tar.gz"
     ];
-    sha256 = "1jhfi5mivdnqvry5la5q919l503ahwdwbf3hjhiv97znccakhd9p";
+    sha256 = "04p0w9ggqq6cqvwhyni0flji1z0rwrz896hmhkxd2mc6dca5xjqf";
   };
 
   meta = {
diff --git a/pkgs/tools/typesetting/xmlto/default.nix b/pkgs/tools/typesetting/xmlto/default.nix
index f99c14720760..37bc1831d5b1 100644
--- a/pkgs/tools/typesetting/xmlto/default.nix
+++ b/pkgs/tools/typesetting/xmlto/default.nix
@@ -1,12 +1,12 @@
 { fetchurl, stdenv, flex, libxml2, libxslt
-, docbook_xml_dtd_42, docbook_xsl, w3m
+, docbook_xml_dtd_45, docbook_xsl, w3m
 , bash, getopt, makeWrapper }:
 
 stdenv.mkDerivation rec {
-  name = "xmlto-0.0.26";
+  name = "xmlto-0.0.28";
   src = fetchurl {
     url = "http://fedorahosted.org/releases/x/m/xmlto/${name}.tar.bz2";
-    sha256 = "1v5mahfg5k9lh3anykl482xnrgxn36zlmqsgwahw29xwncprpd7g";
+    sha256 = "0xhj8b2pwp4vhl9y16v3dpxpsakkflfamr191mprzsspg4xdyc0i";
   };
 
   patchPhase = ''
@@ -20,7 +20,8 @@ stdenv.mkDerivation rec {
 
   # `libxml2' provides `xmllint', needed at build-time and run-time.
   # `libxslt' provides `xsltproc', used by `xmlto' at run-time.
-  buildInputs = [ libxml2 libxslt docbook_xml_dtd_42 docbook_xsl getopt makeWrapper ];
+  nativeBuildInputs = [ makeWrapper ];
+  buildInputs = [ libxml2 libxslt docbook_xml_dtd_45 docbook_xsl getopt ];
 
   postInstall = ''
     wrapProgram "$out/bin/xmlto" \
diff --git a/pkgs/top-level/all-packages.nix b/pkgs/top-level/all-packages.nix
index cbb4b12e5108..b2cbe0fd03fc 100644
--- a/pkgs/top-level/all-packages.nix
+++ b/pkgs/top-level/all-packages.nix
@@ -7298,6 +7298,10 @@ in
     guileBindings = config.gnutls.guile or false;
   };
 
+  gnutls35 = callPackage ../development/libraries/gnutls/3.5.nix {
+    guileBindings = config.gnutls.guile or false;
+  };
+
   gpac = callPackage ../applications/video/gpac { };
 
   gpgme = callPackage ../development/libraries/gpgme {