This is a backport of cf8daf63120adedbeaf5bc8c2f396be2496a741e in stdenv-updates (sans the userHook stuff).