1# NOTE: Make sure to (re-)format this file on changes with `nixpkgs-fmt`!
2
3{ stdenv
4, lib
5, nixosTests
6, fetchFromGitHub
7, fetchpatch
8, fetchzip
9, buildPackages
10, makeBinaryWrapper
11, ninja
12, meson
13, m4
14, pkg-config
15, coreutils
16, gperf
17, getent
18, glibcLocales
19
20 # glib is only used during tests (test-bus-gvariant, test-bus-marshal)
21, glib
22, substituteAll
23, gettext
24, python3Packages
25
26 # Mandatory dependencies
27, libcap
28, util-linux
29, kbd
30, kmod
31, libxcrypt
32
33 # Optional dependencies
34, pam
35, cryptsetup
36, audit
37, acl
38, lz4
39, libgcrypt
40, libgpg-error
41, libidn2
42, curl
43, gnutar
44, gnupg
45, zlib
46, xz
47, zstd
48, tpm2-tss
49, libuuid
50, libapparmor
51, intltool
52, bzip2
53, pcre2
54, e2fsprogs
55, elfutils
56, linuxHeaders ? stdenv.cc.libc.linuxHeaders
57, gnu-efi
58, iptables
59, withSelinux ? false
60, libselinux
61, withLibseccomp ? lib.meta.availableOn stdenv.hostPlatform libseccomp
62, libseccomp
63, withKexectools ? lib.meta.availableOn stdenv.hostPlatform kexec-tools
64, kexec-tools
65, bashInteractive
66, libmicrohttpd
67, libfido2
68, p11-kit
69
70 # the (optional) BPF feature requires bpftool, libbpf, clang and llvm-strip to be available during build time.
71 # Only libbpf should be a runtime dependency.
72, bpftools
73, libbpf
74, llvmPackages
75
76, withAnalyze ? true
77, withApparmor ? true
78, withCompression ? true # adds bzip2, lz4, xz and zstd
79, withCoredump ? true
80, withCryptsetup ? true
81, withDocumentation ? true
82, withEfi ? stdenv.hostPlatform.isEfi
83, withFido2 ? true
84, withHomed ? false
85, withHostnamed ? true
86, withHwdb ? true
87, withImportd ? !stdenv.hostPlatform.isMusl
88, withLibBPF ? lib.versionAtLeast llvmPackages.clang.version "10.0"
89, withLocaled ? true
90, withLogind ? true
91, withMachined ? true
92, withNetworkd ? true
93, withNss ? !stdenv.hostPlatform.isMusl
94, withOomd ? true
95, withPCRE2 ? true
96, withPolkit ? true
97, withPortabled ? !stdenv.hostPlatform.isMusl
98, withRemote ? !stdenv.hostPlatform.isMusl
99, withResolved ? true
100, withShellCompletions ? true
101, withTimedated ? true
102, withTimesyncd ? true
103, withTpm2Tss ? true
104, withUserDb ? true
105, withUtmp ? !stdenv.hostPlatform.isMusl
106 # tests assume too much system access for them to be feasible for us right now
107, withTests ? false
108
109 # name argument
110, pname ? "systemd"
111
112, libxslt
113, docbook_xsl
114, docbook_xml_dtd_42
115, docbook_xml_dtd_45
116}:
117
118assert withImportd -> withCompression;
119assert withCoredump -> withCompression;
120assert withHomed -> withCryptsetup;
121
122let
123 wantCurl = withRemote || withImportd;
124 wantGcrypt = withResolved || withImportd;
125 version = "251.7";
126
127 # Bump this variable on every (major) version change. See below (in the meson options list) for why.
128 # command:
129 # $ curl -s https://api.github.com/repos/systemd/systemd/releases/latest | \
130 # jq '.created_at|strptime("%Y-%m-%dT%H:%M:%SZ")|mktime'
131 releaseTimestamp = "1653143108";
132in
133stdenv.mkDerivation {
134 inherit pname version;
135
136 # We use systemd/systemd-stable for src, and ship NixOS-specific patches inside nixpkgs directly
137 # This has proven to be less error-prone than the previous systemd fork.
138 src = fetchFromGitHub {
139 owner = "systemd";
140 repo = "systemd-stable";
141 rev = "v${version}";
142 sha256 = "sha256-Sa5diyNFyYtREo1xSCcufAW83ZZGZvueoDVuQ2r8wno=";
143 };
144
145 # On major changes, or when otherwise required, you *must* reformat the patches,
146 # `git am path/to/00*.patch` them into a systemd worktree, rebase to the more recent
147 # systemd version, and export the patches again via
148 # `git -c format.signoff=false format-patch v${version} --no-numbered --zero-commit --no-signature`.
149 # Use `find . -name "*.patch" | sort` to get an up-to-date listing of all patches
150 patches = [
151 ./0001-Start-device-units-for-uninitialised-encrypted-devic.patch
152 ./0002-Don-t-try-to-unmount-nix-or-nix-store.patch
153 ./0003-Fix-NixOS-containers.patch
154 ./0004-Look-for-fsck-in-the-right-place.patch
155 ./0005-Add-some-NixOS-specific-unit-directories.patch
156 ./0006-Get-rid-of-a-useless-message-in-user-sessions.patch
157 ./0007-hostnamed-localed-timedated-disable-methods-that-cha.patch
158 ./0008-Fix-hwdb-paths.patch
159 ./0009-Change-usr-share-zoneinfo-to-etc-zoneinfo.patch
160 ./0010-localectl-use-etc-X11-xkb-for-list-x11.patch
161 ./0011-build-don-t-create-statedir-and-don-t-touch-prefixdi.patch
162 ./0012-add-rootprefix-to-lookup-dir-paths.patch
163 ./0013-systemd-shutdown-execute-scripts-in-etc-systemd-syst.patch
164 ./0014-systemd-sleep-execute-scripts-in-etc-systemd-system-.patch
165 ./0015-path-util.h-add-placeholder-for-DEFAULT_PATH_NORMAL.patch
166 ./0016-pkg-config-derive-prefix-from-prefix.patch
167 ./0017-inherit-systemd-environment-when-calling-generators.patch
168 ./0018-core-don-t-taint-on-unmerged-usr.patch
169 ] ++ lib.optional stdenv.hostPlatform.isMusl (
170 let
171 oe-core = fetchzip {
172 url = "https://git.openembedded.org/openembedded-core/snapshot/openembedded-core-86a33f98a7c0d6f2c2b51d02ba9e01b63062cf98.tar.bz2";
173 sha256 = "081j01sw21hl405l7g9z4bavvq0q0k4g80365677m0ykhiqlx3am";
174 };
175 musl-patches = oe-core + "/meta/recipes-core/systemd/systemd";
176 in
177 [
178 (musl-patches + "/0003-missing_type.h-add-comparison_fn_t.patch")
179 (musl-patches + "/0004-add-fallback-parse_printf_format-implementation.patch")
180 (musl-patches + "/0005-src-basic-missing.h-check-for-missing-strndupa.patch")
181 (musl-patches + "/0007-don-t-fail-if-GLOB_BRACE-and-GLOB_ALTDIRFUNC-is-not-.patch")
182 (musl-patches + "/0008-add-missing-FTW_-macros-for-musl.patch")
183 (musl-patches + "/0010-Use-uintmax_t-for-handling-rlim_t.patch")
184 (musl-patches + "/0011-test-sizeof.c-Disable-tests-for-missing-typedefs-in-.patch")
185 (musl-patches + "/0012-don-t-pass-AT_SYMLINK_NOFOLLOW-flag-to-faccessat.patch")
186 (musl-patches + "/0013-Define-glibc-compatible-basename-for-non-glibc-syste.patch")
187 (musl-patches + "/0014-Do-not-disable-buffering-when-writing-to-oom_score_a.patch")
188 (musl-patches + "/0015-distinguish-XSI-compliant-strerror_r-from-GNU-specif.patch")
189 (musl-patches + "/0018-avoid-redefinition-of-prctl_mm_map-structure.patch")
190 (musl-patches + "/0022-do-not-disable-buffer-in-writing-files.patch")
191 (musl-patches + "/0025-Handle-__cpu_mask-usage.patch")
192 (musl-patches + "/0026-Handle-missing-gshadow.patch")
193 (musl-patches + "/0028-missing_syscall.h-Define-MIPS-ABI-defines-for-musl.patch")
194 (musl-patches + "/0001-pass-correct-parameters-to-getdents64.patch")
195 (musl-patches + "/0002-Add-sys-stat.h-for-S_IFDIR.patch")
196 (musl-patches + "/0001-Adjust-for-musl-headers.patch")
197 ]
198 );
199
200 postPatch = ''
201 substituteInPlace src/basic/path-util.h --replace "@defaultPathNormal@" "${placeholder "out"}/bin/"
202 substituteInPlace src/boot/efi/meson.build \
203 --replace \
204 "run_command(cc.cmd_array(), '-print-prog-name=objcopy', check: true).stdout().strip()" \
205 "'${stdenv.cc.bintools.targetPrefix}objcopy'"
206 '' + lib.optionalString withLibBPF ''
207 substituteInPlace meson.build \
208 --replace "find_program('clang'" "find_program('${stdenv.cc.targetPrefix}clang'"
209 # BPF does not work with stack protector
210 substituteInPlace src/core/bpf/meson.build \
211 --replace "clang_flags = [" "clang_flags = [ '-fno-stack-protector',"
212 '' + (
213 let
214 # The following patches references to dynamic libraries to ensure that
215 # all the features that are implemented via dlopen(3) are available (or
216 # explicitly deactivated) by pointing dlopen to the absolute store path
217 # instead of relying on the linkers runtime lookup code.
218 #
219 # All of the shared library references have to be handled. When new ones
220 # are introduced by upstream (or one of our patches) they must be
221 # explicitly declared, otherwise the build will fail.
222 #
223 # As of systemd version 247 we've seen a few errors like `libpcre2.… not
224 # found` when using e.g. --grep with journalctl. Those errors should
225 # become less unexpected now.
226 #
227 # There are generally two classes of dlopen(3) calls. Those that we want to
228 # support and those that should be deactivated / unsupported. This change
229 # enforces that we handle all dlopen calls explicitly. Meaning: There is
230 # not a single dlopen call in the source code tree that we did not
231 # explicitly handle.
232 #
233 # In order to do this we introduced a list of attributes that maps from
234 # shared object name to the package that contains them. The package can be
235 # null meaning the reference should be nuked and the shared object will
236 # never be loadable during runtime (because it points at an invalid store
237 # path location).
238 #
239 # To get a list of dynamically loaded libraries issue something like
240 # `grep -ri '"lib[a-zA-Z0-9-]*\.so[\.0-9a-zA-z]*"'' $src` and update the below list.
241 dlopenLibs =
242 let
243 opt = condition: pkg: if condition then pkg else null;
244 in
245 [
246 # bpf compilation support. We use libbpf 1 now.
247 { name = "libbpf.so.1"; pkg = opt withLibBPF libbpf; }
248 { name = "libbpf.so.0"; pkg = null; }
249
250 # We did never provide support for libxkbcommon & qrencode
251 { name = "libxkbcommon.so.0"; pkg = null; }
252 { name = "libqrencode.so.4"; pkg = null; }
253 { name = "libqrencode.so.3"; pkg = null; }
254
255 # We did not provide libpwquality before so it is safe to disable it for
256 # now.
257 { name = "libpwquality.so.1"; pkg = null; }
258
259 # Only include cryptsetup if it is enabled. We might not be able to
260 # provide it during "bootstrap" in e.g. the minimal systemd build as
261 # cryptsetup has udev (aka systemd) in it's dependencies.
262 { name = "libcryptsetup.so.12"; pkg = opt withCryptsetup cryptsetup; }
263
264 # We are using libidn2 so we only provide that and ignore the others.
265 # Systemd does this decision during configure time and uses ifdef's to
266 # enable specific branches. We can safely ignore (nuke) the libidn "v1"
267 # libraries.
268 { name = "libidn2.so.0"; pkg = libidn2; }
269 { name = "libidn.so.12"; pkg = null; }
270 { name = "libidn.so.11"; pkg = null; }
271
272 # journalctl --grep requires libpcre so let's provide it
273 { name = "libpcre2-8.so.0"; pkg = pcre2; }
274
275 # Support for TPM2 in systemd-cryptsetup, systemd-repart and systemd-cryptenroll
276 { name = "libtss2-esys.so.0"; pkg = opt withTpm2Tss tpm2-tss; }
277 { name = "libtss2-rc.so.0"; pkg = opt withTpm2Tss tpm2-tss; }
278 { name = "libtss2-mu.so.0"; pkg = opt withTpm2Tss tpm2-tss; }
279 { name = "libtss2-tcti-"; pkg = opt withTpm2Tss tpm2-tss; }
280 { name = "libfido2.so.1"; pkg = opt withFido2 libfido2; }
281
282 # inspect-elf support
283 { name = "libelf.so.1"; pkg = opt withCoredump elfutils; }
284 { name = "libdw.so.1"; pkg = opt withCoredump elfutils; }
285 ];
286
287 patchDlOpen = dl:
288 let
289 library = "${lib.makeLibraryPath [ dl.pkg ]}/${dl.name}";
290 in
291 if dl.pkg == null then ''
292 # remove the dependency on the library by replacing it with an invalid path
293 for file in $(grep -lr '"${dl.name}"' src); do
294 echo "patching dlopen(\"${dl.name}\", …) in $file to an invalid store path ("/nix/store/eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee-not-implemented/${dl.name}")…"
295 substituteInPlace "$file" --replace '"${dl.name}"' '"/nix/store/eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee-not-implemented/${dl.name}"'
296 done
297 '' else ''
298 # ensure that the library we provide actually exists
299 if ! [ -e ${library} ]; then
300 # exceptional case, details:
301 # https://github.com/systemd/systemd-stable/blob/v249-stable/src/shared/tpm2-util.c#L157
302 if ! [[ "${library}" =~ .*libtss2-tcti-$ ]]; then
303 echo 'The shared library `${library}` does not exist but was given as substitute for `${dl.name}`'
304 exit 1
305 fi
306 fi
307 # make the path to the dependency explicit
308 for file in $(grep -lr '"${dl.name}"' src); do
309 echo "patching dlopen(\"${dl.name}\", …) in $file to ${library}…"
310 substituteInPlace "$file" --replace '"${dl.name}"' '"${library}"'
311 done
312
313 '';
314 in
315 # patch all the dlopen calls to contain absolute paths to the libraries
316 lib.concatMapStringsSep "\n" patchDlOpen dlopenLibs
317 )
318 # finally ensure that there are no left-over dlopen calls (or rather strings pointing to shared libraries) that we didn't handle
319 + ''
320 if grep -qr '"lib[a-zA-Z0-9-]*\.so[\.0-9a-zA-z]*"' src; then
321 echo "Found unhandled dynamic library calls: "
322 grep -r '"lib[a-zA-Z0-9-]*\.so[\.0-9a-zA-z]*"' src
323 exit 1
324 fi
325 ''
326 # Finally, patch shebangs in scripts used at build time. This must not patch
327 # scripts that will end up in the output, to avoid build platform references
328 # when cross-compiling.
329 + ''
330 shopt -s extglob
331 patchShebangs tools test src/!(rpm)
332 '';
333
334 outputs = [ "out" "man" "dev" ];
335
336 nativeBuildInputs =
337 [
338 pkg-config
339 makeBinaryWrapper
340 gperf
341 ninja
342 meson
343 glibcLocales
344 getent
345 m4
346
347 intltool
348 gettext
349
350 libxslt
351 docbook_xsl
352 docbook_xml_dtd_42
353 docbook_xml_dtd_45
354 (buildPackages.python3Packages.python.withPackages (ps: with ps; [ lxml jinja2 ]))
355 ]
356 ++ lib.optionals withLibBPF [
357 bpftools
358 llvmPackages.clang
359 llvmPackages.libllvm
360 ]
361 ;
362
363 buildInputs =
364 [
365 acl
366 audit
367 kmod
368 libxcrypt
369 libcap
370 libidn2
371 libuuid
372 linuxHeaders
373 pam
374 ]
375
376 ++ lib.optional wantGcrypt libgcrypt
377 ++ lib.optional withTests glib
378 ++ lib.optional withApparmor libapparmor
379 ++ lib.optional wantCurl (lib.getDev curl)
380 ++ lib.optionals withCompression [ bzip2 lz4 xz zstd ]
381 ++ lib.optional withCoredump elfutils
382 ++ lib.optional withCryptsetup (lib.getDev cryptsetup.dev)
383 ++ lib.optional withEfi gnu-efi
384 ++ lib.optional withKexectools kexec-tools
385 ++ lib.optional withLibseccomp libseccomp
386 ++ lib.optional withNetworkd iptables
387 ++ lib.optional withPCRE2 pcre2
388 ++ lib.optional withResolved libgpg-error
389 ++ lib.optional withSelinux libselinux
390 ++ lib.optional withRemote libmicrohttpd
391 ++ lib.optionals withHomed [ p11-kit ]
392 ++ lib.optionals (withHomed || withCryptsetup) [ libfido2 ]
393 ++ lib.optionals withLibBPF [ libbpf ]
394 ++ lib.optional withTpm2Tss tpm2-tss
395 ;
396
397 #dontAddPrefix = true;
398
399 mesonFlags = [
400 "-Dversion-tag=${version}"
401 # We bump this variable on every (major) version change to ensure
402 # that we have known-good value for a timestamp that is in the (not so distant) past.
403 # This serves as a lower bound for valid system timestamps during startup. Systemd will
404 # reset the system timestamp if this date is +- 15 years from the system time.
405 # See the systemd v250 release notes for further details:
406 # https://github.com/systemd/systemd/blob/60e930fc3e6eb8a36fbc184773119eb8d2f30364/NEWS#L258-L266
407 "-Dtime-epoch=${releaseTimestamp}"
408
409 "-Ddbuspolicydir=${placeholder "out"}/share/dbus-1/system.d"
410 "-Ddbussessionservicedir=${placeholder "out"}/share/dbus-1/services"
411 "-Ddbussystemservicedir=${placeholder "out"}/share/dbus-1/system-services"
412 "-Dpamconfdir=${placeholder "out"}/etc/pam.d"
413 "-Drootprefix=${placeholder "out"}"
414 "-Dpkgconfiglibdir=${placeholder "dev"}/lib/pkgconfig"
415 "-Dpkgconfigdatadir=${placeholder "dev"}/share/pkgconfig"
416 "-Dloadkeys-path=${kbd}/bin/loadkeys"
417 "-Dsetfont-path=${kbd}/bin/setfont"
418 "-Dtty-gid=3" # tty in NixOS has gid 3
419 "-Ddebug-shell=${bashInteractive}/bin/bash"
420 "-Dglib=${lib.boolToString withTests}"
421 # while we do not run tests we should also not build them. Removes about 600 targets
422 "-Dtests=false"
423 "-Danalyze=${lib.boolToString withAnalyze}"
424 "-Dgcrypt=${lib.boolToString wantGcrypt}"
425 "-Dimportd=${lib.boolToString withImportd}"
426 "-Dlz4=${lib.boolToString withCompression}"
427 "-Dhomed=${lib.boolToString withHomed}"
428 "-Dlogind=${lib.boolToString withLogind}"
429 "-Dlocaled=${lib.boolToString withLocaled}"
430 "-Dhostnamed=${lib.boolToString withHostnamed}"
431 "-Dmachined=${lib.boolToString withMachined}"
432 "-Dnetworkd=${lib.boolToString withNetworkd}"
433 "-Doomd=${lib.boolToString withOomd}"
434 "-Dpolkit=${lib.boolToString withPolkit}"
435 "-Dlibcryptsetup=${lib.boolToString withCryptsetup}"
436 "-Dportabled=${lib.boolToString withPortabled}"
437 "-Dhwdb=${lib.boolToString withHwdb}"
438 "-Dremote=${lib.boolToString withRemote}"
439 "-Dsysusers=false"
440 "-Dtimedated=${lib.boolToString withTimedated}"
441 "-Dtimesyncd=${lib.boolToString withTimesyncd}"
442 "-Duserdb=${lib.boolToString withUserDb}"
443 "-Dcoredump=${lib.boolToString withCoredump}"
444 "-Dfirstboot=false"
445 "-Dresolve=${lib.boolToString withResolved}"
446 "-Dsplit-usr=false"
447 "-Dlibcurl=${lib.boolToString wantCurl}"
448 "-Dlibidn=false"
449 "-Dlibidn2=true"
450 "-Dquotacheck=false"
451 "-Dldconfig=false"
452 "-Dsmack=true"
453 "-Db_pie=true"
454 "-Dinstall-sysconfdir=false"
455 "-Dsbat-distro=nixos"
456 "-Dsbat-distro-summary=NixOS"
457 "-Dsbat-distro-url=https://nixos.org/"
458 "-Dsbat-distro-pkgname=${pname}"
459 "-Dsbat-distro-version=${version}"
460 /*
461 As of now, systemd doesn't allow runtime configuration of these values. So
462 the settings in /etc/login.defs have no effect on it. Many people think this
463 should be supported however, see
464 - https://github.com/systemd/systemd/issues/3855
465 - https://github.com/systemd/systemd/issues/4850
466 - https://github.com/systemd/systemd/issues/9769
467 - https://github.com/systemd/systemd/issues/9843
468 - https://github.com/systemd/systemd/issues/10184
469 */
470 "-Dsystem-uid-max=999"
471 "-Dsystem-gid-max=999"
472
473 "-Dsysvinit-path="
474 "-Dsysvrcnd-path="
475
476 "-Dkmod-path=${kmod}/bin/kmod"
477 "-Dsulogin-path=${util-linux}/bin/sulogin"
478 "-Dmount-path=${util-linux}/bin/mount"
479 "-Dumount-path=${util-linux}/bin/umount"
480 "-Dcreate-log-dirs=false"
481
482 # Use cgroupsv2. This is already the upstream default, but better be explicit.
483 "-Ddefault-hierarchy=unified"
484 # Upstream defaulted to disable manpages since they optimize for the much
485 # more frequent development builds
486 "-Dman=true"
487
488 "-Defi=${lib.boolToString withEfi}"
489 "-Dgnu-efi=${lib.boolToString withEfi}"
490 ] ++ lib.optionals withEfi [
491 "-Defi-libdir=${toString gnu-efi}/lib"
492 "-Defi-includedir=${toString gnu-efi}/include/efi"
493 ] ++ lib.optionals (withShellCompletions == false) [
494 "-Dbashcompletiondir=no"
495 "-Dzshcompletiondir=no"
496 ] ++ lib.optionals (!withNss) [
497 "-Dnss-myhostname=false"
498 "-Dnss-mymachines=false"
499 "-Dnss-resolve=false"
500 "-Dnss-systemd=false"
501 ] ++ lib.optionals withLibBPF [
502 "-Dbpf-framework=true"
503 ] ++ lib.optionals withTpm2Tss [
504 "-Dtpm2=true"
505 ] ++ lib.optionals (!withUtmp) [
506 "-Dutmp=false"
507 ] ++ lib.optionals stdenv.hostPlatform.isMusl [
508 "-Dgshadow=false"
509 "-Didn=false"
510 ];
511 preConfigure =
512 let
513 # A list of all the runtime binaries that the systemd exectuables, tests and libraries are referencing in their source code, scripts and unit files.
514 # As soon as a dependency isn't required anymore we should remove it from the list. The `where` attribute for each of the replacement patterns must be exhaustive. If another (unhandled) case is found in the source code the build fails with an error message.
515 binaryReplacements = [
516 { search = "/usr/bin/getent"; replacement = "${getent}/bin/getent"; where = [ "src/nspawn/nspawn-setuid.c" ]; }
517
518 {
519 search = "/sbin/mkswap";
520 replacement = "${lib.getBin util-linux}/sbin/mkswap";
521 where = [
522 "man/systemd-makefs@.service.xml"
523 ];
524 }
525 { search = "/sbin/swapon"; replacement = "${lib.getBin util-linux}/sbin/swapon"; where = [ "src/core/swap.c" "src/basic/unit-def.h" ]; }
526 { search = "/sbin/swapoff"; replacement = "${lib.getBin util-linux}/sbin/swapoff"; where = [ "src/core/swap.c" ]; }
527 {
528 search = "/bin/echo";
529 replacement = "${coreutils}/bin/echo";
530 where = [
531 "man/systemd-analyze.xml"
532 "man/systemd.service.xml"
533 "src/analyze/test-verify.c"
534 "src/test/test-env-file.c"
535 "src/test/test-fileio.c"
536 "src/test/test-load-fragment.c"
537 ];
538 }
539 {
540 search = "/bin/cat";
541 replacement = "${coreutils}/bin/cat";
542 where = [ "test/create-busybox-container" "test/test-execute/exec-noexecpaths-simple.service" "src/journal/cat.c" ];
543 }
544 { search = "/sbin/modprobe"; replacement = "${lib.getBin kmod}/sbin/modprobe"; where = [ "units/modprobe@.service" ]; }
545 {
546 search = "/usr/lib/systemd/systemd-fsck";
547 replacement = "$out/lib/systemd/systemd-fsck";
548 where = [
549 "man/systemd-fsck@.service.xml"
550 ];
551 }
552 ] ++ lib.optionals withImportd [
553 {
554 search = "\"gpg\"";
555 replacement = "\\\"${gnupg}/bin/gpg\\\"";
556 where = [ "src/import/pull-common.c" ];
557 }
558 {
559 search = "\"tar\"";
560 replacement = "\\\"${gnutar}/bin/tar\\\"";
561 where = [
562 "src/import/export-tar.c"
563 "src/import/import-common.c"
564 "src/import/import-tar.c"
565 ];
566 ignore = [
567 # occurences here refer to the tar sub command
568 "src/sysupdate/sysupdate-resource.c"
569 "src/sysupdate/sysupdate-transfer.c"
570 "src/import/pull.c"
571 "src/import/export.c"
572 "src/import/import.c"
573 "src/import/importd.c"
574 # runs `tar` but also also creates a temporary directory with the string
575 "src/import/pull-tar.c"
576 ];
577 }
578 ];
579
580 # { replacement, search, where } -> List[str]
581 mkSubstitute = { replacement, search, where, ignore ? [ ] }:
582 map (path: "substituteInPlace ${path} --replace '${search}' \"${replacement}\"") where;
583 mkEnsureSubstituted = { replacement, search, where, ignore ? [ ] }:
584 let
585 ignore' = lib.concatStringsSep "|" (ignore ++ [ "^test" "NEWS" ]);
586 in
587 ''
588 set +e
589 search=$(grep '${search}' -r | grep -v "${replacement}" | grep -Ev "${ignore'}")
590 set -e
591 if [[ -n "$search" ]]; then
592 echo "Not all references to '${search}' have been replaced. Found the following matches:"
593 echo "$search"
594 exit 1
595 fi
596 '';
597 in
598 ''
599 mesonFlagsArray+=(-Dntp-servers="0.nixos.pool.ntp.org 1.nixos.pool.ntp.org 2.nixos.pool.ntp.org 3.nixos.pool.ntp.org")
600 export LC_ALL="en_US.UTF-8";
601
602 ${lib.concatStringsSep "\n" (lib.flatten (map mkSubstitute binaryReplacements))}
603 ${lib.concatMapStringsSep "\n" mkEnsureSubstituted binaryReplacements}
604
605 substituteInPlace src/libsystemd/sd-journal/catalog.c \
606 --replace /usr/lib/systemd/catalog/ $out/lib/systemd/catalog/
607
608 substituteInPlace src/import/pull-tar.c \
609 --replace 'wait_for_terminate_and_check("tar"' 'wait_for_terminate_and_check("${gnutar}/bin/tar"'
610 '';
611
612 # These defines are overridden by CFLAGS and would trigger annoying
613 # warning messages
614 postConfigure = ''
615 substituteInPlace config.h \
616 --replace "POLKIT_AGENT_BINARY_PATH" "_POLKIT_AGENT_BINARY_PATH" \
617 --replace "SYSTEMD_BINARY_PATH" "_SYSTEMD_BINARY_PATH" \
618 --replace "SYSTEMD_CGROUP_AGENTS_PATH" "_SYSTEMD_CGROUP_AGENT_PATH"
619 '';
620
621 NIX_CFLAGS_COMPILE = toString ([
622 # Can't say ${polkit.bin}/bin/pkttyagent here because that would
623 # lead to a cyclic dependency.
624 "-UPOLKIT_AGENT_BINARY_PATH"
625 "-DPOLKIT_AGENT_BINARY_PATH=\"/run/current-system/sw/bin/pkttyagent\""
626
627 # Set the release_agent on /sys/fs/cgroup/systemd to the
628 # currently running systemd (/run/current-system/systemd) so
629 # that we don't use an obsolete/garbage-collected release agent.
630 "-USYSTEMD_CGROUP_AGENTS_PATH"
631 "-DSYSTEMD_CGROUP_AGENTS_PATH=\"/run/current-system/systemd/lib/systemd/systemd-cgroups-agent\""
632
633 "-USYSTEMD_BINARY_PATH"
634 "-DSYSTEMD_BINARY_PATH=\"/run/current-system/systemd/lib/systemd/systemd\""
635
636 ] ++ lib.optionals stdenv.hostPlatform.isMusl [
637 "-D__UAPI_DEF_ETHHDR=0"
638 ]);
639
640 doCheck = false; # fails a bunch of tests
641
642 # trigger the test -n "$DESTDIR" || mutate in upstreams build system
643 preInstall = ''
644 export DESTDIR=/
645 '';
646
647 postInstall = ''
648 mkdir -p $out/example/systemd
649 mv $out/lib/{modules-load.d,binfmt.d,sysctl.d,tmpfiles.d} $out/example
650 mv $out/lib/systemd/{system,user} $out/example/systemd
651
652 rm -rf $out/etc/systemd/system
653
654 # Fix reference to /bin/false in the D-Bus services.
655 for i in $out/share/dbus-1/system-services/*.service; do
656 substituteInPlace $i --replace /bin/false ${coreutils}/bin/false
657 done
658
659 rm -rf $out/etc/rpm
660
661 # "kernel-install" shouldn't be used on NixOS.
662 find $out -name "*kernel-install*" -exec rm {} \;
663 '' + lib.optionalString (!withDocumentation) ''
664 rm -rf $out/share/doc
665 '';
666
667 # Avoid *.EFI binary stripping. At least on aarch64-linux strip
668 # removes too much from PE32+ files:
669 # https://github.com/NixOS/nixpkgs/issues/169693
670 # The hack is to move EFI file out of lib/ before doStrip
671 # run and return it after doStrip run.
672 preFixup = lib.optionalString withEfi ''
673 mv $out/lib/systemd/boot/efi $out/dont-strip-me
674 '';
675
676 # Wrap in the correct path for LUKS2 tokens.
677 postFixup = lib.optionalString withCryptsetup ''
678 for f in lib/systemd/systemd-cryptsetup bin/systemd-cryptenroll; do
679 # This needs to be in LD_LIBRARY_PATH because rpath on a binary is not propagated to libraries using dlopen, in this case `libcryptsetup.so`
680 wrapProgram $out/$f --prefix LD_LIBRARY_PATH : ${placeholder "out"}/lib/cryptsetup
681 done
682 '' + lib.optionalString withEfi ''
683 mv $out/dont-strip-me $out/lib/systemd/boot/efi
684 '';
685
686 passthru = {
687 # The interface version prevents NixOS from switching to an
688 # incompatible systemd at runtime. (Switching across reboots is
689 # fine, of course.) It should be increased whenever systemd changes
690 # in a backwards-incompatible way. If the interface version of two
691 # systemd builds is the same, then we can switch between them at
692 # runtime; otherwise we can't and we need to reboot.
693 interfaceVersion = 2;
694
695 inherit withCryptsetup withHostnamed withImportd withLocaled withMachined withPortabled withTimedated withUtmp util-linux kmod kbd;
696
697 tests = {
698 inherit (nixosTests) switchTest;
699 };
700 };
701
702 meta = with lib; {
703 homepage = "https://www.freedesktop.org/wiki/Software/systemd/";
704 description = "A system and service manager for Linux";
705 license = licenses.lgpl21Plus;
706 platforms = platforms.linux;
707 # https://github.com/systemd/systemd/issues/20600#issuecomment-912338965
708 broken = stdenv.hostPlatform.isStatic;
709 priority = 10;
710 maintainers = with maintainers; [ flokli kloenk mic92 ];
711 };
712}