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